text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Move SCA2 outside of link in acknowledgment
import React from 'react' import PropTypes from 'prop-types' import { siteTitle } from '../../../App' import Help from '../../../components/Help' import Notice from '../../../components/Notice' import { morphInfo } from '../' const MorphHelp = props => ( <Help toolInfo={morphInfo}> <Notice>This tool is still in development.</Notice> <h3 id='using'> Using {siteTitle} {morphInfo.title} </h3> <h3 id='acknowledgments'>Acknowledgments</h3> <p> Much thanks should be given to Mark Rosenfelder and{' '} <a href='http://www.zompist.com/sca2.html' target='_blank' rel='noopener noreferrer' > the Sound Change Applier 2 </a>{' '} (SCA <sup>2</sup> ). {siteTitle} {morphInfo.title} was mainly built as a modernized and updated version of SCA <sup>2</sup>. </p> </Help> ) MorphHelp.propTypes = { classes: PropTypes.object } export default MorphHelp
import React from 'react' import PropTypes from 'prop-types' import { siteTitle } from '../../../App' import Help from '../../../components/Help' import Notice from '../../../components/Notice' import { morphInfo } from '../' const MorphHelp = props => ( <Help toolInfo={morphInfo}> <Notice>This tool is still in development.</Notice> <h3 id='using'> Using {siteTitle} {morphInfo.title} </h3> <h3 id='acknowledgments'>Acknowledgments</h3> <p> Much thanks should be given to Mark Rosenfelder and{' '} <a href='http://www.zompist.com/sca2.html' target='_blank' rel='noopener noreferrer' > the Sound Change Applier 2 (SCA <sup>2</sup>) </a> . {siteTitle} {morphInfo.title} was mainly built as a modernized and updated version of SCA <sup>2</sup>. </p> </Help> ) MorphHelp.propTypes = { classes: PropTypes.object } export default MorphHelp
Add job id and enable/disabled status if the job already exists
from django.utils import timezone from django.core.management.base import BaseCommand, CommandError from scheduler.models import RepeatableJob class Command(BaseCommand): help = 'Returns the API token for a given username. If one does not exist, a token is first created.' def handle(self, *args, **options): job, created = RepeatableJob.objects.get_or_create( callable = 'mrbelvedereci.build.tasks.check_waiting_builds', enabled = True, name = 'check_waiting_builds', queue = 'short', defaults={ 'interval': 1, 'interval_unit': 'minutes', 'scheduled_time': timezone.now(), } ) if created: self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds with id {}'.format(job.id))) else: self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds with id {} already exists and is {}.'.format(job.id, 'enabled' if job.enabled else 'disabled')))
from django.utils import timezone from django.core.management.base import BaseCommand, CommandError from scheduler.models import RepeatableJob class Command(BaseCommand): help = 'Returns the API token for a given username. If one does not exist, a token is first created.' def handle(self, *args, **options): job, created = RepeatableJob.objects.get_or_create( callable = 'mrbelvedereci.build.tasks.check_waiting_builds', enabled = True, name = 'check_waiting_builds', queue = 'short', defaults={ 'interval': 1, 'interval_unit': 'minutes', 'scheduled_time': timezone.now(), } ) if created: self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds')) else: self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds already exists'))
Update ServiceProvider & build tools
<?php namespace AppsLibX\JwtAuth; use Illuminate\Support\ServiceProvider; class JwtAuthServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
<?php namespace JwtAuth; use Illuminate\Support\ServiceProvider; class JwtAuthServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
Fix error in catch source file path.
Plugin.registerCompiler( { extensions: ["md"], isTemplate: true }, () => new MdCompiler ); export class MdCompiler extends CachingCompiler { constructor() { super({ compilerName: 'md', defaultCacheSize: 1024*1024*10, }); } getCacheKey(inputFile) { return inputFile.getSourceHash(); } compileResultSize(compileResult) { return compileResult.length; } compileOneFile(inputFile) { const content = inputFile.getContentsAsString().toString('utf8'); let results; try { results = markdown_scanner.scan(content); } catch (e) { if (! (e instanceof markdown_scanner.ParseError)) { throw e; } inputFile.error({ message: e.message, sourcePath: inputFile.getPathInPackage(), line: e.line }); } return results; } addCompileResult(inputFile, compileResult) { if (! (compileResult && compileResult.js)) return; inputFile.addJavaScript({ path: inputFile.getPathInPackage() + '.js', data: compileResult.js, }); } }
Plugin.registerCompiler( { extensions: ["md"], isTemplate: true }, () => new MdCompiler ); export class MdCompiler extends CachingCompiler { constructor() { super({ compilerName: 'md', defaultCacheSize: 1024*1024*10, }); } getCacheKey(inputFile) { return inputFile.getSourceHash(); } compileResultSize(compileResult) { return compileResult.length; } compileOneFile(inputFile) { const content = inputFile.getContentsAsString().toString('utf8'); let results; try { results = markdown_scanner.scan(content); } catch (e) { if (! (e instanceof markdown_scanner.ParseError)) { throw e; } inputFile.error({ message: e.message, sourcePath: files.inputPath, line: e.line }); } return results; } addCompileResult(inputFile, compileResult) { if (! (compileResult && compileResult.js)) return; inputFile.addJavaScript({ path: inputFile.getPathInPackage() + '.js', data: compileResult.js, }); } }
Backgroundjobs: Fix bug in admin interface
<?php /** * ownCloud * * @author Jakob Sack * @copyright 2012 Jakob Sack owncloud@jakobsack.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ // Init owncloud require_once('../../lib/base.php'); OC_Util::checkAdminUser(); OCP\JSON::callCheck(); OC_Appconfig::setValue( 'core', 'backgroundjobs_mode', $_POST['mode'] ); echo 'true';
<?php /** * ownCloud * * @author Jakob Sack * @copyright 2012 Jakob Sack owncloud@jakobsack.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ // Init owncloud require_once('../../lib/base.php'); OC_Util::checkAdminUser(); OCP\JSON::callCheck(); OC_Appconfig::setValue( 'core', 'backgroundjob_mode', $_POST['mode'] ); echo 'true';
Fix deprecation of `new Buffer()`
import { Transform } from 'stream'; import util from 'util'; import tipograph from './tipograph'; util.inherits(TipographStream, Transform); function TipographStream(options, callback) { if (!(this instanceof TipographStream)) { return new TipographStream(options, callback); } Transform.call(this); this._data = ''; if (typeof options === 'function') { this._typo = tipograph(); this._callback = options; } else { this._typo = tipograph(options); this._callback = callback; } } TipographStream.prototype._transform = function (chunk, enc, done) { this._data += chunk; done(); }; TipographStream.prototype._flush = function (done) { this.push(Buffer.from(this._typo(this._data, this._callback))); done(); }; export default function (options) { return new TipographStream(options); }
import { Transform } from 'stream'; import util from 'util'; import tipograph from './tipograph'; util.inherits(TipographStream, Transform); function TipographStream(options, callback) { if (!(this instanceof TipographStream)) { return new TipographStream(options, callback); } Transform.call(this); this._data = ''; if (typeof options === 'function') { this._typo = tipograph(); this._callback = options; } else { this._typo = tipograph(options); this._callback = callback; } } TipographStream.prototype._transform = function (chunk, enc, done) { this._data += chunk; done(); }; TipographStream.prototype._flush = function (done) { this.push(new Buffer(this._typo(this._data, this._callback))); done(); }; export default function (options) { return new TipographStream(options); }
tests: Make printing of floats hopefully more portable.
try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) elif isinstance(o, float): print('%.3f' % o) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my_print(json.loads('1e2')) my_print(json.loads('-2')) my_print(json.loads('-2.3')) my_print(json.loads('-2e3')) my_print(json.loads('-2e-3')) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads('[]')) my_print(json.loads('[null]')) my_print(json.loads('[null,false,true]')) my_print(json.loads(' [ null , false , true ] ')) my_print(json.loads('{}')) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my_print(json.loads('1e2')) my_print(json.loads('-2')) my_print(json.loads('-2.3')) my_print(json.loads('-2e3')) my_print(json.loads('-2e-3')) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads('[]')) my_print(json.loads('[null]')) my_print(json.loads('[null,false,true]')) my_print(json.loads(' [ null , false , true ] ')) my_print(json.loads('{}')) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
Add a Grunt task to produce a minified version of clever-video.js.
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: { build: { src: "build" } }, copy: { build: { files: [ { expand: true, cwd: 'source/', src: ['demo/**/*.html', 'demo/**/*.css', 'demo/**/*.js', 'clever-video.js'], dest: 'build/' } ] } }, uglify: { build: { files: { 'build/clever-video.min.js': ['source/clever-video.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('build', ['clean', 'copy']); grunt.registerTask('default', ['build']); };
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: { build: { src: "build" } }, copy: { build: { files: [ { expand: true, cwd: 'source/', src: ['demo/**/*.html', 'demo/**/*.css', 'demo/**/*.js', 'clever-video.js'], dest: 'build/' } ] } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerTask('build', ['clean', 'copy']); grunt.registerTask('default', ['build']); };
Fix the default LDAP properties to match the configuration documentation.
#!/usr/bin/env node // // NodeJS script that implements an authentication daemon for eJabberd. // 'use strict'; var assert = require('assert'), etc = require('etc'), yml = require('etc-yaml'), conf = etc().use(yml).etc().add({ "ejabberd-auth": { method: 'ldap', ldap: { uri: 'ldap://127.0.0.1', filter: '(userPassword=*)', uuidAttr: 'uuid' } } }), ldapConf = conf.get('ejabberd-auth:ldap'); assert.equal(conf.get('ejabberd-auth:method'), 'ldap', "LDAP is currently the only supported method."); require('../lib/auth-ldap').start(ldapConf);
#!/usr/bin/env node // // NodeJS script that implements an authentication daemon for eJabberd. // 'use strict'; var assert = require('assert'), etc = require('etc'), yml = require('etc-yaml'), conf = etc().use(yml).etc().add({ "ejabberd-auth": { method: 'ldap', ldap: { uri: 'ldap://127.0.0.1', filter: '(objectClass=*)' } } }), ldapConf = conf.get('ejabberd-auth:ldap'); assert.equal(conf.get('ejabberd-auth:method'), 'ldap', "LDAP is currently the only supported method."); require('../lib/auth-ldap').start(ldapConf);
Add utopic to supported series
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package testing import ( "time" "launchpad.net/juju-core/utils" ) // ShortWait is a reasonable amount of time to block waiting for something that // shouldn't actually happen. (as in, the test suite will *actually* wait this // long before continuing) const ShortWait = 50 * time.Millisecond // LongWait is used when something should have already happened, or happens // quickly, but we want to make sure we just haven't missed it. As in, the test // suite should proceed without sleeping at all, but just in case. It is long // so that we don't have spurious failures without actually slowing down the // test suite const LongWait = 10 * time.Second var LongAttempt = &utils.AttemptStrategy{ Total: LongWait, Delay: ShortWait, } // SupportedSeries lists the series known to Juju. var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty", "utopic"}
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package testing import ( "time" "launchpad.net/juju-core/utils" ) // ShortWait is a reasonable amount of time to block waiting for something that // shouldn't actually happen. (as in, the test suite will *actually* wait this // long before continuing) const ShortWait = 50 * time.Millisecond // LongWait is used when something should have already happened, or happens // quickly, but we want to make sure we just haven't missed it. As in, the test // suite should proceed without sleeping at all, but just in case. It is long // so that we don't have spurious failures without actually slowing down the // test suite const LongWait = 10 * time.Second var LongAttempt = &utils.AttemptStrategy{ Total: LongWait, Delay: ShortWait, } // SupportedSeries lists the series known to Juju. var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty"}
Trim the output line, since we're erasing to EOL anyway Currently renderTemplate ALWAYS produces a string of the length you specify, even if it has to pad stuff to produce that. This renders the "erase-to-eol" command meaningless, so we either should ditch that or we should trim the renderTemplate output. Right now I'm opting for the latter, but testing the former would be useful too.
'use strict' var consoleStrings = require('./console-strings.js') var renderTemplate = require('./render-template.js') var validate = require('aproba') var Plumbing = module.exports = function (theme, template, width) { if (!width) width = 80 validate('OAN', [theme, template, width]) this.showing = false this.theme = theme this.width = width this.template = template } Plumbing.prototype = {} Plumbing.prototype.setTheme = function (theme) { validate('O', [theme]) this.theme = theme } Plumbing.prototype.setTemplate = function (template) { validate('A', [template]) this.template = template } Plumbing.prototype.setWidth = function (width) { validate('N', [width]) this.width = width } Plumbing.prototype.hide = function () { return consoleStrings.gotoSOL() + consoleStrings.eraseLine() } Plumbing.prototype.hideCursor = consoleStrings.hideCursor Plumbing.prototype.showCursor = consoleStrings.showCursor Plumbing.prototype.show = function (status) { var values = Object.create(this.theme) for (var key in status) { values[key] = status[key] } return renderTemplate(this.width, this.template, values).trim() + consoleStrings.eraseLine() + consoleStrings.gotoSOL() }
'use strict' var consoleStrings = require('./console-strings.js') var renderTemplate = require('./render-template.js') var validate = require('aproba') var Plumbing = module.exports = function (theme, template, width) { if (!width) width = 80 validate('OAN', [theme, template, width]) this.showing = false this.theme = theme this.width = width this.template = template } Plumbing.prototype = {} Plumbing.prototype.setTheme = function (theme) { validate('O', [theme]) this.theme = theme } Plumbing.prototype.setTemplate = function (template) { validate('A', [template]) this.template = template } Plumbing.prototype.setWidth = function (width) { validate('N', [width]) this.width = width } Plumbing.prototype.hide = function () { return consoleStrings.gotoSOL() + consoleStrings.eraseLine() } Plumbing.prototype.hideCursor = consoleStrings.hideCursor Plumbing.prototype.showCursor = consoleStrings.showCursor Plumbing.prototype.show = function (status) { var values = Object.create(this.theme) for (var key in status) { values[key] = status[key] } return renderTemplate(this.width, this.template, values) + consoleStrings.eraseLine() + consoleStrings.gotoSOL() }
Add key path config to example settings file
<?php // Maximum number of posts to show on a journal page $postsVisibleOnPage = 5; // Whether in production mode or not $isProduction = false; // Calculate database file name and path from production switch $databaseFileName = $isProduction ? 'production' : 'debug'; $databaseFilePath = './conf/' . $databaseFileName . '.sqlite'; // Prefix for database tables $tablePrefix = 'blog_'; // Aggregated settings array - required for running the backend $settings = array( 'Database' => array('Prefix' => $tablePrefix, 'Database' => $databaseFilePath), 'Formats' => array('ShortDateTime' => 'd M Y, H:i', 'LongDateTime' => 'l, jS F Y, H:i T'), 'Defaults' => array('PostsVisible' => $postsVisibleOnPage), 'Environment' => array('Production' => $isProduction), 'URLs' => array('GalleryRoot' => 'http://my.site/gallery/'), 'Paths' => array('KeyRoot' => '../../private-location/') );
<?php // Maximum number of posts to show on a journal page $postsVisibleOnPage = 5; // Whether in production mode or not $isProduction = false; // Calculate database file name and path from production switch $databaseFileName = $isProduction ? 'production' : 'debug'; $databaseFilePath = './conf/' . $databaseFileName . '.sqlite'; // Prefix for database tables $tablePrefix = 'blog_'; // Aggregated settings array - required for running the backend $settings = array( 'Database' => array('Prefix' => $tablePrefix, 'Database' => $databaseFilePath), 'Formats' => array('ShortDateTime' => 'd M Y, H:i', 'LongDateTime' => 'l, jS F Y, H:i T'), 'Defaults' => array('PostsVisible' => $postsVisibleOnPage), 'Environment' => array('Production' => $isProduction), 'URLs' => array('GalleryRoot' => 'http://my.site/gallery/') );
Fix linkage in the RSS feed
""" Generate an RSS feed of published crosswords from staff users. Uses the built-in feed framework. There's no attempt to send the actual crossword, it's just a message indicating that a new one is available. """ from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils import timezone from puzzle.models import Puzzle class PuzzleFeed(Feed): """RSS feed of new puzzles from the staff.""" #pylint: disable=no-self-use,missing-docstring title = 'Three Pins' link = 'http://www.threepins.org' description = 'A cryptic crossword outlet.' def items(self): return Puzzle.objects.filter(user__is_staff=True, pub_date__lte=timezone.now()).order_by('-pub_date')[:5] def item_title(self, item): return 'Crossword #' + str(item.number) def item_description(self, item): return 'Crossword #' + str(item.number) + ' is now available.' def item_link(self, item): return reverse('puzzle', kwargs={'author': item.user.username, 'number': item.number}) def item_pubdate(self, item): return item.pub_date
""" Generate an RSS feed of published crosswords from staff users. Uses the built-in feed framework. There's no attempt to send the actual crossword, it's just a message indicating that a new one is available. """ from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils import timezone from puzzle.models import Puzzle class PuzzleFeed(Feed): """RSS feed of new puzzles from the staff.""" #pylint: disable=no-self-use,missing-docstring title = 'Three Pins' link = 'http://www.threepins.org' description = 'A cryptic crossword outlet.' def items(self): return Puzzle.objects.filter(user__is_staff=True, pub_date__lte=timezone.now()).order_by('-pub_date')[:5] def item_title(self, item): return 'Crossword #' + str(item.number) def item_description(self, item): return 'Crossword #' + str(item.number) + ' is now available.' def item_link(self, item): return reverse('puzzle', args=[item.number]) def item_pubdate(self, item): return item.pub_date
Serve: Allow first argument as directory Now you can call `serve dir` or `server -d dir`.
// Copyright (C) 2015 Thomas de Zeeuw. // // Licensed onder the MIT license that can be found in the LICENSE file. package main import ( "flag" "fmt" "net/http" "os" "path/filepath" ) const ( portDesc = "The port to listen on, defaults to 8000" dirDesc = "The directory to serve, defaults to the working directory" ) var ( port string dir string ) func init() { flag.StringVar(&port, "port", "8000", portDesc) flag.StringVar(&port, "p", "8000", portDesc) flag.StringVar(&dir, "directory", "", dirDesc) flag.StringVar(&dir, "d", "", dirDesc) } func main() { flag.Parse() // Either grap the directory from the -d flag or use the first argument. if flag.Arg(0) != "" && dir == "" { dir = flag.Arg(0) } dir = filepath.Join(".", dir) nameDir := dir if nameDir == "." { nameDir = "current directory" } fmt.Printf("Serving directory %s, on port %s.\n", nameDir, port) err := http.ListenAndServe(":"+port, http.FileServer(http.Dir(dir))) if err != nil { os.Stderr.WriteString(err.Error()) } }
// Copyright (C) 2015 Thomas de Zeeuw. // // Licensed onder the MIT license that can be found in the LICENSE file. package main import ( "flag" "fmt" "net/http" "os" "path/filepath" ) const ( portDesc = "The port to listen on, defaults to 8000" dirDesc = "The directory to serve, defaults to the working directory" ) var ( port string dir string ) func init() { flag.StringVar(&port, "port", "8000", portDesc) flag.StringVar(&port, "p", "8000", portDesc) flag.StringVar(&dir, "directory", "", dirDesc) flag.StringVar(&dir, "d", "", dirDesc) } func main() { flag.Parse() dir = filepath.Join("./", dir) nameDir := dir if nameDir == "." { nameDir = "current directory" } fmt.Printf("Serving directory %s, on port %s.\n", nameDir, port) err := http.ListenAndServe(":"+port, http.FileServer(http.Dir(dir))) if err != nil { os.Stderr.WriteString(err.Error()) } }
Use Float.compare in java equals Reviewed By: astreet Differential Revision: D4531805 fbshipit-source-id: 723e15381e9fa39837a4c99f726501eda26af11b
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.yoga; import com.facebook.proguard.annotations.DoNotStrip; @DoNotStrip public class YogaValue { static final YogaValue UNDEFINED = new YogaValue(YogaConstants.UNDEFINED, YogaUnit.UNDEFINED); static final YogaValue ZERO = new YogaValue(0, YogaUnit.PIXEL); public final float value; public final YogaUnit unit; public YogaValue(float value, YogaUnit unit) { this.value = value; this.unit = unit; } @DoNotStrip YogaValue(float value, int unit) { this(value, YogaUnit.fromInt(unit)); } @Override public boolean equals(Object other) { if (other instanceof YogaValue) { final YogaValue otherValue = (YogaValue) other; if (unit == otherValue.unit) { return unit == YogaUnit.UNDEFINED || Float.compare(value, otherValue.value) == 0; } } return false; } @Override public int hashCode() { return Float.floatToIntBits(value) + unit.intValue(); } }
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.yoga; import com.facebook.proguard.annotations.DoNotStrip; @DoNotStrip public class YogaValue { static final YogaValue UNDEFINED = new YogaValue(YogaConstants.UNDEFINED, YogaUnit.UNDEFINED); static final YogaValue ZERO = new YogaValue(0, YogaUnit.PIXEL); public final float value; public final YogaUnit unit; public YogaValue(float value, YogaUnit unit) { this.value = value; this.unit = unit; } @DoNotStrip YogaValue(float value, int unit) { this(value, YogaUnit.fromInt(unit)); } @Override public boolean equals(Object other) { if (other instanceof YogaValue) { final YogaValue otherValue = (YogaValue) other; return value == otherValue.value && unit == otherValue.unit; } return false; } @Override public int hashCode() { return Float.floatToIntBits(value) + unit.intValue(); } }
Change environment variable names and add placeholders
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: """ Base configuration with values used in all configurations. """ SERVER_NAME = "localhost:5000" SECRET_KEY = os.getenv("MYDICTIONARY_SECRET_KEY") SQLALCHEMY_RECORD_QUERIES = True SQLALCHEMY_TRACK_MODIFICATIONS = True class DevelopmentConfig(Config): """ Development configuration. Activates the debugger and uses the database specified in the DEV_DATABASE_URL environment variable. """ DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv("MYDICTIONARY_DEV_DATABASE_URL") or \ "sqlite:///" + os.path.join(basedir, "dev_database.sqlite") class TestingConfig(Config): """ Testing configuration. Sets the testing flag to True and uses the database specified in the TEST_DATABASE_URL environment variable. """ TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv("MYDICTIONARY_TEST_DATABASE_URL") or \ "sqlite:///" + os.path.join(basedir, "test_database.sqlite") config = { "development": DevelopmentConfig, "testing": TestingConfig, "default": DevelopmentConfig }
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: """ Base configuration with values used in all configurations. """ SERVER_NAME = "localhost:5000" SECRET_KEY = os.getenv("SECRET_KEY") SQLALCHEMY_RECORD_QUERIES = True SQLALCHEMY_TRACK_MODIFICATIONS = True class DevelopmentConfig(Config): """ Development configuration. Activates the debugger and uses the database specified in the DEV_DATABASE_URL environment variable. """ DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv("DEV_DATABASE_URL") class TestingConfig(Config): """ Testing configuration. Sets the testing flag to True and uses the database specified in the TEST_DATABASE_URL environment variable. """ TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv("TEST_DATABASE_URL") config = { "development": DevelopmentConfig, "testing": TestingConfig, "default": DevelopmentConfig }
Fix typo in 'hide-pipeline' description
package commands import ( "fmt" "github.com/concourse/fly/commands/internal/displayhelpers" "github.com/concourse/fly/commands/internal/flaghelpers" "github.com/concourse/fly/rc" ) type HidePipelineCommand struct { Pipeline flaghelpers.PipelineFlag `short:"p" long:"pipeline" required:"true" description:"Pipeline to hide"` } func (command *HidePipelineCommand) Validate() error { return command.Pipeline.Validate() } func (command *HidePipelineCommand) Execute(args []string) error { err := command.Validate() if err != nil { return err } pipelineName := string(command.Pipeline) target, err := rc.LoadTarget(Fly.Target, Fly.Verbose) if err != nil { return err } err = target.Validate() if err != nil { return err } found, err := target.Team().HidePipeline(pipelineName) if err != nil { return err } if found { fmt.Printf("hid '%s'\n", pipelineName) } else { displayhelpers.Failf("pipeline '%s' not found\n", pipelineName) } return nil }
package commands import ( "fmt" "github.com/concourse/fly/commands/internal/displayhelpers" "github.com/concourse/fly/commands/internal/flaghelpers" "github.com/concourse/fly/rc" ) type HidePipelineCommand struct { Pipeline flaghelpers.PipelineFlag `short:"p" long:"pipeline" required:"true" description:"Pipeline to ide"` } func (command *HidePipelineCommand) Validate() error { return command.Pipeline.Validate() } func (command *HidePipelineCommand) Execute(args []string) error { err := command.Validate() if err != nil { return err } pipelineName := string(command.Pipeline) target, err := rc.LoadTarget(Fly.Target, Fly.Verbose) if err != nil { return err } err = target.Validate() if err != nil { return err } found, err := target.Team().HidePipeline(pipelineName) if err != nil { return err } if found { fmt.Printf("hid '%s'\n", pipelineName) } else { displayhelpers.Failf("pipeline '%s' not found\n", pipelineName) } return nil }
Modify crowdin_bot to only include languages that have >0 translations
"""Script to print list of all crowdin language codes for project.""" from crowdin_bot import api NS_DICT = { 'ns': "urn:oasis:names:tc:xliff:document:1.2" } def get_project_languages(): """Get list of crowdin language codes. Returns: (list) list of project crowdin language codes """ active_languages = [] trans_status = api.api_call_json("status") for language in trans_status: # Check language has actually had some translation done if int(language["words_approved"]) > 0: active_languages.append(language["code"]) return active_languages if __name__ == "__main__": for language in get_project_languages(): print(language)
"""Script to print list of all crowdin language codes for project.""" from crowdin_bot import api NS_DICT = { 'ns': "urn:oasis:names:tc:xliff:document:1.2" } def get_project_languages(): """Get list of crowdin language codes. Returns: (list) list of project crowdin language codes """ info_xml = api.api_call_xml("info") languages = info_xml.find('languages') translatable_languages = [] for language in languages: # Check it's not the incontext pseudo language if language.find("can_translate").text == "1": translatable_languages.append(language.find('code').text) return translatable_languages if __name__ == "__main__": print('\n'.join(get_project_languages()))
Fix NPE in the enrollmentcoc api
package com.servinglynk.hmis.warehouse.service.converter; import com.servinglynk.hmis.warehouse.core.model.EnrollmentCoc; public class EnrollmentCocConverter extends BaseConverter { public static com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc modelToEntity (EnrollmentCoc model ,com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) { if(entity==null) entity = new com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc(); entity.setId(model.getEnrollmentCocId()); entity.setCocCode(model.getCocCode()); return entity; } public static EnrollmentCoc entityToModel (com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) { EnrollmentCoc model = new EnrollmentCoc(); model.setEnrollmentCocId(entity.getId()); model.setCocCode(entity.getCocCode()); model.setEnrollmentId(entity.getEnrollmentid() !=null ? entity.getEnrollmentid().getId() : null); model.setProjectCocId(entity.getProjectCoc() !=null ? entity.getProjectCoc().getId() : null); model.setDateCreated(entity.getDateCreated()); model.setDateUpdated(entity.getDateUpdated()); return model; } }
package com.servinglynk.hmis.warehouse.service.converter; import com.servinglynk.hmis.warehouse.core.model.EnrollmentCoc; public class EnrollmentCocConverter extends BaseConverter { public static com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc modelToEntity (EnrollmentCoc model ,com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) { if(entity==null) entity = new com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc(); entity.setId(model.getEnrollmentCocId()); entity.setCocCode(model.getCocCode()); return entity; } public static EnrollmentCoc entityToModel (com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) { EnrollmentCoc model = new EnrollmentCoc(); model.setEnrollmentCocId(entity.getId()); model.setCocCode(entity.getCocCode()); model.setEnrollmentId(entity.getEnrollmentid().getId()); model.setProjectCocId(entity.getProjectCoc().getId()); model.setDateCreated(entity.getDateCreated()); model.setDateUpdated(entity.getDateUpdated()); return model; } }
Make the database JSON easier to read.
from __future__ import print_function from tinydb import TinyDB from core.models import Movie TABLE_POPULAR = "popular" TABLE_NAME_TO_ID = "name_to_id_mapping" TABLE_MOVIES = "movies" class Application(object): def __init__(self, settings): database = TinyDB(settings["DATABASE"], indent=4) self.Movie = Movie(database, TABLE_MOVIES) self.settings = settings def setting(self, key): return self.settings[key] def debug(self, message): if self.settings.get("DEBUG", False): print(message) def output(self, message): print(message) def debug_or_dot(self, message): if self.settings.get("DEBUG", False): print(message) else: print(".", end="")
from __future__ import print_function from tinydb import TinyDB from core.models import Movie TABLE_POPULAR = "popular" TABLE_NAME_TO_ID = "name_to_id_mapping" TABLE_MOVIES = "movies" class Application(object): def __init__(self, settings): database = TinyDB(settings["DATABASE"]) self.Movie = Movie(database, TABLE_MOVIES) self.settings = settings def setting(self, key): return self.settings[key] def debug(self, message): if self.settings.get("DEBUG", False): print(message) def output(self, message): print(message) def debug_or_dot(self, message): if self.settings.get("DEBUG", False): print(message) else: print(".", end="")
Add state as being anything
/* @flow */ const hasFunctionNature = (maybe: any) => typeof maybe === 'function' const hasStringNature = (maybe: any) => typeof maybe === 'string' type Reducer = (state: any, action: Object) => any export default function reswitch (...args: Array<string | Function | Reducer | Object>): Reducer { const defaultReducer = (state: any) => state const hasDefaultReducer = ( (args.length % 2) && hasFunctionNature(args[args.length - 1]) ) if (args.length % 2 === 1) { if (hasStringNature(args[0]) && !hasDefaultReducer) { return defaultReducer } } if (!hasDefaultReducer) { args.push(defaultReducer) } return (state: any, action: Object) => { const argIndex = args.findIndex(arg => arg === action) + 1 || args.length - 1 if (hasFunctionNature(args[argIndex])) { return args[argIndex](state, action) } return args[argIndex] } }
/* @flow */ const hasFunctionNature = (maybe: any) => typeof maybe === 'function' const hasStringNature = (maybe: any) => typeof maybe === 'string' type Reducer = (state: any, action: Object) => any export default function reswitch (...args: Array<string | Function | Reducer | Object>): Reducer { const defaultReducer = (state: any) => state const hasDefaultReducer = ( (args.length % 2) && hasFunctionNature(args[args.length - 1]) ) if (args.length % 2 === 1) { if (hasStringNature(args[0]) && !hasDefaultReducer) { return defaultReducer } } if (!hasDefaultReducer) { args.push(defaultReducer) } return (state, action: Object) => { const argIndex = args.findIndex(arg => arg === action) + 1 || args.length - 1 if (hasFunctionNature(args[argIndex])) { return args[argIndex](state, action) } return args[argIndex] } }
Make inkEffect values public (used for later)
package net.jselby.escapists.data.chunks; import net.jselby.escapists.data.Chunk; import net.jselby.escapists.util.ByteReader; /** * The LayerEffects chunk is a set of LayerEffects applied on a particular layer. */ public class LayerEffects extends Chunk { @Override public void init(ByteReader buffer, int length) { LayerEffect[] effects = new LayerEffect[length / 20]; for (int i = 0; i < effects.length; i++) { effects[i] = new LayerEffect(buffer); } } /** * A LayerEffect is a special effect applied upon a particular layer. */ private class LayerEffect { public final long inkEffect; public final long inkEffectValue; public LayerEffect(ByteReader buffer) { long pInkEffect = buffer.getUnsignedInt(); inkEffect = pInkEffect & 0xFFFF; inkEffectValue = buffer.getUnsignedInt(); } } }
package net.jselby.escapists.data.chunks; import net.jselby.escapists.data.Chunk; import net.jselby.escapists.util.ByteReader; /** * The LayerEffects chunk is a set of LayerEffects applied on a particular layer. */ public class LayerEffects extends Chunk { @Override public void init(ByteReader buffer, int length) { LayerEffect[] effects = new LayerEffect[length / 20]; for (int i = 0; i < effects.length; i++) { effects[i] = new LayerEffect(buffer); } } /** * A LayerEffect is a special effect applied upon a particular layer. */ private class LayerEffect { private final long inkEffect; private final long inkEffectValue; public LayerEffect(ByteReader buffer) { long pInkEffect = buffer.getUnsignedInt(); inkEffect = pInkEffect & 0xFFFF; inkEffectValue = buffer.getUnsignedInt(); } } }
Remove class after editing details
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service( 'session' ), actions: { authenticate() { if( $( 'form' ).hasClass( 'shake' ) ) { return; } let { username, password } = this.getProperties( 'username', 'password' ); this.get( 'session' ).authenticate( 'authenticator:oauth2', username, password ).catch( (reason) => { var timeout; clearTimeout( timeout ); this.set( 'loginStatus', 'shake' ); $( 'input' ).addClass( 'wrong' ); timeout = setTimeout( function() { this.set( 'loginStatus', '' ); }.bind( this ), 1000); this.set( 'errorMessage', reason.error ); }); } }, checkError: function( top, which ) { var type = which === 'password' ? 'password' : 'text'; $( 'input[type="' + type + '"]' ).removeClass( 'wrong' ); }.observes( 'username', 'password' ) });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service( 'session' ), actions: { authenticate() { if( $( 'form' ).hasClass( 'shake' ) ) { return; } let { username, password } = this.getProperties( 'username', 'password' ); this.get( 'session' ).authenticate( 'authenticator:oauth2', username, password ).catch( (reason) => { var timeout; clearTimeout( timeout ); this.set( 'loginStatus', 'shake' ); $( 'input' ).addClass( 'wrong' ); timeout = setTimeout( function() { this.set( 'loginStatus', '' ); }.bind( this ), 1000); this.set( 'errorMessage', reason.error ); }); }, checkError: function( top, which ) { var type = which === 'password' ? 'password' : 'text'; $( 'input[type="' + type + '"]' ).removeClass( 'wrong' ); }.observes( 'username', 'password' ) } });
Improve error message on invalid conf key
from __future__ import annotations import functools from pathlib import Path from typing import Mapping import tomli DEFAULT_OPTS = { "wrap": "keep", "number": False, "end_of_line": "lf", } class InvalidConfError(Exception): """Error raised given invalid TOML or a key that is not valid for mdformat.""" @functools.lru_cache() def read_toml_opts(conf_dir: Path) -> Mapping: conf_path = conf_dir / ".mdformat.toml" if not conf_path.is_file(): parent_dir = conf_dir.parent if conf_dir == parent_dir: return {} return read_toml_opts(parent_dir) with open(conf_path, "rb") as f: try: toml_opts = tomli.load(f) except tomli.TOMLDecodeError as e: raise InvalidConfError(f"Invalid TOML syntax: {e}") for key in toml_opts: if key not in DEFAULT_OPTS: raise InvalidConfError( f"Invalid key {key!r} in {conf_path}." f" Keys must be one of {set(DEFAULT_OPTS)}." ) return toml_opts
from __future__ import annotations import functools from pathlib import Path from typing import Mapping import tomli DEFAULT_OPTS = { "wrap": "keep", "number": False, "end_of_line": "lf", } class InvalidConfError(Exception): """Error raised given invalid TOML or a key that is not valid for mdformat.""" @functools.lru_cache() def read_toml_opts(conf_dir: Path) -> Mapping: conf_path = conf_dir / ".mdformat.toml" if not conf_path.is_file(): parent_dir = conf_dir.parent if conf_dir == parent_dir: return {} return read_toml_opts(parent_dir) with open(conf_path, "rb") as f: try: toml_opts = tomli.load(f) except tomli.TOMLDecodeError as e: raise InvalidConfError(f"Invalid TOML syntax: {e}") for key in toml_opts: if key not in DEFAULT_OPTS: raise InvalidConfError(f"Invalid key {key!r} in {conf_path}") return toml_opts
Fix time delta with utcnow
import datetime import misaka from flask.ext.babel import gettext as _ def timeago(dt): now = datetime.datetime.utcnow() delta = now - dt print delta if delta < datetime.timedelta(minutes=2): return _('Just now') if delta < datetime.timedelta(hours=1): return _('{} minutes ago').format(delta.seconds / 60) if delta < datetime.timedelta(hours=2): return _('1 hour ago') if delta < datetime.timedelta(days=1): return _('{} hours ago').format(delta.seconds / 3600) if delta < datetime.timedelta(days=2): return _('1 day ago') return _('{} days ago').format(delta.days) def plain_markdown(text): renderer = misaka.HtmlRenderer(flags=misaka.HTML_ESCAPE) md = misaka.Markdown(renderer) return md.render(text)
import datetime import misaka from flask.ext.babel import gettext as _ def timeago(dt): now = datetime.datetime.now() delta = now - dt print delta if delta < datetime.timedelta(minutes=2): return _('Just now') if delta < datetime.timedelta(hours=1): return _('{} minutes ago').format(delta.seconds / 60) if delta < datetime.timedelta(hours=2): return _('1 hour ago') if delta < datetime.timedelta(days=1): return _('{} hours ago').format(delta.seconds / 3600) if delta < datetime.timedelta(days=2): return _('1 day ago') return _('{} days ago').format(delta.days) def plain_markdown(text): renderer = misaka.HtmlRenderer(flags=misaka.HTML_ESCAPE) md = misaka.Markdown(renderer) return md.render(text)
Add comment about moving hashlib extention creation to test harness
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-04 08:36 from __future__ import absolute_import, unicode_literals from django.db import migrations from django.conf import settings from corehq.sql_db.operations import HqRunSQL, noop_migration class Migration(migrations.Migration): dependencies = [ ('sql_accessors', '0055_set_form_modified_on'), ] operations = [ # this originally installed the hashlib extension in production as well # but commcare-cloud does that where possible already # and Amazon RDS doesn't allow it # Todo: Move this to testing harness, doesn't really belong here. # See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976 HqRunSQL( 'CREATE EXTENSION IF NOT EXISTS hashlib', 'DROP EXTENSION hashlib' ) if settings.UNIT_TESTING else noop_migration() ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-04 08:36 from __future__ import absolute_import, unicode_literals from django.db import migrations from django.conf import settings from corehq.sql_db.operations import HqRunSQL, noop_migration class Migration(migrations.Migration): dependencies = [ ('sql_accessors', '0055_set_form_modified_on'), ] operations = [ # this originally installed the hashlib extension in production as well # but commcare-cloud does that where possible already # and Amazon RDS doesn't allow it HqRunSQL( 'CREATE EXTENSION IF NOT EXISTS hashlib', 'DROP EXTENSION hashlib' ) if settings.UNIT_TESTING else noop_migration() ]
Make Django 1.7 migrations compatible with Python3
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='File', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=255, db_index=True)), ('size', models.PositiveIntegerField(db_index=True)), ('_content', models.TextField(db_column='content')), ('created_datetime', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Created datetime', db_index=True)), ('_content_hash', models.CharField(db_index=True, max_length=128, null=True, db_column='content_hash', blank=True)), ], options={ 'db_table': 'database_files_file', }, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='File', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=255, db_index=True)), ('size', models.PositiveIntegerField(db_index=True)), ('_content', models.TextField(db_column=b'content')), ('created_datetime', models.DateTimeField(default=django.utils.timezone.now, verbose_name=b'Created datetime', db_index=True)), ('_content_hash', models.CharField(db_index=True, max_length=128, null=True, db_column=b'content_hash', blank=True)), ], options={ 'db_table': 'database_files_file', }, ), ]
Revert "Used relative import for water_supply fixture" This reverts commit 8615f9c9d8a254dc6a43229e0ec8fc68ebe12e08.
#!/usr/bin/env python # -*- coding: utf-8 -*- """Implements example simulation model which can be run from the command line Arguments ========= raininess : int Sets the amount of rain """ from argparse import ArgumentParser from water_supply import ExampleWaterSupplySimulation def argparse(): parser = ArgumentParser() parser.add_argument("--raininess", type=int, help="Sets the amount of rain") return parser.parse_args() def main(): args = argparse() water_supply = ExampleWaterSupplySimulation(args.raininess) results = water_supply.simulate() for key, val in results.items(): print("{},{}".format(key, val)) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Implements example simulation model which can be run from the command line Arguments ========= raininess : int Sets the amount of rain """ from argparse import ArgumentParser from . water_supply import ExampleWaterSupplySimulation def argparse(): parser = ArgumentParser() parser.add_argument("--raininess", type=int, help="Sets the amount of rain") return parser.parse_args() def main(): args = argparse() water_supply = ExampleWaterSupplySimulation(args.raininess) results = water_supply.simulate() for key, val in results.items(): print("{},{}".format(key, val)) if __name__ == '__main__': main()
Add numeric char to random string generator.
/** * Copyright (C) 2014 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.rx.sample; import java.util.Random; public class RandomStringGenerator { private static final int DEFAULT_STRING_LENGHT = 12; private static final char[] symbols; static { StringBuilder tmpSymbols = new StringBuilder(); for (char numberChar = '0'; numberChar <= '9'; numberChar++) { tmpSymbols.append(numberChar); } for (char letterChar = 'a'; letterChar <= 'z'; letterChar++) { tmpSymbols.append(letterChar); } symbols = tmpSymbols.toString().toCharArray(); } private final int stringLenght; private final char[] charArray; private final Random random; public RandomStringGenerator() { this(DEFAULT_STRING_LENGHT); } public RandomStringGenerator(int stringLength) { this.stringLenght = stringLength; this.charArray = new char[this.stringLenght]; this.random = new Random(); } public String nextString() { for (int i = 0; i < charArray.length; i++) { charArray[i] = symbols[random.nextInt(symbols.length)]; } return String.valueOf(charArray); } }
/** * Copyright (C) 2014 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.rx.sample; import java.util.Random; public class RandomStringGenerator { private static final int DEFAULT_STRING_LENGHT = 10; private static final char[] symbols; static { StringBuilder tmpSymbols = new StringBuilder(); for (char ch = 'a'; ch <= 'z'; ch++) { tmpSymbols.append(ch); } symbols = tmpSymbols.toString().toCharArray(); } private final int stringLenght; private final char[] charArray; private final Random random; public RandomStringGenerator() { this(DEFAULT_STRING_LENGHT); } public RandomStringGenerator(int stringLength) { this.stringLenght = stringLength; this.charArray = new char[this.stringLenght]; this.random = new Random(); } public String nextString() { for (int i = 0; i < charArray.length; i++) { charArray[i] = symbols[random.nextInt(symbols.length)]; } return String.valueOf(charArray); } }
Allow deletion outside working dir Added an 'options' argument that expects an object. If a 'force' property is set, it will be passed through to del.sync to allow deletion of files outside of the current working directory.
// Generated by CoffeeScript 1.7.1 (function() { var path, through, glob, _, del; glob = require("glob-all"); through = require("through"); path = require("path"); _ = require("underscore"); del = require("del"); module.exports = function(dest, destPatterns, options) { var srcFiles, destFiles, files, onEnd, onFile; files = []; srcFiles = []; destFiles = glob.sync( destPatterns ); onFile = function(file) { srcFiles.push(file.path); this.push(file); return files.push(file); }; onEnd = function() { _.each(srcFiles, function(item, index) { srcFiles[index] = item.substr(process.cwd().length); }); _.each(destFiles, function(item, index) { destFiles[index] = item.substr(dest.length); }) //compare source and destination files and delete any missing in source at destination var deletedFiles = _.difference(destFiles, srcFiles); _.each(deletedFiles, function(item, index) { deletedFiles[index] = dest + deletedFiles[index]; del.sync(deletedFiles[index], {force: (options ? (options.force && typeof options.force === 'boolean') : false)}); }) return this.emit("end"); }; return through(onFile, onEnd); }; }).call(this);
// Generated by CoffeeScript 1.7.1 (function() { var path, through, glob, _, del; glob = require("glob-all"); through = require("through"); path = require("path"); _ = require("underscore"); del = require("del"); module.exports = function(dest, destPatterns) { var srcFiles, destFiles, files, onEnd, onFile; files = []; srcFiles = []; destFiles = glob.sync( destPatterns ); onFile = function(file) { srcFiles.push(file.path); this.push(file); return files.push(file); }; onEnd = function() { _.each(srcFiles, function(item, index) { srcFiles[index] = item.substr(process.cwd().length); }); _.each(destFiles, function(item, index) { destFiles[index] = item.substr(dest.length); }) //compare source and destination files and delete any missing in source at destination var deletedFiles = _.difference(destFiles, srcFiles); _.each(deletedFiles, function(item, index) { deletedFiles[index] = dest + deletedFiles[index]; del.sync(deletedFiles[index]); }) return this.emit("end"); }; return through(onFile, onEnd); }; }).call(this);
Add exception throwing performance comment
package com.aemreunal.exception; /* *************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * aemreunal@gmail.com * * emre.unal@ozu.edu.tr * * * * aemreunal.com * *************************** */ public class MalformedRequestException /*extends Throwable*/ extends RuntimeException { // http://normanmaurer.me/blog/2013/11/09/The-hidden-performance-costs-of-instantiating-Throwables/ // public MalformedRequestException() { // super("Your request is malformed. Please try again.", null, true, false); // } public MalformedRequestException() { super("Your request is malformed. Please try again."); } }
package com.aemreunal.exception; /* *************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * aemreunal@gmail.com * * emre.unal@ozu.edu.tr * * * * aemreunal.com * *************************** */ public class MalformedRequestException extends NullPointerException { public MalformedRequestException() { super("Your request is malformed. Please try again."); } }
Add Absorption effect to Sun Dance
package pokefenn.totemic.ceremony; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.potion.PotionEffect; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import pokefenn.totemic.api.ceremony.Ceremony; import pokefenn.totemic.api.music.MusicInstrument; import pokefenn.totemic.util.EntityUtil; public class CeremonySunDance extends Ceremony { public CeremonySunDance(String name, int musicNeeded, int maxStartupTime, MusicInstrument... selectors) { super(name, musicNeeded, maxStartupTime, selectors); } @Override public void effect(World world, BlockPos pos, int time) { if(world.isRemote) return; for(EntityPlayer player : EntityUtil.getEntitiesInRange(EntityPlayer.class, world, pos, 8, 8)) { player.addPotionEffect(new PotionEffect(MobEffects.REGENERATION, 10 * 20, 3)); player.addPotionEffect(new PotionEffect(MobEffects.ABSORPTION, 5 * 60 * 20, 3)); } } }
package pokefenn.totemic.ceremony; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.potion.PotionEffect; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import pokefenn.totemic.api.ceremony.Ceremony; import pokefenn.totemic.api.music.MusicInstrument; import pokefenn.totemic.util.EntityUtil; public class CeremonySunDance extends Ceremony { public CeremonySunDance(String name, int musicNeeded, int maxStartupTime, MusicInstrument... selectors) { super(name, musicNeeded, maxStartupTime, selectors); } @Override public void effect(World world, BlockPos pos, int time) { if(world.isRemote) return; for(EntityPlayer player : EntityUtil.getEntitiesInRange(EntityPlayer.class, world, pos, 8, 8)) { player.addPotionEffect(new PotionEffect(MobEffects.REGENERATION, 20 * 10, 3)); } } }
Test work of API communication
(function () { 'use strict'; angular .module('scrum_retroboard') .controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]); function UserController($scope, $http, sessionService, userService) { var userVm = this; //scope models userVm.username = ""; userVm.sessionId = sessionService.getSessionId(); userVm.newSession = sessionService .sessionExists(userVm.sessionId) .then(function(result) { return result.data; }); console.log(userVm.newSession); //scope method assignments userVm.createAndJoinSession = createAndJoinSession; userVm.joinExistingSession = joinExistingSession; //scope method definitions function createAndJoinSession() { sessionService.createSession(); userService.addUserToSession(userVm.username, userVm.sessionId); } function joinExistingSession() { userService.addUserToSession(userVm.username, userVm.sessionId); } } })();
(function () { 'use strict'; angular .module('scrum_retroboard') .controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]); function UserController($scope, $http, sessionService, userService) { var userVm = this; //scope models userVm.newSession = false; userVm.username = ""; userVm.sessionId = sessionService.getSessionId(); sessionService .sessionExists(userVm.sessionId) .then(function(result) { userVm.newSession = result.data; }); console.log(userVm.newSession); //scope method assignments userVm.createAndJoinSession = createAndJoinSession; userVm.joinExistingSession = joinExistingSession; //scope method definitions function createAndJoinSession() { sessionService.createSession(); userService.addUserToSession(userVm.username, userVm.sessionId); } function joinExistingSession() { userService.addUserToSession(userVm.username, userVm.sessionId); } } })();
Allow moderators and admins to modify replies
<?php namespace App\Policies; use App\Models\Reply; use App\User; class ReplyPolicy { const CREATE = 'create'; const UPDATE = 'update'; const DELETE = 'delete'; /** * Determine if replies can be created by the user. */ public function create(User $user): bool { // We only need to be logged in. return true; } /** * Determine if the given reply can be updated by the user. */ public function update(User $user, Reply $reply): bool { return $reply->isAuthoredBy($user) || $user->isModerator() || $user->isAdmin(); } /** * Determine if the given reply can be deleted by the user. */ public function delete(User $user, Reply $reply): bool { return $reply->isAuthoredBy($user) || $user->isModerator() || $user->isAdmin(); } }
<?php namespace App\Policies; use App\Models\Reply; use App\User; class ReplyPolicy { const CREATE = 'create'; const UPDATE = 'update'; const DELETE = 'delete'; /** * Determine if replies can be created by the user. */ public function create(User $user): bool { // We only need to be logged in. return true; } /** * Determine if the given reply can be updated by the user. */ public function update(User $user, Reply $reply): bool { return $reply->isAuthoredBy($user); } /** * Determine if the given reply can be deleted by the user. */ public function delete(User $user, Reply $reply): bool { return $reply->isAuthoredBy($user); } }
Fix the provides method for the ServiceProvider
<?php namespace Antoineaugusti\LaravelEasyrec; use Illuminate\Support\ServiceProvider; class LaravelEasyrecServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('antoineaugusti/laravel-easyrec', 'antoineaugusti/laravel-easyrec'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['laraveleasyrec'] = $this->app->share(function($app) { $config = []; foreach (['baseURL', 'apiKey', 'tenantID', 'apiVersion'] as $value) $config[$value] = $app['config']->get('antoineaugusti/laravel-easyrec::'.$value); return new Easyrec($config); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('laraveleasyrec'); } }
<?php namespace Antoineaugusti\LaravelEasyrec; use Illuminate\Support\ServiceProvider; class LaravelEasyrecServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('antoineaugusti/laravel-easyrec', 'antoineaugusti/laravel-easyrec'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['laraveleasyrec'] = $this->app->share(function($app) { $config = []; foreach (['baseURL', 'apiKey', 'tenantID', 'apiVersion'] as $value) $config[$value] = $app['config']->get('antoineaugusti/laravel-easyrec::'.$value); return new Easyrec($config); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Support old lower-case entity type `image` for backwards compatibility
import decorateComponentWithProps from 'decorate-component-with-props'; import addImage from './modifiers/addImage'; import ImageComponent from './Image'; import imageStyles from './imageStyles.css'; const defaultTheme = { image: imageStyles.image, }; export default (config = {}) => { const theme = config.theme ? config.theme : defaultTheme; let Image = config.imageComponent || ImageComponent; if (config.decorator) { Image = config.decorator(Image); } const ThemedImage = decorateComponentWithProps(Image, { theme }); return { blockRendererFn: (block, { getEditorState }) => { if (block.getType() === 'atomic') { const contentState = getEditorState().getCurrentContent(); const entity = block.getEntityAt(0); if (!entity) return null; const type = contentState.getEntity(entity).getType(); if (type === 'IMAGE' || type === 'image') { return { component: ThemedImage, editable: false, }; } return null; } return null; }, addImage, }; }; export const Image = ImageComponent;
import decorateComponentWithProps from 'decorate-component-with-props'; import addImage from './modifiers/addImage'; import ImageComponent from './Image'; import imageStyles from './imageStyles.css'; const defaultTheme = { image: imageStyles.image, }; export default (config = {}) => { const theme = config.theme ? config.theme : defaultTheme; let Image = config.imageComponent || ImageComponent; if (config.decorator) { Image = config.decorator(Image); } const ThemedImage = decorateComponentWithProps(Image, { theme }); return { blockRendererFn: (block, { getEditorState }) => { if (block.getType() === 'atomic') { const contentState = getEditorState().getCurrentContent(); const entity = block.getEntityAt(0); if (!entity) return null; const type = contentState.getEntity(entity).getType(); if (type === 'IMAGE') { return { component: ThemedImage, editable: false, }; } return null; } return null; }, addImage, }; }; export const Image = ImageComponent;
Make COB_DATABASE_URI environment variable override existing settings
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
Fix issue causing contacts to list ALL interactions
const winston = require('winston') const authorisedRequest = require('../lib/authorisedrequest') const config = require('../config') function getInteraction (token, interactionId) { return authorisedRequest(token, `${config.apiRoot}/interaction/${interactionId}/`) } function saveInteraction (token, interaction) { const options = { body: interaction } if (interaction.id && interaction.id.length > 0) { // update options.url = `${config.apiRoot}/interaction/${interaction.id}/` options.method = 'PUT' } else { options.url = `${config.apiRoot}/interaction/` options.method = 'POST' } return authorisedRequest(token, options) } /** * Get all the interactions for a contact * * @param {any} token * @param {any} contactId * @return {Array[Object]} Returns a promise that resolves to an array of API interaction objects */ function getInteractionsForContact (token, contactId) { return new Promise((resolve) => { authorisedRequest(token, `${config.apiRoot}/contact/${contactId}/`) .then((response) => { resolve(response.interactions) }) .catch((error) => { winston.info(error) resolve([]) }) }) } module.exports = { saveInteraction, getInteraction, getInteractionsForContact }
const winston = require('winston') const authorisedRequest = require('../lib/authorisedrequest') const config = require('../config') function getInteraction (token, interactionId) { return authorisedRequest(token, `${config.apiRoot}/interaction/${interactionId}/`) } function saveInteraction (token, interaction) { const options = { body: interaction } if (interaction.id && interaction.id.length > 0) { // update options.url = `${config.apiRoot}/interaction/${interaction.id}/` options.method = 'PUT' } else { options.url = `${config.apiRoot}/interaction/` options.method = 'POST' } return authorisedRequest(token, options) } /** * Get all the interactions for a contact * * @param {any} token * @param {any} contactId * @return {Array[Object]} Returns a promise that resolves to an array of API interaction objects */ function getInteractionsForContact (token, contactId) { return new Promise((resolve) => { authorisedRequest(token, `${config.apiRoot}/interaction/?contact_id=${contactId}`) .then((response) => { resolve(response.results) }) .catch((error) => { winston.info(error) resolve([]) }) }) } module.exports = { saveInteraction, getInteraction, getInteractionsForContact }
Fix issue with duplicated call
import sys import os import shutil import composer import configuration import downloader def run(): try: project_dir = configuration.get_value('project-dir') except: project_dir = os.getcwd()+'/' execution_dir = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]+'/' if len(sys.argv) == 2: project_dir = sys.argv[1] os.chdir(execution_dir) print '>>> Execution dir: '+execution_dir print '>>> Project dir: '+project_dir build_dir = project_dir+'build/' configuration.load(project_dir) configuration.add('project-dir', project_dir) configuration.add('build-dir', build_dir) composer.initialization() downloader.initialization() def update(): php_bin = 'php' if len(sys.argv) == 2: php_bin = sys.argv[1] print '>>> PHP version is: '+php_bin configuration.add('php', php_bin) composer.initialization() composer.update() downloader.update() def prepare_dir(path): if os.path.isdir(path): shutil.rmtree(path) os.makedirs(path)
import sys import os import shutil import composer import configuration import downloader def run(): project_dir = os.getcwd()+'/' execution_dir = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]+'/' if len(sys.argv) == 2: project_dir = sys.argv[1] os.chdir(execution_dir) print '>>> Execution dir: '+execution_dir print '>>> Project dir: '+project_dir build_dir = project_dir+'build/' configuration.load(project_dir) configuration.add('project-dir', project_dir) configuration.add('build-dir', build_dir) composer.initialization() downloader.initialization() def update(): php_bin = 'php' if len(sys.argv) == 2: php_bin = sys.argv[1] print '>>> PHP version is: '+php_bin configuration.add('php', php_bin) composer.initialization() composer.update() downloader.update() def prepare_dir(path): if os.path.isdir(path): shutil.rmtree(path) os.makedirs(path)
Correct module import, add carriage return for serial com
var Datas = require('dataviz-tangible'); var datas = new Datas({ forecast: 'myAPIKey',//Replace with user API key from https://developer.forecast.io/ }); // définir comment gérer la réponse du service météo datas.on('weather', function(data) { console.log("Send" + data.hourly.data[0].precipIntensity + "in./hr"); serialPort.write(data.hourly.data[0].precipIntensity/0.4*255 +"\n");//Normalised to 0-255 }); datas.weather('Nantes'); var openFlag; var date = new Date() //console.log(date.getSeconds()); // ouvrir un port série var SerialPort = require("serialport").SerialPort var serialPort = new SerialPort("/dev/ttyACM1", { baudrate: 9600 }); serialPort.on("open", function () { openFlag = true; console.log("Open"); }); serialPort.on('data', function(data){ console.log("Received "+ data); }); var timer = setInterval(function() { if (openFlag) { // lancer un appel au service météo datas.weather('Nantes'); } }, 1000)//10seconds
var Datas = require('../datas'); var datas = new Datas({ forecast: 'myAPIKey',//Replace with user API key from https://developer.forecast.io/ }); // définir comment gérer la réponse du service météo datas.on('weather', function(data) { console.log("Send" + data.hourly.data[0].precipIntensity + "in./hr"); serialPort.write(data.hourly.data[0].precipIntensity/0.4*255);//Normalised to 0-255 }); datas.weather('Nantes'); var openFlag; var date = new Date() console.log(date.getSeconds()); // ouvrir un port série var SerialPort = require("serialport").SerialPort var serialPort = new SerialPort("/dev/ttyACM3", { baudrate: 9600 }); serialPort.on("open", function () { openFlag = true; console.log("Open"); }); serialPort.on('data', function(data){ console.log("Received"+ data); }); var timer = setInterval(function() { if (openFlag) { // lancer un appel au service météo datas.weather('Nantes'); } }, 120000)//10seconds
Add a trailing slash to the base API URL
(function($) { "use strict"; var apiUrl = "http://redjohn.herokuapp.com/api/tweets/"; function addScoresToSuspects(response) { _.each(response.results, function(mentions, suspect) { $("#" + suspect).find(".mentions").text(mentions); }); } function addTotal(response) { $("#tweet-count").text(response.results); } $.ajax({ url: apiUrl + "suspects/count", type: "GET", dataType: "jsonp", success: addScoresToSuspects }); $.ajax({ url: apiUrl + "count", type: "GET", dataType: "jsonp", success: addTotal }); })(jQuery);
(function($) { "use strict"; var apiUrl = "http://redjohn.herokuapp.com/api/tweets"; function addScoresToSuspects(response) { _.each(response.results, function(mentions, suspect) { $("#" + suspect).find(".mentions").text(mentions); }); } function addTotal(response) { $("#tweet-count").text(response.results); } $.ajax({ url: apiUrl + "suspects/count", type: "GET", dataType: "jsonp", success: addScoresToSuspects }); $.ajax({ url: apiUrl + "count", type: "GET", dataType: "jsonp", success: addTotal }); })(jQuery);
Fix gallery images for dev-only Sandcastle demos.
/*global importClass,project,attributes,elements,java,Packages*/ importClass(Packages.org.mozilla.javascript.tools.shell.Main); /*global Main*/ Main.exec(['-e', '{}']); var load = Main.global.load; load(project.getProperty('tasksDirectory') + '/shared.js'); /*global forEachFile,readFileContents,writeFileContents,File,FileReader,FileWriter,FileUtils*/ var demos = []; var output = attributes.get('output'); forEachFile('demos', function(relativePath, file) { "use strict"; var demo = relativePath.substring(0, relativePath.lastIndexOf('.')).replace('\\', '/'); var demoObject = { name : String(demo), date : file.lastModified() }; if (new File(new File(output).getParent(), demo + '.jpg').exists()) { demoObject.img = demo + '.jpg'; } demos.push(JSON.stringify(demoObject, null, 2)); }); var contents = '\ // This file is automatically rebuilt by the Cesium build process.\n\ var gallery_demos = [' + demos.join(', ') + '];'; writeFileContents(output, contents);
/*global importClass,project,attributes,elements,java,Packages*/ importClass(Packages.org.mozilla.javascript.tools.shell.Main); /*global Main*/ Main.exec(['-e', '{}']); var load = Main.global.load; load(project.getProperty('tasksDirectory') + '/shared.js'); /*global forEachFile,readFileContents,writeFileContents,File,FileReader,FileWriter,FileUtils*/ var demos = []; forEachFile('demos', function(relativePath, file) { "use strict"; var demo = relativePath.substring(0, relativePath.lastIndexOf('.')).replace('\\', '/'); var demoObject = { name : String(demo), date : file.lastModified() }; if (new File(file.getParent(), demo + '.jpg').exists()) { demoObject.img = demo + '.jpg'; } demos.push(JSON.stringify(demoObject, null, 2)); }); var contents = '\ // This file is automatically rebuilt by the Cesium build process.\n\ var gallery_demos = [' + demos.join(', ') + '];'; writeFileContents(attributes.get('output'), contents);
Adjust size and spacing of the dots according to specs.
import React, { Component, PropTypes } from 'react' import { Paper } from 'material-ui' const styles = { dot: { width: 8, height: 8, background: '#fff', margin: '0 4px', float: 'left', transition: 'all 400ms cubic-bezier(0.4, 0.0, 0.2, 1)' } } export function Dots ({ count, index, style = {} }) { return ( <div style={{ ...style, width: count * 16 }}> {[...Array(count).keys()].map((i) => ( <Paper key={i} circle zDepth={0} style={{ ...styles.dot, opacity: i === index ? 1 : 0.5 }} /> ))} </div> ) } Dots.propTypes = { count: PropTypes.number.isRequired, index: PropTypes.number.isRequired, style: PropTypes.object }
import React, { Component, PropTypes } from 'react' import { Paper } from 'material-ui' const styles = { dot: { width: 10, height: 10, background: '#fff', margin: '0 3px', float: 'left', transition: 'all 400ms cubic-bezier(0.4, 0.0, 0.2, 1)' } } export function Dots ({ count, index, style = {} }) { return ( <div style={{ ...style, width: count * 16 }}> {[...Array(count).keys()].map((i) => ( <Paper key={i} circle zDepth={0} style={{ ...styles.dot, opacity: i === index ? 1 : 0.5 }} /> ))} </div> ) } Dots.propTypes = { count: PropTypes.number.isRequired, index: PropTypes.number.isRequired, style: PropTypes.object }
Fix result logging of shell plugin
var exec = require('./exec').exec var chalk = require('chalk') module.exports = function WebpackShellPlugin (options) { return { apply: function (compiler) { compiler.plugin('after-emit', function (compilation, callback) { if (options.script) { exec(options.script, { shell: '/bin/bash' }).then(function (res) { if (res.stderr) { console.error(chalk.red('error') + ' Error while running the command after build') console.error(res.stderr) } if (res.stdout.trim().length > 0) { res.stdout.trim().split('\n').map(function (line) { console.log(line) }) } }) .then(callback) .catch(function (err) { console.error(chalk.red('error') + ' Error while running the command after build') console.error(err) callback() }) } else { callback() } }) } } }
var exec = require('./exec').exec var chalk = require('chalk') module.exports = function WebpackShellPlugin (options) { return { apply: function (compiler) { compiler.plugin('after-emit', function (compilation, callback) { if (options.script) { exec(options.script, { shell: '/bin/bash' }).then(function (res) { if (res.stderr) { console.error(chalk.red('error') + ' Error while running the command after build') console.error(res.stderr) } res.stdout.split('\\n').map(function (line) { console.log(line) }) }) .then(callback) .catch(function (err) { console.error(chalk.red('error') + ' Error while running the command after build') console.error(err) callback() }) } else { callback() } }) } } }
Use logger module instead of console for the dummy browser runner sagas Signed-off-by: Victor Porof <4f672cb979ca45495d0cccc37abaefc8713fcc24@gmail.com>
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { takeEvery } from 'redux-saga/effects'; import opn from 'opn'; import logger from '../../logger'; import SharedActions from '../../../shared/actions/shared-actions'; function create({ payload: { url } }) { logger.log(`Chrome frontend hosted at ${url}`); opn(url); } export default function* () { yield [ takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create), ]; }
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { takeEvery } from 'redux-saga/effects'; import opn from 'opn'; import SharedActions from '../../../shared/actions/shared-actions'; function create({ payload: { url } }) { console.log(`Chrome frontend hosted at ${url}`); // eslint-disable-line no-console opn(url); } export default function* () { yield [ takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create), ]; }
Fix for active nav links when URL has hash
$(function() { $('#side-menu').metisMenu(); }); //Loads the correct sidebar on window load, //collapses the sidebar on window resize. // Sets the min-height of #page-wrapper to window size $(function() { $(window).on("load resize", function() { var topOffset = 50; var width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width; if (width < 768) { $('div.navbar-collapse').addClass('collapse'); topOffset = 100; // 2-row-menu } else { $('div.navbar-collapse').removeClass('collapse'); } var height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1; height = height - topOffset; if (height < 1) height = 1; if (height > topOffset) { $("#page-wrapper").css("min-height", (height) + "px"); } }); var url = window.location; var element = $('ul.nav a').filter(function() { return this.href == url || url.href.split('#')[0].indexOf(this.href) == 0; }).addClass('active').parent().parent().addClass('in').parent(); if (element.is('li')) { element.addClass('active'); } });
$(function() { $('#side-menu').metisMenu(); }); //Loads the correct sidebar on window load, //collapses the sidebar on window resize. // Sets the min-height of #page-wrapper to window size $(function() { $(window).on("load resize", function() { var topOffset = 50; var width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width; if (width < 768) { $('div.navbar-collapse').addClass('collapse'); topOffset = 100; // 2-row-menu } else { $('div.navbar-collapse').removeClass('collapse'); } var height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1; height = height - topOffset; if (height < 1) height = 1; if (height > topOffset) { $("#page-wrapper").css("min-height", (height) + "px"); } }); var url = window.location; var element = $('ul.nav a').filter(function() { return this.href == url || url.href.indexOf(this.href) == 0; }).addClass('active').parent().parent().addClass('in').parent(); if (element.is('li')) { element.addClass('active'); } });
Fix copy/pasting error in comment
"use strict"; /** * Takes a method and transforms it into a function by binding this to the first argument * passed to the resulting function. * * `this` gets bound to null when the method is called. * * @see methodify * * @function demethodify * * @example * const { demethodify } = require("helpbox"); * * function Person(age) { * this.age = age; * } * * Person.prototype.tellMyAge = function () { * console.log(this.age); * } * * const person = new Person(3); * const tellPersonAge = demethodify(Person.prototype.tellMyAge); * * // Prints 3. * tellPersonAge(person); * * @param λ {Function} The function to demethodify. * * @return {Function} The function in its demethodified form. */ module.exports = λ => { return function () { return λ.apply(arguments[0], Array.prototype.slice.call(arguments, 1)); }; };
"use strict"; /** * Takes a method and transforms it into a function by binding this to the first argument * passed to the resulting function. * * `this` gets bound to null when the method is called. * * @see methodify * * @function demethodify * * @example * const { demethodify } = require("helpbox"); * * function Person(age) { * this.age = age; * } * * Person.prototype.tellMyAge = function () { * console.log(this.age); * } * * const person = new Person(3); * const tellPersonAge = demethodify(Person.prototype.tellMyAge); * * // Prints 3. * tellPersonAge(person); * * @param λ {Function} The function to methodify. * * @return {Function} The function in its methodified form. */ module.exports = λ => { return function () { return λ.apply(arguments[0], Array.prototype.slice.call(arguments, 1)); }; };
Support colors not in map If you specify a background color that isn't a key in the colors map, we just assume it's an actual color value and let you use it.
const postcss = require('postcss') const _ = require('lodash') function findColor(colors, color) { const colorsNormalized = _.mapKeys(colors, (value, key) => { return _.camelCase(key) }) return _.get(colorsNormalized, _.camelCase(color), color) } module.exports = function ({ colors, backgroundColors }) { if (_.isArray(backgroundColors)) { backgroundColors = _(backgroundColors).map(color => [color, color]).fromPairs() } return _(backgroundColors).toPairs().map(([className, colorName]) => { const kebabClass = _.kebabCase(className) return postcss.rule({ selector: `.bg-${kebabClass}` }).append({ prop: 'background-color', value: findColor(colors, colorName) }) }).value() }
const postcss = require('postcss') const _ = require('lodash') function findColor(colors, color) { return _.mapKeys(colors, (value, key) => { return _.camelCase(key) })[_.camelCase(color)] } module.exports = function ({ colors, backgroundColors }) { if (_.isArray(backgroundColors)) { backgroundColors = _(backgroundColors).map(color => [color, color]).fromPairs() } return _(backgroundColors).toPairs().map(([className, colorName]) => { const kebabClass = _.kebabCase(className) return postcss.rule({ selector: `.bg-${kebabClass}` }).append({ prop: 'background-color', value: findColor(colors, colorName) }) }).value() }
Add manageRequest test in scanconfigform tests
<?php /* Copyright (C) 2016 Teclib' This file is part of Armadito Plugin for GLPI. Armadito Plugin for GLPI is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Armadito Plugin for GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>. **/ class ScanConfigFormTest extends CommonTestCase { /** * @test */ public function showForms() { ob_start(); $scanconfig = new PluginArmaditoScanConfig(); $scanconfig->showForm(3); PluginArmaditoScanConfig::showNoScanConfigForm(); PluginArmaditoScanConfig::showNoAntivirusForm(); $_GET["id"] = 3; $scanconfig->manageRequest(); ob_end_clean(); } }
<?php /* Copyright (C) 2016 Teclib' This file is part of Armadito Plugin for GLPI. Armadito Plugin for GLPI is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Armadito Plugin for GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>. **/ class ScanConfigFormTest extends CommonTestCase { /** * @test */ public function showForms() { ob_start(); $scanconfig = new PluginArmaditoScanConfig(); $scanconfig->showForm(3); PluginArmaditoScanConfig::showNoScanConfigForm(); PluginArmaditoScanConfig::showNoAntivirusForm(); ob_end_clean(); } }
[lib] Handle empty filename in fileInfoFromData
// @flow import type { MediaType } from '../types/media-types'; import fileType from 'file-type'; type FileInfo = {| name: string, mime: string, mediaType: MediaType |}; function fileInfoFromData( data: Uint8Array | Buffer, fileName: string, ): ?FileInfo { const fileTypeResult = fileType(data); if (!fileTypeResult) { return null; } const { ext, mime } = fileTypeResult; const mediaType = mimeTypesToMediaTypes[mime]; if (!mediaType) { return null; } let [ readableFileName ] = fileName.split('.'); if (!readableFileName) { readableFileName = Math.random().toString(36).slice(-5); } const maxReadableLength = 255 - ext.length - 1; const fixedFileName = `${readableFileName.substring(0, maxReadableLength)}.${ext}`; return { name: fixedFileName, mime, mediaType }; } const mimeTypesToMediaTypes = { "image/png": "photo", "image/jpeg": "photo", "image/gif": "photo", "image/heic": "photo", }; export { fileInfoFromData, mimeTypesToMediaTypes, };
// @flow import type { MediaType } from '../types/media-types'; import fileType from 'file-type'; type FileInfo = {| name: string, mime: string, mediaType: MediaType |}; function fileInfoFromData( data: Uint8Array | Buffer, fileName: string, ): ?FileInfo { const fileTypeResult = fileType(data); if (!fileTypeResult) { return null; } const { ext, mime } = fileTypeResult; const mediaType = mimeTypesToMediaTypes[mime]; if (!mediaType) { return null; } const [ readableFileName, extension ] = fileName.split('.'); const maxReadableLength = 255 - ext.length - 1; const fixedFileName = `${readableFileName.substring(0, maxReadableLength)}.${ext}`; return { name: fixedFileName, mime, mediaType }; } const mimeTypesToMediaTypes = { "image/png": "photo", "image/jpeg": "photo", "image/gif": "photo", "image/heic": "photo", }; export { fileInfoFromData, mimeTypesToMediaTypes, };
[FEATURE] Add route for creating transactions
var express = require('express') var requireAll = require('./lib/require-all') ctrls = requireAll({ dirname: __dirname + '/app/controllers', filter: /(.+)\.js(on)?$/ }) var app = express() app.use(express.static(__dirname + '/public')) require('./config/initializers/middleware.js').configure(app) require('./config/routes').configure(app, ctrls) app.post('/api/v1/sessions', ctrls['sessions'].create) app.post('/api/v1/gateway/users', ctrls['gateway_users'].create) app.get('/api/v1/sessions', ctrls['sessions'].show) app.post('/api/v1/sessions/destroy', ctrls['sessions'].destroy) app.post('/api/v1/ripple_transactions', ctrls['ripple_transactions'].create) address = process.env.ADDRESS port = process.env.PORT || 4000 if (address){ app.listen(port, address) console.log('Listening on IP address ', address) } else { app.listen(port) } console.log('Listening on port ', port)
var express = require('express') var requireAll = require('./lib/require-all') ctrls = requireAll({ dirname: __dirname + '/app/controllers', filter: /(.+)\.js(on)?$/ }) var app = express() app.use(express.static(__dirname + '/public')) require('./config/initializers/middleware.js').configure(app) require('./config/routes').configure(app, ctrls) app.post('/api/v1/sessions', ctrls['sessions'].create) app.post('/api/v1/gateway/users', ctrls['gateway_users'].create) app.get('/api/v1/sessions', ctrls['sessions'].show) app.post('/api/v1/sessions/destroy', ctrls['sessions'].destroy) address = process.env.ADDRESS port = process.env.PORT || 4000 if (address){ app.listen(port, address) console.log('Listening on IP address ', address) } else { app.listen(port) } console.log('Listening on port ', port)
Allow other_paths to be passed into TraceViewerProject This allows external embedders to subclass TraceViewerProject and thus use trace viewer. git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@1198 0e6d7f2b-9903-5b78-7403-59d27f066143
# Copyright (c) 2014 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. import sys import os from tvcm import project as project_module class TraceViewerProject(project_module.Project): trace_viewer_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..')) src_path = os.path.abspath(os.path.join( trace_viewer_path, 'trace_viewer')) trace_viewer_third_party_path = os.path.abspath(os.path.join( trace_viewer_path, 'third_party')) jszip_path = os.path.abspath(os.path.join( trace_viewer_third_party_path, 'jszip')) test_data_path = os.path.join(trace_viewer_path, 'test_data') skp_data_path = os.path.join(trace_viewer_path, 'skp_data') def __init__(self, other_paths=None): paths = [self.src_path, self.jszip_path] if other_paths: paths.extend(other_paths) super(TraceViewerProject, self).__init__( paths)
# Copyright (c) 2014 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. import sys import os from tvcm import project as project_module class TraceViewerProject(project_module.Project): trace_viewer_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..')) src_path = os.path.abspath(os.path.join( trace_viewer_path, 'trace_viewer')) trace_viewer_third_party_path = os.path.abspath(os.path.join( trace_viewer_path, 'third_party')) jszip_path = os.path.abspath(os.path.join( trace_viewer_third_party_path, 'jszip')) test_data_path = os.path.join(trace_viewer_path, 'test_data') skp_data_path = os.path.join(trace_viewer_path, 'skp_data') def __init__(self): super(TraceViewerProject, self).__init__( [self.src_path, self.jszip_path])
Use translation.override as a context manager instead of a decorator.
# -*- coding: utf-8 -*- from decimal import Decimal as D from django.utils import translation from django.test import TestCase from django import template def render(template_string, ctx): tpl = template.Template(template_string) return tpl.render(template.Context(ctx)) class TestCurrencyFilter(TestCase): def setUp(self): self.template = template.Template( "{% load currency_filters %}" "{{ price|currency }}" ) def test_renders_price_correctly(self): out = self.template.render(template.Context({ 'price': D('10.23'), })) self.assertTrue(u'£10.23' in out) def test_handles_none_price_gracefully(self): self.template.render(template.Context({ 'price': None })) def test_handles_string_price_gracefully(self): self.template.render(template.Context({ 'price': '' })) def test_handles_no_translation(self): with translation.override(None, deactivate=True): self.template.render(template.Context({ 'price': D('10.23'), }))
# -*- coding: utf-8 -*- from decimal import Decimal as D from django.utils import translation from django.test import TestCase from django import template def render(template_string, ctx): tpl = template.Template(template_string) return tpl.render(template.Context(ctx)) class TestCurrencyFilter(TestCase): def setUp(self): self.template = template.Template( "{% load currency_filters %}" "{{ price|currency }}" ) def test_renders_price_correctly(self): out = self.template.render(template.Context({ 'price': D('10.23'), })) self.assertTrue(u'£10.23' in out) def test_handles_none_price_gracefully(self): self.template.render(template.Context({ 'price': None })) def test_handles_string_price_gracefully(self): self.template.render(template.Context({ 'price': '' })) @translation.override(None, deactivate=True) def test_handles_no_translation(self): self.template.render(template.Context({ 'price': D('10.23'), }))
Allow log-in for people who don+t have pension account Enable DTO debug
package ee.tuleva.onboarding.account; import ee.tuleva.onboarding.auth.principal.Person; import ee.tuleva.onboarding.epis.EpisService; import ee.tuleva.onboarding.epis.account.FundBalanceDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; import static java.util.stream.Collectors.toList; @Service @Slf4j @RequiredArgsConstructor public class AccountStatementService { private final EpisService episService; private final FundBalanceDtoToFundBalanceConverter fundBalanceConverter; public List<FundBalance> getAccountStatement(Person person) { List<FundBalanceDto> accountStatement = episService.getAccountStatement(person); return accountStatement.stream() .map(fundBalanceDto -> convertToFundBalance(fundBalanceDto, person)) .collect(toList()); } private FundBalance convertToFundBalance(FundBalanceDto fundBalanceDto, Person person) { try { if (log.isDebugEnabled()) { log.debug("Fund Balance DTO:" + fundBalanceDto); } return fundBalanceConverter.convert(fundBalanceDto); } catch(IllegalArgumentException e) { throw new IllegalStateException("Could not convert fund balance for person " + person, e); } } }
package ee.tuleva.onboarding.account; import ee.tuleva.onboarding.auth.principal.Person; import ee.tuleva.onboarding.epis.EpisService; import ee.tuleva.onboarding.epis.account.FundBalanceDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; import static java.util.stream.Collectors.toList; @Service @Slf4j @RequiredArgsConstructor public class AccountStatementService { private final EpisService episService; private final FundBalanceDtoToFundBalanceConverter fundBalanceConverter; public List<FundBalance> getAccountStatement(Person person) { List<FundBalanceDto> accountStatement = episService.getAccountStatement(person); return accountStatement.stream() .map(fundBalanceDto -> convertToFundBalance(fundBalanceDto, person)) .collect(toList()); } private FundBalance convertToFundBalance(FundBalanceDto fundBalanceDto, Person person) { try { return fundBalanceConverter.convert(fundBalanceDto); } catch(IllegalArgumentException e) { throw new IllegalStateException("Could not convert fund balance for person " + person, e); } } }
Rename "method parameters" to "method arguments" to avoid confusion with ParameterDefinition
<?php namespace Interop\Container\Definition; /** * Represents an instance declared using the "new" keyword followed by an optional list of * method calls and properties assignations. */ interface InstanceDefinitionInterface extends DefinitionInterface { /** * Returns the name of the class to instantiate. * * @return string */ public function getClassName(); /** * Returns an array of arguments to pass to the constructor of the class. * * Each argument is either a PHP scalar type or a ReferenceInterface instance. * * @return array */ public function getConstructorArguments(); /** * Returns an array of values or container entries to assign to public properties * of the instance. * * @return PropertyAssignmentInterface[] */ public function getPropertyAssignments(); /** * Returns an array of methods to call on the instance. * * @return MethodCallInterface[] */ public function getMethodCalls(); }
<?php namespace Interop\Container\Definition; /** * Represents an instance declared using the "new" keyword followed by an optional list of * method calls and properties assignations. */ interface InstanceDefinitionInterface extends DefinitionInterface { /** * Returns the name of the class to instantiate. * * @return string */ public function getClassName(); /** * Returns an array of parameters to pass to the constructor of the class. * * Each parameter is either a PHP scalar type or a ReferenceInterface instance. * * @return array */ public function getConstructorParameters(); /** * Returns an array of values or container entries to assign to public properties * of the instance. * * @return PropertyAssignmentInterface[] */ public function getPropertyAssignments(); /** * Returns an array of methods to call on the instance. * * @return MethodCallInterface[] */ public function getMethodCalls(); }
TASK: Fix the intendation of the new settings object
module.exports = { parser: 'babel-eslint', extends: [ 'xo', 'xo-react', 'plugin:jsx-a11y/recommended', 'plugin:promise/recommended', 'plugin:react/recommended' ], plugins: [ 'compat', 'promise', 'babel', 'react', 'jsx-a11y' ], env: { node: true, browser: true, jest: true }, globals: { analytics: true, Generator: true, Iterator: true }, settings: { polyfills: ['fetch'] }, rules: { 'compat/compat': 2, 'react/jsx-boolean-value': 0, 'react/require-default-props': 0, 'react/forbid-component-props': 0, 'promise/avoid-new': 0, 'generator-star-spacing': 0 } };
module.exports = { parser: 'babel-eslint', extends: [ 'xo', 'xo-react', 'plugin:jsx-a11y/recommended', 'plugin:promise/recommended', 'plugin:react/recommended' ], plugins: [ 'compat', 'promise', 'babel', 'react', 'jsx-a11y' ], env: { node: true, browser: true, jest: true }, globals: { analytics: true, Generator: true, Iterator: true }, settings: { polyfills: ['fetch'] }, rules: { 'compat/compat': 2, 'react/jsx-boolean-value': 0, 'react/require-default-props': 0, 'react/forbid-component-props': 0, 'promise/avoid-new': 0, 'generator-star-spacing': 0 } };
Make sure that the wrapped function inherits doctring
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value # make sure that the function that is hooked by the shell has the same # __doc__ class bayesdb_shellhookexp(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args): try: return self.func(*args) except Exception as err: print err def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out current_shell()._hook(name, bayesdb_shellhookexp(func), autorehook=autorehook) return wrapper
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out def excepection_handling_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: print err current_shell()._hook(name, excepection_handling_func, autorehook=autorehook) return wrapper
Add With Custom Error Message story.
/** * MediaErrorHandler Component Stories. * * Site Kit by Google, Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import MediaErrorHandler from './'; const ErrorComponent = () => { throw new Error(); }; const Template = ( args ) => ( <MediaErrorHandler { ...args }> <ErrorComponent /> </MediaErrorHandler> ); const NoErrorsTemplate = () => ( <MediaErrorHandler> <div>There are no errors here.</div> </MediaErrorHandler> ); export const Default = Template.bind( {} ); Default.storyName = 'Default'; Default.scenario = { label: 'Global/MediaErrorHandler', }; export const WithCustomErrorMessage = Template.bind( {} ); WithCustomErrorMessage.storyName = 'With Custom Error Message'; WithCustomErrorMessage.args = { errorMessage: 'This is a custom error message 🐞', }; export const NoErrors = NoErrorsTemplate.bind( {} ); NoErrors.storyName = 'No Errors'; export default { title: 'Components/MediaErrorHandler', component: MediaErrorHandler, };
/** * MediaErrorHandler Component Stories. * * Site Kit by Google, Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import MediaErrorHandler from './'; const ErrorComponent = () => { throw new Error(); }; const Template = () => ( <MediaErrorHandler> <ErrorComponent /> </MediaErrorHandler> ); const NoErrorsTemplate = () => ( <MediaErrorHandler> <div>There are no errors here.</div> </MediaErrorHandler> ); export const Default = Template.bind( {} ); Default.storyName = 'Default'; Default.scenario = { label: 'Global/MediaErrorHandler', }; export const NoErrors = NoErrorsTemplate.bind( {} ); NoErrors.storyName = 'No Errors'; export default { title: 'Components/MediaErrorHandler', component: MediaErrorHandler, };
TEST: Remove jQuery dependency, not used
'use strict'; if (!Function.prototype.bind) { // PhantomJS doesn't support bind yet Function.prototype.bind = Function.prototype.bind || function(thisp) { var fn = this; return function() { return fn.apply(thisp, arguments); }; }; } var tests = Object.keys(window.__karma__.files).filter(function(file) { return /-spec\.js$/.test(file); }); requirejs.config({ // Karma serves files from '/base' baseUrl: '/base/src', paths: { 'extend': '../lib/gextend/extend' }, // ask Require.js to load these files (all our tests) deps: tests, // start test run, once Require.js is done callback: window.__karma__.start });
'use strict'; if (!Function.prototype.bind) { // PhantomJS doesn't support bind yet Function.prototype.bind = Function.prototype.bind || function(thisp) { var fn = this; return function() { return fn.apply(thisp, arguments); }; }; } var tests = Object.keys(window.__karma__.files).filter(function(file) { return /-spec\.js$/.test(file); }); requirejs.config({ // Karma serves files from '/base' baseUrl: '/base/src', paths: { 'jquery': '../lib/jquery/jquery', 'extend': '../lib/gextend/extend' }, // ask Require.js to load these files (all our tests) deps: tests, // start test run, once Require.js is done callback: window.__karma__.start });
Use addEventListener('load' instead of onload
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. // This file must be webpacked because it contains .css imports // Load jquery and jquery-ui var $ = require('jquery'); require('jquery-ui'); window.$ = window.jQuery = $; require('jquery-ui'); // Load styling require('jquery-ui/themes/smoothness/jquery-ui.min.css'); require('../css/widgets.min.css'); const widgets = require('./index'); console.info('jupyter-js-widgets loaded successfully'); const manager = new widgets.EmbedManager(); // Magic global widget rendering function: function renderInlineWidgets(event) { var element = event.target || document; var tags = element.querySelectorAll('script.jupyter-widgets'); for (var i=0; i!=tags.length; ++i) { var tag = tags[i]; var widgetStateObject = JSON.parse(tag.innerHTML); var widgetContainer = document.createElement('div'); widgetContainer.className = 'widget-area'; manager.display_widget_state(widgetStateObject, widgetContainer).then(function() { tag.parentElement.insertBefore(widgetContainer, tag); }); } } // Module exports exports.manager = manager; exports.renderInlineWidgets = renderInlineWidgets; // Set window globals window.manager = manager; window.addEventListener('load', renderInlineWidgets);
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. // This file must be webpacked because it contains .css imports // Load jquery and jquery-ui var $ = require('jquery'); require('jquery-ui'); window.$ = window.jQuery = $; require('jquery-ui'); // Load styling require('jquery-ui/themes/smoothness/jquery-ui.min.css'); require('../css/widgets.min.css'); const widgets = require('./index'); console.info('jupyter-js-widgets loaded successfully'); const manager = new widgets.EmbedManager(); // Magic global widget rendering function: function renderInlineWidgets(element) { var element = element || document; var tags = element.querySelectorAll('script.jupyter-widgets'); for (var i=0; i!=tags.length; ++i) { var tag = tags[i]; var widgetStateObject = JSON.parse(tag.innerHTML); var widgetContainer = document.createElement('div'); widgetContainer.className = 'widget-area'; manager.display_widget_state(widgetStateObject, widgetContainer).then(function() { tag.parentElement.insertBefore(widgetContainer, tag); }); } } // Module exports exports.manager = manager; exports.renderInlineWidgets = renderInlineWidgets; // Set window globals window.manager = manager; window.onload = renderInlineWidgets;
Use Overriden, not private method to interact with presenter
package com.malpo.sliver.sample.ui.number; import com.malpo.sliver.sample.models.Number; import timber.log.Timber; class NumberPresenter implements NumberContract.Presenter { private NumberContract.View view; private NumberContract.Interactor interactor; private NumberMapper mapper; NumberPresenter(NumberContract.Interactor interactor) { this.interactor = interactor; this.mapper = new NumberMapper(); } @Override public void setView(NumberContract.View view) { this.view = view; } @Override public void setupView() { //TODO Figure out how to unsubscribe interactor.getNumber().subscribe(this::onNumberUpdated); interactor.onNumberUpdated().subscribe(this::onNumberUpdated); } @Override public void onNumberUpdated(Number number) { Timber.d("Number updated to: %d", number.value); view.display(mapper.map(number)); } @Override public void incrementNumberBy10() { Timber.d("Incrementing number by 10"); interactor.incrementNumberBy(10); } }
package com.malpo.sliver.sample.ui.number; import com.malpo.sliver.sample.models.Number; import timber.log.Timber; class NumberPresenter implements NumberContract.Presenter { private NumberContract.View view; private NumberContract.Interactor interactor; private NumberMapper mapper; NumberPresenter(NumberContract.Interactor interactor) { this.interactor = interactor; this.mapper = new NumberMapper(); } @Override public void setView(NumberContract.View view) { this.view = view; } @Override public void setupView() { //TODO Figure out how to unsubscribe interactor.getNumber().subscribe(this::displayNumber); interactor.onNumberUpdated().subscribe(this::onNumberUpdated); } @Override public void onNumberUpdated(Number number) { Timber.d("Number updated to: %d", number.value); displayNumber(number); } @Override public void incrementNumberBy10() { Timber.d("Incrementing number by 10"); interactor.incrementNumberBy(10); } private void displayNumber(Number number) { view.display(mapper.map(number)); } }
[DDW-608] Implement new About dialog design
// @flow import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; import ReactModal from 'react-modal'; import About from '../../components/static/About'; import styles from './AboutDialog.scss'; import type { InjectedDialogContainerProps } from '../../types/injectedPropsType'; type Props = InjectedDialogContainerProps; @inject('stores', 'actions') @observer export default class AboutDialog extends Component<Props> { static defaultProps = { actions: null, stores: null, children: null, onClose: () => {}, }; render() { const { app } = this.props.stores; const { openExternalLink, environment } = app; const { apiVersion, build, os, version } = environment; return ( <ReactModal isOpen onRequestClose={this.props.actions.app.closeAboutDialog.trigger} className={styles.dialog} overlayClassName={styles.overlay} ariaHideApp={false} > <About apiVersion={apiVersion} build={build} onOpenExternalLink={openExternalLink} os={os} version={version} onClose={this.props.actions.app.closeAboutDialog.trigger} /> </ReactModal> ); } }
// @flow import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; import ReactModal from 'react-modal'; import About from '../../components/static/About'; import styles from './AboutDialog.scss'; import type { InjectedDialogContainerProps } from '../../types/injectedPropsType'; type Props = InjectedDialogContainerProps; @inject('stores', 'actions') @observer export default class AboutDialog extends Component<Props> { static defaultProps = { actions: null, stores: null, children: null, onClose: () => {}, }; render() { const { app } = this.props.stores; const { openExternalLink, environment } = app; const { apiVersion, build, os, version } = environment; return ( <ReactModal isOpen className={styles.dialog} overlayClassName={styles.overlay} ariaHideApp={false} > <About apiVersion={apiVersion} build={build} onOpenExternalLink={openExternalLink} os={os} version={version} onClose={this.props.actions.app.closeAboutDialog.trigger} /> </ReactModal> ); } }
Rename remote field to uri.
package ee.shy.core; import ee.shy.io.Jsonable; import ee.shy.io.Validated; import java.net.URI; import java.util.Objects; /** * Class representing a remote repository's URI. */ public class Remote implements Jsonable, Validated { /** * Repository's URI. */ private final URI uri; /** * Constructs a remote with given URI. * @param uri remote URI for repository */ public Remote(URI uri) { this.uri = uri; assertValid(); } public URI getURI() { return this.uri; } @Override public void assertValid() { Objects.requireNonNull(uri, "repository has no URI"); } }
package ee.shy.core; import ee.shy.io.Jsonable; import ee.shy.io.Validated; import java.net.URI; import java.util.Objects; /** * Class representing a remote repository's URI. */ public class Remote implements Jsonable, Validated { /** * Repository's URI. */ private final URI remote; /** * Constructs a remote with given URI. * @param remote remote URI for repository */ public Remote(URI remote) { this.remote = remote; assertValid(); } public URI getURI() { return this.remote; } @Override public void assertValid() { Objects.requireNonNull(remote, "repository has no URI"); } }
Fix price in de brug
import os import re import sys import json def parse_money(moneystring): # Sometimes 0 is O :( moneystring = moneystring.replace("O", "0") return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.') def stderr_print(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def write_json_to_file(obj, path): """ Write an object to JSON at the specified path. """ directory = os.path.dirname(path) os.makedirs(directory, exist_ok=True) with open(path, mode='w') as f: json.dump(obj, f, sort_keys=True) def split_price(meal): if "-" in meal: price = meal.split('-')[-1].strip() name = '-'.join(meal.split('-')[:-1]).strip() return name, price else: return meal.strip(), ""
import os import re import sys import json def parse_money(moneystring): # Sometimes 0 is O :( moneystring = moneystring.replace("O", "0") return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.') def stderr_print(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def write_json_to_file(obj, path): """ Write an object to JSON at the specified path. """ directory = os.path.dirname(path) os.makedirs(directory, exist_ok=True) with open(path, mode='w') as f: json.dump(obj, f, sort_keys=True) def split_price(meal): price = meal.split('-')[-1].strip() name = '-'.join(meal.split('-')[:-1]).strip() return name, price
Update new open() function docs (and fix bug)
""" A substitute for the Python 3 open() function. Note that io.open() is more complete but maybe slower. Even so, the completeness may be a better default. TODO: compare these """ open_ = open class open(object): """Wrapper providing key part of Python 3 open() interface. From IPython's py3compat.py module. License: BSD. """ def __init__(self, fname, mode="r", encoding="utf-8"): self.f = open_(fname, mode) self.enc = encoding def write(self, s): return self.f.write(s.encode(self.enc)) def read(self, size=-1): return self.f.read(size).decode(self.enc) def close(self): return self.f.close() def __enter__(self): return self def __exit__(self, etype, value, traceback): self.f.close()
class open(object): """Wrapper providing key part of Python 3 open() interface. From IPython's py3compat.py module. License: BSD. """ def __init__(self, fname, mode="r", encoding="utf-8"): self.f = orig_open(fname, mode) self.enc = encoding def write(self, s): return self.f.write(s.encode(self.enc)) def read(self, size=-1): return self.f.read(size).decode(self.enc) def close(self): return self.f.close() def __enter__(self): return self def __exit__(self, etype, value, traceback): self.f.close()
Change name of SSO token parameter from sso-token to ssoToken This makes is consistent with the cookie-name that I am about to implement. The spec for cookies says hyphens are OK in the name, but not everyone's experience agrees: see https://stackoverflow.com/a/27235182 Modifies STCOR-20; relates to STCOR-38.
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; import Link from 'react-router-dom/Link'; import queryString from 'query-string'; const SSOLanding = (props) => { const search = props.location.search; if (!search) { return <div>No search string</div>; } const query = queryString.parse(search); const token = query['ssoToken']; if (!token) { return <div>No <tt>ssoToken</tt> query parameter</div>; } props.stripes.setToken(token); return ( <div> <p>Logged in with: token <tt>{token}</tt></p> <p><Link to="/">continue</Link></p> </div> ); }; SSOLanding.propTypes = { location: PropTypes.shape({ search: PropTypes.string, }).isRequired, stripes: PropTypes.shape({ setToken: PropTypes.func.isRequired, }).isRequired, }; export default withRouter(SSOLanding);
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; import Link from 'react-router-dom/Link'; import queryString from 'query-string'; const SSOLanding = (props) => { const search = props.location.search; if (!search) { return <div>No search string</div>; } const query = queryString.parse(search); const token = query['sso-token']; if (!token) { return <div>No <tt>sso-token</tt> query parameter</div>; } props.stripes.setToken(token); return ( <div> <p>Logged in with: token <tt>{token}</tt></p> <p><Link to="/">continue</Link></p> </div> ); }; SSOLanding.propTypes = { location: PropTypes.shape({ search: PropTypes.string, }).isRequired, stripes: PropTypes.shape({ setToken: PropTypes.func.isRequired, }).isRequired, }; export default withRouter(SSOLanding);
Fix loading of select2 lib Signed-off-by: Christoph Wurst <7abde52c298496fa169fb750f91f213a282142af@winzerhof-wurst.at>
import $ from 'jquery' import '@babel/polyfill' import {init} from '@sentry/browser'; import 'bootstrap' import 'select2/dist/css/select2.css' import 'select2/dist/js/select2' import 'select2/dist/js/i18n/de' import './style/weinstein.less'; import {addGlobal} from './globals'; import './entertab' import {TastersView} from './views/tasterview'; import {retastebutton} from './retastebutton'; import {setUser} from './user'; import {WineCollection} from './models/wine'; import {WinesView} from './views/wineview'; // TODO: refactor away from these globals addGlobal('$', $); addGlobal('TastersView', TastersView); addGlobal('retastebutton', retastebutton); addGlobal('WineCollection', WineCollection); addGlobal('WinesView', WinesView); addGlobal('setUser', setUser); console.debug('Weinstein dependencies and scripts loaded'); window.wsinit = ({csrfToken, dsn, release, environment}) => { $(function () { $.ajaxSetup({ headers: {'X-CSRF-TOKEN': csrfToken} }); }); try { init({ dsn, release, environment }) } catch (e) { console.error('Could not initialize Sentry:', e) } console.info('Weinstein initialized'); }
import $ from 'jquery' import '@babel/polyfill' import {init} from '@sentry/browser'; import 'bootstrap' import './style/weinstein.less'; import {addGlobal} from './globals'; import {TastersView} from './views/tasterview'; import {retastebutton} from './retastebutton'; import {setUser} from './user'; import {WineCollection} from './models/wine'; import {WinesView} from './views/wineview'; // TODO: refactor away from these globals addGlobal('$', $); addGlobal('TastersView', TastersView); addGlobal('retastebutton', retastebutton); addGlobal('WineCollection', WineCollection); addGlobal('WinesView', WinesView); addGlobal('setUser', setUser); console.debug('Weinstein dependencies and scripts loaded'); window.wsinit = ({csrfToken, dsn, release, environment}) => { $(function () { $.ajaxSetup({ headers: {'X-CSRF-TOKEN': csrfToken} }); }); try { init({ dsn, release, environment }) } catch (e) { console.error('Could not initialize Sentry:', e) } console.info('Weinstein initialized'); }
Switch period from var to val.
package main import ( log "github.com/sirupsen/logrus" "github.com/urfave/cli" "time" ) func RunPeriodically(c *cli.Context) error { log.SetFormatter(_makeFormatter(c.String("format"))) log.WithFields(log.Fields{ "appName": c.App.Name, }).Info("Running periodically") period := 1 * time.Second for { go func() { PrintHeartbeat() }() time.Sleep(period) } return nil } func PrintHeartbeat() { log.Info("Every heartbeat bears your name") } func _makeFormatter(format string) log.Formatter { switch format { case "text": return &log.TextFormatter{DisableColors: true} case "json": return &log.JSONFormatter{} default: return &log.JSONFormatter{} } }
package main import ( log "github.com/sirupsen/logrus" "github.com/urfave/cli" "time" ) func RunPeriodically(c *cli.Context) error { log.SetFormatter(_makeFormatter(c.String("format"))) log.WithFields(log.Fields{ "appName": c.App.Name, }).Info("Running periodically") var period time.Duration = 1 * time.Second for { go func() { PrintHeartbeat() }() time.Sleep(period) } return nil } func PrintHeartbeat() { log.Info("Every heartbeat bears your name") } func _makeFormatter(format string) log.Formatter { switch format { case "text": return &log.TextFormatter{DisableColors: true} case "json": return &log.JSONFormatter{} default: return &log.JSONFormatter{} } }
Remove invalid. It was for testing
var auto = require('auto-package') var content = auto.content var policystat = require('./lib') var psPrettyName = policystat.name.pretty var license = policystat.openSource.license.spdx content.name = 'policystat' content.main = 'lib/index.js' auto.versionFile() content.description = psPrettyName + ' strings for easy reuse' auto.githubRepo('mightyiam/policystat.js') content.copyright = policystat.copyrightNotice content.author = require('mightyiam').authorStr content.devDependencies = { mightyiam: '^1.1.5', 'auto-package': '^0.2.0', standard: '*', 'license-generator': '^0.0.13', 'verb-cli': '^0.4.4' } content.scripts = { license: 'license-generator install ' + license.toLowerCase() + ' -n "' + psPrettyName + '"', lint: 'standard', test: 'npm run lint && npm run license' } content.license = license
var auto = require('auto-package') var content = auto.content var policystat = require('./lib') var psPrettyName = policystat.name.pretty var license = policystat.openSource.license.spdx content.name = 'policystat' content.main = 'lib/index.js' auto.versionFile() content.description = psPrettyName + ' strings for easy reuse' auto.githubRepo('mightyiam/policystat.js') content.copyright = policystat.copyrightNotice content.author = require('mightyiam').authorStr content.devDependencies = { mightyiam: '^1.1.5', 'auto-package': '^0.2.0', standard: '*', invalid: '^0.0.2', 'license-generator': '^0.0.13', 'verb-cli': '^0.4.4' } content.scripts = { license: 'license-generator install ' + license.toLowerCase() + ' -n "' + psPrettyName + '"', lint: 'standard', test: 'npm run lint && npm run license' } content.license = license
Connect to local instance and look for signin button
/* eslint max-len: ["error", 100 ] */ /* global describe, beforeEach, afterEach, it, expect */ 'use strict'; describe('Selenium Tutorial', function() { var selenium = require('selenium-webdriver'); var timeoutMilliSec = 10 * 1000; // Open the TECH.insight website in the browser before each test is run beforeEach(function(done) { this.driver = new selenium.Builder(). withCapabilities(selenium.Capabilities.firefox()). build(); this.driver.manage().timeouts().implicitlyWait(timeoutMilliSec); jasmine.DEFAULT_TIMEOUT_INTERVAL = timeoutMilliSec; this.driver.get('http://localhost:9999/narrative/').then(done); }); // Close the website after each test is run (so that it is opened fresh each time) afterEach(function(done) { this.driver.quit().then(done); }); // Test to ensure we are on the home page by checking for username input it('Should be on the narrative tree page', function(done) { var element = this.driver.findElement(selenium.By.id('signin-button')); element.getAttribute('id').then(function(id) { expect(id).toBeDefined(); done(); }); }); });
/* eslint max-len: ["error", 100 ] */ /* global describe, beforeEach, afterEach, it, expect */ 'use strict'; describe('Selenium Tutorial', function() { var selenium = require('selenium-webdriver'); var timeoutMilliSec = 10 * 1000; // Open the TECH.insight website in the browser before each test is run beforeEach(function(done) { this.driver = new selenium.Builder(). withCapabilities(selenium.Capabilities.firefox()). build(); this.driver.manage().timeouts().implicitlyWait(timeoutMilliSec); jasmine.DEFAULT_TIMEOUT_INTERVAL = timeoutMilliSec; this.driver.get('https://narrative.kbase.us/').then(done); }); // Close the website after each test is run (so that it is opened fresh each time) afterEach(function(done) { this.driver.quit().then(done); }); // Test to ensure we are on the home page by checking for username input it('Should be on the login page', function(done) { var element = this.driver.findElement(selenium.By.name('username')); element.getAttribute('id').then(function(id) { expect(id).toBeDefined(); done(); }); }); });
Comment local unit testing from using browserstack
// Include common configuration const {karmaCommon, getKarmaConfig, defaultBrowserMatrix} = require('../../../test/karma.common'); module.exports = function (config) { const cfg = getKarmaConfig({ // I get error from browserstack/karma (not our code) when trying bs_iphone7. // If trying bs_safari it just times out. // Unit tests have been manually tested on Safari 12 though. ci: defaultBrowserMatrix.ci.filter(b => b !== 'bs_iphone7'), //local: ["bs_ie11"], // Uncomment to use browserstack browsers from home // bs_iphone bails out before running any test at all. pre_npm_publish: defaultBrowserMatrix.pre_npm_publish.filter(b => !/bs_iphone7/i.test(b)) }, { // Base path should point at the root basePath: '../../../', files: karmaCommon.files.concat([ 'dist/dexie.js', 'addons/dexie-export-import/dist/dexie-export-import.js', 'addons/dexie-export-import/test/bundle.js', { pattern: 'addons/dexie-export-import/test/*.map', watched: false, included: false }, { pattern: 'addons/dexie-export-import/dist/*.map', watched: false, included: false } ]) }); config.set(cfg); }
// Include common configuration const {karmaCommon, getKarmaConfig, defaultBrowserMatrix} = require('../../../test/karma.common'); module.exports = function (config) { const cfg = getKarmaConfig({ // I get error from browserstack/karma (not our code) when trying bs_iphone7. // If trying bs_safari it just times out. // Unit tests have been manually tested on Safari 12 though. ci: defaultBrowserMatrix.ci.filter(b => b !== 'bs_iphone7'), local: ["bs_ie11"], // Uncomment to use browserstack browsers from home // bs_iphone bails out before running any test at all. pre_npm_publish: defaultBrowserMatrix.pre_npm_publish.filter(b => !/bs_iphone7/i.test(b)) }, { // Base path should point at the root basePath: '../../../', files: karmaCommon.files.concat([ 'dist/dexie.js', 'addons/dexie-export-import/dist/dexie-export-import.js', 'addons/dexie-export-import/test/bundle.js', { pattern: 'addons/dexie-export-import/test/*.map', watched: false, included: false }, { pattern: 'addons/dexie-export-import/dist/*.map', watched: false, included: false } ]) }); config.set(cfg); }
Fix off by 1000 error
from collections import defaultdict import time TIMEOUTS = defaultdict(list) def windows(*args, **kwargs): return [] def set_timeout(func, timeout, *args, **kwargs): then = time.time() + (timeout / 1000.0) TIMEOUTS[then].append(lambda: func(*args, **kwargs)) def call_timeouts(): now = time.time() to_remove = [] for t, timeouts in TIMEOUTS.items(): if now >= t: for timeout in timeouts: timeout() to_remove.append(t) for k in to_remove: del TIMEOUTS[k] def error_message(*args, **kwargs): print(args, kwargs) class Region(object): def __init__(*args, **kwargs): pass
from collections import defaultdict import time TIMEOUTS = defaultdict(list) def windows(*args, **kwargs): return [] def set_timeout(func, timeout, *args, **kwargs): then = time.time() + timeout TIMEOUTS[then].append(lambda: func(*args, **kwargs)) def call_timeouts(): now = time.time() to_remove = [] for t, timeouts in TIMEOUTS.items(): if now >= t: for timeout in timeouts: timeout() to_remove.append(t) for k in to_remove: del TIMEOUTS[k] def error_message(*args, **kwargs): print(args, kwargs) class Region(object): def __init__(*args, **kwargs): pass
Add simple tags for title and description
from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return description.replace('\"', '\'') @register.inclusion_tag('simpleseo/metadata.html', takes_context=True) def get_seo(context): lang_code = get_language()[:2] path = context['request'].path try: metadata = SeoMetadata.objects.get(path=path, lang_code=lang_code) except SeoMetadata.DoesNotExist: metadata = None if metadata is None: return {'title': settings.FALLBACK_TITLE, 'description': settings.FALLBACK_DESCRIPTION} return {'title': metadata.title, 'description': metadata.description} @register.simple_tag(takes_context=True) def get_seo_title(context): return get_seo(context)['title'] @register.simple_tag(takes_context=True) def get_seo_description(context): return get_seo(context)['description']
from django.template import Library from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return description.replace('\"', '\'') @register.inclusion_tag('simpleseo/metadata.html', takes_context=True) def get_seo(context): request = context['request'] lang_code = request.LANGUAGE_CODE path = request.path try: metadata = SeoMetadata.objects.get(path=path, lang_code=lang_code) except SeoMetadata.DoesNotExist: metadata = None if metadata is None: return {'title': settings.FALLBACK_TITLE, 'description': settings.FALLBACK_DESCRIPTION} return {'title': metadata.title, 'description': metadata.description}
Tidy doc representation into swappable one-liner.
var peer = require('./peer'); var textOT = require('ottypes').text var gulf = require('gulf'); var text = 'hello'; var doc = require('gulf-textarea')( document.querySelector('textarea#doc') ); var path = 'chat.sock'; // var transport = require('./transports/socket')(path); // var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' }); var transport = require('./transports/webrtc')(); peer(transport).then(stream => { console.log('started'); console.log(stream.server ? 'master' : 'slave'); window.stream = stream; var textareaMaster = doc.masterLink(); if (stream.server) { // master gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, master) => { var slave1 = master.slaveLink(); stream.pipe(slave1).pipe(stream); var slave2 = master.slaveLink(); textareaMaster.pipe(slave2).pipe(textareaMaster); }); } else { // slave textareaMaster.pipe(stream).pipe(textareaMaster); } });
var peer = require('./peer'); var textOT = require('ottypes').text var gulf = require('gulf'); var bindEditor = require('gulf-textarea'); var textarea = document.querySelector('textarea#doc'); var textareaDoc = bindEditor(textarea); var text = 'hello'; var path = 'chat.sock'; // var transport = require('./transports/socket')(path); // var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' }); var transport = require('./transports/webrtc')(); peer(transport).then(stream => { console.log('started'); console.log(stream.server ? 'master' : 'slave'); window.stream = stream; var textareaMaster = textareaDoc.masterLink(); if (stream.server) { // master gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, doc) => { var slave1 = doc.slaveLink(); stream.pipe(slave1).pipe(stream); var slave2 = doc.slaveLink(); textareaMaster.pipe(slave2).pipe(textareaMaster); }); } else { // slave textareaMaster.pipe(stream).pipe(textareaMaster); } });
Modify example to perform deeper JSON-stringifys
/*jshint node:true */ "use strict"; var fs = require("fs"), util = require("util"), mp3Parser = require(__dirname + "/../mp3-parser"), pathToMp3 = process.argv[2], toArrayBuffer = function (buffer) { var bufferLength = buffer.length, i = 0, uint8Array = new Uint8Array(new ArrayBuffer(bufferLength)); for (; i < bufferLength; ++i) { uint8Array[i] = buffer[i]; } return uint8Array.buffer; }; if (!pathToMp3) { console.log("please give a path to an mp3 file, i.e. 'node parse.js <file>'"); process.exit(0); } fs.readFile(pathToMp3, function (error, buffer) { if (error) { console.log("Oops: " + error); process.exit(1); } buffer = new DataView(toArrayBuffer(buffer)); var lastFrame = mp3Parser.readLastFrame(buffer), tags = mp3Parser.readTags(buffer); util.puts("\nTags:\n-----\n" + util.inspect(tags, { depth: 4, colors: true })); util.puts("\nLast frame:\n-----------\n" + util.inspect(lastFrame, { depth: 3, colors: true })); });
/*jshint node:true */ "use strict"; var fs = require("fs"), util = require("util"), mp3Parser = require(__dirname + "/../mp3-parser"), pathToMp3 = process.argv[2], toArrayBuffer = function (buffer) { var bufferLength = buffer.length, i = 0, uint8Array = new Uint8Array(new ArrayBuffer(bufferLength)); for (; i < bufferLength; ++i) { uint8Array[i] = buffer[i]; } return uint8Array.buffer; }; if (!pathToMp3) { console.log("please give a path to an mp3 file, i.e. 'node parse.js <file>'"); process.exit(0); } fs.readFile(pathToMp3, function (error, buffer) { if (error) { console.log("Oops: " + error); process.exit(1); } buffer = new DataView(toArrayBuffer(buffer)); var lastFrame = mp3Parser.readLastFrame(buffer), tags = mp3Parser.readTags(buffer); util.puts("\nTags:\n-----\n" + util.inspect(tags, { depth: 3, colors: true })); util.puts("\nLast frame:\n-----------\n" + util.inspect(lastFrame, { depth: 3, colors: true })); });
Optimize initial message history size
// // Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi> // // 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. // /* globals $ */ export function calcMsgHistorySize() { const minLines = 40; const maxLines = 180; const lineHeight = 19; const screenHeight = $(window).height(); let twoScreenfulls = Math.floor(screenHeight / lineHeight * 1.7); return Math.min(Math.max(twoScreenfulls, minLines), maxLines); }
// // Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi> // // 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. // /* globals $ */ export function calcMsgHistorySize() { const minLines = 40; const maxLines = 180; const lineHeight = 19; const screenHeight = $(window).height(); let twoScreenfulls = Math.floor(screenHeight / lineHeight * 2); return Math.min(Math.max(twoScreenfulls, minLines), maxLines); }
Make Option extend HTMLOptionElement instead of Element Fixes #1759. Merge pull request #1760 from Dominator008/closure-compiler Closes https://github.com/google/closure-compiler/pull/1760 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=121322776
/* * Copyright 2008 The Closure Compiler Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview JavaScript Built-Ins that are not part of any specifications * but are still needed in some project's build. * @externs */ var opera = {}; opera.postError; /** @nosideeffects */ opera.version = function() {}; /** @constructor */ function XSLTProcessor() {} /** * @constructor * @extends {HTMLOptionElement} * @param {*=} opt_text * @param {*=} opt_value * @param {*=} opt_defaultSelected * @param {*=} opt_selected */ function Option(opt_text, opt_value, opt_defaultSelected, opt_selected) {} // The "methods" object is a place to hang arbitrary external // properties. It is a throwback to pre-typed days, and should // not be used for any new definitions; it exists only to bridge // the gap between the old way and the new way. var methods = {};
/* * Copyright 2008 The Closure Compiler Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview JavaScript Built-Ins that are not part of any specifications * but are still needed in some project's build. * @externs */ var opera = {}; opera.postError; /** @nosideeffects */ opera.version = function() {}; /** @constructor */ function XSLTProcessor() {} /** * @constructor @extends {Element} * @param {*=} opt_text * @param {*=} opt_value * @param {*=} opt_defaultSelected * @param {*=} opt_selected */ function Option(opt_text, opt_value, opt_defaultSelected, opt_selected) {} // The "methods" object is a place to hang arbitrary external // properties. It is a throwback to pre-typed days, and should // not be used for any new definitions; it exists only to bridge // the gap between the old way and the new way. var methods = {};
Add toJson option to verify PDF
import multihash from 'multihashes'; import bs58 from 'bs58'; import invertHash from 'invert-hash'; import objectPath from 'object-path'; import readFromPDF from './readFromPDF'; import hashPDF from './hashPDF'; import { HASH_MAP } from './hashFile'; const INVERTED_HASH_MAP = invertHash(HASH_MAP); export default function verifyPDF(src, root = 'body.content.hash', toJson) { let hash; let algorithm; return readFromPDF(src) .then(json => { if (!json) { throw new Error('Failed'); } hash = objectPath.get(json, root); const buf = new Buffer(bs58.decode(hash)); const algorithmName = multihash.decode(buf).name; algorithm = INVERTED_HASH_MAP[algorithmName]; if (typeof algorithm === 'undefined') { throw new Error('Unsupported algorithm: ' + algorithmName); } return hashPDF(src, algorithm, null); }) .then(h => { if (hash === h) { if (toJson) { return {verified: true, wants: hash, has: h}; } return true; } if (toJson) { return {verified: false, wants: hash, has: h}; } throw new Error('Failed'); }); }
import multihash from 'multihashes'; import bs58 from 'bs58'; import invertHash from 'invert-hash'; import objectPath from 'object-path'; import readFromPDF from './readFromPDF'; import hashPDF from './hashPDF'; import { HASH_MAP } from './hashFile'; const INVERTED_HASH_MAP = invertHash(HASH_MAP); export default function verifyPDF(src, root = 'body.content.hash') { let hash; let algorithm; return readFromPDF(src) .then(json => { if (!json) { throw new Error('Failed'); } hash = objectPath.get(json, root); const buf = new Buffer(bs58.decode(hash)); const algorithmName = multihash.decode(buf).name; algorithm = INVERTED_HASH_MAP[algorithmName]; if (typeof algorithm === 'undefined') { throw new Error('Unsupported algorithm: ' + algorithmName); } return hashPDF(src, algorithm, null); }) .then(h => { if (hash === h) { return true; } throw new Error('Failed'); }); }
Revert "PodioItemDif revert return fixed;" This reverts commit b5d0dc1efac82ce06a3e82106bb82f110dbc1087.
<?php /** * @see https://developers.podio.com/doc/items */ class PodioItemDiff extends PodioObject { public function __construct($attributes = array()) { $this->property('field_id', 'integer'); $this->property('type', 'string'); $this->property('external_id', 'integer'); $this->property('label', 'string'); $this->property('from', 'array'); $this->property('to', 'array'); $this->init($attributes); } /** * @see https://developers.podio.com/doc/items/revert-item-revision-953195 */ public static function revert($item_id, $revision_id) { $body = Podio::delete("/item/{$item_id}/revision/{$revision_id}"); return $body['revision']; } /** * @see https://developers.podio.com/doc/items/get-item-revision-difference-22374 */ public static function get_for($item_id, $revision_from_id, $revision_to_id) { return self::listing(Podio::get("/item/{$item_id}/revision/{$revision_from_id}/{$revision_to_id}")); } }
<?php /** * @see https://developers.podio.com/doc/items */ class PodioItemDiff extends PodioObject { public function __construct($attributes = array()) { $this->property('field_id', 'integer'); $this->property('type', 'string'); $this->property('external_id', 'integer'); $this->property('label', 'string'); $this->property('from', 'array'); $this->property('to', 'array'); $this->init($attributes); } /** * @see https://developers.podio.com/doc/items/revert-item-revision-953195 */ public static function revert($item_id, $revision_id) { $response = Podio::delete("/item/{$item_id}/revision/{$revision_id}"); if($response->body){ $body=json_decode($response->body,true); return $body['revision']; }else return false; } /** * @see https://developers.podio.com/doc/items/get-item-revision-difference-22374 */ public static function get_for($item_id, $revision_from_id, $revision_to_id) { return self::listing(Podio::get("/item/{$item_id}/revision/{$revision_from_id}/{$revision_to_id}")); } }
Revert migration version 3 to previous state
package migration import ( "errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1" "github.com/sapcc/kubernikus/pkg/client/openstack" etcd_util "github.com/sapcc/kubernikus/pkg/util/etcd" ) func CreateEtcdBackupStorageContainer(rawKluster []byte, current *v1.Kluster, client kubernetes.Interface, openstackFactory openstack.SharedOpenstackClientFactory) (err error) { secret, err := client.CoreV1().Secrets(current.GetNamespace()).Get(current.GetName(), metav1.GetOptions{}) if err != nil { return err } username, ok := secret.Data["openstack-username"] if !ok { return errors.New("openstack username secret not set") } domain, ok := secret.Data["openstack-domain-name"] if !ok { return errors.New("openstack domain name secret not set") } adminClient, err := openstackFactory.AdminClient() if err != nil { return err } err = adminClient.CreateStorageContainer( current.Spec.Openstack.ProjectID, etcd_util.DefaultStorageContainer(current), string(username), string(domain), ) return err }
package migration import ( "k8s.io/client-go/kubernetes" v1 "github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1" "github.com/sapcc/kubernikus/pkg/client/openstack" "github.com/sapcc/kubernikus/pkg/util" etcd_util "github.com/sapcc/kubernikus/pkg/util/etcd" ) func CreateEtcdBackupStorageContainer(rawKluster []byte, current *v1.Kluster, client kubernetes.Interface, openstackFactory openstack.SharedOpenstackClientFactory) (err error) { secret, err := util.KlusterSecret(client, current) if err != nil { return err } adminClient, err := openstackFactory.AdminClient() if err != nil { return err } err = adminClient.CreateStorageContainer( current.Spec.Openstack.ProjectID, etcd_util.DefaultStorageContainer(current), secret.Openstack.Username, secret.Openstack.DomainName, ) return err }
Check for error if use_3D and non-interactive
import pytest from matplotlib import pyplot as plt from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D from poliastro.plotting.misc import plot_solar_system @pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)]) def test_plot_solar_system_has_expected_number_of_orbits(outer, expected): assert len(plot_solar_system(outer).trajectories) == expected @pytest.mark.parametrize( "use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)] ) def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class): assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class) if use_3d: with pytest.raises(ValueError) as excinfo: plot_solar_system(use_3d=use_3d) assert ("The static plotter does not support 3D" in excinfo.exconly()) @pytest.mark.mpl_image_compare def test_plot_inner_solar_system_static(earth_perihelion): plot_solar_system(outer=False, epoch=earth_perihelion) return plt.gcf() @pytest.mark.mpl_image_compare def test_plot_outer_solar_system_static(earth_perihelion): plot_solar_system(outer=True, epoch=earth_perihelion) return plt.gcf()
import pytest from matplotlib import pyplot as plt from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D from poliastro.plotting.misc import plot_solar_system @pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)]) def test_plot_solar_system_has_expected_number_of_orbits(outer, expected): assert len(plot_solar_system(outer).trajectories) == expected @pytest.mark.parametrize( "use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)] ) def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class): assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class) @pytest.mark.mpl_image_compare def test_plot_inner_solar_system_static(earth_perihelion): plot_solar_system(outer=False, epoch=earth_perihelion) return plt.gcf() @pytest.mark.mpl_image_compare def test_plot_outer_solar_system_static(earth_perihelion): plot_solar_system(outer=True, epoch=earth_perihelion) return plt.gcf()
Fix validation of "hidden" checkbox not working
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Tags; use Flarum\Core\Validator\AbstractValidator; class TagValidator extends AbstractValidator { /** * {@inheritdoc} */ protected $rules = [ 'name' => ['required'], 'slug' => ['required', 'unique:tags'], 'is_hidden' => ['bool'], 'description' => ['string', 'max:700'], 'color' => ['regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i'], ]; }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Tags; use Flarum\Core\Validator\AbstractValidator; class TagValidator extends AbstractValidator { /** * {@inheritdoc} */ protected $rules = [ 'name' => ['required'], 'slug' => ['required', 'unique:tags'], 'isHidden' => ['bool'], 'description' => ['string', 'max:700'], 'color' => ['regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i'], ]; }
Fix line too long error
/** * Bootstraps and starts the http server */ 'use strict'; /** * Module dependencies * @private */ var connect = require('connect'); var http = require('http'); var morgan = require('morgan'); var qs = require('qs'); var parse = require('./parse'); var calculate = require('./calculate'); /** * Configure connect app and start http server */ module.exports = function() { var app = connect(); // Log all incoming requests to the console app.use(morgan('common')); app.use('/calculate', function(req, res) { if(req.method === 'GET') { var params = qs.parse(req.url.substring(2)); parse(params.expression, function(err, firstNum, operator, secondNum) { if(err) { res.statusCode = 422; return res.end(err); } var result = calculate(firstNum, operator, secondNum); res.end(result + ''); }); } }); // Create server and listen on port 3000 http.createServer(app).listen(3000); return app; };
/** * Bootstraps and starts the http server */ 'use strict'; /** * Module dependencies * @private */ var connect = require('connect'); var http = require('http'); var morgan = require('morgan'); var qs = require('qs'); var parse = require('./parse'); var calculate = require('./calculate'); /** * Configure connect app and start http server */ module.exports = function() { var app = connect(); // Log all incoming requests to the console app.use(morgan('common')); app.use('/calculate', function(req, res, next) { if(req.method === 'GET') { var params = qs.parse(req.url.substring(2)); parse(params.expression, function(err, firstNumber, operator, secondNumber) { if(err) { res.statusCode = 422; return res.end(err); } var result = calculate(firstNumber, operator, secondNumber); res.end(result + ''); }); } }); // Create server and listen on port 3000 http.createServer(app).listen(3000); return app; };
Fix order of tools in the toolbar (translate tool on top) CURA-838
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import TranslateTool from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "tool", "plugin": { "name": i18n_catalog.i18nc("@label", "Translate Tool"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Translate tool."), "api": 2 }, "tool": { "name": i18n_catalog.i18nc("@action:button", "Translate"), "description": i18n_catalog.i18nc("@info:tooltip", "Translate Object"), "icon": "translate", "tool_panel": "TranslateTool.qml", "weight": -1 } } def register(app): return { "tool": TranslateTool.TranslateTool() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import TranslateTool from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "tool", "plugin": { "name": i18n_catalog.i18nc("@label", "Translate Tool"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Translate tool."), "api": 2 }, "tool": { "name": i18n_catalog.i18nc("@action:button", "Translate"), "description": i18n_catalog.i18nc("@info:tooltip", "Translate Object"), "icon": "translate", "tool_panel": "TranslateTool.qml", "weight": 3 } } def register(app): return { "tool": TranslateTool.TranslateTool() }
Fix requesthandler tests (new version of datamodel).
from ppp_datamodel import Sentence, Resource from ppp_datamodel.communication import Request, TraceItem, Response from ppp_libmodule.tests import PPPTestCase from ppp_natural_math import app class TestFollowing(PPPTestCase(app)): config_var = 'PPP_NATURALMATH' config = '' def testBasics(self): q = Request('1', 'en', Resource('x'), {}, []) r = self.request(q) self.assertEqual(r, []) q = Request('1', 'en', Sentence('integral of x^y'), {}, []) r = self.request(q) self.assertEqual(len(r), 1, r) self.assertEqual(r[0].tree, Sentence('Integrate(x^y, y)')) q = Request('1', 'en', Sentence('x'), {}, []) r = self.request(q) self.assertEqual(r, []) q = Request('1', 'en', Sentence('*$$!-|'), {}, []) r = self.request(q) self.assertEqual(r, [])
from ppp_datamodel import Sentence, Resource from ppp_datamodel.communication import Request, TraceItem, Response from ppp_libmodule.tests import PPPTestCase from ppp_natural_math import app class TestFollowing(PPPTestCase(app)): config_var = 'PPP_NATURALMATH' config = '' def testBasics(self): q = Request('1', 'en', Resource('x')) r = self.request(q) self.assertEqual(r, []) q = Request('1', 'en', Sentence('integral of x^y')) r = self.request(q) self.assertEqual(len(r), 1, r) self.assertEqual(r[0].tree, Sentence('Integrate(x^y, y)')) q = Request('1', 'en', Sentence('x')) r = self.request(q) self.assertEqual(r, []) q = Request('1', 'en', Sentence('*$$!-|')) r = self.request(q) self.assertEqual(r, [])
Add proper solution for projects 18 and 67
# Project Euler # problems 18 and 67 def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums)
Allow passing arguments to dynamic placeholders
import { Action } from './../lib/Action'; import { Util } from '@aegis-framework/artemis'; export class Placeholder extends Action { static matchString ([ action ]) { return action === '$'; } constructor ([action, name, ...args]) { super (); this.name = name; this.action = this.engine.$ (name); this.arguments = args; } willApply () { if (this.name.indexOf ('_') === 0) { return Util.callAsync (this.action, this.engine, ...this.arguments).then ((action) => { this.action = action; return Promise.resolve (); }); } return Promise.resolve (); } apply () { return this.engine.run (this.action); } revert () { return this.engine.revert (this.action); } } Placeholder.id = 'Placeholder'; export default Placeholder;
import { Action } from './../lib/Action'; import { Util } from '@aegis-framework/artemis'; export class Placeholder extends Action { static matchString ([ action ]) { return action === '$'; } constructor ([action, name]) { super (); this.name = name; this.action = this.engine.$ (name); } willApply () { if (this.name.indexOf ('_') === 0) { return Util.callAsync (this.action, this.engine).then ((action) => { this.action = action; return Promise.resolve (); }); } return Promise.resolve (); } apply () { return this.engine.run (this.action); } revert () { return this.engine.revert (this.action); } } Placeholder.id = 'Placeholder'; export default Placeholder;
Disable timeslots that have passed Refs #42.
import moment from 'moment'; import React, { Component, PropTypes } from 'react'; import { Label } from 'react-bootstrap'; export class TimeSlot extends Component { render() { const { onChange, selected, slot } = this.props; const disabled = slot.reserved || moment(slot.end) < moment(); return ( <tr className={slot.reserved ? 'reserved' : ''}> <td style={{ textAlign: 'center' }}> <input checked={slot.reserved || selected} disabled={disabled} onChange={() => onChange(slot.asISOString)} type="checkbox" /> </td> <td> <time dateTime={slot.asISOString}> {slot.asString} </time> </td> <td> <Label bsStyle={slot.reserved ? 'danger' : 'success'}> {slot.reserved ? 'Varattu' : 'Vapaa'} </Label> </td> </tr> ); } } TimeSlot.propTypes = { onChange: PropTypes.func.isRequired, selected: PropTypes.bool.isRequired, slot: PropTypes.object.isRequired, }; export default TimeSlot;
import React, { Component, PropTypes } from 'react'; import { Label } from 'react-bootstrap'; export class TimeSlot extends Component { render() { const { onChange, selected, slot } = this.props; return ( <tr className={slot.reserved ? 'reserved' : ''}> <td style={{ textAlign: 'center' }}> <input checked={slot.reserved || selected} disabled={slot.reserved} onChange={() => onChange(slot.asISOString)} type="checkbox" /> </td> <td> <time dateTime={slot.asISOString}> {slot.asString} </time> </td> <td> <Label bsStyle={slot.reserved ? 'danger' : 'success'}> {slot.reserved ? 'Varattu' : 'Vapaa'} </Label> </td> </tr> ); } } TimeSlot.propTypes = { onChange: PropTypes.func.isRequired, selected: PropTypes.bool.isRequired, slot: PropTypes.object.isRequired, }; export default TimeSlot;
Upgrade version to publish a release without tests
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() classifiers = [ 'Programming Language :: Python :: 3', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved', 'Intended Audience :: Developers', 'Natural Language :: French', 'Operating System :: OS Independent', 'Topic :: Utilities', ] setup(name='PyEventEmitter', version='1.0.3', description='Simple python events library', long_description=long_description, author='Etienne Tissieres', author_email='etienne.tissieres@gmail.com', url='https://github.com/etissieres/PyEventEmitter', packages=['event_emitter'], license='MIT', classifiers=classifiers)
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() classifiers = [ 'Programming Language :: Python :: 3', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved', 'Intended Audience :: Developers', 'Natural Language :: French', 'Operating System :: OS Independent', 'Topic :: Utilities', ] setup(name='PyEventEmitter', version='1.0.2', description='Simple python events library', long_description=long_description, author='Etienne Tissieres', author_email='etienne.tissieres@gmail.com', url='https://github.com/etissieres/PyEventEmitter', packages=['event_emitter'], license='MIT', classifiers=classifiers)
Reduce the column size for well known content
package org.ligoj.app.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import org.ligoj.bootstrap.core.model.AbstractAudited; import lombok.Getter; import lombok.Setter; /** * A message to target audience. */ @Getter @Setter @Entity @Table(name = "LIGOJ_MESSAGE") public class Message extends AbstractAudited<Integer> { /** * SID */ private static final long serialVersionUID = 1L; /** * Type of target (group, user, ...). When <code>null</code> the target is everybody. * * @see MessageTargetType */ @Enumerated(EnumType.STRING) @NotNull @Column(length = 10) private MessageTargetType targetType; /** * Optional related target : user, group, node, ... */ @NotNull private String target; /** * Value of the message. */ @Length(max = 500) @NotNull @NotBlank private String value; }
package org.ligoj.app.model; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import org.ligoj.bootstrap.core.model.AbstractAudited; import lombok.Getter; import lombok.Setter; /** * A message to target audience. */ @Getter @Setter @Entity @Table(name = "LIGOJ_MESSAGE") public class Message extends AbstractAudited<Integer> { /** * SID */ private static final long serialVersionUID = 1L; /** * Type of target (group, user, ...). When <code>null</code> the target is everybody. * * @see MessageTargetType */ @Enumerated(EnumType.STRING) @NotNull private MessageTargetType targetType; /** * Optional related target : user, group, node, ... */ @NotNull private String target; /** * Value of the message. */ @Length(max = 500) @NotNull @NotBlank private String value; }
Add proper URL for getting json on GitHub
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("INPUT"); submit.setAttribute("id", "submit"); submit.setAttribute("type", "button"); submit.setAttribute("value", "Consultar descargas de última versión"); p.appendChild(label); form.appendChild(p); form.appendChild(submit); aside.appendChild(form); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/" + input.value + "releases/latest", function(json) { var name = json.name; }); }); });
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("INPUT"); submit.setAttribute("id", "submit"); submit.setAttribute("type", "button"); submit.setAttribute("value", "Consultar descargas de última versión"); p.appendChild(label); form.appendChild(p); form.appendChild(submit); aside.appendChild(form); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/releases/latest", function(json) { var name = json.name; }); }); });
Improve code: Add semi-colon after closing curly-braces for functions.
var portal = require('/lib/xp/portal'); // Import the portal functions var thymeleaf = require('/lib/xp/thymeleaf'); // Import the Thymeleaf rendering function // Handle the GET request exports.get = function(req) { // Get the content that is using the page var content = portal.getContent(); var site = portal.getSite(); // Extract the main region which contains component parts var mainRegion = content.page.regions.main; // Prepare the model that will be passed to the view var model = { site: site, mainRegion: mainRegion }; // Specify the view file to use var view = resolve('form-page.html'); // Render the dynamic HTML with values from the model var body = thymeleaf.render(view, model); // Return the response object return { body: body }; };
var portal = require('/lib/xp/portal'); // Import the portal functions var thymeleaf = require('/lib/xp/thymeleaf'); // Import the Thymeleaf rendering function // Handle the GET request exports.get = function(req) { // Get the content that is using the page var content = portal.getContent(); var site = portal.getSite(); // Extract the main region which contains component parts var mainRegion = content.page.regions.main; // Prepare the model that will be passed to the view var model = { site: site, mainRegion: mainRegion } // Specify the view file to use var view = resolve('form-page.html'); // Render the dynamic HTML with values from the model var body = thymeleaf.render(view, model); // Return the response object return { body: body } };
Fix typo and namespace root
<?php /** * Helper functions to work with the Twig template engine. */ namespace Siler\Twig; use Siler\Container; /** * Initialize the Twig environment. * * @param string $templatesPath Path to templates * @param string $templatesCachePath Path to templates cache * @param bool $debug Should TwigEnv allow debugging * * @return \Twig_Environment */ function init($templatesPath, $templatesCachePath = null, $debug = null) { if (is_null($templatesCachePath)) { $templatesCachePath = false; } if (is_null($debug)) { $debug = false; } $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($templatesPath), [ 'debug' => $debug, 'cache' => $templatesCachePath, ]); Container\set('twig', $twig); return $twig; } /** * Renders the given template within the given data. * * @param string $name The template name in the templates path * @param array $data The array of data to used within the template * * @throws \RuntimeException if Twig isn't initialized * * @return string */ function render($name, $data = []) { $twig = Container\get('twig'); if (is_null($twig)) { throw new \RuntimeException('Twig should be initialized first'); } return $twig->render($name, $data); }
<?php /** * Helper functions to work with the Twig template engine. */ namespace Siler\Twig; use Siler\Container; /** * Initialze the Twig environment. * * @param string $templatesPath Path to templates * @param string $templatesCachePath Path to templates cache * @param bool $debug Should TwigEnv allow debugging * * @return \Twig_Environment */ function init($templatesPath, $templatesCachePath = null, $debug = null) { if (is_null($templatesCachePath)) { $templatesCachePath = false; } if (is_null($debug)) { $debug = false; } $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($templatesPath), [ 'debug' => $debug, 'cache' => $templatesCachePath, ]); Container\set('twig', $twig); return $twig; } /** * Renders the given template within the given data. * * @param string $name The template name in the templates path * @param array $data The array of data to used within the template * * @throws RuntimeException if Twig isn't initialized * * @return string */ function render($name, $data = []) { $twig = Container\get('twig'); if (is_null($twig)) { throw new \RuntimeException('Twig should be initialized first'); } return $twig->render($name, $data); }
Fix typo that made private notes viewable by any other user.
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from django.db import models class NoteManager(models.Manager): def user_viewable(self, request_user, author): notes = self.filter(author=author) if request_user != author: # Public notes only notes = notes.filter(permissions=1) return notes
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from django.db import models class NoteManager(models.Manager): def user_viewable(self, request_user, author): notes = self.filter(author=author) if request_user != author: # Public notes only notes.filter(permissions=1) return notes
Test push after changing local remote
angular.module('gitphaser').controller('NearbyCtrl', NearbyCtrl); /** * Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter' * Subscription to 'connections' is handled in the route resolve. Also * exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user * clicks on list item to see profile) * @controller NearbyCtrl * @route: /tab/nearby */ function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){ $reactive(this).attach($scope); var self = this; // Slide constants bound to the GeoLocate directive // and other DOM events, trigger updates based on // whether we are looking at List || Map view. self.listSlide = 0 self.mapSlide = 1; self.slide = 0; // Services self.geolocate = GeoLocate; self.notify = Notify; self.helpers({ connections: function () { if (Meteor.userId()){ return Connections.find( {transmitter: Meteor.userId() } ); } } }); };
angular.module('gitphaser') .controller('NearbyCtrl', NearbyCtrl); // @controller NearbyCtrl // @params: $scope, $reactive // @route: /tab/nearby // // Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter' // Subscription to 'connections' is handled in the route resolve. Also // exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user // clicks on list item to see profile) function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){ $reactive(this).attach($scope); var self = this; // Slide constants bound to the GeoLocate directive // and other DOM events, trigger updates based on // whether we are looking at List || Map view. self.listSlide = 0 self.mapSlide = 1; self.slide = 0; // Services self.geolocate = GeoLocate; self.notify = Notify; self.helpers({ connections: function () { if (Meteor.userId()){ return Connections.find( {transmitter: Meteor.userId() } ); } } }); };
Fix amount of partner logos.
<?php /* Template Name: Partner */ ?> <div class="large-12 medium-12 small-12 column"> <?php get_template_part('templates/page', 'header'); ?> <?php get_template_part('templates/content', 'page'); ?> <div class="partner-logos"> <?php if( have_rows('partner_logos') ) { ?> <ul class="large-block-grid-3 medium-block-grid-3 small-block-grid-2"> <?php while ( have_rows('partner_logos') ) { the_row(); ?> <li> <?php $sub = get_sub_field('logo_image'); ?> <img src="<?php echo $sub['url']; ?>"> </li> <?php } ?> </ul> <?php } ?> </div> </div>
<?php /* Template Name: Partner */ ?> <div class="large-12 medium-12 small-12 column"> <?php get_template_part('templates/page', 'header'); ?> <?php get_template_part('templates/content', 'page'); ?> <div class="partner-logos"> <?php if( have_rows('partner_logos') ) { ?> <ul class="large-block-grid-5 medium-block-grid-3 small-block-grid-2"> <?php while ( have_rows('partner_logos') ) { the_row(); ?> <li> <?php $sub = get_sub_field('logo_image'); ?> <img src="<?php echo $sub['url']; ?>"> </li> <?php } ?> </ul> <?php } ?> </div> </div>
Print JSON string to response object
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package servlets; import data.FileParser; import java.io.IOException; import java.util.ArrayList; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; @WebServlet("/VendorServlet") public class VendorServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // GET method --> returns a JSON array of existing Vendor IDs FileParser fileParser = new FileParser(); ArrayList<String> vendorIDs = fileParser.getVendorIDs(); Gson gson = new Gson(); String json = gson.toJson(vendorIDs); response.setContentType("text/html;"); response.getWriter().println(json); } @Override public void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException { // DELETE method --> deletes vendor configuration directory } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package servlets; import data.FileParser; import java.io.IOException; import java.util.ArrayList; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; @WebServlet("/VendorServlet") public class VendorServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // GET method --> returns a JSON array of existing Vendor IDs FileParser fileParser = new FileParser(); ArrayList<String> vendorIDs = fileParser.getVendorIDs(); Gson gson = new Gson(); String dummyResponse = "[\"CADE01\",\"VINCENT01\",\"CHARLIE01\",\"JAKE01\",\"IAN01\"]"; response.setContentType("text/html;"); response.getWriter().println(dummyResponse); } @Override public void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException { // DELETE method --> deletes vendor configuration directory } }
Bring in code commented out for tests
var queue = require('queue-async'); var _ = require('underscore'); function MapConfigNamedLayersAdapter(overviewsApi) { this.overviewsApi = overviewsApi; } module.exports = MapConfigNamedLayersAdapter; MapConfigNamedLayersAdapter.prototype.getLayers = function(username, layers, callback) { var self = this; if (!layers) { return callback(null); } var augmentLayersQueue = queue(layers.length); function augmentLayer(layer, done) { self.overviewsApi.getOverviewsMetadata(username, layer.options.sql, function(err, metadata){ if (err) { done(err, layer); } else { if ( !_.isEmpty(metadata) ) { layer = _.extend({}, layer, { overviews: metadata }); } done(null, layer); } }); } function layersAugmentQueueFinish(err, layers) { if (err) { return callback(err); } if (!layers || layers.length === 0) { return callback(new Error('Missing layers array from layergroup config')); } return callback(null, layers); } layers.forEach(function(layer) { augmentLayersQueue.defer(augmentLayer, layer); }); augmentLayersQueue.awaitAll(layersAugmentQueueFinish); };
var queue = require('queue-async'); var _ = require('underscore'); function MapConfigNamedLayersAdapter(overviewsApi) { this.overviewsApi = overviewsApi; } module.exports = MapConfigNamedLayersAdapter; MapConfigNamedLayersAdapter.prototype.getLayers = function(username, layers, callback) { var self = this; if (!layers) { return callback(null); } var augmentLayersQueue = queue(layers.length); function augmentLayer(layer, done) { self.overviewsApi.getOverviewsMetadata(username, layer.options.sql, function(err, metadata){ if (err) { done(err, layer); } else { if ( !_.isEmpty(metadata) ) { // layer = _.extend({}, layer, { overviews: metadata }); } done(null, layer); } }); } function layersAugmentQueueFinish(err, layers) { if (err) { return callback(err); } if (!layers || layers.length === 0) { return callback(new Error('Missing layers array from layergroup config')); } return callback(null, layers); } layers.forEach(function(layer) { augmentLayersQueue.defer(augmentLayer, layer); }); augmentLayersQueue.awaitAll(layersAugmentQueueFinish); };
Revert back to custom class servo
package com.rmrobotics.library; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.Range; /** * Created by RM Robotics on 11/23/2015. */ public class rServo{ private static final double MAX_POWER = 1.0; private static final double MIN_POWER = 0.1; private Servo parent; private Servo.Direction defaultDirection; private double minPower; private double maxPower; private double desiredPower; private double currentPower; private boolean isContinuous; public rServo(Servo s, boolean x){ parent = s; isContinuous = x; if(!isContinuous){ maxPower = 0.9; minPower = 0.1; } else { maxPower = 1; minPower = 0; } } public void set(double x) { desiredPower = x; currentPower = speedCheck(desiredPower); //TODO feed power to servo } private double speedCheck(double p){ p = Range.clip(minPower, maxPower); } }
package com.rmrobotics.library; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.Range; /** * Created by RM Robotics on 11/23/2015. */ public class rServo extends Servo { private double minPower; private double maxPower; private double desiredPower; private double currentPower; private boolean isContinuous; public rServo(boolean x) { isContinuous = x; if (!isContinuous) { maxPower = 0.9; minPower = 0.1; } else { maxPower = 1; minPower = 0.1; } } public void set(double x) { desiredPower = x; currentPower = Range.clip(desiredPower, minPower, maxPower); setPosition(currentPower); } }
Setup.py: Fix author field and maintainer one
from setuptools import setup, find_packages import os name = 'docrepr' here = os.path.abspath(os.path.dirname(__file__)) version_ns = {} with open(os.path.join(here, name, '_version.py')) as f: exec(f.read(), {}, version_ns) setup( name=name, version=version_ns['__version__'], description='docrepr renders Python docstrings in HTML', long_description='docrepr renders Python docstrings in HTML. It is based on the sphinxify module developed by Tim Dumol for the Sage Notebook and the utils.inspector developed for ther Spyder IDE.', packages=find_packages(), include_package_data=True, install_requires=['docutils', 'jinja2', 'sphinx'], url='https://github.com/spyder-ide/docrepr', author='Tim Dumol / The Spyder Development Team', maintainer='The Spyder Development Team', license='BSD', )
from setuptools import setup, find_packages import os name = 'docrepr' here = os.path.abspath(os.path.dirname(__file__)) version_ns = {} with open(os.path.join(here, name, '_version.py')) as f: exec(f.read(), {}, version_ns) setup( name=name, version=version_ns['__version__'], description='docrepr renders Python docstrings in HTML', long_description='docrepr renders Python docstrings in HTML. It is based on the sphinxify module developed by Tim Dumol for the Sage Notebook and the utils.inspector developed for ther Spyder IDE.', packages=find_packages(), include_package_data=True, install_requires=['docutils', 'jinja2', 'sphinx'], url='https://github.com/spyder-ide/docrepr', author='The Spyder Development Team', license='BSD', )