text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change audition recommendations on auditions page
<div class="row"> <div class="small-12 columns"> <h1>Auditions</h1> <p>Auditions for Partial Credit are held once per semester. Come check us out at the activities fair to sign up for an audition time or look for fliers posted around campus for information about audition opportunities!</p> <p>During auditions, we'll ask you to: <ul> <li>Go up and down scales to warm up and test your range</li> <li>Do a volume exercise (crescendo and decrescendo on a single pitch)</li> <li>Match patterns of notes played on a piano</li> <li>Perform about one minute of a song of your choice (usually a verse and a chorus)</li> <li>Do some impromptu vocal percussion if you can</li> </ul> </p> <p>Just remember to relax, do your best, and have fun! <a href="?p=contact">Contact us</a> if you have any questions and to sign up for an audition time slot.</p> </div> </div>
<div class="row"> <div class="small-12 columns"> <h1>Auditions</h1> <p>Auditions for Partial Credit are held once per semester. Come check us out at the activities fair to sign up for an audition time or look for fliers posted around campus for information about audition opportunities!</p> <p>During auditions, we'll ask you to: <ul> <li>Go up and down scales to warm up and test your range</li> <li>Do a volume exercise (crescendo and decrescendo on a single pitch)</li> <li>Match patterns of notes played on a piano</li> <li>Perform one to two minutes of a song of your choice (usually a verse and a chorus)</li> <li>Do some impromptu vocal percussion if you can</li> </ul> </p> <p>Just remember to relax, do your best, and have fun! <a href="?p=contact">Contact us</a> if you have any questions and to sign up for an audition time slot.</p> </div> </div>
Update tests with diacritical cases
const expect = require('chai').expect; const path = require('path'); const _ = require(path.join(__dirname, '../../dist/lodash-addons')); describe('slugify', function() { it('exists', function() { expect(_.slugify).to.be.a('function'); }); it('converts invalid types to strings', function() { expect(_.slugify(5)).to.equal('5'); expect(_.slugify(undefined)).to.equal(''); }); it('removes illegal characters', function() { expect(_.slugify('test?ing')).to.equal('testing'); }); it('removes consecutive illegal characters', function() { expect(_.slugify('test??ing')).to.equal('testing'); }); it('replaces whitespace', function() { expect(_.slugify('test ing')).to.equal('test-ing'); }); it('replaces diacritical marks', function() { expect(_.slugify('estado de comunicación')).to.equal('estado-de-comunicacion'); }); it('replaces consecutive diacritical marks', function() { expect(_.slugify('estado de comunicaciòón')).to.equal('estado-de-comunicacioon'); }); it('replaces diacritical marks and illegal characters', function() { expect(_.slugify('estado de comuni?cación')).to.equal('estado-de-comunicacion'); }); });
const expect = require('chai').expect; const path = require('path'); const _ = require(path.join(__dirname, '../../dist/lodash-addons')); describe('slugify', function() { it('exists', function() { expect(_.slugify).to.be.a('function'); }); it('converts invalid types to strings', function() { expect(_.slugify(5)).to.equal('5'); expect(_.slugify(undefined)).to.equal(''); }); it('removes illegal characters', function() { expect(_.slugify('test?ing')).to.equal('testing'); }); it('removes consecutive illegal characters', function() { expect(_.slugify('test??ing')).to.equal('testing'); }); it('replaces whitespace', function() { expect(_.slugify('test ing')).to.equal('test-ing'); }); });
Use wildcard in Gulp minify task.
'use strict'; var gulp = require('gulp'), nodemon = require('gulp-nodemon'), uglify = require('gulp-uglify'), sass = require('gulp-sass'), minifyCSS = require('gulp-minify-css'), rename = require('gulp-rename'), concat = require('gulp-concat'); function restartTime () { function checkTime(i) { return (i < 10) ? '0' + i : i; } var today = new Date(), hrs = checkTime(today.getHours()), min = checkTime(today.getMinutes()), sec = checkTime(today.getMinutes()); return hrs + ':' + min + ':' + sec; } gulp.task('watch', function () { nodemon({ script: 'server.js', ext: 'jade js'}) .on('restart', function () { console.log('Server restarted at ' + restartTime + '!'); }); }); gulp.task('minify', function () { gulp.src('./app/css/*.sass') .pipe(sass({ indentedSyntax: true, errLogToConsole: true })) .pipe(minifyCSS()) .pipe(rename('main.min.css')) .pipe(gulp.dest('./public/css')); gulp.src(['./app/controllers/**/*.client.js']) .pipe(uglify()) .pipe(rename('site.min.js')) .pipe(gulp.dest('./public/scripts')); }); gulp.task('default', ['watch']);
'use strict'; var gulp = require('gulp'), nodemon = require('gulp-nodemon'), uglify = require('gulp-uglify'), sass = require('gulp-sass'), minifyCSS = require('gulp-minify-css'), rename = require('gulp-rename'), concat = require('gulp-concat'); function restartTime () { function checkTime(i) { return (i < 10) ? '0' + i : i; } var today = new Date(), hrs = checkTime(today.getHours()), min = checkTime(today.getMinutes()), sec = checkTime(today.getMinutes()); return hrs + ':' + min + ':' + sec; } gulp.task('watch', function () { nodemon({ script: 'server.js', ext: 'jade js'}) .on('restart', function () { console.log('Server restarted at ' + restartTime + '!'); }); }); gulp.task('minify', function () { gulp.src('./app/css/*.sass') .pipe(sass({ indentedSyntax: true, errLogToConsole: true })) .pipe(minifyCSS()) .pipe(rename('main.min.css')) .pipe(gulp.dest('./public/css')); gulp.src(['./app/controllers/clickController.client.js']) .pipe(uglify()) .pipe(rename('site.min.js')) .pipe(gulp.dest('./public/scripts')); }); gulp.task('default', ['watch']);
[test] Add `deviceName` field for Android
'use strict'; const sauceBrowsers = require('sauce-browsers'); const run = require('sauce-test'); const path = require('path'); const pkg = require('../package'); const platforms = sauceBrowsers([ { name: 'android', version: ['oldest', 'latest'] }, { name: 'chrome', version: ['oldest', 'latest'] }, { name: 'firefox', version: ['oldest', 'latest'] }, { name: 'internet explorer', version: 'oldest..latest' }, { name: 'iphone', version: ['oldest', 'latest'] }, { name: 'opera', version: 'oldest..latest' }, { name: 'safari', version: 'oldest..latest' }, { name: 'microsoftedge', version: 'oldest..latest' } ]).then((platforms) => { return platforms.map((platform) => { const ret = { browserName: platform.api_name, version: platform.short_version, platform: platform.os }; if (ret.browserName === 'android') ret.deviceName = platform.long_name; return ret; }); }); run(path.join(__dirname, 'test.js'), 'saucelabs', { html: path.join(__dirname, 'index.html'), accessKey: process.env.SAUCE_ACCESS_KEY, username: process.env.SAUCE_USERNAME, browserify: true, disableSSL: true, name: pkg.name, parallel: 5, platforms }).done((results) => { if (!results.passed) process.exit(1); });
'use strict'; const sauceBrowsers = require('sauce-browsers'); const run = require('sauce-test'); const path = require('path'); const pkg = require('../package'); const platforms = sauceBrowsers([ { name: 'android', version: ['oldest', 'latest'] }, { name: 'chrome', version: ['oldest', 'latest'] }, { name: 'firefox', version: ['oldest', 'latest'] }, { name: 'internet explorer', version: 'oldest..latest' }, { name: 'iphone', version: ['oldest', 'latest'] }, { name: 'opera', version: 'oldest..latest' }, { name: 'safari', version: 'oldest..latest' }, { name: 'microsoftedge', version: 'oldest..latest' } ]).then((platforms) => { return platforms.map((platform) => { return { browserName: platform.api_name, version: platform.short_version, platform: platform.os }; }); }); run(path.join(__dirname, 'test.js'), 'saucelabs', { html: path.join(__dirname, 'index.html'), accessKey: process.env.SAUCE_ACCESS_KEY, username: process.env.SAUCE_USERNAME, browserify: true, disableSSL: true, name: pkg.name, parallel: 5, platforms }).done((results) => { if (!results.passed) process.exit(1); });
Remove @Override annotation for Java5 compatibility
/*-------------------------------------------------------------------------- * Copyright 2011 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // XerialJ // // SnappyBundleActivator.java // Since: 2011/06/22 10:01:46 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.snappy; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; /** * OSGi bundle entry point * * @author leo * */ public class SnappyBundleActivator implements BundleActivator { public void start(BundleContext context) throws Exception { } public void stop(BundleContext context) throws Exception { } }
/*-------------------------------------------------------------------------- * Copyright 2011 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // XerialJ // // SnappyBundleActivator.java // Since: 2011/06/22 10:01:46 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.snappy; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class SnappyBundleActivator implements BundleActivator { @Override public void start(BundleContext context) throws Exception { } @Override public void stop(BundleContext context) throws Exception { } }
Fix for submit for approval button not always showing. Ensure event lookup uses consistent uri format.
function getLastEditedEvent(collection, page) { var uri = page; if (uri.charAt(0) !== '/') { uri = "/" + uri; } var pageEvents = collection.eventsByUri[uri]; var lastEditedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'EDITED' }) .sortBy(function (event) { return event.date; }) .last() .value(); return lastEditedEvent; } function getLastCompletedEvent(collection, page) { var uri = page; if (uri.charAt(0) !== '/') { uri = "/" + uri; } var lastCompletedEvent; if (collection.eventsByUri) { var pageEvents = collection.eventsByUri[uri]; if (pageEvents) { lastCompletedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'COMPLETED' }) .sortBy(function (event) { return event.date; }) .last() .value(); } } return lastCompletedEvent; }
function getLastEditedEvent(collection, page) { var pageEvents = collection.eventsByUri[page]; var lastEditedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'EDITED' }) .sortBy(function (event) { return event.date; }) .last() .value(); return lastEditedEvent; } function getLastCompletedEvent(collection, page) { var lastCompletedEvent; if (collection.eventsByUri) { var pageEvents = collection.eventsByUri[page]; if (pageEvents) { lastCompletedEvent = _.chain(pageEvents) .filter(function (event) { return event.type === 'COMPLETED' }) .sortBy(function (event) { return event.date; }) .last() .value(); } } return lastCompletedEvent; }
Change database url for create_engine()
from sqlalchemy import create_engine, Column, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() def db_connect(): """ Performs database connection Returns sqlalchemy engine instance """ return create_engine('postgres://fbcmeskynsvati:aURfAdENt6-kumO0j224GuXRWH' '@ec2-54-221-235-135.compute-1.amazonaws.com' ':5432/d2cc1tb2t1iges', echo=False) def create_battletag_table(engine): Base.metadata.create_all(engine) class Battletags(Base): """ Table to store user battletags """ __tablename__ = 'Battletags' disc_name = Column(String, primary_key=True) battletag = Column(String, unique=True)
from sqlalchemy import create_engine, Column, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() def db_connect(): """ Performs database connection Returns sqlalchemy engine instance """ return create_engine('postgres://avvcurseaphtxf:X0466JySVtLq6nyq_5pb7BQNjR@' 'ec2-54-227-250-80.compute-1.amazonaws.com' ':5432/d7do67r1b7t1nn', echo=False) def create_battletag_table(engine): Base.metadata.create_all(engine) class Battletags(Base): """ Table to store user battletags """ __tablename__ = 'Battletags' disc_name = Column(String, primary_key=True) battletag = Column(String, unique=True)
Correct name to LoggingCleanupSuite in SetUp methods
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package testbase import ( "flag" "github.com/juju/loggo" "github.com/juju/testing" gc "launchpad.net/gocheck" ) // LoggingSuite redirects the juju logger to the test logger // when embedded in a gocheck suite type. type LoggingSuite struct { testing.LoggingCleanupSuite } func (t *LoggingSuite) SetUpSuite(c *gc.C) { t.LoggingCleanupSuite.SetUpSuite(c) t.setUp(c) } func (t *LoggingSuite) SetUpTest(c *gc.C) { t.LoggingCleanupSuite.SetUpTest(c) t.PatchEnvironment("JUJU_LOGGING_CONFIG", "") t.setUp(c) } var logConfig = flag.String("juju.log", "DEBUG", "logging configuration (see http://godoc.org/github.com/juju/loggo#ConfigureLoggers; also accepts a bare log level to configure the log level of the root module") func (t *LoggingSuite) setUp(c *gc.C) { if _, ok := loggo.ParseLevel(*logConfig); ok { *logConfig = "<root>=" + *logConfig } err := loggo.ConfigureLoggers(*logConfig) c.Assert(err, gc.IsNil) }
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package testbase import ( "flag" "github.com/juju/loggo" "github.com/juju/testing" gc "launchpad.net/gocheck" ) // LoggingSuite redirects the juju logger to the test logger // when embedded in a gocheck suite type. type LoggingSuite struct { testing.LoggingCleanupSuite } func (t *LoggingSuite) SetUpSuite(c *gc.C) { t.LoggingSuite.SetUpSuite(c) t.setUp(c) } func (t *LoggingSuite) SetUpTest(c *gc.C) { t.LoggingSuite.SetUpTest(c) t.PatchEnvironment("JUJU_LOGGING_CONFIG", "") t.setUp(c) } var logConfig = flag.String("juju.log", "DEBUG", "logging configuration (see http://godoc.org/github.com/juju/loggo#ConfigureLoggers; also accepts a bare log level to configure the log level of the root module") func (t *LoggingSuite) setUp(c *gc.C) { if _, ok := loggo.ParseLevel(*logConfig); ok { *logConfig = "<root>=" + *logConfig } err := loggo.ConfigureLoggers(*logConfig) c.Assert(err, gc.IsNil) }
Fix layout bug by properly closing SPAN element The "E-mail" label ended up right of the "Real name" label earlier.
<?php if (is_guest()) { echo('<p class="qmText">The guest account does not have a profile. If you register a personal account '); echo('you will be able to create you own quizzes and see your user information plus statistics here!</p>'); echo('<br><br><br><br><br><br><br><br>'); die; } # PREPROCESS INPUT $username = mysql_real_escape_string(canonical_username(get_client_username())); # EXECUTE QUERY $result = exec_query("SELECT * FROM qmtbl_users WHERE username='$username'"); $profile = mysql_fetch_assoc($result); ?> <h2>Profile</h2> <a href="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>"> <img id="userImage" class="qmProfileImage" src="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>"> </a> <label>Username</label> <div class="qmFormFieldBox"> <span class="qm_shadedText"><?php echo stripslashes($profile['username']) ?></span> </div> <label>Real name</label> <div class="qmFormFieldBox"> <span class="qm_shadedText"><?php echo stripslashes($profile['realname']) ?></span> </div> <label>E-mail</label> <div class="qmFormFieldBox"> <span class="qm_shadedText"><?php echo stripslashes($profile['email']) ?></span> </div>
<?php if (is_guest()) { echo('<p class="qmText">The guest account does not have a profile. If you register a personal account '); echo('you will be able to create you own quizzes and see your user information plus statistics here!</p>'); echo('<br><br><br><br><br><br><br><br>'); die; } # PREPROCESS INPUT $username = mysql_real_escape_string(canonical_username(get_client_username())); # EXECUTE QUERY $result = exec_query("SELECT * FROM qmtbl_users WHERE username='$username'"); $profile = mysql_fetch_assoc($result); ?> <h2>Profile</h2> <a href="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>"> <img id="userImage" class="qmProfileImage" src="?action=serve_user_image&username=<?php echo $_COOKIE[QM_COOKIE_NAME__USERNAME] ?>"> </a> <label>Username</label> <div class="qmFormFieldBox"> <span class="qm_shadedText"><?php echo stripslashes($profile['username']) ?></span> </div> <label>Real name</label> <div class="qmFormFieldBox"> <span class="qm_shadedText"><?php echo stripslashes($profile['realname']) ?></span </div> <label>E-mail</label> <div class="qmFormFieldBox"> <span class="qm_shadedText"><?php echo stripslashes($profile['email']) ?></span> </div>
Add sample date into migration script
<?php class m131226_162226_create_user_table extends CDbMigration { public function up() { date_default_timezone_set('Europe/Berlin'); $this->createTable('tbl_user', array( 'id' => 'pk', 'email' => 'varchar(128) NOT NULL', 'password' => 'varchar(128) NOT NULL', 'create_time' => 'int NOT NULL', 'update_time' => 'int NOT NULL', 'last_login_time' => 'int', )); $this->createIndex('tbl_user_email_unique', 'tbl_user', 'email', true); $this->insert('tbl_user', array( "email" => "admin@einsle.de", "password" => sha1("ni.xd.ol"), "create_time" => strtotime('now'), "update_time" => strtotime('now'), )); } public function down() { $this->dropTable('tbl_user'); } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }
<?php class m131226_162226_create_user_table extends CDbMigration { public function up() { $this->createTable('tbl_user', array( 'id' => 'pk', 'email' => 'varchar(128) NOT NULL', 'password' => 'varchar(128) NOT NULL', 'create_time' => 'int NOT NULL', 'update_time' => 'int NOT NULL', 'last_login_time' => 'int', )); $this->createIndex('tbl_user_email_unique', 'tbl_user', 'email', true); } public function down() { $this->dropTable('tbl_user'); } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }
Add qunit task for failing test.
/* eslint-disable */ 'use strict'; var gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), qunit = require('./index'); var paths = { scripts: ['./*.js', '!./gulpfile.js'] }; gulp.task('lint', function() { return gulp.src(paths.scripts) .pipe(eslint()) .pipe(eslint.format()); }); gulp.task('test', function() { return gulp.src('./test/*.js') .pipe(mocha()); }); gulp.task('qunit:pass', function() { qunit('./test/fixtures/passing.html'); }); gulp.task('qunit:fail', function() { qunit('./test/fixtures/failing.html'); }); gulp.task('qunit-verbose', function() { qunit('./test/fixtures/passing.html', { 'verbose': true }); }); gulp.task('watch', function () { gulp.watch(paths.scripts, ['lint', 'jscs', 'test']); }); gulp.task('default', ['lint', 'jscs', 'test', 'watch']);
/* eslint-disable */ 'use strict'; var gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), qunit = require('./index'); var paths = { scripts: ['./*.js', '!./gulpfile.js'] }; gulp.task('lint', function() { return gulp.src(paths.scripts) .pipe(eslint()) .pipe(eslint.format()); }); gulp.task('test', function() { return gulp.src('./test/*.js') .pipe(mocha()); }); gulp.task('qunit', function() { qunit('./test/fixtures/passing.html'); }); gulp.task('qunit-verbose', function() { qunit('./test/fixtures/passing.html', { 'verbose': true }); }); gulp.task('watch', function () { gulp.watch(paths.scripts, ['lint', 'jscs', 'test']); }); gulp.task('default', ['lint', 'jscs', 'test', 'watch']);
Add support for 16-bit fixed point
define(function() { 'use strict'; return { fromInt32: function(i32) { var frac = 0; for (var i = 0; i < 16; i++) { if (i32 & (0x8000 >> i)) { frac += 1 / (2 << i); } } return (i32 >>> 16) + frac; }, fromInt32_2_30: function(i32) { var frac = 0; for (var i = 0; i < 30; i++) { if (i32 & (0x20000000 >> i)) { frac += 1 / (2 << i); } } return (i32 >>> 30) + frac; }, fromUint16: function(u16) { var frac = 0; for (var i = 0; i < 8; i++) { if (u16 & (0x80 >> i)) { frac += 1 / (2 << i); } } return (u16 >>> 8) + frac; }, }; });
define(function() { 'use strict'; return { fromInt32: function(i32) { var frac = 0; for (var i = 0; i < 16; i++) { if (i32 & (0x8000 >> i)) { frac += 1 / (2 << i); } } return (i32 >>> 16) + frac; }, fromInt32_2_30: function(i32) { var frac = 0; for (var i = 0; i < 30; i++) { if (i32 & (0x20000000 >> i)) { frac += 1 / (2 << i); } } return (i32 >>> 30) + frac; }, }; });
Add date as part of the log messages.
package main import ( "flag" "github.com/alinpopa/barvin/handlers/slack" "github.com/op/go-logging" "os" "sync" ) func main() { userID := flag.String("userid", "", "The privileged slack userid.") token := flag.String("token", "", "Slack token to connect.") flag.Parse() var format = logging.MustStringFormatter( `%{color}%{time:2006-01-02T15:04:05.000} %{shortfunc} >>> %{level} %{id:03x} %{message}%{color:reset}`, ) loggingBackend := logging.NewLogBackend(os.Stderr, "", 0) backend2Formatter := logging.NewBackendFormatter(loggingBackend, format) loggingBackendLeveled := logging.AddModuleLevel(loggingBackend) loggingBackendLeveled.SetLevel(logging.DEBUG, "") logging.SetBackend(backend2Formatter) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() restartChannel := make(chan string) go func() { restartChannel <- "Initial start" }() for { msg := <-restartChannel go slack.SlackHandler(msg, restartChannel, *userID, *token) } }() wg.Wait() }
package main import ( "flag" "github.com/alinpopa/barvin/handlers/slack" "github.com/op/go-logging" "os" "sync" ) func main() { userID := flag.String("userid", "", "The privileged slack userid.") token := flag.String("token", "", "Slack token to connect.") flag.Parse() var format = logging.MustStringFormatter( `%{color}%{time:15:04:05.000} %{shortfunc} >>> %{level} %{id:03x} %{message}%{color:reset}`, ) loggingBackend := logging.NewLogBackend(os.Stderr, "", 0) backend2Formatter := logging.NewBackendFormatter(loggingBackend, format) loggingBackendLeveled := logging.AddModuleLevel(loggingBackend) loggingBackendLeveled.SetLevel(logging.DEBUG, "") logging.SetBackend(backend2Formatter) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() restartChannel := make(chan string) go func() { restartChannel <- "Initial start" }() for { msg := <-restartChannel go slack.SlackHandler(msg, restartChannel, *userID, *token) } }() wg.Wait() }
Add mute param to generate mute video
<?php ini_set("display_errors", 0); $thumbdir = 'clip/'; $uuid = uniqid(); $start = floatval($_GET['t']) - 0.9; $duration = 3; $anilistID = rawurldecode($_GET['anilist_id']); $season = rawurldecode($_GET['season']); // deprecated $anime = rawurldecode($_GET['anime']); // deprecated $file = rawurldecode($_GET['file']); $filepath = str_replace('`', '\`', '/mnt/data/anilist/'.$anilistID.'/'.$file); if ($season && $anime) { // deprecated $filepath = str_replace('`', '\`', '/mnt/data/anime_new/'.$season.'/'.$anime.'/'.$file); } $thumbpath = $thumbdir.$uuid.'.mp4'; $mute = isset($_GET['mute']) ? "-an" : ""; if(file_exists($filepath)){ exec("ffmpeg -y -ss ".$start." -i \"$filepath\" -to ".$duration." -vf scale=640:-1 -c:v libx264 ".$mute." -preset fast ".$thumbpath); } header('Content-type: video/mp4'); readfile($thumbpath); unlink($thumbpath); ?>
<?php ini_set("display_errors", 0); $thumbdir = 'clip/'; $uuid = uniqid(); $start = floatval($_GET['t']) - 0.9; $duration = 3; $anilistID = rawurldecode($_GET['anilist_id']); $season = rawurldecode($_GET['season']); // deprecated $anime = rawurldecode($_GET['anime']); // deprecated $file = rawurldecode($_GET['file']); $filepath = str_replace('`', '\`', '/mnt/data/anilist/'.$anilistID.'/'.$file); if ($season && $anime) { // deprecated $filepath = str_replace('`', '\`', '/mnt/data/anime_new/'.$season.'/'.$anime.'/'.$file); } $thumbpath = $thumbdir.$uuid.'.mp4'; if(file_exists($filepath)){ exec("ffmpeg -y -ss ".$start." -i \"$filepath\" -to ".$duration." -vf scale=640:-1 -c:v libx264 -preset fast ".$thumbpath); } header('Content-type: video/mp4'); readfile($thumbpath); unlink($thumbpath); ?>
Test against phpunit version, not php version
<?php namespace EngineWorks\DBAL\Tests; use EngineWorks\DBAL\DBAL; use PHPUnit\Framework\Error\Notice; use PHPUnit\Runner\Version; /* @var $this \EngineWorks\DBAL\Tests\TestCaseWithDatabase */ trait TransactionsWithExceptionsTestTrait { /** @return DBAL */ abstract protected function getDbal(); private function checkPhpUnitVersion($minimalVersion) { $phpUnitVersion = '5.6'; if (class_exists(Version::class)) { $phpUnitVersion = Version::series(); } if (version_compare($phpUnitVersion, $minimalVersion, '<')) { $this->markTestSkipped(sprintf('This test only runs on phpunit %s or higher', $minimalVersion)); } } public function testCommitThrowsWarningWithOutBegin() { $this->checkPhpUnitVersion('6.0'); $this->expectException(Notice::class); $this->getDbal()->transCommit(); } public function testRollbackThrowsWarningWithOutBegin() { $this->checkPhpUnitVersion('6.0'); $this->expectException(Notice::class); $this->getDbal()->transRollback(); } }
<?php namespace EngineWorks\DBAL\Tests; use EngineWorks\DBAL\DBAL; use PHPUnit\Framework\Error\Notice; /* @var $this \EngineWorks\DBAL\Tests\TestCaseWithDatabase */ trait TransactionsWithExceptionsTestTrait { /** @return DBAL */ abstract protected function getDbal(); public function testCommitThrowsWarningWithOutBegin() { if (version_compare(PHP_VERSION, '7.0', '<')) { $this->markTestSkipped('This test only runs on php 7.0 or higher'); } $this->expectException(Notice::class); $this->getDbal()->transCommit(); } public function testRollbackThrowsWarningWithOutBegin() { if (version_compare(PHP_VERSION, '7.0', '<')) { $this->markTestSkipped('This test only runs on php 7.0 or higher'); } $this->expectException(Notice::class); $this->getDbal()->transRollback(); } }
Debug Google Cloud Run support
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') # app = Flask(__name__) # @app.route('/') # def ContainerService(): # return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' # app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') # stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) # output = stream.read() # output
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
Update to latest api change
/* * Copyright 2014 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.embeddedmongo.test; import io.vertx.core.VertxOptions; import io.vertx.test.core.VertxTestBase; import org.junit.Test; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public class EmbeddedMongoVerticleTest extends VertxTestBase { @Override public VertxOptions getOptions() { // It can take some time to download the first time! return new VertxOptions().setMaxWorkerExecuteTime(30 * 60 * 1000); } @Test public void testEmbeddedMongo() { // Not really sure what to test here apart from start and stop vertx.deployVerticle("service:io.vertx:vertx-mongo-embedded-db", onSuccess(deploymentID -> { assertNotNull(deploymentID); vertx.undeploy(deploymentID, onSuccess(v -> { assertNull(v); testComplete(); })); })); await(); } }
/* * Copyright 2014 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.embeddedmongo.test; import io.vertx.core.VertxOptions; import io.vertx.test.core.VertxTestBase; import org.junit.Test; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public class EmbeddedMongoVerticleTest extends VertxTestBase { @Override public VertxOptions getOptions() { // It can take some time to download the first time! return new VertxOptions().setMaxWorkerExecuteTime(30 * 60 * 1000); } @Test public void testEmbeddedMongo() { // Not really sure what to test here apart from start and stop vertx.deployVerticle("service:io.vertx:vertx-mongo-embedded-db", onSuccess(deploymentID -> { assertNotNull(deploymentID); vertx.undeployVerticle(deploymentID, onSuccess(v -> { assertNull(v); testComplete(); })); })); await(); } }
:ambulance: Fix caching of app fragments
/** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /* eslint-env node */ module.exports = { staticFileGlobs: [ 'index.html', 'preview-comms.html', 'manifest.json', 'src/**/*', 'bower_components/webcomponentsjs/*', 'node_modules/dexie/dist/dexie.min.js', 'bower_components/ace-builds/src-min-noconflict/theme-monokai.js', 'bower_components/ace-builds/src-min-noconflict/{mode,worker}-{html,js,css}.js', ], navigateFallback: 'index.html', };
/** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /* eslint-env node */ module.exports = { staticFileGlobs: [ 'index.html', 'preview-comms.html', 'manifest.json', 'bower_components/webcomponentsjs/*', 'node_modules/dexie/dist/dexie.min.js', 'bower_components/ace-builds/src-min-noconflict/theme-monokai.js', 'bower_components/ace-builds/src-min-noconflict/{mode,worker}-{html,js,css}.js', ], navigateFallback: 'index.html', };
Fix missing return in loadPrivateKey
package main import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "errors" "io/ioutil" "os" ) func generatePrivateKey(file string) (crypto.PrivateKey, error) { privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, err } keyBytes, err := x509.MarshalECPrivateKey(privateKey) if err != nil { return nil, err } pemKey := pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes} certOut, err := os.Create(file) if err != nil { return nil, err } pem.Encode(certOut, &pemKey) certOut.Close() return privateKey, nil } func loadPrivateKey(file string) (crypto.PrivateKey, error) { keyBytes, err := ioutil.ReadFile(file) if err != nil { return nil, err } keyBlock, _ := pem.Decode(keyBytes) switch keyBlock.Type { case "RSA PRIVATE KEY": return x509.ParsePKCS1PrivateKey(keyBlock.Bytes) case "EC PRIVATE KEY": return x509.ParseECPrivateKey(keyBlock.Bytes) } return nil, errors.New("Unknown private key type.") }
package main import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "errors" "io/ioutil" "os" ) func generatePrivateKey(file string) (crypto.PrivateKey, error) { privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, err } keyBytes, err := x509.MarshalECPrivateKey(privateKey) if err != nil { return nil, err } pemKey := pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes} certOut, err := os.Create(file) if err != nil { return nil, err } pem.Encode(certOut, &pemKey) certOut.Close() return privateKey, nil } func loadPrivateKey(file string) (crypto.PrivateKey, error) { keyBytes, err := ioutil.ReadFile(file) if err != nil { return nil, err } keyBlock, _ := pem.Decode(keyBytes) switch keyBlock.Type { case "RSA PRIVATE KEY": x509.ParsePKCS1PrivateKey(keyBlock.Bytes) case "EC PRIVATE KEY": return x509.ParseECPrivateKey(keyBlock.Bytes) } return nil, errors.New("Unknown private key type.") }
Switch from filter to backdrop-filter to blur background
// Show message // --------------------------------------------------------------------- class Message { show(msg, timing, animations, new_game_btn, field) { if (new_game_btn === undefined) { new_game_btn = false; } $('#msg_new_game').off('click'); var msg_box = $('#message_box'); msg_box.hide(); var msg_div = $('<div>').attr('id', "message_text").html(msg); msg_box.html(msg_div); if (new_game_btn) { $('#message_text').append('<input type="button" id="msg_new_game" value="New Game">'); $('#msg_new_game').on('click', function() { field.initialize(field); }); } if (animations) { $('#message_box').css({backdropFilter: 'blur(5px)'}); msg_box.fadeIn(timing); } else { msg_box.show(); } } // Hide message box // --------------------------------------------------------------------- hide(animations) { // Remove end message, if present if (animations) { $('#mineblaster').css('filter', 'none'); $("#message_box").fadeOut(); } else { $("#message_box").hide(); } } }
// Show message // --------------------------------------------------------------------- class Message { show(msg, timing, animations, new_game_btn, field) { if (new_game_btn === undefined) { new_game_btn = false; } $('#msg_new_game').off('click'); var msg_box = $('#message_box'); msg_box.hide(); var msg_div = $('<div>').attr('id', "message_text").html(msg); msg_box.html(msg_div); if (new_game_btn) { $('#message_text').append('<input type="button" id="msg_new_game" value="New Game">'); $('#msg_new_game').on('click', function() { field.initialize(field); }); } if (animations) { $('#mineblaster').css({filter: 'blur(5px)'}); msg_box.fadeIn(timing); } else { msg_box.show(); } } // Hide message box // --------------------------------------------------------------------- hide(animations) { // Remove end message, if present if (animations) { $('#mineblaster').css('filter', 'none'); $("#message_box").fadeOut(); } else { $("#message_box").hide(); } } }
Add SavedSarch to project defaults
from __future__ import absolute_import, print_function from django.db import models from django.utils import timezone from sentry.db.models import FlexibleForeignKey, Model, sane_repr class SavedSearch(Model): """ A saved search query. """ __core__ = True project = FlexibleForeignKey('sentry.Project') name = models.CharField(max_length=128) query = models.TextField() date_added = models.DateTimeField(default=timezone.now) is_default = models.BooleanField(default=False) class Meta: app_label = 'sentry' db_table = 'sentry_savedsearch' unique_together = (('project', 'name'),) __repr__ = sane_repr('project_id', 'name') class SavedSearchUserDefault(Model): """ Indicates the default saved search for a given user """ __core__ = True savedsearch = FlexibleForeignKey('sentry.SavedSearch') project = FlexibleForeignKey('sentry.Project') user = FlexibleForeignKey('sentry.User') class Meta: unique_together = (('project', 'user'),) app_label = 'sentry' db_table = 'sentry_savedsearch_userdefault'
from __future__ import absolute_import, print_function from django.db import models from django.utils import timezone from sentry.db.models import FlexibleForeignKey, Model, sane_repr class SavedSearch(Model): """ A saved search query. """ __core__ = True project = FlexibleForeignKey('sentry.Project') name = models.CharField(max_length=128) query = models.TextField() date_added = models.DateTimeField(default=timezone.now) is_default = models.BooleanField(default=False) class Meta: app_label = 'sentry' db_table = 'sentry_savedsearch' unique_together = (('project', 'name'),) __repr__ = sane_repr('project_id', 'name') class SavedSearchUserDefault(Model): """ Indicates the default saved search for a given user """ savedsearch = FlexibleForeignKey('sentry.SavedSearch') project = FlexibleForeignKey('sentry.Project') user = FlexibleForeignKey('sentry.User') class Meta: unique_together = (('project', 'user'),) app_label = 'sentry' db_table = 'sentry_savedsearch_userdefault'
Clean up sample city file
from bs4 import BeautifulSoup import datetime import pytz from geodata import GeoData # The URL for the page where the parking lots are listed data_url = "http://example.com" # Name of the city, just in case it contains umlauts which this filename shouldn't city_name = "Sample City" # Name of this file (without '.py'), sorry for needing this, but it makes things easier file_name = "Sample_City" # Uncomment the following line if there's geodata in the format of Sample_City.geodata in this directory # geodata = GeoData(city_name) def parse_html(html): soup = BeautifulSoup(html) # Do everything necessary to scrape the contents of the html # into a dictionary of the format specified by the schema. data = { "last_updated": "", "lots": [] } print(data) return data # the following is for testing this out, just delete it all when done if __name__ == "__main__": with open("../tests/sample_city.html") as f: parse_html(f.read())
from bs4 import BeautifulSoup import json import datetime import pytz # The URL for the page where the parking lots are listed data_url = "http://example.com" # Name of the city, just in case it contains umlauts which this filename shouldn't city_name = "Sample City" # Name of this file (without '.py'), sorry for needing this, but it makes things easier file_name = "Sample_City" def parse_html(html): soup = BeautifulSoup(html) # Do everything necessary to scrape the contents of the html # into a dictionary of the format specified by the schema. def get_geodata_for_lot(lot_name): geofile = open("./cities/" + file_name + ".geojson") geodata = geofile.read() geofile.close() geodata = json.loads(geodata) for feature in geodata["features"]: if feature["properties"]["name"] == lot_name: return { "lon": feature["geometry"]["coordinates"][0], "lat": feature["geometry"]["coordinates"][1] } return [] if __name__ == "__main__": file = open("../tests/sample_city.html") html_data = file.read() file.close() parse_html(html_data)
Add success message for saving project settings.
<?php class ProjectsController extends Controller { public function show(Project $project) { $currentSprint = $project->currentSprint(); return $currentSprint ? App::make('SprintsController')->show($currentSprint) : View::make('project.view', compact('project')); } public function index() { return View::make('project.index')->with('projects', Project::all()); } public function store() { $title = Input::get('title'); $project = new Project([ 'title' => $title, 'slug' => Str::slug($title) ]); $validation = $project->validate(); if ($validation->fails()) { foreach ($validation->messages()->all() as $error) { Flash::error($error); } } elseif ($project->save()) { Flash::success('Successfully created the new project'); } else { Flash::error('Could not create the project. Please try again'); } return Redirect::back(); } public function update(Project $project) { $project->update(Input::all()); Flash::success('The project settings have been updated'); return Redirect::back(); } }
<?php class ProjectsController extends Controller { public function show(Project $project) { $currentSprint = $project->currentSprint(); return $currentSprint ? App::make('SprintsController')->show($currentSprint) : View::make('project.view', compact('project')); } public function index() { return View::make('project.index')->with('projects', Project::all()); } public function store() { $title = Input::get('title'); $project = new Project([ 'title' => $title, 'slug' => Str::slug($title) ]); $validation = $project->validate(); if ($validation->fails()) { foreach ($validation->messages()->all() as $error) { Flash::error($error); } } elseif ($project->save()) { Flash::success('Successfully created the new project'); } else { Flash::error('Could not create the project. Please try again'); } return Redirect::back(); } public function update(Project $project) { $project->update(Input::all()); return Redirect::back(); } }
Sort items by votes annd created at
import { connect } from "react-redux" import _ from 'lodash' import * as trackActions from '../actions/trackActions' import * as playlistActions from '../actions/playlistActions' import VideoFeed from './VideoFeed' const mapStateToProps = (state) => ({ activeFeedId: state.main.show, items: _.orderBy(state[state.main.show].items, ["value", "created_at"], ['desc', 'asc']), selectedId: state[state.main.show].selectedId }) const mapDispatchToProps = (dispatch) => ({ tracks: { onUpvote: (track) => dispatch(trackActions.upvoteTrack(track)), onDownvote: (track) => dispatch(trackActions.downvoteTrack(track)), onClickItem: (track) => dispatch(trackActions.setFeedNavigate(track.id)) }, playlists: { onUpvote: (playlist) => dispatch(playlistActions.upvotePlaylist(playlist)), onDownvote: (playlist) => dispatch(playlistActions.downvotePlaylist(playlist)), onClickItem: (playlist) => dispatch(playlistActions.setFeedNavigate(playlist.id)) } }) const mergeProps = (stateProps, dispatchProps, ownProps) => ({ ...ownProps, ...stateProps, ...dispatchProps[stateProps.activeFeedId] }); export default connect( mapStateToProps, mapDispatchToProps, mergeProps )(VideoFeed)
import { connect } from "react-redux" import * as trackActions from '../actions/trackActions' import * as playlistActions from '../actions/playlistActions' import VideoFeed from './VideoFeed' const mapStateToProps = (state) => ({ activeFeedId: state.main.show, items: state[state.main.show].items, selectedId: state[state.main.show].selectedId }) const mapDispatchToProps = (dispatch) => ({ tracks: { onUpvote: (track) => dispatch(trackActions.upvoteTrack(track)), onDownvote: (track) => dispatch(trackActions.downvoteTrack(track)), onClickItem: (track) => dispatch(trackActions.setFeedNavigate(track.id)) }, playlists: { onUpvote: (playlist) => dispatch(playlistActions.upvotePlaylist(playlist)), onDownvote: (playlist) => dispatch(playlistActions.downvotePlaylist(playlist)), onClickItem: (playlist) => dispatch(playlistActions.setFeedNavigate(playlist.id)) } }) const mergeProps = (stateProps, dispatchProps, ownProps) => ({ ...ownProps, ...stateProps, ...dispatchProps[stateProps.activeFeedId] }); export default connect( mapStateToProps, mapDispatchToProps, mergeProps )(VideoFeed)
Print eval results in test
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(output_dir=output_dir) print(trainer.bert_model_hub) data = pd.DataFrame({ 'abstract': ['test one', 'test two', 'test three'] * 5, 'section': ['U.S.', 'Arts', 'U.S.'] * 5, }) data_column = 'abstract' label_column = 'section' train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length) trainer.train(train_features, label_list) results = trainer.test(test_features) print('Evaluation results:', results) if __name__ == '__main__': unittest.main()
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(output_dir=output_dir) print(trainer.bert_model_hub) data = pd.DataFrame({ 'abstract': ['test one', 'test two', 'test three'] * 5, 'section': ['U.S.', 'Arts', 'U.S.'] * 5, }) data_column = 'abstract' label_column = 'section' train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length) trainer.train(train_features, label_list) trainer.test(test_features) if __name__ == '__main__': unittest.main()
Adjust the description of Config
package adapt // Config represents a configuration of the algorithm. type Config struct { // The refinement rate of the algorithm. The parameter specifies the // fraction of the nodes queued for refinement to be taken from the queue at // each iteration. Rate float64 // ⊆ (0, 1] // The minimum level of interpolation. The nodes that belong to lower levels // are unconditionally included in the surrogate. MinLevel uint // The maximum level of interpolation. The nodes that belong to this level // are never refined. MaxLevel uint // A flag to enable grid balancing. If it is set to true, additional nodes // are added at each iteration to balance the underlying grid. Note that // Target.Score should not reject any nodes in this case. Balance bool // The number of concurrent workers. The evaluation of the target function // and the surrogate itself is distributed among this many goroutines. Workers uint } // NewConfig returns a new configuration with default values. func NewConfig() *Config { return &Config{ Rate: 1, MinLevel: 1, MaxLevel: 9, } }
package adapt // Config represents a configuration of the algorithm. type Config struct { // The refinement rate of the algorithm. The parameter specifies the // fraction of the nodes queued for refinement to be taken from the queue at // each iteration. Rate float64 // ⊆ (0, 1] // The minimal level of interpolation. The nodes that belong to lower levels // are unconditionally included in the surrogate. MinLevel uint // The maximal level of interpolation. The nodes that belong to this level // are never refined. MaxLevel uint // A flag to enable grid balancing. If it is set to true, additional nodes // are added at each iteration to balance the underlying grid. Note that // Target.Score should not reject any nodes in this case. Balance bool // The number of concurrent workers. The evaluation of the target function // and the surrogate itself is distributed among this many goroutines. Workers uint } // NewConfig returns a new configuration with default values. func NewConfig() *Config { return &Config{ Rate: 1, MinLevel: 1, MaxLevel: 9, } }
Add the good old middleware
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 by Florian Mounier, Kozea # This file is part of pystil, licensed under a 3-clause BSD license. """ pystil - An elegant site web traffic analyzer """ from pystil import app, config import werkzeug.contrib.fixers import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi application = werkzeug.contrib.fixers.ProxyFix(Application(app())) ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 by Florian Mounier, Kozea # This file is part of pystil, licensed under a 3-clause BSD license. """ pystil - An elegant site web traffic analyzer """ from pystil import app, config import werkzeug.contrib import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi application = Application(werkzeug.contrib.fixers.ProxyFix(app())) ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever()
Support the AutoPagerize in the click event
$(document).ready(function() { $(document).on('click', '.star', function(e) { // Toggle a display of star $(this).toggleClass('favorited'); var isFavorited = $(this).hasClass('favorited'); // Get a page info var id = $(this).attr('honyomi-id'); var page_no = $(this).attr('honyomi-page-no'); // ajax $.post( '/command', { kind: 'favorite', id: id, page_no: page_no, favorited: isFavorited }, function(data) { // Return a result of POST } ); e.preventDefault(); }); });
$(document).ready(function() { $('.star').click(function() { // Toggle a display of star $(this).toggleClass('favorited'); var isFavorited = $(this).hasClass('favorited'); // Get a page info var id = $(this).attr('honyomi-id'); var page_no = $(this).attr('honyomi-page-no'); // ajax $.post( '/command', { kind: 'favorite', id: id, page_no: page_no, favorited: isFavorited }, function(data) { // Return a result of POST } ); }); });
Refactor and change signature of the method that returns an empty profile
package sizebay.catalog.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Data @Accessors(chain = true) @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class UserProfile implements Serializable { String id; String email; String facebook; String password; List<UserProfileIdentification> profiles; public static UserProfile empty(String id) { List<UserProfileIdentification> profile = new ArrayList<>(); profile.add(UserProfileIdentification.empty()); UserProfile user = new UserProfile().setId(id).setProfiles(profile); return user; } }
package sizebay.catalog.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Data @Accessors(chain = true) @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class UserProfile implements Serializable { String id; String email; String facebook; String password; List<UserProfileIdentification> profiles; public static UserProfile empty() { UserProfile user = new UserProfile(); List<UserProfileIdentification> profile = new ArrayList<>(); profile.add(UserProfileIdentification.empty()); user.setProfiles(profile); return user; } }
Use just newline for file terminator.
import pypyodbc import csv conn = pypyodbc.connect("DSN=HOSS_DB") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: print(table) cur.execute("select * from {}".format(table)) column_names = [] for d in cur.description: column_names.append(d[0]) # file = open("{}.csv".format(table), "w", encoding="ISO-8859-1") file = open("{}.csv".format(table), "w", encoding="utf-8") writer = csv.writer(file, lineterminator='\n') writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
import pypyodbc import csv conn = pypyodbc.connect("DSN=HOSS_DB") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: print(table) cur.execute("select * from {}".format(table)) column_names = [] for d in cur.description: column_names.append(d[0]) # file = open("{}.csv".format(table), "w", encoding="ISO-8859-1") file = open("{}.csv".format(table), "w", encoding="utf-8") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
Add some more tests for isympy -a
"""Tests of tools for setting up interactive IPython sessions. """ from sympy.interactive.session import init_ipython_session, enable_automatic_symbols from sympy.core import Symbol from sympy.external import import_module from sympy.utilities.pytest import raises # TODO: The code below could be made more granular with something like: # # @requires('IPython', version=">=0.11") # def test_automatic_symbols(ipython): ipython = import_module("IPython", min_module_version="0.11") if not ipython: #bin/test will not execute any tests now disabled = True # TODO: Add tests that would verify that enable_automatic_symbols() doesn't # break anything. For example typing `factorial` or `all` in an interpreter # shouldn't result in a new symbol. def test_automatic_symbols(): app = init_ipython_session() app.run_cell("from sympy import *") enable_automatic_symbols(app) symbol = "verylongsymbolname" assert symbol not in app.user_ns app.run_cell(symbol, False) assert symbol in app.user_ns assert isinstance(app.user_ns[symbol], Symbol) # Check that built-in names aren't overridden app.run_cell("a = all == __builtin__.all", False) assert "all" not in app.user_ns assert app.user_ns['a'] == True # Check that sympy names aren't overridden app.run_cell("import sympy") app.run_cell("a = factorial == sympy.factorial") assert app.user_ns['a'] == True
"""Tests of tools for setting up interactive IPython sessions. """ from sympy.interactive.session import init_ipython_session, enable_automatic_symbols from sympy.core import Symbol from sympy.external import import_module from sympy.utilities.pytest import raises # TODO: The code below could be made more granular with something like: # # @requires('IPython', version=">=0.11") # def test_automatic_symbols(ipython): ipython = import_module("IPython", min_module_version="0.11") if not ipython: #bin/test will not execute any tests now disabled = True # TODO: Add tests that would verify that enable_automatic_symbols() doesn't # break anything. For example typing `factorial` or `all` in an interpreter # shouldn't result in a new symbol. def test_automatic_symbols(): app = init_ipython_session() app.run_cell("from sympy import *") enable_automatic_symbols(app) symbol = "verylongsymbolname" assert symbol not in app.user_ns app.run_cell(symbol, False) assert symbol in app.user_ns assert isinstance(app.user_ns[symbol], Symbol)
Use relative paths for emitted files
var path = require('path'); var DtsCreator = require('typed-css-modules'); var loaderUtils = require('loader-utils'); module.exports = function(source, map) { this.cacheable && this.cacheable(); this.addDependency(this.resourcePath); var callback = this.async(); // Pass on query parameters as an options object to the DtsCreator. This lets // you change the default options of the DtsCreator and e.g. use a different // output folder. var queryOptions = loaderUtils.getOptions(this); var options; if (queryOptions) { options = Object.assign({}, queryOptions); } var creator = new DtsCreator(options); // creator.create(..., source) tells the module to operate on the // source variable. Check API for more details. creator.create(this.resourcePath, source).then(content => { // Emit the created content as well this.emitFile(path.relative(this.options.context, content.outputFilePath), content.contents || [''], map); content.writeFile().then(_ => { callback(null, source, map); }); }); };
var DtsCreator = require('typed-css-modules'); var loaderUtils = require('loader-utils'); module.exports = function(source, map) { this.cacheable && this.cacheable(); this.addDependency(this.resourcePath); var callback = this.async(); // Pass on query parameters as an options object to the DtsCreator. This lets // you change the default options of the DtsCreator and e.g. use a different // output folder. var queryOptions = loaderUtils.getOptions(this); var options; if (queryOptions) { options = Object.assign({}, queryOptions); } var creator = new DtsCreator(options); // creator.create(..., source) tells the module to operate on the // source variable. Check API for more details. creator.create(this.resourcePath, source).then(content => { // Emit the created content as well this.emitFile(content.outputFilePath, content.contents || [''], map); content.writeFile().then(_ => { callback(null, source, map); }); }); };
Remove default error log file
'use strict'; var defaultLogAdapter = require('./adapter/logger/winston'); var defaultFsAdapter = require('./adapter/fs/fs'); function logger(logDirectory, adapters) { logDirectory = typeof logDirectory !== 'undefined' ? logDirectory : '/tmp/sonumi-logs'; adapters = typeof adapters !== 'undefined' ? adapters : {}; var fsAdapter = adapters.hasOwnProperty('fs') ? adapters['fs'] : new defaultFsAdapter(); var logAdapter = adapters.hasOwnProperty('logger') ? adapters['logger'] : new defaultLogAdapter(); try { fsAdapter.mkdir(logDirectory); } catch(e) { if (e.code != 'EEXIST') { throw e; } } return logAdapter; } module.exports = logger;
'use strict'; var defaultLogAdapter = require('./adapter/logger/winston'); var defaultFsAdapter = require('./adapter/fs/fs'); function logger(logDirectory, adapters) { logDirectory = typeof logDirectory !== 'undefined' ? logDirectory : '/tmp/sonumi-logs'; adapters = typeof adapters !== 'undefined' ? adapters : {}; var fsAdapter = adapters.hasOwnProperty('fs') ? adapters['fs'] : new defaultFsAdapter(); var logAdapter = adapters.hasOwnProperty('logger') ? adapters['logger'] : new defaultLogAdapter(); try { fsAdapter.mkdir(logDirectory); } catch(e) { if (e.code != 'EEXIST') { throw e; } } logAdapter.addLogFile('errors', logDirectory + '/errors.log', 'error'); return logAdapter; } module.exports = logger;
Improve the ability for developers to extend or modify
# -*- coding: utf-8 -*- from django import forms from django.db import models from django.utils.translation import ugettext_lazy as _ from .widgets import AppHookConfigWidget class AppHookConfigFormField(forms.ModelChoiceField): def __init__(self, queryset, empty_label="---------", required=True, widget=AppHookConfigWidget, *args, **kwargs): super(AppHookConfigFormField, self).__init__(queryset, empty_label, required, widget, *args, **kwargs) class AppHookConfigField(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs.update({'help_text': _(u'When selecting a value, the form is reloaded to get the updated default')}) super(AppHookConfigField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): kwargs.update({'form_class': AppHookConfigFormField}) return super(AppHookConfigField, self).formfield(**kwargs)
# -*- coding: utf-8 -*- from django import forms from django.db import models from django.utils.translation import ugettext_lazy as _ from .widgets import AppHookConfigWidget class AppHookConfigField(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs.update({'help_text': _(u'When selecting a value, the form is reloaded to get the updated default')}) super(AppHookConfigField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): class AppHookConfigFormField(forms.ModelChoiceField): widget = AppHookConfigWidget kwargs.update({'form_class': AppHookConfigFormField}) return super(AppHookConfigField, self).formfield(**kwargs)
Fix module export of new instance of merlin class
const { Configuration } = require('@schul-cloud/commons'); const request = require('request-promise-native'); class MerlinTokenGenerator { setup(app) { this.app = app; } async FIND(data) { const { merlinReference } = data.query; const url = await this.getMerlinUrl(merlinReference); return url; } async getMerlinUrl(ref) { const options = { method: 'POST', url: `http://merlin.nibis.de/auth.php?nbc&identifier=${ref}`, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, form: { username: Configuration.get('ES_MERLIN_USERNAME'), password: Configuration.get('ES_MERLIN_PW'), }, }; try { const merlinUrl = await request(options); return merlinUrl; } catch (e) { throw Error(`Failed to obtain merlin url. Error: ${e}`); } } } module.exports = new MerlinTokenGenerator();
const { Configuration } = require('@schul-cloud/commons'); const request = require('request-promise-native'); class MerlinTokenGenerator { setup(app) { this.app = app; } async FIND(data) { const { merlinReference } = data.query; const url = await this.getMerlinUrl(merlinReference); return url; } async getMerlinUrl(ref) { const options = { method: 'POST', url: `http://merlin.nibis.de/auth.php?nbc&identifier=${ref}`, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, form: { username: Configuration.get('ES_MERLIN_USERNAME'), password: Configuration.get('ES_MERLIN_PW'), }, }; try { const merlinUrl = await request(options); return merlinUrl; } catch (e) { throw Error(`Failed to obtain merlin url. Error: ${e}`); } } } module.exports = MerlinTokenGenerator;
Fix template path after moving it to init
package handlers import ( "encoding/json" "fmt" html "html/template" "net/http" ) var helloTemplate *html.Template func init() { fmt.Println("Try: /hello/world") var err error helloTemplate, err = html.ParseFiles("../templates/hello.html") if err != nil { panic(err) } } func HelloWorld(w http.ResponseWriter, r *http.Request) { // write the response //fmt.Fprintf(w, "Hello %s!", r.URL.Path[len("/hello/"):]) page := Page{Title: r.URL.Path[len("/hello/"):], Body: "This is a test"} contentType := resolveContentType(r) if contentType == "text/html" { helloTemplate.Execute(w, page) } else { // json var b []byte var err error w.Header().Set("Content-Type", "application/json") b, err = json.Marshal(page) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } w.Write(b) } }
package handlers import ( "encoding/json" "fmt" html "html/template" "net/http" ) var helloTemplate *html.Template func init() { fmt.Println("Try: /hello/world") var err error helloTemplate, err = html.ParseFiles("templates/hello.html") if err != nil { panic(err) } } func HelloWorld(w http.ResponseWriter, r *http.Request) { // write the response //fmt.Fprintf(w, "Hello %s!", r.URL.Path[len("/hello/"):]) page := Page{Title: r.URL.Path[len("/hello/"):], Body: "This is a test"} contentType := resolveContentType(r) if contentType == "text/html" { helloTemplate.Execute(w, page) } else { // json var b []byte var err error w.Header().Set("Content-Type", "application/json") b, err = json.Marshal(page) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } w.Write(b) } }
Return custom icon for custom events
package com.alexstyl.specialdates.events.peopleevents; import com.alexstyl.specialdates.R; import com.alexstyl.resources.StringResources; import com.alexstyl.specialdates.events.database.EventColumns; public class CustomEventType implements EventType { private final String name; public CustomEventType(String name) { this.name = name; } @Override public String getEventName(StringResources stringResources) { return name; } @Override public int getColorRes() { return R.color.purple_custom_event; } @Override public int getId() { return EventColumns.TYPE_CUSTOM; } @Override public int getIconResId() { return R.drawable.ic_custom; } }
package com.alexstyl.specialdates.events.peopleevents; import com.alexstyl.specialdates.R; import com.alexstyl.resources.StringResources; import com.alexstyl.specialdates.events.database.EventColumns; public class CustomEventType implements EventType { private final String name; public CustomEventType(String name) { this.name = name; } @Override public String getEventName(StringResources stringResources) { return name; } @Override public int getColorRes() { return R.color.purple_custom_event; } @Override public int getId() { return EventColumns.TYPE_CUSTOM; } @Override public int getIconResId() { return R.drawable.ic_cake; } }
Fix version typo in grunt task
'use strict'; var grunt = require('grunt'); // Check that the version we're exporting is the same one we expect in the // package. This is not an ideal way to do this, but makes sure that we keep // them in sync. var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/; module.exports = function() { var reactVersion = reactVersionExp.exec( grunt.file.read('./src/browser/ui/React.js') )[1]; var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version; var reactToolsVersion = grunt.config.data.pkg.version; if (reactVersion !== reactToolsVersion) { grunt.log.error( 'React version does not match react-tools version. Expected %s, saw %s', reactToolsVersion, reactVersion ); return false; } if (npmReactVersion !== reactToolsVersion) { grunt.log.error( 'npm-react version does not match react-tools version. Expected %s, saw %s', reactToolsVersion, npmReactVersion ); return false; } };
'use strict'; var grunt = require('grunt'); // Check that the version we're exporting is the same one we expect in the // package. This is not an ideal way to do this, but makes sure that we keep // them in sync. var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/; module.exports = function() { var reactVersion = reactVersionExp.exec( grunt.file.read('./src/browser/ui/React.js') )[1]; var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version; var reactToolsVersion = grunt.config.data.pkg.version; if (reactVersion !== reactToolsVersion) { grunt.log.error( 'React version does not match react-tools version. Expected %s, saw %s', reactToolsVersion, reactVersion ); return false; } if (npmReactVersion !== reactToolsVersion) { grunt.log.error( 'npm-react version does not match react-tools veersion. Expected %s, saw %s', reactToolsVersion, npmReactVersion ); return false; } };
Move functionality into a createModel method. Allows for model instantiation outside of this static class. Creating getters for model retrieval.
// ### Part of the [Rosy Framework](http://github.com/ff0000/rosy) /* site.js */ // ## The RED Namespace var RED = RED || {}; // ## Local Namespace // Example Site object, controls global functionality and instantiates the Example Default Page. // You should replace the namespace "Example" with your own Site namespace, this is only an example. var Example = Example || {}; // Site shell object // Model manager and shell manager RED.SITE = $.extend(true, Example, RED, (function () { return { models : {}, init : function () { // Create the site shell this.models.Shell = new Example.Shell(); // Wait for DOMContentLoaded $(document).ready(this.onReady.call(this)); }, createModel : function (page, vars) { var master = Example.Page, model = (page && typeof master[page] === "function" ? master[page] : master); return this.models[page || "page"] = new model(vars); }, getModel : function (page) { return this.models[page]; }, getModels : function () { return this.models; }, onReady : function () { var body = $("body"), // Use `attr("data-page-class")` if < jQuery 1.6 pageClass = body.data("pageClass"); // creates `Page()` based on `<div data-page-class="Home">` this.createModel(pageClass); } }; }()));
// ### Part of the [Rosy Framework](http://github.com/ff0000/rosy) /* site.js */ // ## The RED Namespace var RED = RED || {}; // ## Local Namespace // Example Site object, controls global functionality and instantiates the Example Default Page. // You should replace the namespace "Example" with your own Site namespace, this is only an example. var Example = Example || {}; // Site shell object // Model manager and shell manager RED.SITE = $.extend(true, Example, RED, (function () { return { models : {}, init : function () { // Create the site shell this.models.Shell = new Example.Shell(); // Wait for DOMContentLoaded $(document).ready(this.onReady.call(this)); }, onReady : function () { var body = $("body"), // Use `attr("data-page-class")` if < jQuery 1.6 pageClass = body.data("pageClass"); // creates `Page()` based on `<div data-page-class="Home">` if (pageClass && typeof Example.Page[pageClass] === "function") { this.models[pageClass] = new Example.Page[pageClass](); // defaults to `Example.Page();` } else { this.models.page = new Example.Page(); } } }; }()));
Fix for dir being ignored when supplied and files always saved to cwd.
const createUrl = require('./lib/create-url'); const downloadAndSave = require('./lib/download-and-save'); const parsePage = require('./lib/parse-page'); module.exports = save; /** * @param {string} urlOrMediaId * @return {Promise} */ function save(urlOrMediaId, dir) { return new Promise((resolve, reject) => { const url = createUrl(urlOrMediaId); parsePage(url) .then(post => { const downloadUrl = post.downloadUrl; const filename = post.filename; const isVideo = post.isVideo; const mimeType = post.mimeType; const file = `${dir}/${filename}`; downloadAndSave(downloadUrl, file).then(() => { return resolve({ file, mimeType, url, label: isVideo ? 'video' : 'photo', source: downloadUrl }); }); }) .catch(err => { return reject({ url, error: err, message: `Download failed` }); }); }); }
const createUrl = require('./lib/create-url'); const downloadAndSave = require('./lib/download-and-save'); const parsePage = require('./lib/parse-page'); module.exports = save; /** * @param {string} urlOrMediaId * @return {Promise} */ function save(urlOrMediaId, dir) { return new Promise((resolve, reject) => { const url = createUrl(urlOrMediaId); parsePage(url) .then(post => { const downloadUrl = post.downloadUrl; const filename = post.filename; const isVideo = post.isVideo; const mimeType = post.mimeType; const file = `${dir}/${filename}`; downloadAndSave(downloadUrl, filename).then(() => { return resolve({ file, mimeType, url, label: isVideo ? 'video' : 'photo', source: downloadUrl }); }); }) .catch(err => { return reject({ url, error: err, message: `Download failed` }); }); }); }
Remove default constructor to ensure that consumers understand this is a remote service
package wtf.password; import retrofit.RestAdapter; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.POST; /** * @author <a href="mailto:erik.beeson@gmail.com">Erik Beeson</a> */ public class ZxcvbnRemote { private final ZxcvbnRemoteService service; public ZxcvbnRemote(String endpoint) { this.service = new RestAdapter.Builder() .setEndpoint(endpoint) .build() .create(ZxcvbnRemoteService.class); } public PasswordStrength zxcvbn(String password) throws IllegalArgumentException { if(password != null && password.length() > 0) { return service.zxcvbn(password); } else { throw new IllegalArgumentException("Invalid password: " + password); } } interface ZxcvbnRemoteService { @POST("/zxcvbn") @FormUrlEncoded PasswordStrength zxcvbn(@Field("password") String password); } }
package wtf.password; import retrofit.RestAdapter; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.POST; /** * @author <a href="mailto:erik.beeson@gmail.com">Erik Beeson</a> */ public class ZxcvbnRemote { private final ZxcvbnRemoteService service; public ZxcvbnRemote() { this("https://password.wtf"); } public ZxcvbnRemote(String endpoint) { this.service = new RestAdapter.Builder() .setEndpoint(endpoint) .build() .create(ZxcvbnRemoteService.class); } public PasswordStrength zxcvbn(String password) throws IllegalArgumentException { if(password != null && password.length() > 0) { return service.zxcvbn(password); } else { throw new IllegalArgumentException("Invalid password: " + password); } } interface ZxcvbnRemoteService { @POST("/zxcvbn") @FormUrlEncoded PasswordStrength zxcvbn(@Field("password") String password); } }
Fix format error in RemoveCtrl
package controller; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import boundary.PlayerApplication; import model.Move; import model.PlayerModel; import model.PlayerState; import model.Point; import model.Variation; /** * @author Nick Chaput */ public class PlayerRemoveCtrl implements ActionListener{ PlayerApplication app; PlayerModel model; public PlayerRemoveCtrl(PlayerApplication app, PlayerModel model) { this.app = app; this.model = model; } public void startRemove(Point point) { // TODO: generic implementation PlayerVariationCtrl pVar = model.variation.createCtrl(app, model); if (model.variation != Variation.RELEASE && model.level.currentBoard.grid[point.x][point.y].tile.number != 6) { // GO INTO PLAYERMODEL AND REPLACE PLAYERVARIATIONCTRL WITH VARIATION // TODO: This is suboptimal, decide whether to change PlayerVariationCtrl. // specialMove() to individual methods for each special move // TODO: resolve the move Move reMove = new Move(); reMove.expand(model.level.currentBoard, point); } pVar.remove(); } @Override public void actionPerformed(ActionEvent arg0) { model.playerState = PlayerState.REMOVE; } }
package controller; import boundary.PlayerApplication; import model.Move; import model.PlayerModel; import model.Point; import model.Variation; /** * @author Nick Chaput */ public class PlayerRemoveCtrl { PlayerApplication app; PlayerModel model; public PlayerRemoveCtrl(PlayerApplication app, PlayerModel model) { this.app = app; this.model = model; } public void mouseClicked(Point point) { // TODO: generic implementation PlayerVariationCtrl pVar = model.variation.createCtrl(app, model); if (model.variation != Variation.RELEASE && model.level.currentBoard.grid[point.x][point.y].tile.number != 6) { // GO INTO PLAYERMODEL AND REPLACE PLAYERVARIATIONCTRL WITH VARIATION // TODO: This is suboptimal, decide whether to change PlayerVariationCtrl. // specialMove() to individual methods for each special move // TODO: resolve the move Move reMove = new Move(); reMove.expand(model.level.currentBoard, point); } pVar.remove(); } }
Store clinical track fields with null values in session
package org.cbioportal.web.parameter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.ALWAYS) public class ResultPageSettings extends PageSettingsData implements Serializable { private List<ClinicalTrackConfig> clinicallist = new ArrayList<>(); public List<ClinicalTrackConfig> getClinicallist() { return clinicallist; } public void setClinicallist(List<ClinicalTrackConfig> clinicallist) { this.clinicallist = clinicallist; } } @JsonInclude(Include.ALWAYS) class ClinicalTrackConfig { public String stableId; public String sortOrder; public Boolean gapOn; }
package org.cbioportal.web.parameter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) public class ResultPageSettings extends PageSettingsData implements Serializable { private List<ClinicalTrackConfig> clinicallist = new ArrayList<>(); public List<ClinicalTrackConfig> getClinicallist() { return clinicallist; } public void setClinicallist(List<ClinicalTrackConfig> clinicallist) { this.clinicallist = clinicallist; } } class ClinicalTrackConfig { public String stableId; public String sortOrder; public boolean gapOn; }
Deploy: Use call API to call generate console
var term = require('term'), async = require('async'), fs = require('graceful-fs'), extend = require('../../extend'), list = extend.deployer.list(), util = require('../../util'), spawn = util.spawn; extend.console.register('deploy', 'Deploy', function(args){ var config = hexo.config.deploy; if (!config || !config.type){ var help = '\nYou should configure deployment settings in ' + '_config.yml'.bold + ' first!\n\nType:\n'; help += ' ' + Object.keys(list).join(', '); console.log(help + '\n\nMore info: http://zespia.tw/hexo/docs/deploy.html\n'); } else { async.series([ function(next){ if (args.g || args.generate){ hexo.call('generate', next); } else { fs.exists(hexo.public_dir, function(exist){ if (exist) return next(); hexo.call('generate', next); }); } }, function(next){ list[config.type](args, callback); } ]); } });
var term = require('term'), async = require('async'), fs = require('graceful-fs'), extend = require('../../extend'), list = extend.deployer.list(), util = require('../../util'), spawn = util.spawn; /* var generate = function(callback){ spawn({ command: hexo.core_dir + 'bin/hexo', args: ['generate'], exit: function(code){ if (code === 0) callback(); } }); }; */ extend.console.register('deploy', 'Deploy', function(args){ var config = hexo.config.deploy; if (!config || !config.type){ var help = '\nYou should configure deployment settings in ' + '_config.yml'.bold + ' first!\n\nType:\n'; help += ' ' + Object.keys(list).join(', '); console.log(help + '\n\nMore info: http://zespia.tw/hexo/docs/deploy.html\n'); } else { async.series([ function(next){ if (args.generate){ generate(next); } else { fs.exists(hexo.public_dir, function(exist){ if (exist) return next(); generate(next); }); } }, function(next){ list[config.type](args, callback); } ]); } });
[Telemetry] Fix browser restart in TimelineBasedPageTest The TimelineBasedPageTest constructor was passing in error a string where its parent constructor expects a Boolean value for the needs_browser_restart_after_each_page option. BUG=504368 Review URL: https://codereview.chromium.org/1206323002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#336188}
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): super(TimelineBasedPageTest, self).__init__() self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller)
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): super(TimelineBasedPageTest, self).__init__('RunPageInteractions') self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller)
Add back button support back in
document.observe("dom:loaded", function() { function get_index() { var index = parseInt(location.hash.substr(1)); if(isNaN(index)) index = 0; return index; } function go_next_page() { var index = get_index(); index += 1; if(index >= pages.length) index = pages.length - 1; location.hash = "#" + index; } window.onhashchange = function() { var index = get_index(); $("image").src = "/images/blank.png"; window.scrollTo(0, 0); $("image").src = pages[index]; if((index + 1) < pages.length) { preload = new Image(); preload.src = pages[index + 1]; } } window.onkeydown = function(event) { if(event.keyCode == 32 && scrollDistanceFromBottom() == 0) { Event.stop(event); go_next_page(); } else if(event.keyCode == 8) { Event.stop(event); history.back(); } }; $("image").onclick = go_next_page; location.hash = "#0"; });
document.observe("dom:loaded", function() { function get_index() { var index = parseInt(location.hash.substr(1)); if(isNaN(index)) index = 0; return index; } function go_next_page() { var index = get_index(); index += 1; if(index >= pages.length) index = pages.length - 1; location.hash = "#" + index; } window.onhashchange = function() { var index = get_index(); $("image").src = "/images/blank.png"; window.scrollTo(0, 0); $("image").src = pages[index]; if((index + 1) < pages.length) { preload = new Image(); preload.src = pages[index + 1]; } } window.onkeydown = function(event) { if(event.keyCode == 32 && scrollDistanceFromBottom() == 0) { Event.stop(event); go_next_page(); } }; $("image").onclick = go_next_page; location.hash = "#0"; });
Move query to line 33
// Bulk Operation exports.updateOperation = (id, actionType, contentType, connection) => { return connection(contentType) .where(`${contentType}.id`, '=', id) .update(`${contentType}.status`, actionType) .then((result) => { return connection(contentType) .select() }) } exports.deleteOperation = (id, contentType, connection) => { return connection(contentType) .where(`${contentType}.id`, '=', id) .delete() .then((result) => { return connection(contentType) .select() }) } // ADMIN SECTION SQL // Manage Content - URL - /admin/contenttype/content exports.getAdminContent = (contentType, connection) => { return connection(contentType) .join('users', 'users.id', `${contentType}.author`) .select(`${contentType}.id as contentId`, 'title', 'status', 'type', 'published_date', 'users.name as name', 'slug') .orderByRaw(`${contentType}.id DESC`) } // Manage Taxonomy & Tags - URL - /admin/taxonomies exports.getTaxonomy = (connection) => { return connection('taxonomy_vocabulary') .select() .orderByRaw(`${taxonomy_vocabulary}.name DESC`) } // Manage Menu Structure - URL - /admin/menus // Manage Users - URL - /admin/users // TAXONOMY SQL
// Bulk Operation exports.updateOperation = (id, actionType, contentType, connection) => { return connection(contentType) .where(`${contentType}.id`, '=', id) .update(`${contentType}.status`, actionType) .then((result) => { return connection(contentType) .select() }) } exports.deleteOperation = (id, contentType, connection) => { return connection(contentType) .where(`${contentType}.id`, '=', id) .delete() .then((result) => { return connection(contentType) .select() }) } // ADMIN SECTION SQL // Manage Content - URL - /admin/contenttype/content exports.getAdminContent = (contentType, connection) => { return connection(contentType) .join('users', 'users.id', `${contentType}.author`) .select(`${contentType}.id as contentId`, 'title', 'status', 'type', 'published_date', 'users.name as name', 'slug') .orderByRaw(`${contentType}.id DESC`) } // Manage Taxonomy & Tags - URL - /admin/taxonomies // Manage Menu Structure - URL - /admin/menus // Manage Users - URL - /admin/users // TAXONOMY SQL exports.getTaxonomy = (connection) => { return connection('taxonomy_vocabulary') .select() }
Simplify code by passing an Observer
package arez.doc.examples.at_observe2; import arez.Observer; import arez.SafeProcedure; import arez.annotations.ArezComponent; import arez.annotations.CascadeDispose; import arez.annotations.Observe; import elemental2.dom.DomGlobal; import elemental2.dom.Element; import javax.annotation.Nonnull; @ArezComponent public abstract class CurrencyView { @CascadeDispose final Currency bitcoin = new Arez_Currency(); @Observe void render() { final Element element = DomGlobal.document.getElementById( "currencyTracker" ); element.innerHTML = "1 BTC = $" + bitcoin.getAmount() + "AUD"; } void onRenderDepsChange( @Nonnull final Observer observer ) { debounce( observer::schedule, 2000 ); } private void debounce( @Nonnull final SafeProcedure action, final long timeInMillis ) { // Execute this action at most one every timeInMillis //DOC ELIDE START //DOC ELIDE END } }
package arez.doc.examples.at_observe2; import arez.Observer; import arez.SafeProcedure; import arez.annotations.Action; import arez.annotations.ArezComponent; import arez.annotations.CascadeDispose; import arez.annotations.Observe; import arez.annotations.ObserverRef; import arez.annotations.OnDepsChange; import elemental2.dom.DomGlobal; import elemental2.dom.Element; import javax.annotation.Nonnull; @ArezComponent public abstract class CurrencyView { @CascadeDispose final Currency bitcoin = new Arez_Currency(); @Observe void render() { final Element element = DomGlobal.document.getElementById( "currencyTracker" ); element.innerHTML = "1 BTC = $" + bitcoin.getAmount() + "AUD"; } @OnDepsChange void onRenderDepsChange() { debounce( this::scheduleRender, 2000 ); } @ObserverRef abstract Observer getRenderObserver(); @Action( verifyRequired = false ) void scheduleRender() { // Actually schedule the re-render. Has to occur within // an action or inside a read-write transaction getRenderObserver().schedule(); } private void debounce( @Nonnull final SafeProcedure action, final long timeInMillis ) { // Execute this action at most one every timeInMillis //DOC ELIDE START //DOC ELIDE END } }
Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <jezdez@enn.io> for the pointer. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
Use of thumb and icon method
<div class="clearfix well media @if($errors->has($field))has-error @endif"> @if($model->$field) {{ $model->present()->icon(2, $field) }} @endif <div> {{ Form::label($field, trans('validation.attributes.' . $field), array('class' => 'control-label')) }} {{ Form::file($field) }} <span class="help-block"> @lang('validation.attributes.max :size MB', array('size' => 2)) </span> {{ $errors->first($field, '<p class="help-block">:message</p>') }} </div> </div>
<div class="clearfix well media @if($errors->has($field))has-error @endif"> @if($model->$field) <div> <span class="fa fa-file-text-o fa-3x"></span> <a href="/uploads/{{ $model->getTable() }}/{{ $model->$field }}">{{ $model->$field }}</a> </div> @endif <div> {{ Form::label($field, trans('validation.attributes.' . $field), array('class' => 'control-label')) }} {{ Form::file($field) }} <span class="help-block"> @lang('validation.attributes.max :size MB', array('size' => 2)) </span> @if($errors->has($field)) <span class="help-block">{{ $errors->first($field) }}</span> @endif </div> </div>
Add DatePart invalid date unit test
<?php namespace ZBateson\MailMimeParser\Header\Part; use PHPUnit_Framework_TestCase; use DateTime; /** * Description of DateTest * * @group HeaderParts * @group DatePart * @covers ZBateson\MailMimeParser\Header\Part\DatePart * @author Zaahid Bateson */ class DatePartTest extends PHPUnit_Framework_TestCase { public function testDateString() { $value = 'Wed, 17 May 2000 19:08:29 -0400'; $part = new DatePart($value); $this->assertEquals($value, $part->getValue()); $date = $part->getDateTime(); $this->assertNotEmpty($date); $this->assertEquals($value, $date->format(DateTime::RFC2822)); } public function testInvalidDate() { $value = 'Invalid Date'; $part = new DatePart($value); $this->assertEquals($value, $part->getValue()); $date = $part->getDateTime(); $this->assertNull($date); } }
<?php namespace ZBateson\MailMimeParser\Header\Part; use PHPUnit_Framework_TestCase; use DateTime; /** * Description of DateTest * * @group HeaderParts * @group DatePart * @covers ZBateson\MailMimeParser\Header\Part\DatePart * @author Zaahid Bateson */ class DatePartTest extends PHPUnit_Framework_TestCase { public function testDateString() { $value = 'Wed, 17 May 2000 19:08:29 -0400'; $part = new DatePart($value); $this->assertEquals($value, $part->getValue()); $date = $part->getDateTime(); $this->assertNotEmpty($date); $this->assertEquals($value, $date->format(DateTime::RFC2822)); } }
Update get pretty date in clienside
module.exports.getPrettyDate = function(date) { var month = addLeadingZero(date.getMonth() + 1); var day = addLeadingZero(date.getDate()); return month + "/" + day + "/" + date.getFullYear(); }; var addLeadingZero = function (number) { if (number < 10) { return '0' + number; } return number; }; module.exports.roundNumber = function (val) { return Math.round(val * 100000) / 100000; }; module.exports.getDistanceFromLatLng = function(lat1, lng1, lat2, lng2) { var R = 6371; // Radius of the earth in KM var dLat = deg2rad(lat2 - lat1); var dLng = deg2rad(lng2 - lng1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; }; var deg2rad = function (deg) { return deg * (Math.PI / 180); }; module.exports.isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); };
module.exports.getPrettyDate = function(date) { var month = date.getMonth() + 1; var day = date.getDate(); if (month < 10) { month = "0" + month; } if (day < 10) { day = "0" + day; } return month + "/" + day + "/" + date.getFullYear(); }; module.exports.roundNumber = function (val) { return Math.round(val * 100000) / 100000; }; module.exports.getDistanceFromLatLng = function(lat1, lng1, lat2, lng2) { var R = 6371; // Radius of the earth in KM var dLat = deg2rad(lat2 - lat1); var dLng = deg2rad(lng2 - lng1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; }; var deg2rad = function (deg) { return deg * (Math.PI / 180); }; module.exports.isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); };
Improve logging of invalid JSON data.
(function () { 'use strict'; define( [ ], function () { return function (string) { try { return JSON.parse(string); } catch (e) { if (console && typeof console.error === 'function') { console.error('Could not parse string as JSON', string, e); } return ''; } }; } ); }());
(function () { 'use strict'; define( [ ], function () { return function (string) { try { return JSON.parse(string); } catch (e) { if (console && typeof console.error === 'function') { console.error(e); } return ''; } }; } ); }());
Remove following array on auth redux state
import * as types from './authActions'; const initialState = { isAuthenticated: false, isFetching: false, user: {}, }; export default (state = initialState, action) => { switch (action.type) { case types.LOGIN_REQUEST: return Object.assign({}, state, { isFetching: true, isAuthenticated: false, user: {} }); case types.LOGIN_SUCCESS: return Object.assign({}, state, { isFetching: false, isAuthenticated: true, errorMessage: '', user: action.user }); case types.LOGIN_FAILURE: return Object.assign({}, state, { isFetching: false, isAuthenticated: false, errorMessage: action.message }); case types.LOGOUT_SUCCESS: return Object.assign({}, state, { isFetching: true, isAuthenticated: false }); default: return state; } };
import * as types from './authActions'; const initialState = { isAuthenticated: false, isFetching: false, user: {}, following: [], followingIsLoading: true, }; export default (state = initialState, action) => { switch (action.type) { case types.LOGIN_REQUEST: return Object.assign({}, state, { isFetching: true, isAuthenticated: false, user: {} }); case types.LOGIN_SUCCESS: return Object.assign({}, state, { isFetching: false, isAuthenticated: true, errorMessage: '', user: action.user }); case types.LOGIN_FAILURE: return Object.assign({}, state, { isFetching: false, isAuthenticated: false, errorMessage: action.message }); case types.LOGOUT_SUCCESS: return Object.assign({}, state, { isFetching: true, isAuthenticated: false }); default: return state; } };
Fix typing for JSONInput and JSONInputBin.
from pathlib import Path from typing import Union, Dict, Any, List, Tuple from collections import OrderedDict # fmt: off FilePath = Union[str, Path] # Superficial JSON input/output types # https://github.com/python/typing/issues/182#issuecomment-186684288 JSONOutput = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] JSONOutputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any]] # For input, we also accept tuples, ordered dicts etc. JSONInput = Union[str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any, ...], OrderedDict] JSONInputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any, ...], OrderedDict] YAMLInput = JSONInput YAMLOutput = JSONOutput # fmt: on def force_path(location, require_exists=True): if not isinstance(location, Path): location = Path(location) if require_exists and not location.exists(): raise ValueError(f"Can't read file: {location}") return location def force_string(location): if isinstance(location, str): return location return str(location)
from pathlib import Path from typing import Union, Dict, Any, List, Tuple from collections import OrderedDict # fmt: off FilePath = Union[str, Path] # Superficial JSON input/output types # https://github.com/python/typing/issues/182#issuecomment-186684288 JSONOutput = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] JSONOutputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any]] # For input, we also accept tuples, ordered dicts etc. JSONInput = Union[str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any], OrderedDict] JSONInputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any], OrderedDict] YAMLInput = JSONInput YAMLOutput = JSONOutput # fmt: on def force_path(location, require_exists=True): if not isinstance(location, Path): location = Path(location) if require_exists and not location.exists(): raise ValueError(f"Can't read file: {location}") return location def force_string(location): if isinstance(location, str): return location return str(location)
Access to all accounts only for superusers
from django.contrib import admin from bejmy.categories.models import Category from mptt.admin import MPTTModelAdmin @admin.register(Category) class CategoryAdmin(MPTTModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields = ( 'name', ) raw_id_fields = ('parent',) def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs) if not self.request.user.is_superuser(): queryset = queryset.filter(user=request.user) return queryset
from django.contrib import admin from bejmy.categories.models import Category @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields = ( 'name', ) raw_id_fields = ('parent',) def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs) if not self.request.user.is_superuser(): queryset = queryset.filter(user=request.user) return queryset
Fix people transfer when previous week was empty
<?php namespace TmlpStats\Reports\Arrangements; class TeamMembersByQuarter extends BaseArrangement { /* * Builds an array of TDO attendance for each team member */ public function build($data) { $teamMembersData = $data['teamMembersData']; $reportData = [ 'team1' => [], 'team2' => [], 'withdrawn' => [], ]; foreach ($teamMembersData as $data) { $index = $data->withdrawCodeId !== null ? 'withdrawn' : "team{$data->teamMember->teamYear}"; $reportData[$index]["Q{$data->teamMember->quarterNumber}"][] = $data; } return compact('reportData'); } }
<?php namespace TmlpStats\Reports\Arrangements; class TeamMembersByQuarter extends BaseArrangement { /* * Builds an array of TDO attendance for each team member */ public function build($data) { $teamMembersData = $data['teamMembersData']; $reportData = []; foreach ($teamMembersData as $data) { $index = $data->withdrawCodeId !== null ? 'withdrawn' : "team{$data->teamMember->teamYear}"; $reportData[$index]["Q{$data->teamMember->quarterNumber}"][] = $data; } return compact('reportData'); } }
Add temporary selection of time range While we still don't have the time range filter
import _ from 'lodash'; import {API_PATH} from 'power-ui/conf'; import {urlToRequestObjectWithHeaders, isTruthy} from 'power-ui/utils'; // Handle all HTTP networking logic of this page function PeoplePageHTTP(sources) { const PEOPLE_URL = `${API_PATH}/people/`; const atomicResponse$ = sources.HTTP .filter(response$ => _.startsWith(response$.request.url, PEOPLE_URL)) .mergeAll() .filter(response => isTruthy(response.body)) .shareReplay(1); const request$ = atomicResponse$ .filter(response => response.body.next) .map(response => response.body.next.replace('limit=5', 'limit=40')) // TODO get real time range from sources somehow .startWith(PEOPLE_URL + '?limit=5&range_start=2015-09-01&range_end=2015-11-30') .map(urlToRequestObjectWithHeaders); const response$ = atomicResponse$ .map(response => response.body.results) .scan((acc, curr) => acc.concat(curr)); return {request$, response$}; // sink } export default PeoplePageHTTP;
import _ from 'lodash'; import {API_PATH} from 'power-ui/conf'; import {urlToRequestObjectWithHeaders, isTruthy} from 'power-ui/utils'; // Handle all HTTP networking logic of this page function PeoplePageHTTP(sources) { const PEOPLE_URL = `${API_PATH}/people/`; const atomicResponse$ = sources.HTTP .filter(response$ => _.startsWith(response$.request.url, PEOPLE_URL)) .mergeAll() .filter(response => isTruthy(response.body)) .shareReplay(1); const request$ = atomicResponse$ .filter(response => response.body.next) .map(response => response.body.next.replace('limit=5', 'limit=40')) .startWith(PEOPLE_URL + '?limit=5') .map(urlToRequestObjectWithHeaders); const response$ = atomicResponse$ .map(response => response.body.results) .scan((acc, curr) => acc.concat(curr)); return {request$, response$}; // sink } export default PeoplePageHTTP;
Use Mongoose to find user and pass to show page
const express = require('express'), router = express.Router(), db = require('../models'); router.get('/', function(req, res, next) { res.render('index'); }); router.get('/new', function(req, res, next) { res.render('users/new'); }); router.get('/:username', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/show', {user}); }); }); router.get('/:username/edit', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/edit', {user}); }); }); router.post('/', function(req, res, next) { db.User.create(req.body).then(function() { res.redirect('/'); }); }); // find not by ID and update router.patch('/:username', function(req, res, next) { db.User.findByIdAndUpdate(req.params.username, req.body.newUsername).then(function() { res.redirect('/:username'); }); }); // find and then remove router.delete('/:username', function(req, res, next) { db.User.findByIdAndRemove(req.params.username).then(function() { res.redirect('/'); }); }); module.exports = router;
const express = require('express'), router = express.Router(), db = require('../models'); router.get('/', function(req, res, next) { res.render('index'); }); router.get('/new', function(req, res, next) { res.render('users/new'); }); router.get('/:username', function(req, res, next) { // db.User.find({username: req.params.username}).then(function(user) { // res.render('users/show', {user}); // }); var user = req.params.username; res.render('users/show', {user}); }); router.get('/:username/edit', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/edit', {user}); }); }); router.post('/', function(req, res, next) { db.User.create(req.body).then(function() { res.redirect('/'); }); }); // find not by ID and update router.patch('/:username', function(req, res, next) { db.User.findByIdAndUpdate(req.params.username, req.body.newUsername).then(function() { res.redirect('/:username'); }); }); // find and then remove router.delete('/:username', function(req, res, next) { db.User.findByIdAndRemove(req.params.username).then(function() { res.redirect('/'); }); }); module.exports = router;
Update body class for drawer.
<?php use Roots\Sage\Setup; use Roots\Sage\Wrapper; ?> <!doctype html> <html <?php language_attributes(); ?>> <?php get_template_part('templates/head'); ?> <body <?php body_class('has-drawer'); ?>> <!--[if IE]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'sage'); ?> </div> <![endif]--> <?php do_action('get_header'); get_template_part('templates/header'); ?> <div class="wrap container" role="document"> <div class="content row"> <main class="main"> <?php include Wrapper\template_path(); ?> </main><!-- /.main --> <?php if (Setup\display_sidebar()) : ?> <aside class="sidebar"> <?php include Wrapper\sidebar_path(); ?> </aside><!-- /.sidebar --> <?php endif; ?> </div><!-- /.content --> </div><!-- /.wrap --> <?php do_action('get_footer'); get_template_part('templates/footer'); wp_footer(); ?> </body> </html>
<?php use Roots\Sage\Setup; use Roots\Sage\Wrapper; ?> <!doctype html> <html <?php language_attributes(); ?>> <?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--[if IE]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'sage'); ?> </div> <![endif]--> <?php do_action('get_header'); get_template_part('templates/header'); ?> <div class="wrap container" role="document"> <div class="content row"> <main class="main"> <?php include Wrapper\template_path(); ?> </main><!-- /.main --> <?php if (Setup\display_sidebar()) : ?> <aside class="sidebar"> <?php include Wrapper\sidebar_path(); ?> </aside><!-- /.sidebar --> <?php endif; ?> </div><!-- /.content --> </div><!-- /.wrap --> <?php do_action('get_footer'); get_template_part('templates/footer'); wp_footer(); ?> </body> </html>
Make makeDelayedTask return fn with same signature - now returns a Promise returning fn that resolves to whatever the original function does - allow any args to be passed to the delayed function
/** * Higher order function to make another function only be invoked when user is deemed idle. * Wraps around the web extension browser.idle API. * * @param {(any) => Promise<any>} task Async or sync function to run after idle. * @param {number} [idleTimeout=15] Number of seconds to consider user idle (min is 15) * @return {(any) => Promise<any>} Augmented version of `task` that, when invoked, will only run when user idle. * A Promise will be returned which the invoker can use to wait for eventual output. */ export const makeDelayedTask = (task, idleTimeout = 15) => (...args) => new Promise((resolve, reject) => { browser.idle.setDetectionInterval(idleTimeout) async function runWhenIdle(idleState) { if (idleState === 'idle') { try { const output = await task(...args) resolve(output) } catch (error) { reject(error) } finally { // Make sure to remove listner (itself) after running once browser.idle.onStateChanged.removeListener(runWhenIdle) } } } browser.idle.onStateChanged.addListener(runWhenIdle) })
/** * Higher order function to make another function only be invoked when user is deemed idle. * Wraps around the web extension browser.idle API. * * @param {function} task Async or sync function to run after idle. * @param {number} [idleTimeout=15] Number of seconds to consider user idle (min is 15) */ export const makeDelayedTask = (task, idleTimeout = 15) => () => { browser.idle.setDetectionInterval(idleTimeout) async function runWhenIdle(idleState) { if (idleState === 'idle') { await task() // Make sure to remove listner (itself) after runnings once browser.idle.onStateChanged.removeListener(runWhenIdle) } } browser.idle.onStateChanged.addListener(runWhenIdle) }
Add unit test for LogAutoConfiguration
package com.github.vbauer.herald.ext.spring; import com.github.vbauer.herald.core.BasicTest; import com.github.vbauer.herald.ext.spring.bean.CheckerBean; import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; /** * @author Vladislav Bauer */ @ContextConfiguration(classes = SpringBootTestContext.class) @RunWith(SpringJUnit4ClassRunner.class) public class SpringBootTest extends BasicTest { @Autowired private CheckerBean checkerBean; @Test public void testAll() { checkerBean.checkBeans(); checkerBean.checkPostProcessor(); } @Test public void testAutoConfiguration() { final LogAutoConfiguration configuration = new LogAutoConfiguration(); final LogBeanPostProcessor processor = configuration.logBeanPostProcessor(); assertThat(processor, notNullValue()); } }
package com.github.vbauer.herald.ext.spring; import com.github.vbauer.herald.core.BasicTest; import com.github.vbauer.herald.ext.spring.bean.CheckerBean; import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Vladislav Bauer */ @ContextConfiguration(classes = SpringBootTestContext.class) @RunWith(SpringJUnit4ClassRunner.class) public class SpringBootTest extends BasicTest { @Autowired private CheckerBean checkerBean; @Test public void testAll() { checkerBean.checkBeans(); checkerBean.checkPostProcessor(); } }
Allow conroller to set editable state
var _ = require('underscore'), ControlBones = require('./ControlBones'), AmountEntry = require('../model/AmountEntry'), AmountEntryCollection = require('../model/AmountEntryCollection'), ParticularsModel = require('../model/ParticularsModel'), StatementCollection = require('../model/StatementCollection'), StatementsByCategory = require('../model/operations/statements/StatementsByCategory'), TotalByMonth = require('../model/operations/entries/TotalByMonth'), MonthlyTable = require('../view/table/MonthlyTable'); var CategorizedController = ControlBones.extend({ title: 'Categorized Table', source: 'fieldnamehere', editable: false, render: function(data) { var collection = new AmountEntryCollection(_.map(data[this.source], function(note) { return new AmountEntry(note); })); var categorized = (new StatementsByCategory()).run(collection); var monthly = categorized.reduce(function(carry, statement) { statement.set( 'entries', (new TotalByMonth()).run(statement.get('entries')) ); carry.add(statement); return carry; }, new StatementCollection()); return new ParticularsModel({ name: this.title, dataset: monthly, displayType: MonthlyTable, editable: this.editable }); } }); module.exports = CategorizedController;
var _ = require('underscore'), ControlBones = require('./ControlBones'), AmountEntry = require('../model/AmountEntry'), AmountEntryCollection = require('../model/AmountEntryCollection'), ParticularsModel = require('../model/ParticularsModel'), StatementCollection = require('../model/StatementCollection'), StatementsByCategory = require('../model/operations/statements/StatementsByCategory'), TotalByMonth = require('../model/operations/entries/TotalByMonth'), MonthlyTable = require('../view/table/MonthlyTable'); var CategorizedController = ControlBones.extend({ title: 'Categorized Table', source: 'fieldnamehere', render: function(data) { var collection = new AmountEntryCollection(_.map(data[this.source], function(note) { return new AmountEntry(note); })); var categorized = (new StatementsByCategory()).run(collection); var monthly = categorized.reduce(function(carry, statement) { statement.set( 'entries', (new TotalByMonth()).run(statement.get('entries')) ); carry.add(statement); return carry; }, new StatementCollection()); return new ParticularsModel({ name: this.title, dataset: monthly, displayType: MonthlyTable, editable: false }); } }); module.exports = CategorizedController;
Update the documentation link for doc migration This patch is proposed according to the Direction 10 of doc migration(https://etherpad.openstack.org/p/doc-migration-tracking). Change-Id: I62ae28d10f70d63ba693ac0ab6581faf85f1bf6e
# 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. """oslo.i18n integration module. See https://docs.openstack.org/oslo.i18n/latest/user/index.html """ import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='oslo_cache') # The primary translation function using the well-known name "_" _ = _translators.primary
# 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. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html """ import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='oslo_cache') # The primary translation function using the well-known name "_" _ = _translators.primary
Fix bug: log dir path: set it thru file location, not current working path
#!/usr/bin/python import shlex, os from subprocess import Popen, PIPE #from time import sleep import threading def exe_cmd(log_name, command_line): args = shlex.split(command_line) log_dir=os.path.join(os.path.dirname(__file__),"..", "log") if not os.path.isdir(log_dir): os.mkdir(log_dir) file_name= os.path.join(log_dir, log_name) f_d=open(file_name,"w+") p = Popen(args, stdout=f_d, stdin=PIPE, stderr=f_d) #Dump stdout and stderr to log file output = p.communicate() print command_line+ " " + "executed!" f_d.close() def create_thread(argv_list): io_thread=[] for argv in argv_list: thread=threading.Thread(target=exe_cmd,kwargs =argv) io_thread.append(thread) for thread in io_thread: #Add this "for loop" for better understanding thread.start() for thread in io_thread: thread.join()
#!/usr/bin/python import shlex, os from subprocess import Popen, PIPE #from time import sleep import threading def exe_cmd(log_name, command_line): args = shlex.split(command_line) log_dir=os.path.join(os.getcwd(),"..", "log") if not os.path.isdir(log_dir): os.mkdir(log_dir) file_name= os.path.join(log_dir, log_name) f_d=open(file_name,"w+") p = Popen(args, stdout=f_d, stdin=PIPE, stderr=f_d) #Dump stdout and stderr to log file output = p.communicate() print command_line+ " " + "executed!" f_d.close() def create_thread(argv_list): io_thread=[] for argv in argv_list: thread=threading.Thread(target=exe_cmd,kwargs =argv) io_thread.append(thread) for thread in io_thread: #Add this "for loop" for better understanding thread.start() for thread in io_thread: thread.join()
Fix hook => command typo
<?php declare(strict_types=1); /** * This file is part of CaptainHook. * * (c) Sebastian Feldmann <sf@sebastian.feldmann.info> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CaptainHook\App; /** * Class Hooks * * Defines the list of hooks that can be handled with captainhook and provides some name constants. * * @package CaptainHook * @author Andrea Heigl <andreas@heigl.org> * @link https://github.com/sebastianfeldmann/captainhook * @since Class available since Release 3.0.1 */ final class Hooks { const PRE_COMMIT = 'pre-commit'; const PRE_PUSH = 'pre-push'; const COMMIT_MSG = 'commit-msg'; const PREPARE_COMMIT_MSG = 'prepare-commit-msg'; /** * Returns the list of valid hooks * * @return array */ public static function getValidHooks() : array { return [ self::COMMIT_MSG => 'CommitMsg', self::PRE_PUSH => 'PrePush', self::PRE_COMMIT => 'PreCommit', self::PREPARE_COMMIT_MSG => 'PrepareCommitMsg', ]; } }
<?php declare(strict_types=1); /** * This file is part of CaptainHook. * * (c) Sebastian Feldmann <sf@sebastian.feldmann.info> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CaptainHook\App; /** * Class Hooks * * Defines the list of hooks that can be handled with captainhook and provides some name constants. * * @package CaptainHook * @author Andrea Heigl <andreas@heigl.org> * @link https://github.com/sebastianfeldmann/captainhook * @since Class available since Release 3.0.1 */ final class Hooks { const PRE_COMMIT = 'pre-commit'; const PRE_PUSH = 'pre-push'; const COMMIT_MSG = 'commit-msg'; const PREPARE_COMMIT_MSG = 'prepare-commit-msg'; /** * Returns the list of valid hooks * * @return array */ public static function getValidHooks() : array { return [ self::COMMIT_MSG => 'PreCommit', self::PRE_PUSH => 'PrePush', self::PRE_COMMIT => 'PreCommit', self::PREPARE_COMMIT_MSG => 'PrepareCommitMessage', ]; } }
Fix issue where black boarders would appear on thumbnail
import io import logging import PIL.Image import selenium.webdriver def fetch_screen_capture(uri, size): browser = selenium.webdriver.PhantomJS() browser.set_window_size(*size) browser.get(uri) return browser.get_screenshot_as_png() def toast(uri): logging.info("Toasting %s",uri) toast_image = PIL.Image.open("/app/toast-01.png") black_image = PIL.Image.open("/app/toast-02.png") capture_cropbox = (0, 0) + toast_image.size capture = fetch_screen_capture(uri, toast_image.size) capture_image = PIL.Image.open(io.BytesIO(capture)) capture_image.save("/app/capture.png") capture_mask = capture_image.crop(capture_cropbox).convert("L") composite_image = PIL.Image.composite(toast_image, black_image, capture_mask) renderedImagePath = "/app/render.png" thumbnailPath = "/app/thumbnail.png" composite_image.save(renderedImagePath) size = 500, 500 #open previously generated file compImg = PIL.Image.open(renderedImagePath) compImg.thumbnail(size, PIL.Image.ANTIALIAS) compImg.save(thumbnailPath, "PNG", quality=60) logging.info("Done toasting %s",uri) return renderedImagePath, thumbnailPath
import io import logging import PIL.Image import selenium.webdriver def fetch_screen_capture(uri, size): browser = selenium.webdriver.PhantomJS() browser.set_window_size(*size) browser.get(uri) return browser.get_screenshot_as_png() def toast(uri): logging.info("Toasting %s",uri) toast_image = PIL.Image.open("/app/toast-01.png") black_image = PIL.Image.open("/app/toast-02.png") capture_cropbox = (0, 0) + toast_image.size capture = fetch_screen_capture(uri, toast_image.size) capture_image = PIL.Image.open(io.BytesIO(capture)) capture_image.save("/app/capture.png") capture_mask = capture_image.crop(capture_cropbox).convert("L") composite_image = PIL.Image.composite(toast_image, black_image, capture_mask) renderedImagePath = "/app/render.png" thumbnailPath = "/app/thumbnail.png" composite_image.save(renderedImagePath) size = 500, 500 #open previously generated file compImg = PIL.Image.open(renderedImagePath) compImg.thumbnail(size, PIL.Image.ANTIALIAS) compImg.save(thumbnailPath, "JPEG", quality=60) logging.info("Done toasting %s",uri) return renderedImagePath, thumbnailPath
Remove unneeded null check, format
/* * 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.beam.runners.core.metrics; import java.io.Serializable; import org.apache.beam.sdk.metrics.MetricQueryResults; /** Abstract base class for all metric sinks it can use different serializers. */ public abstract class MetricsSink<OutputT> implements Serializable { private MetricsSerializer<OutputT> metricsSerializer = provideSerializer(); void writeMetrics(MetricQueryResults metricQueryResults) throws Exception { OutputT serializedMetrics = metricsSerializer.serializeMetrics(metricQueryResults); writeSerializedMetrics(serializedMetrics); } protected abstract MetricsSerializer<OutputT> provideSerializer(); protected abstract void writeSerializedMetrics(OutputT metrics) throws Exception; }
/* * 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.beam.runners.core.metrics; import java.io.Serializable; import org.apache.beam.sdk.metrics.MetricQueryResults; /** * Abstract base class for all metric sinks it can use different serializers. */ public abstract class MetricsSink<OutputT> implements Serializable{ private MetricsSerializer<OutputT> metricsSerializer = provideSerializer(); void writeMetrics(MetricQueryResults metricQueryResults) throws Exception { if (metricsSerializer != null) { OutputT serializedMetrics = metricsSerializer.serializeMetrics(metricQueryResults); writeSerializedMetrics(serializedMetrics); } } protected abstract MetricsSerializer<OutputT> provideSerializer(); protected abstract void writeSerializedMetrics(OutputT metrics) throws Exception; }
Fix test setUp method signatures
<?php namespace Enqueue\Bundle\Tests\Functional; use Enqueue\Bundle\Tests\Functional\App\AppKernel; use Enqueue\Client\TraceableProducer; use Symfony\Bundle\FrameworkBundle\Client; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase; use Symfony\Component\DependencyInjection\ContainerInterface; abstract class WebTestCase extends BaseWebTestCase { /** * @var Client */ protected static $client; /** * @var ContainerInterface */ protected static $container; protected function setUp(): void { parent::setUp(); static::$class = null; static::$client = static::createClient(); static::$container = static::$kernel->getContainer(); /** @var TraceableProducer $producer */ $producer = static::$container->get('test_enqueue.client.default.traceable_producer'); $producer->clearTraces(); } protected function tearDown(): void { static::ensureKernelShutdown(); static::$client = null; } /** * @return string */ public static function getKernelClass() { include_once __DIR__.'/App/AppKernel.php'; return AppKernel::class; } }
<?php namespace Enqueue\Bundle\Tests\Functional; use Enqueue\Bundle\Tests\Functional\App\AppKernel; use Enqueue\Client\TraceableProducer; use Symfony\Bundle\FrameworkBundle\Client; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase; use Symfony\Component\DependencyInjection\ContainerInterface; abstract class WebTestCase extends BaseWebTestCase { /** * @var Client */ protected static $client; /** * @var ContainerInterface */ protected static $container; protected function setUp() { parent::setUp(); static::$class = null; static::$client = static::createClient(); static::$container = static::$kernel->getContainer(); /** @var TraceableProducer $producer */ $producer = static::$container->get('test_enqueue.client.default.traceable_producer'); $producer->clearTraces(); } protected function tearDown(): void { static::ensureKernelShutdown(); static::$client = null; } /** * @return string */ public static function getKernelClass() { include_once __DIR__.'/App/AppKernel.php'; return AppKernel::class; } }
Fix logger level isIn bug
// Copyright 2014, Renasar Technologies Inc. /* jshint: node:true */ 'use strict'; var di = require('di'); module.exports = loggingProtocolFactory; di.annotate(loggingProtocolFactory, new di.Provide('Protocol.Logging')); di.annotate(loggingProtocolFactory, new di.Inject( 'Assert', 'Constants', 'Services.Messenger', '_' ) ); function loggingProtocolFactory (assert, Constants, messenger, _) { var levels = _.keys(Constants.Logging.Levels); function LoggingProtocol() { } LoggingProtocol.prototype.publishLog = function (level, data) { assert.isIn(level, levels); assert.object(data, 'data'); messenger.publish( Constants.Protocol.Exchanges.Logging.Name, level, data ); }; return new LoggingProtocol(); }
// Copyright 2014, Renasar Technologies Inc. /* jshint: node:true */ 'use strict'; var di = require('di'); module.exports = loggingProtocolFactory; di.annotate(loggingProtocolFactory, new di.Provide('Protocol.Logging')); di.annotate(loggingProtocolFactory, new di.Inject( 'Assert', 'Constants', 'Services.Messenger', '_' ) ); function loggingProtocolFactory (assert, Constants, messenger, _) { var levels = _.keys(Constants.Logging.Levels); function LoggingProtocol() { } LoggingProtocol.prototype.publishLog = function (level, data) { assert.isIn('level', levels); assert.object(data, 'data'); messenger.publish( Constants.Protocol.Exchanges.Logging.Name, level, data ); }; return new LoggingProtocol(); }
ADD - TDD for POST employees endpoint without employee data
var chakram = require('chakram'), expect = chakram.expect; describe("mPayroll API", function() { const empRec = { "name": 'Harry Hourly', "type": 'H', "rate": '10.00' }; it("should have POST employees endpoint", function () { this.timeout(4000); expect(chakram.post("http://localhost:3000/api_mpayroll/employees", empRec)).to.have.status(201); return chakram.wait(); }); it("POST employees endpoint without employee data is Bad Request", function () { this.timeout(4000); expect(chakram.post("http://localhost:3000/api_mpayroll/employees")).to.have.status(400); return chakram.wait(); }); });
var chakram = require('chakram'), expect = chakram.expect; describe("mPayroll API", function() { const empRec = { "name": 'Harry Hourly', "type": 'H', "rate": '10.00' }; it("should have POST employees endpoint", function () { this.timeout(4000); expect(chakram.post("http://localhost:3000/api_mpayroll/employees", empRec)).to.have.status(201); return chakram.wait(); }); it("POST employees endpoint without employee data is Bad Request", function () { this.timeout(4000); expect(chakram.post("http://localhost:3000/api_mpayroll/employees")).to.have.status(400); return chakram.wait(); }); });
Create models dir and copy user model for mongodb generator
import { join } from 'path'; import { replaceCode, mkdirs, copy, appendFile, addNpmPackage } from '../utils'; async function generateMongodbDatabase(params) { const build = join(__base, 'build', params.uuid); switch (params.framework) { case 'express': const app = join(build, 'app.js'); const mongooseRequire = join(__base, 'modules', 'database', 'mongodb', 'mongoose-require.js'); const mongooseConnect = join(__base, 'modules', 'database', 'mongodb', 'mongoose-connect.js'); const mongooseUserModel = join(__base, 'modules', 'database', 'mongodb', 'mongoose-model.js'); await replaceCode(app, 'DATABASE_REQUIRE', mongooseRequire); await replaceCode(app, 'DATABASE_CONNECTION', mongooseConnect, { leadingBlankLine: true }); await appendFile(join(build, '.env'), 'MONGODB=mongodb://localhost/test'); await addNpmPackage('mongoose', params); // Create models dir await mkdirs(join(__base, 'build', params.uuid, 'models')); await copy(mongooseUserModel, join(build, 'models', 'user.js')); break; case 'hapi': break; case 'meteor': break; default: } } export default generateMongodbDatabase;
import { join } from 'path'; import { replaceCode, appendFile, addNpmPackage } from '../utils'; async function generateMongodbDatabase(params) { switch (params.framework) { case 'express': const app = join(__base, 'build', params.uuid, 'app.js'); const mongooseRequire = join(__base, 'modules', 'database', 'mongodb', 'mongoose-require.js'); const mongooseConnect = join(__base, 'modules', 'database', 'mongodb', 'mongoose-connect.js'); await replaceCode(app, 'DATABASE_REQUIRE', mongooseRequire); await replaceCode(app, 'DATABASE_CONNECTION', mongooseConnect, { leadingBlankLine: true }); await appendFile(join(__base, 'build', params.uuid, '.env'), 'MONGODB=mongodb://localhost/test'); await addNpmPackage('mongoose', params); break; case 'hapi': break; case 'meteor': break; default: } } export default generateMongodbDatabase;
Add some extra redirect logic for root path
const TYPES = [ 'communities', 'featured-users', 'recent', 'recommended', 'trending', ] const getComponents = (location, cb) => { cb(null, require('../../containers/discover/Discover').default) } const bindOnEnter = path => (nextState, replace) => { const type = nextState.params.type // redirect back to root path if type is unrecognized if (type && TYPES.indexOf(type) === -1) { replace({ state: nextState, pathname: path }) } } const indexRoute = { getComponents, } const explore = { path: 'explore(/:type)', getComponents, onEnter: bindOnEnter('/explore'), } const exploreRoot = store => ({ path: '/explore', getComponents, onEnter: (nextState, replace) => { const { params: { type } } = nextState const { authentication } = store.getState() const rootPath = authentication.isLoggedIn ? '/discover' : '/' if (type && TYPES.indexOf(type) === -1) { replace({ state: nextState, pathname: rootPath }) } else if (authentication.isLoggedIn) { replace({ state: nextState, pathname: '/discover' }) } else { replace({ state: nextState, pathname: '/' }) } }, }) const discover = { path: 'discover(/:type)', getComponents, onEnter: bindOnEnter('/discover'), } export { indexRoute, getComponents, discover, explore, exploreRoot, } export default [ discover, explore, ]
const TYPES = [ 'communities', 'featured-users', 'recent', 'recommended', 'trending', ] const getComponents = (location, cb) => { cb(null, require('../../containers/discover/Discover').default) } const bindOnEnter = path => (nextState, replace) => { const type = nextState.params.type // redirect back to root path if type is unrecognized if (type && TYPES.indexOf(type) === -1) { replace({ state: nextState, pathname: path }) } } const indexRoute = { getComponents, } const explore = { path: 'explore(/:type)', getComponents, onEnter: bindOnEnter('/explore'), } const discover = { path: 'discover(/:type)', getComponents, onEnter: bindOnEnter('/discover'), } export { indexRoute, getComponents, discover, explore, } export default [ discover, explore, ]
Make the bound value more perdictable. If the file input is set to multiple, always bind an array. If it's not set to multiple is gets the single file.
// // angular-file-model // ================== // // Directive that makes the inputs with type `file` to be // available in the `$scope` and be assigned to a model. // (function () { 'use strict'; angular.module('file-model', []) .directive('fileModel', [ '$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ if (attrs.multiple) { modelSetter(scope, element[0].files); } else { modelSetter(scope, element[0].files[0]); } }); }); } }; } ]); })();
// // angular-file-model // ================== // // Directive that makes the inputs with type `file` to be // available in the `$scope` and be assigned to a model. // (function () { 'use strict'; angular.module('file-model', []) .directive('fileModel', [ '$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ if (element[0].files.length > 1) { modelSetter(scope, element[0].files); } else { modelSetter(scope, element[0].files[0]); } }); }); } }; } ]); })();
Disable analysis and subscription from the Indonesia Forest Area layer as requested
/** * The Indonesian Forest Area layer module. (based on IdnPlantationsLayerBySpecies.js) * More info @ https://basecamp.com/3063126/projects/10726176/todos/303918841 * @return IdnForestArea class (extends CartoDBLayerClass) */ // 'text!map/cartocss/IdnForestArea.cartocss'], function(CartoDBLayerClass, ) { define([ 'abstract/layer/CartoDBLayerClass', 'text!map/cartocss/IdnForestArea.cartocss' ], function(CartoDBLayerClass, IdnForestAreaCartocss) { 'use strict'; var IdnForestArea = CartoDBLayerClass.extend({ options: { sql: 'SELECT the_geom_webmercator, fungsi_kws, legend as name, cartodb_id, \'{tableName}\' AS tablename, \'{tableName}\' AS layer, {analysis} AS analysis FROM {tableName}', cartocss: IdnForestAreaCartocss, infowindow: true, interactivity: 'cartodb_id, tablename, layer, name, analysis', analysis: false } }); return IdnForestArea; });
/** * The Indonesian Forest Area layer module. (based on IdnPlantationsLayerBySpecies.js) * More info @ https://basecamp.com/3063126/projects/10726176/todos/303918841 * @return IdnForestArea class (extends CartoDBLayerClass) */ // 'text!map/cartocss/IdnForestArea.cartocss'], function(CartoDBLayerClass, ) { define([ 'abstract/layer/CartoDBLayerClass', 'text!map/cartocss/IdnForestArea.cartocss' ], function(CartoDBLayerClass, IdnForestAreaCartocss) { 'use strict'; var IdnForestArea = CartoDBLayerClass.extend({ options: { sql: 'SELECT the_geom_webmercator, fungsi_kws, legend as name, cartodb_id, \'{tableName}\' AS tablename, \'{tableName}\' AS layer, {analysis} AS analysis FROM {tableName}', cartocss: IdnForestAreaCartocss, infowindow: true, interactivity: 'cartodb_id, tablename, layer, name, analysis', analysis: true, }, }); return IdnForestArea; });
Add empty string check to prevent tooltip creation for empty strings
package io.bisq.gui.components; import javafx.scene.control.Labeled; import javafx.scene.control.SkinBase; import javafx.scene.control.Tooltip; import javafx.scene.text.Text; public class TooltipUtil { public static void showTooltipIfTruncated(SkinBase skinBase, Labeled labeled) { for (Object node : skinBase.getChildren()) { if (node instanceof Text) { String displayedText = ((Text) node).getText(); String untruncatedText = labeled.getText(); if (displayedText.equals(untruncatedText)) { if (labeled.getTooltip() != null) { labeled.setTooltip(null); } } else if (untruncatedText != null && !untruncatedText.trim().isEmpty()){ labeled.setTooltip(new Tooltip(untruncatedText)); } } } } }
package io.bisq.gui.components; import javafx.scene.control.Labeled; import javafx.scene.control.SkinBase; import javafx.scene.control.Tooltip; import javafx.scene.text.Text; public class TooltipUtil { public static void showTooltipIfTruncated(SkinBase skinBase, Labeled labeled) { for (Object node : skinBase.getChildren()) { if (node instanceof Text) { String displayedText = ((Text) node).getText(); if (displayedText.equals(labeled.getText())) { if (labeled.getTooltip() != null) { labeled.setTooltip(null); } } else if (labeled.getText() != null){ labeled.setTooltip(new Tooltip(labeled.getText())); } } } } }
Add testcase that fails old code.
package util import ( "testing" ) func TestNormalizeName(t *testing.T) { packages := map[string]string{ "github.com/Masterminds/cookoo/web/io/foo": "github.com/Masterminds/cookoo", `github.com\Masterminds\cookoo\web\io\foo`: "github.com/Masterminds/cookoo", "golang.org/x/crypto/ssh": "golang.org/x/crypto", "incomplete/example": "incomplete/example", "net": "net", } for start, expected := range packages { if finish, extra := NormalizeName(start); expected != finish { t.Errorf("Expected '%s', got '%s'", expected, finish) } else if start != finish && start != finish+"/"+extra { t.Errorf("Expected %s to end with %s", finish, extra) } } }
package util import ( "testing" ) func TestNormalizeName(t *testing.T) { packages := map[string]string{ "github.com/Masterminds/cookoo/web/io/foo": "github.com/Masterminds/cookoo", "golang.org/x/crypto/ssh": "golang.org/x/crypto", "incomplete/example": "incomplete/example", "net": "net", } for start, expected := range packages { if finish, extra := NormalizeName(start); expected != finish { t.Errorf("Expected '%s', got '%s'", expected, finish) } else if start != finish && start != finish+"/"+extra { t.Errorf("Expected %s to end with %s", finish, extra) } } }
Fix bug in the PyQt4 binding selection logic.
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside')
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') if qt_api == 'pyqt': # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside')
Add rba url, since it's normally taken from the config
# Filename: test_srv.py # pylint: disable=locally-disabled,C0111,R0904,C0103 from km3pipe.testing import TestCase, patch from km3pipe.dataclasses import Table from km3pipe.srv import srv_event __author__ = "Tamas Gal" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer__ = "Tamas Gal" __email__ = "tgal@km3net.de" __status__ = "Development" class TestSrvEvent(TestCase): @patch('km3pipe.srv.srv_data') def test_call(self, srv_data_mock): hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6], 'time': [100, 200], 'tot': [11, 22]}) srv_event('token', hits, 'rba_url') srv_data_mock.assert_called_once()
# Filename: test_srv.py # pylint: disable=locally-disabled,C0111,R0904,C0103 from km3pipe.testing import TestCase, patch from km3pipe.dataclasses import Table from km3pipe.srv import srv_event __author__ = "Tamas Gal" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer__ = "Tamas Gal" __email__ = "tgal@km3net.de" __status__ = "Development" class TestSrvEvent(TestCase): @patch('km3pipe.srv.srv_data') def test_call(self, srv_data_mock): hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6], 'time': [100, 200], 'tot': [11, 22]}) srv_event('token', hits) srv_data_mock.assert_called_once()
Add version constraint for reactive-obj
/*global Package*/ Package.describe({ name: 'dschnare:meteor-components-ioc-plugin', version: '0.2.0', // Brief, one-line summary of the package. summary: 'A plugin for Meteor Components that integrates IOC Containers.', // URL to the Git repository containing the source code for this package. git: 'https://github.com/dschnare/meteor-components-ioc-plugin', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use('ecmascript', 'client'); api.use('xamfoo:reactive-obj@0.5.0', 'client'); api.use('ejson', 'client'); api.use([ 'dschnare:meteor-components@0.5.0', 'dschnare:ioc-container@0.2.0' ], 'client', { weak: true }); api.addFiles('meteor-components-ioc-plugin.js', 'client'); api.export('ComponentRootIoc', 'client'); }); Package.onTest(function(api) { api.use('ecmascript', 'client'); api.use('tinytest', 'client'); api.use('dschnare:meteor-components-ioc-plugin', 'client'); api.addFiles('meteor-components-ioc-plugin-tests.js', 'client'); });
/*global Package*/ Package.describe({ name: 'dschnare:meteor-components-ioc-plugin', version: '0.2.0', // Brief, one-line summary of the package. summary: 'A plugin for Meteor Components that integrates IOC Containers.', // URL to the Git repository containing the source code for this package. git: 'https://github.com/dschnare/meteor-components-ioc-plugin', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use('ecmascript', 'client'); api.use('xamfoo:reactive-obj', 'client'); api.use('ejson', 'client'); api.use([ 'dschnare:meteor-components@0.5.0', 'dschnare:ioc-container@0.2.0' ], 'client', { weak: true }); api.addFiles('meteor-components-ioc-plugin.js', 'client'); api.export('ComponentRootIoc', 'client'); }); Package.onTest(function(api) { api.use('ecmascript', 'client'); api.use('tinytest', 'client'); api.use('dschnare:meteor-components-ioc-plugin', 'client'); api.addFiles('meteor-components-ioc-plugin-tests.js', 'client'); });
[attachments] Send error details when there's "Corrupt image"
"use strict"; var models = require('../../../models') , formidable = require('formidable') , AttachmentSerializer = models.AttachmentSerializer exports.addController = function(app) { var AttachmentsController = function() { } AttachmentsController.create = function(req, res) { if (!req.user) return res.status(401).jsonp({ err: 'Not found' }) var form = new formidable.IncomingForm() form.on('file', function(inputName, file) { req.user.newAttachment({ file: file }) .then(function(newAttachment) { return newAttachment.create() }) .then(function(newAttachment) { new AttachmentSerializer(newAttachment).toJSON(function(err, json) { res.jsonp(json) }) }) .catch(function(e) { let errorDetails = {} if (e.message && e.message.indexOf('Corrupt image') > -1) { errorDetails = { message: 'Corrupt image' } } res.status(422).send(errorDetails) }) }) form.parse(req) } return AttachmentsController }
"use strict"; var models = require('../../../models') , formidable = require('formidable') , AttachmentSerializer = models.AttachmentSerializer exports.addController = function(app) { var AttachmentsController = function() { } AttachmentsController.create = function(req, res) { if (!req.user) return res.status(401).jsonp({ err: 'Not found' }) var form = new formidable.IncomingForm() form.on('file', function(inputName, file) { req.user.newAttachment({ file: file }) .then(function(newAttachment) { return newAttachment.create() }) .then(function(newAttachment) { new AttachmentSerializer(newAttachment).toJSON(function(err, json) { res.jsonp(json) }) }) .catch(function(e) { res.status(422).send({}) }) }) form.parse(req) } return AttachmentsController }
Fix tests with different length strings to look for undefined result, rather than zero.
var compute = require('./hamming').compute; describe('Hamming', function () { it('no difference between identical strands', function () { expect(compute('A', 'A')).toEqual(0); }); xit('complete hamming distance for single nucleotide strand', function () { expect(compute('A','G')).toEqual(1); }); xit('complete hamming distance for small strand', function () { expect(compute('AG','CT')).toEqual(2); }); xit('small hamming distance', function () { expect(compute('AT','CT')).toEqual(1); }); xit('small hamming distance in longer strand', function () { expect(compute('GGACG', 'GGTCG')).toEqual(1); }); xit('no defined hamming distance for unequal string (first way)', function () { expect(compute('AAAG', 'AAA')).toBeUndefined(); }); xit('no defined hamming distance for unequal string (second way)', function () { expect(compute('AAA', 'AAAG')).toBeUndefined(); }); xit('large hamming distance', function () { expect(compute('GATACA', 'GCATAA')).toEqual(4); }); xit('hamming distance in very long strand', function () { expect(compute('GGACGGATTCTG', 'AGGACGGATTCT')).toEqual(9); }); });
var compute = require('./hamming').compute; describe('Hamming', function () { it('no difference between identical strands', function () { expect(compute('A', 'A')).toEqual(0); }); xit('complete hamming distance for single nucleotide strand', function () { expect(compute('A','G')).toEqual(1); }); xit('complete hamming distance for small strand', function () { expect(compute('AG','CT')).toEqual(2); }); xit('small hamming distance', function () { expect(compute('AT','CT')).toEqual(1); }); xit('small hamming distance in longer strand', function () { expect(compute('GGACG', 'GGTCG')).toEqual(1); }); xit('ignores extra length on first strand when longer', function () { expect(compute('AAAG', 'AAA')).toEqual(0); }); xit('ignores extra length on other strand when longer', function () { expect(compute('AAA', 'AAAG')).toEqual(0); }); xit('large hamming distance', function () { expect(compute('GATACA', 'GCATAA')).toEqual(4); }); xit('hamming distance in very long strand', function () { expect(compute('GGACGGATTCTG', 'AGGACGGATTCT')).toEqual(9); }); });
FIX: Remove a bunch of unnecessary import
#!/usr/bin/python3 # -*- coding: utf8 -* import sys # Fix for file paths errors import os PATH = os.path.dirname(os.path.realpath(__file__)) # Import other files from the project from game import Game from idlerpg import IdleRPG from logger import log, story # Import Graphic Lib from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QTimer def main(): # instatiate the game object game = Game() # initiate window app = QApplication(sys.argv) app.setStyleSheet("") idlerpg = IdleRPG(game) # setup timer for the game tick (1 tick per 2 seconds) timer = QTimer() timer.start(1500) timer.timeout.connect(idlerpg.tick) idlerpg.show() # run the main loop sys.exit(app.exec_()) if __name__ == '__main__': log.info("========== STARTING NEW SESSION ============") main() #EOF
#!/usr/bin/python3 # -*- coding: utf8 -* import sys # Fix for file paths errors import os PATH = os.path.dirname(os.path.realpath(__file__)) # Import other files from the project from game import Game from idlerpg import IdleRPG from logger import log, story # Import Graphic Lib from PyQt5.QtWidgets import (QApplication, QMainWindow, QToolTip, QPushButton, QWidget, QStackedWidget, QHBoxLayout, QVBoxLayout, QLabel, QLineEdit, QFormLayout, QDockWidget, QListWidget, QListWidgetItem, QAction, qApp, QButtonGroup, QProgressBar, QSpacerItem) from PyQt5.QtCore import QTimer, Qt from PyQt5.QtGui import QFont, QIcon def main(): # instatiate the game object game = Game() # initiate window app = QApplication(sys.argv) app.setStyleSheet("") idlerpg = IdleRPG(game) # setup timer for the game tick (1 tick per 2 seconds) timer = QTimer() timer.start(1500) timer.timeout.connect(idlerpg.tick) idlerpg.show() # run the main loop sys.exit(app.exec_()) if __name__ == '__main__': log.info("========== STARTING NEW SESSION ============") main() #EOF
Use open context to load readme (per best practices)
#!/usr/bin/env python from setuptools import setup, find_packages with open('VERSION') as version_stream: version = version_stream.read().strip() with open('README.rst') as readme_stream: readme = readme_stream.read() setup( name='PlayerPiano', version=version, description='Amazes your friends by running Python doctests in a fake interactive shell.', author='Peter Fein', author_email='pete@wearpants.org', url='https://github.com/wearpants/playerpiano', entry_points = { 'console_scripts': [ 'playerpiano=playerpiano.piano:main', 'recorderpiano=playerpiano.recorder:main', ]}, packages=find_packages(), include_package_data = True, install_requires=['pygments'], license="BSD", long_description=readme, classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Education :: Computer Aided Instruction (CAI)", "Topic :: System :: Shells", ], )
#!/usr/bin/env python from setuptools import setup, find_packages with open('VERSION') as version_stream: version = version_stream.read().strip() setup( name='PlayerPiano', version=version, description='Amazes your friends by running Python doctests in a fake interactive shell.', author='Peter Fein', author_email='pete@wearpants.org', url='https://github.com/wearpants/playerpiano', entry_points = { 'console_scripts': [ 'playerpiano=playerpiano.piano:main', 'recorderpiano=playerpiano.recorder:main', ]}, packages=find_packages(), include_package_data = True, install_requires=['pygments'], license="BSD", long_description=open("README.rst").read(), classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Education :: Computer Aided Instruction (CAI)", "Topic :: System :: Shells", ], )
Fix Filename Errors Module folder had changed at some point in the past, fixed the file path so it could find the CSV
import os import csv abilityList = {} def loadAbilities(): global abilityList fileName = "FF4P/FF4P_Abil.csv" if not os.path.exists(fileName): fileName = "FF4P_Abil.csv" with open(fileName, 'r') as csvFile: abilityReader = csv.reader(csvFile, delimiter=',', quotechar='|') i = 0 for row in abilityReader: abilityList[i] = row i += 1 def reloadAbilities(): loadAbilities() print("Abilities reloaded.") def getAbility(name): if abilityList == {}: loadAbilities() none = ["none"] for _,ability in abilityList.items(): if ability[0].lower() == name.lower(): return ability return none
import csv abilityList = {} def loadAbilities(): global abilityList with open('FF4/FF4Abil.csv', 'r') as csvFile: abilityReader = csv.reader(csvFile, delimiter=',', quotechar='|') i = 0 for row in abilityReader: abilityList[i] = row i += 1 def reloadAbilities(): loadAbilities() print("Abilities reloaded.") def getAbility(name): if abilityList == {}: loadAbilities() none = ["none"] for _,ability in abilityList.items(): if ability[0].lower() == name.lower(): return ability return none
Fix KeyError: 'version' due to 403 Forbidden error
import json import sys import requests def py_version(): if sys.version_info < (3, 0, 0): print(sys.version) print('You must use Python 3.x to run this application.') sys.exit(1) def get_version(endpoint): r = requests.get('https://{}'.format(endpoint)) es_version = json.loads(r.text)['version']['number'] return es_version def test_con(endpoint): r = requests.get('https://{}'.format(endpoint)) try: es_version = get_version(endpoint) except KeyError: print('Status: {}'.format(r.status_code)) sys.exit(1) else: if r.status_code == 200: print('ESVersion: {}'.format(es_version)) print('Connection: OK') print('Status: {}\n'.format(r.status_code))
import json import sys import requests def py_version(): if sys.version_info < (3, 0, 0): print(sys.version) print('You must use Python 3.x to run this application.') sys.exit(1) def get_version(endpoint): r = requests.get('https://{}'.format(endpoint)) es_version = json.loads(r.text)['version']['number'] return es_version def test_con(endpoint): r = requests.get('https://{}'.format(endpoint)) es_version = get_version(endpoint) if r.status_code == 200: print('ESVersion: {}'.format(es_version)) print('Connection: OK') print('Status: {}\n'.format(r.status_code)) else: print(json.loads(msg)['Message']) print('Status: {}'.format(status_code)) sys.exit(1)
Increase timeouts in attempt to get windows CI build working!
"use strict"; var path = require("path"); var _ = require("lodash"); var assert = require("chai").assert; var request = require("supertest"); var fork = require("child_process").fork; var index = path.resolve( __dirname + "/../../../index.js"); describe("E2E CLI Snippet test", function () { this.timeout(5000); var bs, options; before(function (done) { bs = fork(index, ["start", "--logLevel=silent"]); bs.on("message", function (data) { options = data.options; done(); }); bs.send({send: "options"}); }); after(function () { bs.kill("SIGINT"); }); it("can serve the client JS", function (done) { request(options.urls.local) .get(options.scriptPath) .expect(200) .end(function (err, res) { assert.isTrue(_.contains(res.text, "Connected to BrowserSync")); done(); }); }); });
"use strict"; var path = require("path"); var _ = require("lodash"); var assert = require("chai").assert; var request = require("supertest"); var fork = require("child_process").fork; var index = path.resolve( __dirname + "/../../../index.js"); describe("E2E CLI Snippet test", function () { var bs, options; before(function (done) { bs = fork(index, ["start", "--logLevel=silent"]); bs.on("message", function (data) { options = data.options; done(); }); bs.send({send: "options"}); }); after(function () { bs.kill("SIGINT"); }); it("can serve the client JS", function (done) { request(options.urls.local) .get(options.scriptPath) .expect(200) .end(function (err, res) { assert.isTrue(_.contains(res.text, "Connected to BrowserSync")); done(); }); }); });
Remove hard coding the 401 and instead give it a readable name.
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. var http = require('http'); var httpStatus = require('http-status'); module.exports = function(apikeyCache) { 'use strict'; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function* validateAPIKey(next) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Invalid apikey'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Invalid apikey'); } this.mcapp = { user: user }; yield next; }; };
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. var http = require('http'); module.exports = function(apikeyCache) { 'use strict'; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function* validateAPIKey(next) { let apikey = this.query.apikey || this.throw(401, 'Invalid apikey'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(401, 'Invalid apikey'); } this.mcapp = { user: user }; yield next; }; };
[lib] Use hook instead of connect function in MessageHandler Test Plan: Checked if onMessage still fired and worked correcly on web and native Reviewers: palys-swm, ashoat, atul Reviewed By: ashoat Subscribers: ashoat, KatPo, zrebcu411, Adrian, atul Differential Revision: https://phabricator.ashoat.com/D828
// @flow import * as React from 'react'; import { useDispatch } from 'react-redux'; import { processMessagesActionType } from '../actions/message-actions'; import { type ServerSocketMessage, serverSocketMessageTypes, type SocketListener, } from '../types/socket-types'; type Props = {| +addListener: (listener: SocketListener) => void, +removeListener: (listener: SocketListener) => void, |}; export default function MessageHandler(props: Props) { const { addListener, removeListener } = props; const dispatch = useDispatch(); const onMessage = React.useCallback( (message: ServerSocketMessage) => { if (message.type !== serverSocketMessageTypes.MESSAGES) { return; } dispatch({ type: processMessagesActionType, payload: message.payload, }); }, [dispatch], ); React.useEffect(() => { addListener(onMessage); return () => { removeListener(onMessage); }; }, [addListener, removeListener, onMessage]); return null; }
// @flow import PropTypes from 'prop-types'; import * as React from 'react'; import { processMessagesActionType } from '../actions/message-actions'; import { type ServerSocketMessage, serverSocketMessageTypes, type SocketListener, } from '../types/socket-types'; import type { DispatchActionPayload } from '../utils/action-utils'; import { connect } from '../utils/redux-utils'; type Props = {| addListener: (listener: SocketListener) => void, removeListener: (listener: SocketListener) => void, // Redux dispatch functions dispatchActionPayload: DispatchActionPayload, |}; class MessageHandler extends React.PureComponent<Props> { static propTypes = { addListener: PropTypes.func.isRequired, removeListener: PropTypes.func.isRequired, dispatchActionPayload: PropTypes.func.isRequired, }; componentDidMount() { this.props.addListener(this.onMessage); } componentWillUnmount() { this.props.removeListener(this.onMessage); } render() { return null; } onMessage = (message: ServerSocketMessage) => { if (message.type !== serverSocketMessageTypes.MESSAGES) { return; } this.props.dispatchActionPayload( processMessagesActionType, message.payload, ); }; } export default connect(null, null, true)(MessageHandler);
Fix possible exception by using empty object for options
/** * @providesModule MusicControl * @flow */ 'use strict'; import { NativeModules, DeviceEventEmitter } from 'react-native'; const NativeMusicControl = NativeModules.MusicControlManager; /** * High-level docs for the MusicControl iOS API can be written here. */ var handlers = { }; var subscription = null; var MusicControl = { enableBackgroundMode: function(enable){ NativeMusicControl.enableBackgroundMode(enable) }, setNowPlaying: function(info){ NativeMusicControl.setNowPlaying(info) }, resetNowPlaying: function(){ NativeMusicControl.resetNowPlaying() }, enableControl: function(controlName, bool, options = {}){ NativeMusicControl.enableControl(controlName, bool, options || {}) }, handleCommand: function(commandName){ if(handlers[commandName]){ handlers[commandName]() } }, on: function(actionName, cb){ if(subscription){ subscription.remove(); } subscription = DeviceEventEmitter.addListener( 'RNMusicControlEvent', (event) => { MusicControl.handleCommand(event.name) } ); handlers[actionName] = cb }, off: function(actionName, cb){ delete(handlers[actionName]) if(!Object.keys(handlers).length && subscription){ subscription.remove() subscription = null; } } }; module.exports = MusicControl;
/** * @providesModule MusicControl * @flow */ 'use strict'; import { NativeModules, DeviceEventEmitter } from 'react-native'; const NativeMusicControl = NativeModules.MusicControlManager; /** * High-level docs for the MusicControl iOS API can be written here. */ var handlers = { }; var subscription = null; var MusicControl = { enableBackgroundMode: function(enable){ NativeMusicControl.enableBackgroundMode(enable) }, setNowPlaying: function(info){ NativeMusicControl.setNowPlaying(info) }, resetNowPlaying: function(){ NativeMusicControl.resetNowPlaying() }, enableControl: function(controlName, bool, options){ NativeMusicControl.enableControl(controlName, bool, options) }, handleCommand: function(commandName){ if(handlers[commandName]){ handlers[commandName]() } }, on: function(actionName, cb){ if(subscription){ subscription.remove(); } subscription = DeviceEventEmitter.addListener( 'RNMusicControlEvent', (event) => { MusicControl.handleCommand(event.name) } ); handlers[actionName] = cb }, off: function(actionName, cb){ delete(handlers[actionName]) if(!Object.keys(handlers).length && subscription){ subscription.remove() subscription = null; } } }; module.exports = MusicControl;
Fix passed id of state add
"use strict"; var LocalStorageUtils = require("./utils/LocalStorageUtils"); var StateIds = require("./states/States"); var InitializeState = require("./states/InitializeState"); var MenuState = require("./states/MenuState"); var SettingsState = require("./states/SettingsState"); var LoadingState = require("./states/LoadingState"); var GameState = require("./states/GameState") var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS, 'phaser-example'); window.Game = game; window.onresize = function() { Game.scale.setGameSize(window.innerWidth, window.innerHeight); } game.state.add(StateIds.INITIALIZE_STATE_ID, new InitializeState(game), true); game.state.add(StateIds.MENU_STATE_ID, new MenuState(game)); game.state.add(StateIds.SETTINGS_STATE_ID, new SettingsState(game)); game.state.add(StateIds.LOADING_STATE_ID, new LoadingState(game)); game.state.add(StateIds.GAME_STATE_ID, new GameState(game));
"use strict"; var LocalStorageUtils = require("./utils/LocalStorageUtils"); var StateIds = require("./states/States"); var InitializeState = require("./states/InitializeState"); var MenuState = require("./states/MenuState"); var SettingsState = require("./states/SettingsState"); var LoadingState = require("./states/LoadingState"); var GameState = require("./states/GameState") var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS, 'phaser-example'); window.Game = game; window.onresize = function() { Game.scale.setGameSize(window.innerWidth, window.innerHeight); } game.state.add(StateIds.INITIALIZE_STATE_ID, new InitializeState(game), true); game.state.add(StateIds.MENU_STATE_ID, new MenuState(game)); game.state.add(StateIds.SETTINGS_STATE_ID, new SettingsState(game)); game.state.add(StateIds.LOADING_STATE_ID, new LoadingState(game)); game.state.add(StateIds.LOADING_STATE_ID, new GameState(game));
Remove isSupported check: cookie fallback appears to be automatic From the https://github.com/grevory/angular-local-storage#get docs: > If local storage is not supported, use cookies instead.
'use strict'; /** * @ngdoc directive * @name vlui.directive:modal * @description * # modal */ angular.module('vlui') .directive('welcomeModal', function (Modals, localStorageService) { return { templateUrl: 'welcomemodal/welcomemodal.html', restrict: 'E', transclude: true, scope: true, link: function(scope/*, element, attrs*/) { // Determine whether the modal has been shown before var modalHasBeenShown = localStorageService.get('welcomeModalShown'); if ( ! modalHasBeenShown ) { scope.showWelcomeModal = true; localStorageService.set('welcomeModalShown', true); } } }; });
'use strict'; /** * @ngdoc directive * @name vlui.directive:modal * @description * # modal */ angular.module('vlui') .directive('welcomeModal', function (Modals, localStorageService) { return { templateUrl: 'welcomemodal/welcomemodal.html', restrict: 'E', transclude: true, scope: true, link: function(scope/*, element, attrs*/) { if ( ! localStorageService.isSupported ) { // How do we handle cases where localStorage is not supported? return; } // Determine whether the modal has been shown before var modalHasBeenShown = localStorageService.get('welcomeModalShown'); if ( ! modalHasBeenShown ) { scope.showWelcomeModal = true; localStorageService.set('welcomeModalShown', true); } } }; });
Remove undefined version from CLI
import 'babel-polyfill'; import fs from 'fs'; import readline from 'readline'; import program from 'commander'; import { observer as globalObserver } from '../../common/utils/observer'; import { createInterpreter } from './CliTools'; const log = (...args) => console.log(`${new Date().toLocaleTimeString()}:`, ...args); // eslint-disable-line no-console process.on('unhandledRejection', e => log('Unhandled Rejection:', e)); setInterval(() => {}, 2147483647); // Keep node alive let filename; program .usage('[filename]') .arguments('[filename]') .action(fn => { filename = fn; }) .parse(process.argv); const lineReader = readline.createInterface({ input: filename ? fs.createReadStream(filename) : process.stdin, }); let code = ''; const interpreter = createInterpreter(); globalObserver.register('Error', e => log(e)); globalObserver.register('Notify', ({ className, message }) => log(`${className.toUpperCase()}: ${message}`)); lineReader .on('line', line => { code += `${line}\n`; }) .on('error', e => log(e)) .on('close', () => interpreter .run(code) .then(v => log(v.data)) .catch(e => log(e)) );
import 'babel-polyfill'; import fs from 'fs'; import readline from 'readline'; import program from 'commander'; import { observer as globalObserver } from '../../common/utils/observer'; import { version } from '../../../package.json'; import { createInterpreter } from './CliTools'; const log = (...args) => console.log(`${new Date().toLocaleTimeString()}:`, ...args); // eslint-disable-line no-console process.on('unhandledRejection', e => log('Unhandled Rejection:', e)); setInterval(() => {}, 2147483647); // Keep node alive let filename; program .version(version) .usage('[filename]') .arguments('[filename]') .action(fn => { filename = fn; }) .parse(process.argv); const lineReader = readline.createInterface({ input: filename ? fs.createReadStream(filename) : process.stdin, }); let code = ''; const interpreter = createInterpreter(); globalObserver.register('Error', e => log(e)); globalObserver.register('Notify', ({ className, message }) => log(`${className.toUpperCase()}: ${message}`)); lineReader .on('line', line => { code += `${line}\n`; }) .on('error', e => log(e)) .on('close', () => interpreter .run(code) .then(v => log(v.data)) .catch(e => log(e)) );
Make sure base tag is not added
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Test for pydbus instead of dbus on startup
from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '1.4.0' class Extension(ext.Extension): dist_name = 'Mopidy-MPRIS' ext_name = 'mpris' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_schema() schema['desktop_file'] = config.Path() schema['bus_type'] = config.String(choices=['session', 'system']) return schema def validate_environment(self): try: import pydbus # noqa except ImportError as e: raise exceptions.ExtensionError('pydbus library not found', e) def setup(self, registry): from .frontend import MprisFrontend registry.add('frontend', MprisFrontend)
from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '1.4.0' class Extension(ext.Extension): dist_name = 'Mopidy-MPRIS' ext_name = 'mpris' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_schema() schema['desktop_file'] = config.Path() schema['bus_type'] = config.String(choices=['session', 'system']) return schema def validate_environment(self): try: import dbus # noqa except ImportError as e: raise exceptions.ExtensionError('dbus library not found', e) def setup(self, registry): from .frontend import MprisFrontend registry.add('frontend', MprisFrontend)
Fix formatting for hours greater than 9
function pad(num, size) { var s = '0000' + num return s.substring(s.length - size) } function capitalize(s) { return s[0].toUpperCase() + s.slice(1) } export function formatTime(time) { let h, m, s, ms = 0 var newTime = '' h = Math.floor( time / (60 * 60) ) time = time % (60 * 60) m = Math.floor( time / (60) ) time = time % (60) s = Math.floor( time ) ms = time % 1 newTime = pad(m, 2) + ':' + pad(s, 2) + '.' + (ms.toString() + '00').substring(2, 4) if (h !== 0) { newTime = h + ':' + newTime } return newTime } export function prettyZoneName(zoneType, index) { if (zoneType === 'map') { return 'Map Run' } else { return capitalize(zoneType) + ' ' + index } } export function mapScreenshot(name, size) { return `http://tempus.site.nfoservers.com/web/screenshots/raw/${name}_${size}.jpeg` }
function pad(num, size) { var s = '0000' + num return s.substring(s.length - size) } function capitalize(s) { return s[0].toUpperCase() + s.slice(1) } export function formatTime(time) { let h, m, s, ms = 0 var newTime = '' h = Math.floor( time / (60 * 60) ) time = time % (60 * 60) m = Math.floor( time / (60) ) time = time % (60) s = Math.floor( time ) ms = time % 1 newTime = pad(m, 2) + ':' + pad(s, 2) + '.' + (ms.toString() + '00').substring(2, 4) if (h !== 0) { newTime = pad(h, 1) + ':' + newTime } return newTime } export function prettyZoneName(zoneType, index) { if (zoneType === 'map') { return 'Map Run' } else { return capitalize(zoneType) + ' ' + index } } export function mapScreenshot(name, size) { return `http://tempus.site.nfoservers.com/web/screenshots/raw/${name}_${size}.jpeg` }
Use django TestCase in tutorial send email test It was using regular Python unittest.TestCase for some reason, resulting in leaving old BulkEmail objects in the database that other tests weren't expecting.
"""Test for the tutorials.utils package""" import datetime from mock import patch from django.template import Template from django.test import TestCase from pycon.bulkemail.models import BulkEmail from ..utils import queue_email_message today = datetime.date.today() class TestSendEmailMessage(TestCase): @patch('django.core.mail.message.EmailMessage.send') @patch('pycon.tutorials.utils.get_template') def test_send_email_message(self, get_template, send_mail): # queue_email_message comes up with the expected template names # and calls send_mail with the expected arguments test_template = Template("test template") get_template.return_value = test_template context = {'a': 1, 'b': 2} queue_email_message("TESTNAME", "from_address", ["1", "2"], [], context) args, kwargs = get_template.call_args_list[0] expected_template_name = "tutorials/email/TESTNAME/subject.txt" self.assertEqual(expected_template_name, args[0]) args, kwargs = get_template.call_args_list[1] expected_template_name = "tutorials/email/TESTNAME/body.txt" self.assertEqual(expected_template_name, args[0]) # Creates a BulkEmail object self.assertEqual(1, BulkEmail.objects.count())
"""Test for the tutorials.utils package""" import datetime import unittest from mock import patch from django.template import Template from pycon.bulkemail.models import BulkEmail from ..utils import queue_email_message today = datetime.date.today() class TestSendEmailMessage(unittest.TestCase): @patch('django.core.mail.message.EmailMessage.send') @patch('pycon.tutorials.utils.get_template') def test_send_email_message(self, get_template, send_mail): # queue_email_message comes up with the expected template names # and calls send_mail with the expected arguments test_template = Template("test template") get_template.return_value = test_template context = {'a': 1, 'b': 2} queue_email_message("TESTNAME", "from_address", ["1", "2"], [], context) args, kwargs = get_template.call_args_list[0] expected_template_name = "tutorials/email/TESTNAME/subject.txt" self.assertEqual(expected_template_name, args[0]) args, kwargs = get_template.call_args_list[1] expected_template_name = "tutorials/email/TESTNAME/body.txt" self.assertEqual(expected_template_name, args[0]) # Creates a BulkEmail object self.assertEqual(1, BulkEmail.objects.count())
Add requirements for developers necessary for tests
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1', 'requests'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1', 'requests'], extras_require={ 'dev': ['sphinx_rtd_theme', 'pytest']})
Use golang parser for .hxx and .cxx files
package plaintext import ( "strings" ) // returns the mimetype of the full filename if none func getSuffix(filename string) string { idx := strings.LastIndex(filename, ".") if idx == -1 || idx+1 == len(filename) { return filename } return filename[idx+1:] } // ExtractorByFilename returns an plaintext extractor based on // filename heuristic func ExtractorByFilename(filename string) (Extractor, error) { var e Extractor var err error switch getSuffix(filename) { case "md": e, err = NewMarkdownText() case "html": e, err = NewHTMLText() case "go", "h", "c", "java", "hxx", "cxx": e, err = NewGolangText() default: e, err = NewIdentity() } if err != nil { return nil, err } return e, nil }
package plaintext import ( "strings" ) // returns the mimetype of the full filename if none func getSuffix(filename string) string { idx := strings.LastIndex(filename, ".") if idx == -1 || idx+1 == len(filename) { return filename } return filename[idx+1:] } // ExtractorByFilename returns an plaintext extractor based on // filename heuristic func ExtractorByFilename(filename string) (Extractor, error) { var e Extractor var err error switch getSuffix(filename) { case "md": e, err = NewMarkdownText() case "html": e, err = NewHTMLText() case "go", "h", "c", "java": e, err = NewGolangText() default: e, err = NewIdentity() } if err != nil { return nil, err } return e, nil }
Use card display store from Guild ball app
import { createReducer } from 'redux-immutablejs'; import { createSelector } from 'reselect'; import Immutable from 'immutable'; import constants from './constants'; // Constants const { CHANGE_CARD, FLIP_CARD, } = constants; // Initial State const initialState = Immutable.fromJS({ playerName: '', showFront: true, }); // Selectors const cardDisplayState = state => state.cardDisplayStore; export const getCurrentCard = createSelector( cardDisplayState, c => c.get('playerName'), ); export const showCardFront = createSelector( cardDisplayState, c => c.get('showFront'), ); // Actions export const changeCard = playerName => dispatch => dispatch({ type: CHANGE_CARD, payload: { playerName, showFront: true, }, }); export const flipCard = () => (dispatch, getState) => dispatch({ type: FLIP_CARD, payload: { showFront: !showCardFront(getState), }, }); // Reducers export default createReducer(initialState, { [CHANGE_CARD]: (state, action) => state.merge(Immutable.fromJS(action.payload)), [FLIP_CARD]: (state, action) => state.merge(Immutable.fromJS(action.payload)), });
import { createReducer } from 'redux-immutablejs'; import { createSelector } from 'reselect'; import Immutable from 'immutable'; import constants from './constants'; // Constants const { FLIP_CARD, } = constants; // Initial State const initialState = Immutable.fromJS({ showFront: false, }); // Selectors const cardDisplayState = state => state.cardDisplayStore; export const showCardFront = createSelector( cardDisplayState, c => c.get('showFront'), ); // Actions export const flipCard = () => (dispatch, getState) => dispatch({ type: FLIP_CARD, payload: { showFront: !showCardFront(getState()), }, }); export const flipCardDown = () => dispatch => dispatch({ type: FLIP_CARD, payload: { showFront: false, }, }); // Reducers export default createReducer(initialState, { [FLIP_CARD]: (state, action) => state.merge(Immutable.fromJS(action.payload)), });