text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove dev suffix from version It is not a valid Python version specifier.
#!/usr/bin/env python3 from setuptools import setup with open("README.rst") as file: long_description = file.read() setup( name="tvnamer", version="1.0.0", description="Utility to rename lots of TV video files using the TheTVDB.", long_description=long_description, author="Tom Leese", author_email="inbox@tomleese.me.uk", url="https://github.com/tomleese/tvnamer", packages=["tvnamer"], test_suite="tests", install_requires=[ "pytvdbapi", "pyside" ], entry_points={ "console_scripts": [ "tvnamer = tvnamer:main", "tvnamer-cli = tvnamer.cli:main" ], 'gui_scripts': [ "tvnamer-gui = tvnamer.gui:main", ] }, classifiers=[ "Topic :: Internet", "Topic :: Multimedia :: Video", "Development Status :: 2 - Pre-Alpha", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4" ] )
#!/usr/bin/env python3 from setuptools import setup with open("README.rst") as file: long_description = file.read() setup( name="tvnamer", version="1.0.0-dev", description="Utility to rename lots of TV video files using the TheTVDB.", long_description=long_description, author="Tom Leese", author_email="inbox@tomleese.me.uk", url="https://github.com/tomleese/tvnamer", packages=["tvnamer"], test_suite="tests", install_requires=[ "pytvdbapi", "pyside" ], entry_points={ "console_scripts": [ "tvnamer = tvnamer:main", "tvnamer-cli = tvnamer.cli:main" ], 'gui_scripts': [ "tvnamer-gui = tvnamer.gui:main", ] }, classifiers=[ "Topic :: Internet", "Topic :: Multimedia :: Video", "Development Status :: 2 - Pre-Alpha", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4" ] )
Fix import path for rest plugins
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from http_test_suite import HTTPTestSuite from mozdef_util.utilities.dot_dict import DotDict import mock from configlib import OptionParser import importlib class RestTestDict(DotDict): @property def __dict__(self): return self class RestTestSuite(HTTPTestSuite): def setup(self): sample_config = RestTestDict() sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf') OptionParser.parse_args = mock.Mock(return_value=(sample_config, {})) sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../rest")) import plugins importlib.reload(plugins) from rest import index self.application = index.application super(RestTestSuite, self).setup()
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from http_test_suite import HTTPTestSuite from mozdef_util.utilities.dot_dict import DotDict import mock from configlib import OptionParser class RestTestDict(DotDict): @property def __dict__(self): return self class RestTestSuite(HTTPTestSuite): def setup(self): sample_config = RestTestDict() sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf') OptionParser.parse_args = mock.Mock(return_value=(sample_config, {})) from rest import index self.application = index.application super(RestTestSuite, self).setup()
Add build world, Lesson 7
// Preloader.js BunnyDefender.Preloader = function (game) { this.preloadBar = null; this.titleText = null; this.ready = false; }; BunnyDefender.Preloader.prototype.preload = function () { this.preloadBar = this.add.sprite(this.world.centerX, this.world.centerY, 'preloaderBar'); this.preloadBar.anchor.setTo(0.5, 0.5); this.load.setPreloadSprite(this.preloadBar); this.titleText = this.add.image(this.world.centerX, this.world.centerY - 220, 'titleimage'); this.titleText.anchor.setTo(0.5, 0.5); this.load.image('titlescreen', 'images/TitleBG.png'); this.load.bitmapFont('eightbitwonder', 'fonts/eightbitwonder.png', 'fonts/eightbitwonder.fnt'); this.load.image('hill', 'images/hill.png'); this.load.image('sky', 'images/sky.png'); }; BunnyDefender.Preloader.prototype.create = function () { this.preloadBar.cropEnabled = false; }; BunnyDefender.Preloader.prototype.update = function () { this.ready = true; this.state.start('StartMenu'); };
// Preloader.js BunnyDefender.Preloader = function (game) { this.preloadBar = null; this.titleText = null; this.ready = false; }; BunnyDefender.Preloader.prototype.preload = function () { this.preloadBar = this.add.sprite(this.world.centerX, this.world.centerY, 'preloaderBar'); this.preloadBar.anchor.setTo(0.5, 0.5); this.load.setPreloadSprite(this.preloadBar); this.titleText = this.add.image(this.world.centerX, this.world.centerY - 220, 'titleimage'); this.titleText.anchor.setTo(0.5, 0.5); this.load.image('titlescreen', 'images/TitleBG.png'); this.load.bitmapFont('eightbitwonder', 'fonts/eightbitwonder.png', 'fonts/eightbitwonder.fnt'); }; BunnyDefender.Preloader.prototype.create = function () { this.preloadBar.cropEnabled = false; }; BunnyDefender.Preloader.prototype.update = function () { this.ready = true; this.state.start('StartMenu'); };
Update GitHub repos from blancltd to developersociety
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='blanc-contentfiles', version='0.2.4', description='Blanc Content Files', long_description=readme, url='https://github.com/developersociety/blanc-contentfiles', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='blanc-contentfiles', version='0.2.4', description='Blanc Content Files', long_description=readme, url='https://github.com/blancltd/blanc-contentfiles', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
Add js-enabled class to body if doesn't exist
// Vendor assets //= require jquery //= require jquery_ujs //= require jquery-ui-autocomplete //= require modernizr-custom //= require dest/respond.min // GOVUK modules //= require govuk_toolkit //= require vendor/polyfills/bind //= require govuk/selection-buttons // MOJ elements //= require moj //= require src/moj.TimeoutPrompt // Candidates for re-usable components //= require modules/moj.analytics //= require modules/moj.autocomplete //= require modules/moj.hijacks //= require modules/moj.submit-once //= require modules/moj.Conditional //= require modules/moj.RevealAdditional //= require modules/moj.checkbox-summary //= require modules/moj.AgeLabel.js //= require modules/moj.booking-calendar //= require modules/moj.set-dimension //= require modules/moj.AsyncGA (function() { 'use strict'; if (!document.body.classList.contains('js-enabled')) { document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled'); } delete moj.Modules.devs; var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']"); moj.init(); }());
// Vendor assets //= require jquery //= require jquery_ujs //= require jquery-ui-autocomplete //= require modernizr-custom //= require dest/respond.min // GOVUK modules //= require govuk_toolkit //= require vendor/polyfills/bind //= require govuk/selection-buttons // MOJ elements //= require moj //= require src/moj.TimeoutPrompt // Candidates for re-usable components //= require modules/moj.analytics //= require modules/moj.autocomplete //= require modules/moj.hijacks //= require modules/moj.submit-once //= require modules/moj.Conditional //= require modules/moj.RevealAdditional //= require modules/moj.checkbox-summary //= require modules/moj.AgeLabel.js //= require modules/moj.booking-calendar //= require modules/moj.set-dimension //= require modules/moj.AsyncGA (function() { 'use strict'; delete moj.Modules.devs; var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']"); moj.init(); }());
Switch off debugging func that got through...
import pyrc import pyrc.utils.hooks as hooks class GangstaBot(pyrc.Bot): @hooks.command() def bling(self, channel, sender): "will print yo" self.message(channel, "%s: yo" % sender) @hooks.command("^repeat\s+(?P<msg>.+)$") def repeat(self, channel, sender, **kwargs): "will repeat whatever yo say" self.message(channel, "%s: %s" % (sender, kwargs["msg"])) @hooks.privmsg("(lol|lmao|rofl(mao)?)") def stopword(self, channel, sender, *args): """ will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message """ self.message(channel, args[0]) @hooks.interval(10000) def keeprepeating(self): "will say something" self.message("#turntechgodhead", "stop repeating myself") if __name__ == '__main__': bot = GangstaBot('irc.freenode.net', channels = ['#turntechgodhead']) bot.connect()
import pyrc import pyrc.utils.hooks as hooks class GangstaBot(pyrc.Bot): @hooks.command() def bling(self, channel, sender): "will print yo" self.message(channel, "%s: yo" % sender) @hooks.command("^repeat\s+(?P<msg>.+)$") def repeat(self, channel, sender, **kwargs): "will repeat whatever yo say" self.message(channel, "%s: %s" % (sender, kwargs["msg"])) @hooks.privmsg("(lol|lmao|rofl(mao)?)") def stopword(self, channel, sender, *args): """ will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message """ print(args) self.message(channel, args[0]) @hooks.interval(10000) def keeprepeating(self): "will say something" self.message("#turntechgodhead", "stop repeating myself") if __name__ == '__main__': bot = GangstaBot('irc.freenode.net', channels = ['#turntechgodhead']) bot.connect()
Add comment for future work
import selftest from '../selftest'; import { parse, markBottom } from '../parse-stack'; import _ from 'underscore'; import Fiber from 'fibers'; import Future from 'fibers/future'; selftest.define("parse-stack - parse stack traces without fibers", () => { const err = new Error(); const parsedStack = parse(err); selftest.expectEqual(_.last(parsedStack[0].file.split("/")), "parse-stack-test.js"); markBottom(() => { const markedErr = new Error(); const parsedStack = parse(markedErr); // The stack trace should only contain this one function since we marked the // bottom selftest.expectEqual(parsedStack.length, 1); selftest.expectEqual(_.last(parsedStack[0].file.split("/")), "parse-stack-test.js"); })(); }); // XXX I really want to add a test here for the crazy double-stack-trace Fiber // situation, but I don't know how to create it inside a test.
import selftest from '../selftest'; import { parse, markBottom } from '../parse-stack'; import _ from 'underscore'; import Fiber from 'fibers'; import Future from 'fibers/future'; selftest.define("parse-stack - parse stack traces without fibers", () => { const err = new Error(); const parsedStack = parse(err); selftest.expectEqual(_.last(parsedStack[0].file.split("/")), "parse-stack-test.js"); markBottom(() => { const markedErr = new Error(); const parsedStack = parse(markedErr); // The stack trace should only contain this one function since we marked the // bottom selftest.expectEqual(parsedStack.length, 1); selftest.expectEqual(_.last(parsedStack[0].file.split("/")), "parse-stack-test.js"); })(); });
Check for subclasses of ElementpageExtension as well
<?php /** * @package elemental */ class ElementalArea extends WidgetArea { public function Elements() { $result = $this->getComponents('Widgets'); $list = new HasManyList('BaseElement', $result->getForeignKey()); $list->setDataModel($this->model); $list->sort('Sort ASC'); $list = $list->forForeignID($this->ID); return $list; } /** * Return an ArrayList of pages with the Element Page Extension * * @return ArrayList */ public function getOwnerPage() { foreach (get_declared_classes() as $class) { if (is_subclass_of($class, 'SiteTree')) { $object = singleton($class); $classes = ClassInfo::subclassesFor('ElementPageExtension'); $isElemental = false; foreach($classes as $extension) { if($object->hasExtension($extension)) $isElemental = true; } if($isElemental) { $page = $class::get()->filter('ElementAreaID', $this->ID); if($page && $page->exists()) { return $page->first(); } } } } return false; } }
<?php /** * @package elemental */ class ElementalArea extends WidgetArea { public function Elements() { $result = $this->getComponents('Widgets'); $list = new HasManyList('BaseElement', $result->getForeignKey()); $list->setDataModel($this->model); $list->sort('Sort ASC'); $list = $list->forForeignID($this->ID); return $list; } /** * Return an ArrayList of pages with the Element Page Extension * * @return ArrayList */ public function getOwnerPage() { foreach (get_declared_classes() as $class) { if (is_subclass_of($class, 'SiteTree')) { $object = singleton($class); if ($object->hasExtension('ElementPageExtension')) { $page = $class::get()->filter('ElementAreaID', $this->ID); if ($page->exists()) { return $page->First(); } } } } return false; } }
Remove subclassing of exception, since there is only one.
# -*- encoding: utf-8 -*- # Odoo, Open Source Management Solution # Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # # 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 openerp import _, exceptions class EmptyNames(exceptions.ValidationError): def __init__(self, record, value=_("No name is set.")): self.record = record self._value = value self.name = _("Error(s) with partner %d's name.") % record.id
# -*- encoding: utf-8 -*- # Odoo, Open Source Management Solution # Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # # 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 openerp import _, exceptions class PartnerNameError(exceptions.ValidationError): def __init__(self, record, value=None): self.record = record self._value = value self.name = _("Error(s) with partner %d's name.") % record.id @property def value(self): raise NotImplementedError() class EmptyNames(PartnerNameError): @property def value(self): return _("No name is set.")
Fix bug in endpoint test opn heroku
import express from 'express'; import logger from 'morgan'; import bodyParser from 'body-parser'; import routes from './routes'; const app = express(); const port = process.env.PORT || 3001; app.use(logger('dev')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api-docs', express.static('docs')); app.use('/api/v1/', routes); if (process.env.NODE_ENV === 'production') { app.use('/', express.static('client/build')); app.use('/dashboard', express.static('client/build')); } if (process.env.NODE_ENV === 'production') { app.use('*', express.static('client/build')); } app.get('/', (req, res) => { res.status(201).json({ title: 'More-Recipes', message: 'Please navigate this API via \'/api/v1/\' url prefix' }); }); app.get('*', (req, res) => { res.status(404).send({ success: false, message: 'invalid link' }); }); app.post('*', (req, res) => { res.status(404).send({ success: false, message: 'invalid link' }); }); app.listen(port, () => { }); export default app;
import express from 'express'; import logger from 'morgan'; import bodyParser from 'body-parser'; import routes from './routes'; const app = express(); const port = process.env.PORT || 3001; app.use(logger('dev')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api-docs', express.static('docs')); app.use('/api/v1', routes); if (process.env.NODE_ENV === 'production') { app.use('/', express.static('client/build')); app.use('/dashboard', express.static('client/build')); } if (process.env.NODE_ENV === 'production') { app.use('*', express.static('client/build')); } app.get('/', (req, res) => { res.status(201).json({ title: 'More-Recipes', message: 'Please navigate this API via \'/api/v1/\' url prefix' }); }); app.get('*', (req, res) => { res.status(404).send({ success: false, message: 'invalid link' }); }); app.post('*', (req, res) => { res.status(404).send({ success: false, message: 'invalid link' }); }); app.listen(port, () => { }); export default app;
Disable parallelism, caching for terser
// @ts-check const path = require("path") const WebpackManifestPlugin = require("webpack-manifest-plugin") const { HashedModuleIdsPlugin } = require("webpack") const { getCSSManifest } = require("../utils/getCSSManifest") const TerserPlugin = require("terser-webpack-plugin") const { BUILD_SERVER, NODE_ENV, isProduction, } = require("../../src/lib/environment") const buildCSS = isProduction && !BUILD_SERVER exports.productionConfig = { parallelism: 75, mode: NODE_ENV, devtool: "source-map", output: { filename: "[name].[contenthash].js", }, plugins: [ new HashedModuleIdsPlugin(), new WebpackManifestPlugin({ fileName: path.resolve(__dirname, "../../manifest.json"), basePath: "/assets/", seed: buildCSS ? getCSSManifest() : {}, }), ], optimization: { minimizer: [ new TerserPlugin({ cache: false, parallel: false, sourceMap: true, // Must be set to true if using source-maps in production }), ], }, }
// @ts-check const path = require("path") const WebpackManifestPlugin = require("webpack-manifest-plugin") const { HashedModuleIdsPlugin } = require("webpack") const { getCSSManifest } = require("../utils/getCSSManifest") const { BUILD_SERVER, NODE_ENV, isProduction, } = require("../../src/lib/environment") const buildCSS = isProduction && !BUILD_SERVER exports.productionConfig = { parallelism: 75, mode: NODE_ENV, devtool: "source-map", output: { filename: "[name].[contenthash].js", }, plugins: [ new HashedModuleIdsPlugin(), new WebpackManifestPlugin({ fileName: path.resolve(__dirname, "../../manifest.json"), basePath: "/assets/", seed: buildCSS ? getCSSManifest() : {}, }), ], optimization: { minimize: false, }, }
Add Lunar scene to menu
import React from 'react'; import DinoScene from '../../aframe/components/DinoScene'; import WarScene from '../../aframe/components/WarScene'; import MoonScene from '../../aframe/components/MoonScene'; const pooScenes = { war: WarScene, dino: DinoScene, moon: MoonScene, } class PickYourPoo extends React.Component { constructor(props) { super(props); this.state = {}; } loadPoo(poo) { this.setState({ scene: pooScenes[poo] }); } render () { if (this.state.scene) { return <this.state.scene />; } else { return ( <div> <h1 class="title">PoopVR</h1> <i class="em em-poop"></i> <div class="status"> <p>Pick your Poo!</p> </div> <ul> <li onClick={() => this.loadPoo('war')}>World War Two</li> <li onClick={() => this.loadPoo('dino')}>Prehistoric Poo</li> <li onClick={() => this.loadPoo('moon')}>Lunar Poo</li> </ul> </div> ); } } }; module.exports = PickYourPoo;
import React from 'react'; import DinoScene from '../../aframe/components/DinoScene'; import WarScene from '../../aframe/components/WarScene'; const pooScenes = { war: WarScene, dino: DinoScene, } class PickYourPoo extends React.Component { constructor(props) { super(props); this.state = {}; } loadPoo(poo) { this.setState({ scene: pooScenes[poo] }); } render () { if (this.state.scene) { return <this.state.scene />; } else { return ( <div> <h1 class="title">PoopVR</h1> <i class="em em-poop"></i> <div class="status"> <p>Pick your Poo!</p> </div> <ul> <li onClick={() => this.loadPoo('war')}>World War Two</li> <li onClick={() => this.loadPoo('dino')}>Prehistoric Poo</li> </ul> </div> ); } } }; module.exports = PickYourPoo;
Test(script): Rewrite to new code rewrite
/* Name: openkvk - test.js Description: Test script for openkvk.js Author: Franklin van de Meent (https://frankl.in) Source & docs: https://github.com/fvdm/nodejs-openkvk Feedback: https://github.com/fvdm/nodejs-openkvk/issues License: Unlicense (Public Domain) - see LICENSE file */ // Setup var dotest = require ('dotest'); var app = require ('./'); var config = { apikey: process.env.OPENKVK_APIKEY || null, timeout: process.env.OPENKVK_TIMEOUT || null }; var openkvk = app (config): function testArrayObject (err, data) { var item = data && data instanceof Array && data [0]; dotest.test (err) .isArray ('fail', 'data', data) .isNotEmpty ('fail', 'data', data) .isObject ('fail', 'data[0]', item) .isString ('fail', 'data[0].kvk', item && item.kvk) .done (); } dotest.add ('Module', function (test) { test () .isFunction ('fail', 'exports', app) .isFunction ('fail', 'interface', openkvk) .done (); }); dotest.add ('search by keywords', function () { openkvk ('ahold kunst', testArrayObject); }); dotest.add ('search by kvks', function () { openkvk ('35030138', testArrayObject); }); // Start the tests dotest.run ();
/* Name: openkvk - test.js Description: Test script for openkvk.js Author: Franklin van de Meent (https://frankl.in) Source & docs: https://github.com/fvdm/nodejs-openkvk Feedback: https://github.com/fvdm/nodejs-openkvk/issues License: Unlicense (Public Domain) - see LICENSE file */ // Setup var dotest = require ('dotest'); var openkvk = require ('./'); function testArrayObject (err, data) { var item = data && data instanceof Array && data [0]; dotest.test (err) .isArray ('fail', 'data', data) .isNotEmpty ('fail', 'data', data) .isObject ('fail', 'data[0]', item) .isString ('fail', 'data[0].kvk', item && item.kvk) .done (); } dotest.add ('search by keywords', function () { openkvk ('ahold kunst', testArrayObject); }); dotest.add ('search by kvks', function () { openkvk ('35030138', testArrayObject); }); // Start the tests dotest.run ();
Fix 'In the Media' title
<article id="post-<?php the_ID(); ?>" <?php post_class('index-card'); ?>> <header> <h2><a href="<?php echo esc_attr( get_field('in_the_media_url', get_the_ID()) ); ?>"><?php the_title(); ?></a></h2> <span class="byline author"> Published by <?php echo get_the_publisher_link(get_the_ID()) ?> <time class="updated" datetime="<?php echo get_the_time('c') ?>" pubdate><?php echo get_the_time('F jS, Y') ?></time> </span> </header> <br> <div class="entry-content"> <div class="row"> <div class="medium-2 hide-for-small columns"><?php echo get_the_publisher_logo( get_the_ID() ); ?></div> <div class="medium-10 columns"><?php the_content(); ?></div> </div> <div class="row"> <div class="columns"><p class="entry-tags"><?php echo get_the_term_list(get_the_ID(),'in-the-media-tags', 'tagged as:&nbsp;', ', ') ?></p></div> </div> <?php edit_post_link('Edit this \'In the Media\' Item','','<br><br>'); ?> </div> </article>
<article id="post-<?php the_ID(); ?>" <?php post_class('index-card'); ?>> <header> <h2><a href="<?php echo esc_attr( get_field('article_url', get_the_ID()) ); ?>"><?php the_title(); ?></a></h2> <span class="byline author"> Published by <?php echo get_the_publisher_link(get_the_ID()) ?> <time class="updated" datetime="<?php echo get_the_time('c') ?>" pubdate><?php echo get_the_time('F jS, Y') ?></time> </span> </header> <br> <div class="entry-content"> <div class="row"> <div class="medium-2 hide-for-small columns"><?php echo get_the_publisher_logo( get_the_ID() ); ?></div> <div class="medium-10 columns"><?php the_content(); ?></div> </div> <div class="row"> <div class="columns"><p class="entry-tags"><?php echo get_the_term_list(get_the_ID(),'in-the-media-tags', 'tagged as:&nbsp;', ', ') ?></p></div> </div> <?php edit_post_link('Edit this \'In the Media\' Item','','<br><br>'); ?> </div> </article>
Remove conversion to set, as the new file format uses sets in tuples.
""" Derive a list of impossible differentials. """ from ast import literal_eval import sys def parse(line): return literal_eval(line) def in_set(s, xs): return any(i in s for i in xs) def main(): if len(sys.argv) != 3: print("usage: ./find_ids.py [forward differentials file] [backward differentials file]", file=sys.stderr) sys.exit(1) ids = [] with open(sys.argv[1], "rt") as f: for i, forward_rounds, xs in map(parse, f): with open(sys.argv[2], "rt") as g: for j, backward_rounds, ys in map(parse, g): if xs.isdisjoint(ys): backward_rounds -= 1 print((i, forward_rounds, backward_rounds, j)) if __name__ == "__main__": main()
""" Derive a list of impossible differentials. """ from ast import literal_eval import sys def parse(line): return literal_eval(line) def in_set(s, xs): return any(i in s for i in xs) def main(): if len(sys.argv) != 3: print("usage: ./find_ids.py [forward differentials file] [backward differentials file]", file=sys.stderr) sys.exit(1) ids = [] with open(sys.argv[1], "rt") as f: for i, forward_rounds, xs in map(parse, f): sx = set(xss[-1]) with open(sys.argv[2], "rt") as g: for j, backward_rounds, ys in map(parse, g): if in_set(sx, ys): backward_rounds -= 1 print((i, forward_rounds, backward_rounds, j)) if __name__ == "__main__": main()
Add entry_point for command-line application Closes #31.
# -*- coding: utf-8 -*- from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="joshua.r.smith@gmail.com", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], install_requires=["pybtex"], entry_points={"console_scripts":"ref=refmanage.refmanage:main"},)
# -*- coding: utf-8 -*- from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="joshua.r.smith@gmail.com", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], install_requires=["pybtex"], )
Add autofocus on the first input text or textarea
$(function() { // toggle on/off switch $(document).on('click', '[data-toggle]', function() { targetHide = $(this).data('toggle-hide') targetShow = $(this).data('toggle-show') $('[data-toggle-name="' + targetHide + '"]').addClass('hide') $('[data-toggle-name="' + targetShow + '"]').removeClass('hide') .find('input:text, textarea').first().focus() }); // AJAX request utility AJAXRequest = function(url, method, data, success, error) { $.ajax({ url : url, type : method, data : data, dataType : 'JSON', cache : false, success : function(json) { success(json) }, error : function() { error() } }); } });
$(function() { // toggle on/off switch $(document).on('click', '[data-toggle]', function() { targetHide = $(this).data('toggle-hide') targetShow = $(this).data('toggle-show') $('[data-toggle-name="' + targetHide + '"]').addClass('hide') $('[data-toggle-name="' + targetShow + '"]').removeClass('hide') }); // AJAX request utility AJAXRequest = function(url, method, data, success, error) { $.ajax({ url : url, type : method, data : data, dataType : 'JSON', cache : false, success : function(json) { success(json) }, error : function() { error() } }); } });
Replace LHS with replacement values
package matlab.syntax; import java.util.*; import dl.syntax.*; public class MatlabAssignment extends MatlabProgram { private final RealVariable lhs; private final Term rhs; public MatlabAssignment( RealVariable lhs, Term rhs ) { this.lhs = lhs; this.rhs = rhs; } public RealVariable getLHS() { return lhs; } public Term getRHS() { return rhs; } public Set<RealVariable> getModifiedVariables() { Set<RealVariable> variables = new HashSet<>(); variables.add(getLHS()); return variables; } public MatlabAssignment replace( Replacement replacement ) { return new MatlabAssignment( (RealVariable) lhs.replace(replacement), rhs.replace( replacement )); } public String toString() { return lhs.toString() + " = " + rhs.toString() + ";\n"; } }
package matlab.syntax; import java.util.*; import dl.syntax.*; public class MatlabAssignment extends MatlabProgram { private final RealVariable lhs; private final Term rhs; public MatlabAssignment( RealVariable lhs, Term rhs ) { this.lhs = lhs; this.rhs = rhs; } public RealVariable getLHS() { return lhs; } public Term getRHS() { return rhs; } public Set<RealVariable> getModifiedVariables() { Set<RealVariable> variables = new HashSet<>(); variables.add(getLHS()); return variables; } public MatlabAssignment replace( Replacement replacement ) { return new MatlabAssignment( lhs, rhs.replace( replacement )); } public String toString() { return lhs.toString() + " = " + rhs.toString() + ";\n"; } }
Clean up File edit view
from __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
Fix bbl up for AWS - Different calls to AWS return different lists of availability zones - Short-term fix ignores the az that is not returned by cloudformation call [#139857703]
package ec2 import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type AvailabilityZoneRetriever struct { ec2ClientProvider ec2ClientProvider } func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever { return AvailabilityZoneRetriever{ ec2ClientProvider: ec2ClientProvider, } } func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) { output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{ Filters: []*awsec2.Filter{{ Name: goaws.String("region-name"), Values: []*string{goaws.String(region)}, }}, }) if err != nil { return []string{}, err } azList := []string{} for _, az := range output.AvailabilityZones { if az == nil { return []string{}, errors.New("aws returned nil availability zone") } if az.ZoneName == nil { return []string{}, errors.New("aws returned availability zone with nil zone name") } if *az.ZoneName != "us-east-1d" { azList = append(azList, *az.ZoneName) } } return azList, nil }
package ec2 import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type AvailabilityZoneRetriever struct { ec2ClientProvider ec2ClientProvider } func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever { return AvailabilityZoneRetriever{ ec2ClientProvider: ec2ClientProvider, } } func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) { output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{ Filters: []*awsec2.Filter{{ Name: goaws.String("region-name"), Values: []*string{goaws.String(region)}, }}, }) if err != nil { return []string{}, err } azList := []string{} for _, az := range output.AvailabilityZones { if az == nil { return []string{}, errors.New("aws returned nil availability zone") } if az.ZoneName == nil { return []string{}, errors.New("aws returned availability zone with nil zone name") } azList = append(azList, *az.ZoneName) } return azList, nil }
Fix url pattern for main
"""cv URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^djadm/', admin.site.urls), url(r'^', include('main.urls')), ]
"""cv URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^djadm/', admin.site.urls), url(r'^$', include('main.urls')), ]
Fix annotation link. EncodedPath is gone.
package retrofit; /** Intercept every request before it is executed in order to add additional data. */ public interface RequestInterceptor { /** Called for every request. Add data using methods on the supplied {@link RequestFacade}. */ void intercept(RequestFacade request); interface RequestFacade { /** Add a header to the request. This will not replace any existing headers. */ void addHeader(String name, String value); /** * Add a path parameter replacement. This works exactly like a {@link retrofit.http.Path * &#64;Path}-annotated method argument. */ void addPathParam(String name, String value); /** * Add a path parameter replacement without first URI encoding. This works exactly like a * {@link retrofit.http.Path &#64;Path}-annotated method argument with {@code encode=false}. */ void addEncodedPathParam(String name, String value); /** Add an additional query parameter. This will not replace any existing query parameters. */ void addQueryParam(String name, String value); /** * Add an additional query parameter without first URI encoding. This will not replace any * existing query parameters. */ void addEncodedQueryParam(String name, String value); } /** A {@link RequestInterceptor} which does no modification of requests. */ RequestInterceptor NONE = new RequestInterceptor() { @Override public void intercept(RequestFacade request) { // Do nothing. } }; }
package retrofit; /** Intercept every request before it is executed in order to add additional data. */ public interface RequestInterceptor { /** Called for every request. Add data using methods on the supplied {@link RequestFacade}. */ void intercept(RequestFacade request); interface RequestFacade { /** Add a header to the request. This will not replace any existing headers. */ void addHeader(String name, String value); /** * Add a path parameter replacement. This works exactly like a {@link retrofit.http.Path * &#64;Path}-annotated method argument. */ void addPathParam(String name, String value); /** * Add a path parameter replacement without first URI encoding. This works exactly like a * {@link retrofit.http.EncodedPath &#64;EncodedPath}-annotated method argument. */ void addEncodedPathParam(String name, String value); /** Add an additional query parameter. This will not replace any existing query parameters. */ void addQueryParam(String name, String value); /** * Add an additional query parameter without first URI encoding. This will not replace any * existing query parameters. */ void addEncodedQueryParam(String name, String value); } /** A {@link RequestInterceptor} which does no modification of requests. */ RequestInterceptor NONE = new RequestInterceptor() { @Override public void intercept(RequestFacade request) { // Do nothing. } }; }
Convert reply from bytes to string The GET message reply is a byte string and it needs to be converted to a string before being passed to the JSON parser.
# -*- coding: utf-8 -*- """Unit tests for the Master Controller REST variant. - http://flask.pocoo.org/docs/0.12/testing/ """ import unittest import json from app.app import APP class MasterControllerTests(unittest.TestCase): """Tests of the Master Controller""" def setUp(self): """Executed prior to each test.""" APP.config['TESTING'] = True APP.config['DEBUG'] = False APP.config['JSONIFY_PRETTYPRINT_REGULAR'] = False self.app = APP.test_client() self.assertEqual(APP.debug, False) def tearDown(self): """Executed after each test.""" pass def test_get_state_successful(self): """Test of successfully returning the SDP state.""" states = ['OFF', 'INIT', 'STANDBY', 'ON', 'DISABLE', 'FAULT', 'ALARM', 'UNKNOWN'] response = self.app.get('/state') self.assertEqual(response.mimetype, 'application/json') self.assertEqual(response.status_code, 200) data = json.loads(response.get_data().decode('utf-8')) self.assertTrue(data['state'] in states)
# -*- coding: utf-8 -*- """Unit tests for the Master Controller REST variant. - http://flask.pocoo.org/docs/0.12/testing/ """ import unittest import json from app.app import APP class MasterControllerTests(unittest.TestCase): """Tests of the Master Controller""" def setUp(self): """Executed prior to each test.""" APP.config['TESTING'] = True APP.config['DEBUG'] = False APP.config['JSONIFY_PRETTYPRINT_REGULAR'] = False self.app = APP.test_client() self.assertEqual(APP.debug, False) def tearDown(self): """Executed after each test.""" pass def test_get_state_successful(self): """Test of successfully returning the SDP state.""" states = ['OFF', 'INIT', 'STANDBY', 'ON', 'DISABLE', 'FAULT', 'ALARM', 'UNKNOWN'] response = self.app.get('/state') self.assertEqual(response.mimetype, 'application/json') self.assertEqual(response.status_code, 200) data = json.loads(response.get_data()) self.assertTrue(data['state'] in states)
Disable pylint signature-differs in md.py
import os import multiprocessing.util def apply_workaround(): # Implements: # https://github.com/python/cpython/commit/e8a57b98ec8f2b161d4ad68ecc1433c9e3caad57 # # Detection of fix: os imported to compare pids, before the fix os has not # been imported if getattr(multiprocessing.util, 'os', None): return class FixedFinalize(multiprocessing.util.Finalize): def __init__(self, *args, **kwargs): super(FixedFinalize, self).__init__(*args, **kwargs) self._pid = os.getpid() def __call__(self, *args, **kwargs): # pylint: disable=signature-differs if self._pid != os.getpid(): return None return super(FixedFinalize, self).__call__(*args, **kwargs) setattr(multiprocessing.util, 'Finalize', FixedFinalize)
import os import multiprocessing.util def apply_workaround(): # Implements: # https://github.com/python/cpython/commit/e8a57b98ec8f2b161d4ad68ecc1433c9e3caad57 # # Detection of fix: os imported to compare pids, before the fix os has not # been imported if getattr(multiprocessing.util, 'os', None): return class FixedFinalize(multiprocessing.util.Finalize): def __init__(self, *args, **kwargs): super(FixedFinalize, self).__init__(*args, **kwargs) self._pid = os.getpid() def __call__(self, *args, **kwargs): if self._pid != os.getpid(): return None return super(FixedFinalize, self).__call__(*args, **kwargs) setattr(multiprocessing.util, 'Finalize', FixedFinalize)
Add overflow: auto to allow scrolling of menu items by default
'use strict'; let styles = { overlay(isOpen) { return { position: 'fixed', zIndex: 1, width: '100%', height: '100%', background: 'rgba(0, 0, 0, 0.3)', opacity: isOpen ? 1 : 0, transform: isOpen ? '' : 'translate3d(-100%, 0, 0)', transition: isOpen ? 'opacity 0.3s' : 'opacity 0.3s, transform 0s 0.3s' }; }, menuWrap(isOpen, width, right) { return { position: 'fixed', right: right ? 0 : 'inherit', zIndex: 2, width, height: '100%', transform: isOpen ? '' : right ? 'translate3d(100%, 0, 0)' : 'translate3d(-100%, 0, 0)', transition: 'all 0.5s' }; }, menu() { return { height: '100%', boxSizing: 'border-box', overflow: 'auto' }; }, itemList() { return { height: '100%' }; }, item() { return { display: 'block', outline: 'none' }; } }; export default styles;
'use strict'; let styles = { overlay(isOpen) { return { position: 'fixed', zIndex: 1, width: '100%', height: '100%', background: 'rgba(0, 0, 0, 0.3)', opacity: isOpen ? 1 : 0, transform: isOpen ? '' : 'translate3d(-100%, 0, 0)', transition: isOpen ? 'opacity 0.3s' : 'opacity 0.3s, transform 0s 0.3s' }; }, menuWrap(isOpen, width, right) { return { position: 'fixed', right: right ? 0 : 'inherit', zIndex: 2, width, height: '100%', transform: isOpen ? '' : right ? 'translate3d(100%, 0, 0)' : 'translate3d(-100%, 0, 0)', transition: 'all 0.5s' }; }, menu() { return { height: '100%', boxSizing: 'border-box' }; }, itemList() { return { height: '100%' }; }, item() { return { display: 'block', outline: 'none' }; } }; export default styles;
Disable voting if already voted
jQuery(function() { jQuery('[data-star-rating]').each(function(index, element) { element = $(element); var data = element.data('star-rating'), globalOptions = window.StarRatingsOptions ? window.StarRatingsOptions : {}, options = jQuery.extend(data.options, globalOptions, { callback: function(currentRating, element) { $.post(data.uri, { id: data.id, rating: currentRating }) .done(function() { console.log('success'); }) .fail(function() { console.log('fail'); }); } }); if (element.data('voted')) { options.readOnly = true; } if (options.readOnly) { element.addClass('disabled'); } element.starRating(options); }); });
jQuery(function() { jQuery('[data-star-rating]').each(function(index, element) { element = $(element); var data = element.data('star-rating'), globalOptions = window.StarRatingsOptions ? window.StarRatingsOptions : {}, options = jQuery.extend(data.options, globalOptions, { callback: function(currentRating, element) { $.post(data.uri, { id: data.id, rating: currentRating }) .done(function() { console.log('success'); }) .fail(function() { console.log('fail'); }); } }); if (options.readOnly) { element.addClass('disabled'); } element.starRating(options); }); });
Add picture display after taken on mirror, need to set a timer for that
Module.register("recognizer",{ start() { this.display = false; this.image = ""; console.log("Recognizer started"); this.sendSocketNotification("RECOGNIZER_STARTUP"); return; }, socketNotificationReceived: function(notification) { console.log("Recognizer recieved a notification: " + notification) if (notification === "RECOGNIZER_CONNECTED") { console.log("Recognizer initialized, awaiting Activation"); } else if (notification === "SELFIE_IS_GO") { console.log("Begin Display Selfie"); this.display = true; this.updateDom(); } }, notificationReceived: function(notification) { if(notification === "picture") { console.log("========== pic request ==================="); this.sendSocketNotification("TAKE_SELFIE"); } }, getDom: function() { var wrapper = document.createElement("div"); wrapper.className = "selfie-display"; if (this.display) { var imgElem = document.createElement("img"); imgElem.src = "./public/webcam_pic.jpg"; wrapper.appendChild(imgElem); return wrapper; } return wrapper; }, }); //this should cause a change
Module.register("recognizer",{ start() { this.display = false; this.image = ""; console.log("Recognizer started"); this.sendSocketNotification("RECOGNIZER_STARTUP"); return; }, socketNotificationReceived: function(notification) { console.log("Recognizer recieved a notification: " + notification) if (notification === "RECOGNIZER_CONNECTED") { console.log("Recognizer initialized, awaiting Activation"); } else if (notification === "SELFIE_IS_GO") { console.log("Begin Display Selfie"); this.display = true; this.updateDom(); } }, notificationReceived: function(notification) { if(notification === "picture") { console.log("========== pic request ==================="); this.sendSocketNotification("TAKE_SELFIE"); } }, getDom: function() { var wrapper = document.createElement("div"); wrapper.className = "selfie-display"; if (this.display) { var imgElem = document.createElement("img"); imgElem.src = "./public/webcam_pic.jpg"; wrapper.innerHTML = '<img id="selfie" src="./public/webcam_pic.jpg" />'; document.getElementById("selfie-display").appendChild(imgElem); return wrapper; } }, }); //this should cause a change
Make the HLTV search escape uri fragments
'use strict'; var request = require( 'request' ); module.exports = { baseUrl : 'http://www.hltv.org/?pageid=255&res=5&team=1&term=', search : function( searchPhrase, callback ){ var _this = this, rawTeamList = false, teamList = [], i; request( _this.baseUrl + encodeURIComponent( searchPhrase ), function( error, response, teams ) { rawTeamList = JSON.parse( teams ); for( i = 0; i < rawTeamList.length; i = i + 1 ){ teamList.push({ name : rawTeamList[ i ].name, id : rawTeamList[ i ].teamid, country : rawTeamList[ i ].country }); } callback.call( this, teamList ); }); } };
'use strict'; var request = require( 'request' ); module.exports = { baseUrl : 'http://www.hltv.org/?pageid=255&res=5&team=1&term=', search : function( searchPhrase, callback ){ var _this = this, rawTeamList = false, teamList = [], i; request( _this.baseUrl + searchPhrase, function( error, response, teams ) { rawTeamList = JSON.parse( teams ); for( i = 0; i < rawTeamList.length; i = i + 1 ){ teamList.push({ name : rawTeamList[ i ].name, id : rawTeamList[ i ].teamid, country : rawTeamList[ i ].country }); } callback.call( this, teamList ); }); } };
Rename the control script to "cobe"
#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name = "cobe", version = "0.5", author = "Peter Teichman", author_email = "peter@teichman.org", packages = ["cobe"], test_suite = "tests.cobe_suite", install_requires = ["cmdparse>=0.9"], classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Artificial Intelligence" ], entry_points = { "console_scripts" : [ "cobe = cobe.control:main" ] } )
#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name = "cobe", version = "0.5", author = "Peter Teichman", author_email = "peter@teichman.org", packages = ["cobe"], test_suite = "tests.cobe_suite", install_requires = ["cmdparse>=0.9"], classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Artificial Intelligence" ], entry_points = { "console_scripts" : [ "cobe-control = cobe.control:main" ] } )
Fix kebab-to-camel conversion for CLI arguments
#! /usr/bin/env node /* Copyright (c) 2018 Looker Data Sciences, Inc. See https://github.com/looker-open-source/look-at-me-sideways/blob/master/LICENSE.txt */ const minimist = require('minimist') const lams = require('./index.js') const fromEntries = require('fromentries') const cliArgs = fromEntries( // ponyfill for Object.fromEntries Object.entries( minimist( process.argv.slice( process.argv[0]=='lams' ? 1 // e.g. lams --bla : 2 // e.g. node index.js --bla ), { alias:{ source: ["input", "i"] } } ) ) //Convert kebab-case and snake_case to camelCase .map(([k,v])=>[k.replace(/[-_][a-zA-Z-0-9]/g,s=>s.slice(1).toUpperCase()),v]) ) !async function() { await lams(cliArgs) }()
#! /usr/bin/env node /* Copyright (c) 2018 Looker Data Sciences, Inc. See https://github.com/looker-open-source/look-at-me-sideways/blob/master/LICENSE.txt */ const minimist = require('minimist') const lams = require('./index.js') const fromEntries = require('fromentries') const cliArgs = fromEntries( // ponyfill for Object.fromEntries Object.entries( minimist( process.argv.slice( process.argv[0]=='lams' ? 1 // e.g. lams --bla : 2 // e.g. node index.js --bla ), { alias:{ source: ["input", "i"] } } ) ) //Convert kebab-case and snake_case to camelCase .map(([k,v])=>[k.replace(/[-_][a-zA-Z-0-9]/g,s=>s.toUpperCase()),v]) ) !async function() { await lams(cliArgs) }()
Update with modern class definition
from tip.algorithms.sorting.mergesort import mergesort class TestMergesort: """Test class for Merge Sort algorithm.""" def test_mergesort_basic(self): """Test basic sorting.""" unsorted_list = [5, 3, 7, 8, 9, 3] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list) def test_mergesort_trivial(self): """Test sorting when it's only one item.""" unsorted_list = [1] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list) def test_mergesort_with_duplicates(self): """Test sorting a list with duplicates.""" unsorted_list = [1, 1, 1, 1] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list) def test_mergesort_with_empty_list(self): """Test sorting a empty list.""" unsorted_list = [] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list)
from tip.algorithms.sorting.mergesort import mergesort class TestMergesort(): """Test class for Merge Sort algorithm.""" def test_mergesort_basic(self): """Test basic sorting.""" unsorted_list = [5, 3, 7, 8, 9, 3] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list) def test_mergesort_trivial(self): """Test sorting when it's only one item.""" unsorted_list = [1] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list) def test_mergesort_with_duplicates(self): """Test sorting a list with duplicates.""" unsorted_list = [1, 1, 1, 1] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list) def test_mergesort_with_empty_list(self): """Test sorting a empty list.""" unsorted_list = [] sorted_list = mergesort(unsorted_list) assert sorted_list == sorted(unsorted_list)
Fix unread count in notifications (again)
package com.fsck.k9.helper; import android.app.Notification; import android.content.Context; import android.os.Build; import android.support.v4.app.NotificationCompat; /** * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices. * * @see <a href="http://code.google.com/p/android/issues/detail?id=38028">android - Issue 38028</a> */ public class NotificationBuilder extends NotificationCompat.Builder { protected int mNumber; public NotificationBuilder(Context context) { super(context); } @Override public NotificationCompat.Builder setNumber(int number) { super.setNumber(number); mNumber = number; return this; } @Override public Notification build() { Notification notification = super.build(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { notification.number = mNumber; } return notification; } }
package com.fsck.k9.helper; import android.app.Notification; import android.content.Context; import android.os.Build; import android.support.v4.app.NotificationCompat; /** * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices. * * @see <a href="http://code.google.com/p/android/issues/detail?id=38028">android - Issue 38028</a> */ public class NotificationBuilder extends NotificationCompat.Builder { protected int mNumber; public NotificationBuilder(Context context) { super(context); } @Override public NotificationCompat.Builder setNumber(int number) { mNumber = number; return this; } @Override public Notification build() { Notification notification = super.build(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { notification.number = mNumber; } return notification; } }
Change the serial number of the problem Change the serial number of the problem
package com.insightfullogic.java8.answers.chapter3; import java.util.Comparator; import java.util.List; import java.util.Optional; public class StringExercises { // Question 6 public static int countLowercaseLetters(String string) { return (int) string.chars() .filter(Character::isLowerCase) .count(); } // Question 7 public static Optional<String> mostLowercaseString(List<String> strings) { return strings.stream() .max(Comparator.comparing(StringExercises::countLowercaseLetters)); } }
package com.insightfullogic.java8.answers.chapter3; import java.util.Comparator; import java.util.List; import java.util.Optional; public class StringExercises { // Question 7 public static int countLowercaseLetters(String string) { return (int) string.chars() .filter(Character::isLowerCase) .count(); } // Question 8 public static Optional<String> mostLowercaseString(List<String> strings) { return strings.stream() .max(Comparator.comparing(StringExercises::countLowercaseLetters)); } }
Use a non static Joker again
/* For step-by-step instructions on connecting your Android application to this backend module, see "App Engine Java Endpoints Module" template documentation at https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints */ package com.example.Jose.myapplication.backend; import com.example.Jose.myapplication.backend.domain.JokeBean; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.ApiNamespace; import com.jmlb0003.jokes.gradlejokesproject.Joker; /** * An endpoint class we are exposing */ @Api( name = "jokeApi", version = "v1", namespace = @ApiNamespace( ownerDomain = "backend.myapplication.Jose.example.com", ownerName = "backend.myapplication.Jose.example.com" ) ) public final class JokeEndpoint { /** * A simple endpoint method that returns a joke */ @ApiMethod(name = "getJoke") public JokeBean getAJoke() { final JokeBean response = new JokeBean(); final Joker joker = new Joker(); response.setData(joker.getJoke()); return response; } }
/* For step-by-step instructions on connecting your Android application to this backend module, see "App Engine Java Endpoints Module" template documentation at https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints */ package com.example.Jose.myapplication.backend; import com.example.Jose.myapplication.backend.domain.JokeBean; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.ApiNamespace; import com.jmlb0003.jokes.gradlejokesproject.Joker; /** * An endpoint class we are exposing */ @Api( name = "jokeApi", version = "v1", namespace = @ApiNamespace( ownerDomain = "backend.myapplication.Jose.example.com", ownerName = "backend.myapplication.Jose.example.com" ) ) public final class JokeEndpoint { /** * A simple endpoint method that takes a name and says Hi back */ @ApiMethod(name = "getJoke") public JokeBean getAJoke() { final JokeBean response = new JokeBean(); response.setData(Joker.getJoke()); return response; } }
Add urldecode to query string class
<? //Get query string because $_GET does not work with mod rewrite //This code should be rewritten at some point... It's ugly // //Multiple identical keys cannot be passed into pooch. This is a Limitation of this implimentation. //Example: Give the query string "id=2&id=3" the value of $query_string['id'] would be 3. function getQueryString(){ global $query_string; $query_string = array(); $new_query_string = array(); if(strpos($_SERVER['REQUEST_URI'], '?')){ $query_string = explode('?', $_SERVER['REQUEST_URI']); if(strpos($query_string[1], '&')){ $query_string = explode('&', $query_string[1]); foreach ($query_string as $value) { $value_array = explode('=', $value); $new_query_string[urldecode($value_array[0])] = urldecode($value_array[1]); } $query_string = $new_query_string; }else{ $value_array = explode('=', $query_string[1]); $new_query_string[urldecode($value_array[0])] = urldecode($value_array[1]); } } $query_string = $new_query_string; } getQueryString(); ?>
<? //Get query string because $_GET does not work with mod rewrite //This code should be rewritten at some point... It's ugly // //Multiple identical keys cannot be passed into pooch. This is a Limitation of this implimentation. //Example: Give the query string "id=2&id=3" the value of $query_string['id'] would be 3. function getQueryString(){ global $query_string; $query_string = array(); $new_query_string = array(); if(strpos($_SERVER['REQUEST_URI'], '?')){ $query_string = explode('?', $_SERVER['REQUEST_URI']); if(strpos($query_string[1], '&')){ $query_string = explode('&', $query_string[1]); foreach ($query_string as $value) { $value_array = explode('=', $value); $new_query_string[$value_array[0]] = $value_array[1]; } $query_string = $new_query_string; }else{ $value_array = explode('=', $query_string[1]); $new_query_string[$value_array[0]] = $value_array[1]; } } $query_string = $new_query_string; } getQueryString(); ?>
Handle factions >5 Nobody knows what they are and where they come from.
package com.faforever.api.data.domain; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import java.util.HashMap; public enum Faction { // Order is crucial AEON("aeon"), CYBRAN("cybran"), UEF("uef"), SERAPHIM("seraphim"), NOMAD("nomad"), UNKNOWN(null); private static final java.util.Map<String, Faction> fromString; static { fromString = new HashMap<>(); for (Faction faction : values()) { fromString.put(faction.string, faction); } } private final String string; Faction(String string) { this.string = string; } @JsonCreator public static Faction fromFaValue(int value) { if (value > 5) { return UNKNOWN; } return Faction.values()[value - 1]; } public static Faction fromString(String string) { return fromString.get(string); } /** * Returns the faction value used as in "Forged Alliance Forever". */ @JsonValue public int toFaValue() { return ordinal() + 1; } @Converter(autoApply = true) public static class FactionConverter implements AttributeConverter<Faction, Integer> { @Override public Integer convertToDatabaseColumn(Faction attribute) { return attribute.toFaValue(); } @Override public Faction convertToEntityAttribute(Integer dbData) { return fromFaValue(dbData); } } }
package com.faforever.api.data.domain; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import java.util.HashMap; public enum Faction { // Order is crucial AEON("aeon"), CYBRAN("cybran"), UEF("uef"), SERAPHIM("seraphim"), NOMAD("nomad"); private static final java.util.Map<String, Faction> fromString; static { fromString = new HashMap<>(); for (Faction faction : values()) { fromString.put(faction.string, faction); } } private final String string; Faction(String string) { this.string = string; } @JsonCreator public static Faction fromFaValue(int value) { return Faction.values()[value - 1]; } public static Faction fromString(String string) { return fromString.get(string); } /** * Returns the faction value used as in "Forged Alliance Forever". */ @JsonValue public int toFaValue() { return ordinal() + 1; } @Converter(autoApply = true) public static class FactionConverter implements AttributeConverter<Faction, Integer> { @Override public Integer convertToDatabaseColumn(Faction attribute) { return attribute.toFaValue(); } @Override public Faction convertToEntityAttribute(Integer dbData) { return fromFaValue(dbData); } } }
Use $.ajaxSuccess to show "add new course" button
this.mmooc=this.mmooc||{}; this.mmooc.courseList = function() { return { listCourses: function(parentId) { mmooc.api.getEnrolledCourses(function(courses) { var html = mmooc.util.renderTemplateWithData("courselist", {courses: courses}); document.getElementById(parentId).innerHTML = html; }); }, showAddCourseButton : function() { $(document).ajaxSuccess(function () { var button = $('#start_new_course'); if (button.size() > 0) { $('#content').append(button); } }); } }; }();
this.mmooc=this.mmooc||{}; this.mmooc.courseList = function() { return { listCourses: function(parentId) { mmooc.api.getEnrolledCourses(function(courses) { var html = mmooc.util.renderTemplateWithData("courselist", {courses: courses}); document.getElementById(parentId).innerHTML = html; }); }, showAddCourseButton : function() { var button = $('#start_new_course'); if (button.size() > 0) { $('#content').append(button); } } }; }();
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
Use phantomJs and headless chrome as browsers Especially useful for CI
module.exports = function(config) { config.set({ frameworks: ["jasmine", "karma-typescript"], files: [ { pattern: "src/**/*.ts" }, { pattern: "src/**/*.tsx" }, ], preprocessors: { "**/*.ts": ["karma-typescript"], "**/*.tsx": ["karma-typescript"], }, reporters: ["progress", "karma-typescript"], browsers: ["PhantomJS", "ChromeHeadless"], singleRun: true, karmaTypescriptConfig: { tsconfig: "./tsconfig.test.json", bundlerOptions: { transforms: [ require("karma-typescript-es6-transform")({presets: ["env"]}) ] } } }); };
module.exports = function(config) { config.set({ frameworks: ["jasmine", "karma-typescript"], files: [ { pattern: "src/**/*.ts" }, { pattern: "src/**/*.tsx" }, ], preprocessors: { "**/*.ts": ["karma-typescript"], "**/*.tsx": ["karma-typescript"], }, reporters: ["progress", "karma-typescript"], // browsers: ["Chrome"], karmaTypescriptConfig: { tsconfig: "./tsconfig.test.json", bundlerOptions: { transforms: [ require("karma-typescript-es6-transform")({presets: ["env"]}) ] } } }); };
IBM-109: Remove quotes from url query string
(function () { const UNAUTHORIZED = 401; const REQUEST_FINISHED = 4; var keycloakRedirect = { authenticate: (config, client, window) => { if (config.backend === void 0) { throw "Missing backend in config."; } if (config.clientId === void 0) { throw "Missing clientId in config."; } if (config.keycloakUrl === void 0) { throw "Missing keycloakUrl in config."; } client.withCredentials = true; client.open("GET", config.backend + "/oauth/expired", true); client.send(); client.onreadystatechange = () => { if (client.readyState === REQUEST_FINISHED && client.status === UNAUTHORIZED) { window.location = config.keycloakUrl + encodeURI(`?redirect_uri="${window.location}"&client_id="${config.clientId}"&response_type=code`); } }; } }; module.exports = keycloakRedirect; }());
(function () { const UNAUTHORIZED = 401; const REQUEST_FINISHED = 4; var keycloakRedirect = { authenticate: (config, client, window) => { if (config.backend === void 0) { throw "Missing backend in config."; } if (config.clientId === void 0) { throw "Missing clientId in config."; } if (config.keycloakUrl === void 0) { throw "Missing keycloakUrl in config."; } client.withCredentials = true; client.open("GET", config.backend + "/oauth/expired", true); client.send(); client.onreadystatechange = () => { if (client.readyState === REQUEST_FINISHED && client.status === UNAUTHORIZED) { window.location = config.keycloakUrl + encodeURI("?redirect_uri=\"" + window.location + "\"&client_id=\"" + config.clientId + "\"&response_type=code"); } }; } }; module.exports = keycloakRedirect; }());
HV-426: Use Hibernate Validator in version logging message.
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibernate.validator.util; /** * @author Hardy Ferentschik */ public final class Version { static { LoggerFactory.make().info( "Hibernate Validator {}", getVersionString() ); } public static String getVersionString() { return "[WORKING]"; } public static void touch() { } // helper class should not have a public constructor private Version() { } }
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibernate.validator.util; /** * @author Hardy Ferentschik */ public final class Version { static { LoggerFactory.make().info( "Hibernate Search {}", getVersionString() ); } public static String getVersionString() { return "[WORKING]"; } public static void touch() { } // helper class should not have a public constructor private Version() { } }
Fix private discussions page breaking when user is loaded async
import UserPage from 'flarum/components/UserPage'; import PrivateDiscussionList from './PrivateDiscussionList'; export default class PrivateDiscussionsUserPage extends UserPage { init() { super.init(); this.loadUser(m.route.param('username')); } show(user) { // We can not create the list in init because the user will not be available if it has to be loaded asynchronously this.list = new PrivateDiscussionList({ params: { q: `byobu:${user.username()} is:private`, sort: 'newest' } }); this.list.refresh(); // We call the parent method after creating the list, this way the this.list property // is set before content() is called for the first time super.show(user); } content() { return ( <div className="DiscussionsUserPage"> {this.list.render()} </div> ); } }
import UserPage from 'flarum/components/UserPage'; import PrivateDiscussionList from './PrivateDiscussionList'; export default class PrivateDiscussionsUserPage extends UserPage { init() { super.init(); this.loadUser(m.route.param('username')); this.list = new PrivateDiscussionList({ params: { q: `byobu:${this.user.username()} is:private`, sort: 'newest' } }); this.list.refresh(); } content() { return ( <div className="DiscussionsUserPage"> {this.list.render()} </div> ); } }
FIX minor bug with UEs not calculating after populating planner with full 160 mcs
import { searchByModuleCode } from '../../../../../../../database-controller/module/methods'; export const findUnrestrictedElectivesRequirementModules = function findUnrestrictedElectivesRequirementModules(totalRequiredMCs, graduationMCs, studentSemesters) { // get total required MC to graduate let totalMCsInPlanner = 0; // loop through the planner, find total MCs in planner for (var i=0; i<studentSemesters.length; i++) { let modules = Object.keys(studentSemesters[i].moduleHashmap); for (var j=0; j<modules.length; j++) { totalMCsInPlanner += searchByModuleCode(modules[j]).moduleMC; //console.log(modules[j] + " " + totalMCsInPlanner); } } const requiredMCsForUEs = graduationMCs - totalRequiredMCs; const plannerMCsForUEs = totalMCsInPlanner - totalRequiredMCs; if (plannerMCsForUEs >= requiredMCsForUEs) { return true; } return false; }
import { searchByModuleCode } from '../../../../../../../database-controller/module/methods'; export const findUnrestrictedElectivesRequirementModules = function findUnrestrictedElectivesRequirementModules(totalRequiredMCs, graduationMCs, studentSemesters) { // get total required MC to graduate let totalMCsInPlanner = 0; // loop through the planner, find total MCs in planner for (var i=0; i<studentSemesters.length; i++) { let modules = Object.keys(studentSemesters[i].moduleHashmap); for (var j=0; j<modules.length; j++) { totalMCsInPlanner += searchByModuleCode(modules[i]).moduleMC; } } const requiredMCsForUEs = graduationMCs - totalRequiredMCs; const plannerMCsForUEs = totalMCsInPlanner - totalRequiredMCs; if (plannerMCsForUEs >= requiredMCsForUEs) { return true; } return false; }
Add simple helper properties to Problem.
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
Add favName field to addFavorite()
var Storage = require('FuseJS/Storage'); var data = 'favorites'; /* ... -----------------------------------------------------------------------------*/ var addFavorite , deleteFavorite , getFavorites; /* Functions -----------------------------------------------------------------------------*/ addFavorite = function(id, favName) { var favorite = getFavorites(); if (favorite[id]) { return; } favorite[id] = { name: favName }; Storage.writeSync(data, JSON.stringify(favorite)); }; deleteFavorite = function(id) { var favorite = getFavorites(); if (favorite[id]) { delete favorite[id]; Storage.writeSync(data, JSON.stringify(favorite)); } }; getFavorites = function() { var favorites = JSON.parse(Storage.readSync(data)); if (favorites === null) { favorites = {}; Storage.write(data, JSON.stringify(favorites)); } return favorites; }; /* Exports -----------------------------------------------------------------------------*/ module.exports = { addFavorite: addFavorite, deleteFavorite: deleteFavorite, getFavorites: getFavorites };
var Storage = require('FuseJS/Storage'); var data = 'favorites'; /* ... -----------------------------------------------------------------------------*/ var addFavorite , deleteFavorite , getFavorites; /* Functions -----------------------------------------------------------------------------*/ addFavorite = function(id) { var favorite = getFavorites(); if (favorite[id]) { return; } favorite[id] = { name: 'woop' }; Storage.writeSync(data, JSON.stringify(favorite)); }; deleteFavorite = function(id) { var favorite = getFavorites(); if (favorite[id]) { delete favorite[id]; Storage.writeSync(data, JSON.stringify(favorite)); } }; getFavorites = function() { var favorites = JSON.parse(Storage.readSync(data)); if (favorites === null) { favorites = {}; Storage.write(data, JSON.stringify(favorites)); } return favorites; }; /* Exports -----------------------------------------------------------------------------*/ module.exports = { addFavorite: addFavorite, deleteFavorite: deleteFavorite, getFavorites: getFavorites };
Replace Ember bindings with aliases
define([ "Ember", "text!templates/components/infinitescroll.html.hbs" ], function( Ember, template ) { var get = Ember.get; var alias = Ember.computed.alias; var or = Ember.computed.or; return Ember.Component.extend({ layout: Ember.HTMLBars.compile( template ), tagName: "button", classNameBindings: [ ":btn", ":btn-with-icon", ":infinitescroll", "hasFetchedAll:hidden" ], attributeBindings: [ "type", "disabled" ], type: "button", disabled: or( "isFetching", "hasFetchedAll" ), error: alias( "targetObject.fetchError" ), isFetching: alias( "targetObject.isFetching" ), hasFetchedAll: alias( "targetObject.hasFetchedAll" ), click: function() { var targetObject = get( this, "targetObject" ); targetObject.send( "willFetchContent", true ); } }); });
define([ "Ember", "text!templates/components/infinitescroll.html.hbs" ], function( Ember, template ) { var get = Ember.get; var or = Ember.computed.or; return Ember.Component.extend({ layout: Ember.HTMLBars.compile( template ), tagName: "button", classNameBindings: [ ":btn", ":btn-with-icon", ":infinitescroll", "hasFetchedAll:hidden" ], attributeBindings: [ "type", "disabled" ], type: "button", disabled: or( "isFetching", "hasFetchedAll" ), errorBinding: "targetObject.fetchError", isFetchingBinding: "targetObject.isFetching", hasFetchedAllBinding: "targetObject.hasFetchedAll", click: function() { var targetObject = get( this, "targetObject" ); targetObject.send( "willFetchContent", true ); } }); });
Fix - removed "public" access modifiers on interface methods
package com.maxmind.geoip2; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.model.CountryResponse; import java.io.IOException; import java.net.InetAddress; public interface GeoIp2Provider { /** * @param ipAddress IPv4 or IPv6 address to lookup. * @return A Country model for the requested IP address. * @throws GeoIp2Exception if there is an error looking up the IP * @throws IOException if there is an IO error */ CountryResponse country(InetAddress ipAddress) throws IOException, GeoIp2Exception; /** * @param ipAddress IPv4 or IPv6 address to lookup. * @return A City model for the requested IP address. * @throws GeoIp2Exception if there is an error looking up the IP * @throws IOException if there is an IO error */ CityResponse city(InetAddress ipAddress) throws IOException, GeoIp2Exception; }
package com.maxmind.geoip2; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.model.CountryResponse; import java.io.IOException; import java.net.InetAddress; public interface GeoIp2Provider { /** * @param ipAddress IPv4 or IPv6 address to lookup. * @return A Country model for the requested IP address. * @throws GeoIp2Exception if there is an error looking up the IP * @throws IOException if there is an IO error */ public CountryResponse country(InetAddress ipAddress) throws IOException, GeoIp2Exception; /** * @param ipAddress IPv4 or IPv6 address to lookup. * @return A City model for the requested IP address. * @throws GeoIp2Exception if there is an error looking up the IP * @throws IOException if there is an IO error */ public CityResponse city(InetAddress ipAddress) throws IOException, GeoIp2Exception; }
Allow actions to use `publish.when`. Since publish was being defined and not alias, actions could not use ``publish.when`. In addition, publish and publish.when must be defined on the instance as publish.when calls will not have the right `this` context.
import App from "./App"; export default class Action { constructor() { // Need to save publishers on this instance so we can mutate the publish w/ when. this.publish = this.publish.bind(this); this.publish.when = this.publishWhen.bind(this); } dispatchAction(...args) { return App.dispatchAction(...args); } get logger() { return App.logger(this.ns); } get events() { return App.events; } publish(...args) { return this._publishWith(App.events.publish, ...args); } publishWhen(...args) { return this._publishWith(App.events.publish.when, ...args); } _publishWith(publish, ev, ...args) { return publish(`${this.ns}.${ev}`, ...args); } get ns() { return this._ns || "app"; } set ns(namespace) { this._ns = namespace; } static ns(key) { // Decorator for easily adding namespace. return (ActionWithNS) => { ActionWithNS.prototype.ns = key; }; } }
import App from "./App"; export default class Action { dispatchAction(...args) { return App.dispatchAction(...args); } get logger() { return App.logger(this.ns); } get events() { return App.events; } publish(ev, ...args) { return App.events.publish(`${this.ns}.${ev}`, ...args); } get ns() { return this._ns || "app"; } set ns(namespace) { this._ns = namespace; } static ns(key) { // Decorator for easily adding namespace. return (ActionWithNS) => { ActionWithNS.prototype.ns = key; }; } }
Change where legacy outputs to in order to match current components.
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ /** * Pull in the package.json file so we can read its metadata. */ pkg: grunt.file.readJSON('package.json'), /** * LESS: https://github.com/gruntjs/grunt-contrib-less * * Compile LESS files to CSS. */ less: { legacy: { options: { paths: ["src"], yuicompress: false }, files: { 'demo/static/css/ghost.css': ['src/ghost-legacy.less'], 'src/examples/grid/static/example.css': ['src/examples/grid/static/example.less'] } } } }); /** * The above tasks are loaded here. */ grunt.loadNpmTasks('grunt-contrib-less'); /** * The 'default' task will run whenever `grunt` is run without specifying a task */ grunt.registerTask('default', ['less']); };
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ /** * Pull in the package.json file so we can read its metadata. */ pkg: grunt.file.readJSON('package.json'), /** * LESS: https://github.com/gruntjs/grunt-contrib-less * * Compile LESS files to CSS. */ less: { legacy: { options: { paths: ["src"], yuicompress: false }, files: { 'dist/ghost.css': ['src/ghost-legacy.less'], 'src/examples/grid/static/example.css': ['src/examples/grid/static/example.less'] } } } }); /** * The above tasks are loaded here. */ grunt.loadNpmTasks('grunt-contrib-less'); /** * The 'default' task will run whenever `grunt` is run without specifying a task */ grunt.registerTask('default', ['less']); };
Add a stub implementation of onWritabilityChange
package io.elssa.net; import java.util.ArrayList; import java.util.Collections; import java.util.List; import io.netty.channel.ChannelHandlerContext; public abstract class MessageRouterBase { private List<MessageListener> listeners = Collections.synchronizedList(new ArrayList<>()); /** * Adds a message listener (consumer) to this MessageRouter. Listeners * receive messages that are published by this MessageRouter. * * @param listener {@link MessageListener} that will consume messages * published by this MessageRouter. */ public void addListener(MessageListener listener) { listeners.add(listener); } public void removeListener(MessageListener listener) { listeners.remove(listener); } protected void onWritabilityChange(ChannelHandlerContext ctx) { } protected void onConnnect(NetworkEndpoint endpoint) { for (MessageListener listener : listeners) { listener.onConnect(endpoint); } } protected void onDisconnect(NetworkEndpoint endpoint) { for (MessageListener listener : listeners) { listener.onDisconnect(endpoint); } } protected void onMessage(ElssaMessage msg) { for (MessageListener listener : listeners) { listener.onMessage(msg); } } }
package io.elssa.net; import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class MessageRouterBase { private List<MessageListener> listeners = Collections.synchronizedList(new ArrayList<>()); /** * Adds a message listener (consumer) to this MessageRouter. Listeners * receive messages that are published by this MessageRouter. * * @param listener {@link MessageListener} that will consume messages * published by this MessageRouter. */ public void addListener(MessageListener listener) { listeners.add(listener); } public void removeListener(MessageListener listener) { listeners.remove(listener); } protected void onConnnect(NetworkEndpoint endpoint) { for (MessageListener listener : listeners) { listener.onConnect(endpoint); } } protected void onDisconnect(NetworkEndpoint endpoint) { for (MessageListener listener : listeners) { listener.onDisconnect(endpoint); } } protected void onMessage(ElssaMessage msg) { for (MessageListener listener : listeners) { listener.onMessage(msg); } } }
Add charset to HTML5 doc (and make more XHTML friendly) git-svn-id: e52e7dec99011c9686d89c3d3c01e7ff0d333eee@2609 eee81c28-f429-11dd-99c0-75d572ba1ddd
<!DOCTYPE html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script> </head><body></body> </html>
<!doctype html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script>
Include providerData for queue items
const db = require('sqlite') const squel = require('squel') async function getQueue (roomId) { const result = [] const entities = {} try { const q = squel.select() .field('queueId, mediaId, userId') .field('media.title, media.duration, media.provider, media.providerData') .field('users.name AS username, artists.name AS artist') .from('queue') .join('users USING(userId)') .join('media USING(mediaId)') .join('artists USING (artistId)') .where('roomId = ?', roomId) .order('queueId') const { text, values } = q.toParam() const rows = await db.all(text, values) for (const row of rows) { result.push(row.queueId) row.providerData = JSON.parse(row.providerData) entities[row.queueId] = row } } catch (err) { return Promise.reject(err) } return { result, entities } } module.exports = getQueue
const db = require('sqlite') const squel = require('squel') async function getQueue (roomId) { const result = [] const entities = {} try { const q = squel.select() .field('queueId, mediaId, userId') .field('media.title, media.duration, media.provider, users.name AS username, artists.name AS artist') .from('queue') .join('users USING(userId)') .join('media USING(mediaId)') .join('artists USING (artistId)') .where('roomId = ?', roomId) .order('queueId') const { text, values } = q.toParam() const rows = await db.all(text, values) for (const row of rows) { result.push(row.queueId) entities[row.queueId] = row } } catch (err) { return Promise.reject(err) } return { result, entities } } module.exports = getQueue
Kill this use strict for now Should explicitly assign to global at some point I guess.
/*global browser:true, protractor:true, httpBackend:true, By:true, expect:true, Promise:true */ var CustomWorld = (function () { var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var HttpBackendProxy = require('http-backend-proxy'); var CustomWorld = function CustomWorld () { browser = protractor = require('protractor').getInstance(); httpBackend = new HttpBackendProxy(browser, { buffer: true }); By = protractor.By; chai.use(chaiAsPromised); expect = chai.expect; Promise = require('bluebird'); }; return CustomWorld; })(); module.exports = function () { this.World = function (callback) { var w = new CustomWorld(); return callback(w); }; return this.World; };
/*global browser:true, protractor:true, httpBackend:true, By:true, expect:true, Promise:true */ 'use strict'; var CustomWorld = (function () { var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var HttpBackendProxy = require('http-backend-proxy'); var CustomWorld = function CustomWorld () { browser = protractor = require('protractor').getInstance(); httpBackend = new HttpBackendProxy(browser, { buffer: true }); By = protractor.By; chai.use(chaiAsPromised); expect = chai.expect; Promise = require('bluebird'); }; return CustomWorld; })(); module.exports = function () { this.World = function (callback) { var w = new CustomWorld(); return callback(w); }; return this.World; };
Fix regex to include .jsx
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [{ test: /\.jsx?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [{ test: /\.js?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }] } };
Switch sitemap index extractor to use sax speediness
<?php namespace webignition\WebResource\Sitemap\UrlExtractor; class SitemapsOrgXmlIndexUrlExtractor extends UrlExtractor { public function extract($content) { $urls = array(); $xmlParser = new \Hobnob\XmlStreamReader\Parser(); $xmlParser->registerCallback( '/sitemapindex/sitemap', function( \Hobnob\XmlStreamReader\Parser $parser, \SimpleXMLElement $node) use (&$urls) { $urls[] = (string)$node; } ); $xmlParser->parse($content); return $urls; } }
<?php namespace webignition\WebResource\Sitemap\UrlExtractor; class SitemapsOrgXmlIndexUrlExtractor extends UrlExtractor { public function extract($content) { $urls = array(); $queryPath = new \QueryPath(); try { $queryPath->withXML($content, 'sitemap loc')->each(function ($index, \DOMElement $domElement) use (&$urls) { if ($domElement->nodeName == 'loc') { $urls[] = \trim($domElement->nodeValue); } }); } catch (QueryPath\ParseException $parseException) { // Invalid XML } return $urls; } }
Return early from main fn instead of using conditionals
'use strict' var toArray = require('stream-to-array') var Promise = require('bluebird') module.exports = streamToPromise function streamToPromise (stream) { if (stream.readable) return fromReadable(stream) if (stream.writable) return fromWritable(stream) return Promise.resolve() } function fromReadable (stream) { var promise = toArray(stream) // Ensure stream is in flowing mode stream.resume() return promise .then(function concat (parts) { return Buffer.concat(parts.map(bufferize)) }) } function fromWritable (stream) { return new Promise(function (resolve, reject) { stream.once('finish', resolve) stream.once('error', reject) }) } function bufferize (chunk) { return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk) }
'use strict' var toArray = require('stream-to-array') var Promise = require('bluebird') module.exports = streamToPromise function streamToPromise (stream) { var promise if (stream.readable) { promise = fromReadable(stream) } else if (stream.writable) { promise = fromWritable(stream) } else { promise = Promise.resolve() } return promise } function fromReadable (stream) { var promise = toArray(stream) // Ensure stream is in flowing mode stream.resume() return promise .then(function concat (parts) { return Buffer.concat(parts.map(bufferize)) }) } function fromWritable (stream) { return new Promise(function (resolve, reject) { stream.once('finish', resolve) stream.once('error', reject) }) } function bufferize (chunk) { return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk) }
Include the examples in the LiSE package
# This file is part of LiSE, a framework for life simulation games. # Copyright (c) Zachary Spector, zacharyspector@gmail.com import sys if sys.version_info[0] < 3 or ( sys.version_info[0] == 3 and sys.version_info[1] < 3 ): raise RuntimeError("LiSE requires Python 3.3 or later") from setuptools import setup setup( name="LiSE", version="0.0.0a6", description="Rules engine for life simulation games", author="Zachary Spector", author_email="zacharyspector@gmail.com", license="GPL3", keywords="game simulation", url="https://github.com/LogicalDash/LiSE", packages=[ "LiSE", "LiSE.server", "LiSE.examples" ], package_data={ 'LiSE': ['sqlite.json'] }, install_requires=[ "gorm>=0.8.3", ], )
# This file is part of LiSE, a framework for life simulation games. # Copyright (c) Zachary Spector, zacharyspector@gmail.com import sys if sys.version_info[0] < 3 or ( sys.version_info[0] == 3 and sys.version_info[1] < 3 ): raise RuntimeError("LiSE requires Python 3.3 or later") from setuptools import setup setup( name="LiSE", version="0.0.0a6", description="Rules engine for life simulation games", author="Zachary Spector", author_email="zacharyspector@gmail.com", license="GPL3", keywords="game simulation", url="https://github.com/LogicalDash/LiSE", packages=[ "LiSE", "LiSE.server" ], package_data={ 'LiSE': ['sqlite.json'] }, install_requires=[ "gorm>=0.8.3", ], )
Set base url for production env
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-cli-holderjs' } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Add ENFORCE_PRIVACY to Travis testing settings.
SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <info@pybossa.com>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es'] ENFORCE_PRIVACY = False
SQLALCHEMY_DATABASE_TEST_URI = 'postgresql://postgres:@localhost/pybossa' GOOGLE_CLIENT_ID = '' GOOGLE_CLIENT_SECRET = '' TWITTER_CONSUMER_KEY='' TWITTER_CONSUMER_SECRET='' FACEBOOK_APP_ID='' FACEBOOK_APP_SECRET='' TERMSOFUSE = 'http://okfn.org/terms-of-use/' DATAUSE = 'http://opendatacommons.org/licenses/by/' ITSDANGEORUSKEY = 'its-dangerous-key' LOGO = 'logo.png' MAIL_SERVER = 'localhost' MAIL_USERNAME = None MAIL_PASSWORD = None MAIL_PORT = 25 MAIL_FAIL_SILENTLY = False MAIL_DEFAULT_SENDER = 'PyBossa Support <info@pybossa.com>' ANNOUNCEMENT = {'admin': 'Root Message', 'user': 'User Message', 'owner': 'Owner Message'} LOCALES = ['en', 'es']
Add "short" param serialized name.
package com.github.daniel_sc.rocketchat.modern_client.request; import com.google.gson.annotations.SerializedName; /** * {@link} https://rocket.chat/docs/developer-guides/rest-api/chat/postmessage/#attachments-detail * */ public class AttachmentField { /** * Whether this field should be a short field. * */ @SerializedName("short") public boolean _short = false; /** * The title of this field. */ public final String title; /** * The value of this field, displayed underneath the title value. */ public final String value; public AttachmentField(String title, String value) { this.title = title; this.value = value; } /* public AttachmentField(boolean _short, String title, String value) { this._short = _short; this.title = title; this.value = value; } */ @Override public String toString() { return "AttachmentField [title=" + title + ", value=" + value + "]"; } }
package com.github.daniel_sc.rocketchat.modern_client.request; /** * {@link} https://rocket.chat/docs/developer-guides/rest-api/chat/postmessage/#attachments-detail * */ public class AttachmentField { /** * Whether this field should be a short field. */ public boolean _short = false; /** * The title of this field. */ public final String title; /** * The value of this field, displayed underneath the title value. */ public final String value; public AttachmentField(String title, String value) { this.title = title; this.value = value; } /* public AttachmentField(boolean _short, String title, String value) { this._short = _short; this.title = title; this.value = value; } */ @Override public String toString() { return "AttachmentField [title=" + title + ", value=" + value + "]"; } }
Revert "Add angular to document directly" This reverts commit 09212f1a5b650856cab67ffa080830f1505a3944.
import test from 'ava'; import jsdom from 'jsdom'; test.before(t => { // Angular dependencies global.document = jsdom.jsdom('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>'); global.window = document.defaultView; global.Node = global.window.Node; require('angular/angular'); // Make angular available for angular-mocks global.angular = global.window.angular; // Set some window properties required by angular-mocks global.window.mocha = {}; global.window.beforeEach = test.beforeEach; global.window.afterEach = test.afterEach; require('angular-mocks'); angular.module('app', ['NgModelOptionsOnInvalid']); }); test('a', t => { angular.mock.inject(($rootScope, $compile) => { const scope = $rootScope.$new(); const element = $compile('<div><div ng-if="notInScope">aabbcc</div></div>')(scope); $rootScope.$digest(); const abc = element.html() || ''; console.log('abc', abc); t.false(abc.includes('aabbcc')); }); });
import test from 'ava'; import jsdom from 'jsdom'; import fs from 'fs'; test.before(t => { // Angular dependencies const angularScript = fs.readFileSync('../node_modules/angular/angular.js', 'utf8'); global.document = jsdom.jsdom(`<!doctype html><html><head><meta charset="utf-8"><script>${angularScript}</script></head><body ng-app="app"><div><div ng-if="notInScope">aabbcc</div></div></body></html>`); global.window = document.defaultView; global.Node = global.window.Node; require('angular/angular'); // Make angular available for angular-mocks global.angular = global.window.angular; // Set some window properties required by angular-mocks global.window.mocha = {}; global.window.beforeEach = test.beforeEach; global.window.afterEach = test.afterEach; require('angular-mocks'); angular.module('app', ['NgModelOptionsOnInvalid']); }); test('a', t => { angular.mock.inject(($rootScope, $compile) => { const scope = $rootScope.$new(); const element = $compile('<div><div ng-if="notInScope">aabbcc</div></div>')(scope); $rootScope.$digest(); const abc = element.html() || ''; console.log('abc', abc); t.false(abc.includes('aabbcc')); }); });
Add missing import for navigation
import React from 'react'; import Router from 'react-router'; import stores from 'stores'; import SecondaryAdminNavigation from './SecondaryAdminNavigation.react'; import ResourceMaster from './ResourceMaster.react'; import ImageMaster from './ImageMaster.react'; let RouteHandler = Router.RouteHandler; export default React.createClass({ mixins: [Router.State], render: function () { return ( <div> <SecondaryAdminNavigation/> <div className = "container admin"> <span className="adminHeader"> <h1>Admin</h1> <RouteHandler /> </span> </div> </div> ); } });
import React from 'react'; import Router from 'react-router'; import stores from 'stores'; import ResourceMaster from './ResourceMaster.react'; import ImageMaster from './ImageMaster.react'; let RouteHandler = Router.RouteHandler; export default React.createClass({ mixins: [Router.State], render: function () { return ( <div> <SecondaryAdminNavigation/> <div className = "container admin"> <span className="adminHeader"> <h1>Admin</h1> <RouteHandler /> </span> </div> </div> ); } });
Put database and nonces in modals
<?php define('COOKIE_SESSION', true); require_once("../config.php"); session_start(); require_once("gate.php"); if ( $REDIRECTED === true || ! isset($_SESSION["admin"]) ) return; setcookie("adminmenu","true", 0, "/"); \Tsugi\Core\LTIX::getConnection(); $OUTPUT->header(); $OUTPUT->bodyStart(); $OUTPUT->topNav(); require_once("sanity-db.php"); ?> <div id="iframe-dialog" title="Read Only Dialog" style="display: none;"> <iframe name="iframe-frame" style="height:400px" id="iframe-frame" src="<?= $OUTPUT->getSpinnerUrl() ?>"></iframe> </div> <h1>Welcome Adminstrator</h1> <ul> <li> <a href="upgrade.php" title="Upgrade Database" target="iframe-frame" onclick="showModalIframe(this.title, 'iframe-dialog', 'iframe-frame', _TSUGI.spinnerUrl);" > Ugrade Database </a> <li> <a href="nonce.php" title="Check Nonces" target="iframe-frame" onclick="showModalIframe(this.title, 'iframe-dialog', 'iframe-frame', _TSUGI.spinnerUrl);" > Check Nonces </a> <li><a href="context/index.php">View Contexts</a></li> <?php if ( $CFG->providekeys ) { ?> <li><a href="key/index.php">Manage Access Keys</a></li> <?php } ?> <li><a href="install/index.php">Manage Installed Modules</a></li> </ul> <?php $OUTPUT->footer();
<?php define('COOKIE_SESSION', true); require_once("../config.php"); session_start(); require_once("gate.php"); if ( $REDIRECTED === true || ! isset($_SESSION["admin"]) ) return; setcookie("adminmenu","true", 0, "/"); \Tsugi\Core\LTIX::getConnection(); $OUTPUT->header(); $OUTPUT->bodyStart(); $OUTPUT->topNav(); require_once("sanity-db.php"); ?> <h1>Welcome Adminstrator</h1> <ul> <li><a href="upgrade.php" target="_new">Upgrade Database</a></li> <li><a href="nonce.php" target="_new">Check Nonces</a></li> <li><a href="context/index.php">View Contexts</a></li> <?php if ( $CFG->providekeys ) { ?> <li><a href="key/index.php">Manage Access Keys</a></li> <?php } ?> <li><a href="install/index.php">Manage Installed Modules</a></li> </ul> <?php $OUTPUT->footer();
Fix long description format to be markdown
#! /usr/bin/env python from setuptools import setup import re from os import path version = '' with open('cliff/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md')) as f: long_description = f.read() setup(name='mediacloud-cliff', version=version, description='Media Cloud CLIFF API Client Library', long_description=long_description, long_description_content_type='text/markdown', author='Rahul Bhargava', author_email='rahulb@media.mit.edu', url='http://cliff.mediacloud.org', packages={'cliff'}, package_data={'': ['LICENSE']}, include_package_data=True, install_requires=['requests'], license='MIT', zip_safe=False )
#! /usr/bin/env python from setuptools import setup import re from os import path version = '' with open('cliff/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md')) as f: long_description = f.read() setup(name='mediacloud-cliff', version=version, description='Media Cloud CLIFF API Client Library', long_description=long_description, author='Rahul Bhargava', author_email='rahulb@media.mit.edu', url='http://cliff.mediacloud.org', packages={'cliff'}, package_data={'': ['LICENSE']}, include_package_data=True, install_requires=['requests'], license='MIT', zip_safe=False )
Add PIN variables and constants
package org.cryptonit; import javacard.framework.APDU; import javacard.framework.Applet; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.OwnerPIN; public class CryptonitApplet extends Applet { private OwnerPIN pin; private final static byte PIN_MAX_LENGTH = 8; private final static byte PIN_MAX_TRIES = 5; protected CryptonitApplet(byte[] bArray, short bOffset, byte bLength) { register(); } public static void install(byte[] bArray, short bOffset, byte bLength) { new CryptonitApplet(bArray, bOffset, bLength); } @Override public void process(APDU apdu) { byte buffer[] = apdu.getBuffer(); if (apdu.isISOInterindustryCLA()) { if (buffer[ISO7816.OFFSET_INS] == (byte) (0xA4)) { return; } ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } }
package org.cryptonit; import javacard.framework.APDU; import javacard.framework.Applet; import javacard.framework.ISO7816; import javacard.framework.ISOException; public class CryptonitApplet extends Applet { protected CryptonitApplet(byte[] bArray, short bOffset, byte bLength) { register(); } public static void install(byte[] bArray, short bOffset, byte bLength) { new CryptonitApplet(bArray, bOffset, bLength); } @Override public void process(APDU apdu) { byte buffer[] = apdu.getBuffer(); if (apdu.isISOInterindustryCLA()) { if (buffer[ISO7816.OFFSET_INS] == (byte) (0xA4)) { return; } ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); } }
Discard active tabs if their window is minimized
(function(tabs, windows){ "use strict"; const specialUrls =/chrome-extension:|chrome:|chrome-devtools:|file:|chrome.google.com\/webstore/; let discardAllTabs = () => { windows.getAll({populate: true}, windowsList => windowsList.forEach( win => { const minimized = win.state === 'minimized'; win.tabs.forEach( tab => { if(tab.discarded) { return; } if(tab.pinned) { return; } if(tab.active && !minimized) { return; } if(tab.url && specialUrls.test(tab.url)){ return; } tabs.discard(tab.id); } ) } )); }; chrome.browserAction.onClicked.addListener( discardAllTabs ); chrome.runtime.onStartup.addListener( discardAllTabs ); })(chrome.tabs, chrome.windows);
(function(tabs, windows){ "use strict"; const specialUrls =/chrome-extension:|chrome:|chrome-devtools:|file:|chrome.google.com\/webstore/; let discardAllTabs = () => { windows.getAll({populate: true}, windowsList => windowsList.forEach( win => { win.tabs.forEach( tab => { if(tab.pinned || tab.active || tab.discarded) { return; } if(tab.url && specialUrls.test(tab.url)){ return; } tabs.discard(tab.id); } ) } )); }; chrome.browserAction.onClicked.addListener( discardAllTabs ); chrome.runtime.onStartup.addListener( discardAllTabs ); })(chrome.tabs, chrome.windows);
Add getLanguage method to languages mixin. This is more suitable for passing to JST template
window.ModelWithLanguageMixin = { LANGUAGE_CHOICES: { en: 'English', es: 'Spanish', hi: 'Hindi', pt: 'Portuguese', ru: 'Russian', ja: 'Japanese', de: 'German', id: 'Malay/Indonesian', vi: 'Vietnamese', ko: 'Korean', fr: 'French', fa: 'Persian', tk: 'Turkish', it: 'Italian', no: 'Norwegian', pl: 'Polish', chi: 'Chinese (simplified)', zho: 'Chinese (traditional)', ar: 'Aribic', th: 'Thai' }, getLanguageCode: function(){ return this.get('language') || 'en'; }, getLanguageName: function(){ return this.LANGUAGE_CHOICES[ this.getLanguageCode() ]; }, getLanguage: function(){ return { code: this.getLanguageCode(), name: this.getLanguageName() }; } };
window.ModelWithLanguageMixin = { LANGUAGE_CHOICES: { en: 'English', es: 'Spanish', hi: 'Hindi', pt: 'Portuguese', ru: 'Russian', ja: 'Japanese', de: 'German', id: 'Malay/Indonesian', vi: 'Vietnamese', ko: 'Korean', fr: 'French', fa: 'Persian', tk: 'Turkish', it: 'Italian', no: 'Norwegian', pl: 'Polish', chi: 'Chinese (simplified)', zho: 'Chinese (traditional)', ar: 'Aribic', th: 'Thai' }, getLanguageCode: function(){ return this.get('language') || 'en'; }, getLanguageName: function(){ return this.LANGUAGE_CHOICES[ this.getLanguageCode() ]; } };
Use multiple WebKit web processes. A new feature for WebKit2GTK+ 2.4, we can now specify to use multiple webkit web processes rather than all webviews sharing the same process. If a tab's web process is not shared with any other's (although currently unimplemented, this may happen when a tab is opened by another webview, either through javascript or middle-clicking a hyperlink), killing or crashing that web process only results in one broken tab rather than crashing the entire browser (WebKit1) or breaking every tab (WebKit2GTK+ <= 2.2).
// Copyright (c) 2014 Josh Rickmar. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package main import ( "runtime" "github.com/conformal/gotk3/gtk" "github.com/jrick/go-webkit2/wk2" ) const HomePage HTMLPageDescription = "https://www.duckduckgo.com/lite" const ( defaultWinWidth = 1024 defaultWinHeight = 768 ) // RunGUI initializes GTK, creates the toplevel window and all child widgets, // opens the pages for the default session, and runs the Glib main event loop. // This function blocks until the toplevel window is destroyed and the event // loop exits. func RunGUI() { gtk.Init(nil) window, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) window.Connect("destroy", func() { gtk.MainQuit() }) window.SetDefaultGeometry(defaultWinWidth, defaultWinHeight) window.Show() wc := wk2.DefaultWebContext() wc.SetProcessModel(wk2.ProcessModelMultipleSecondaryProcesses) session := []PageDescription{HomePage} pm := NewPageManager(session) window.Add(pm) pm.Show() gtk.Main() } func main() { runtime.GOMAXPROCS(runtime.NumCPU()) RunProfiler("localhost:7070") RunGUI() }
// Copyright (c) 2014 Josh Rickmar. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package main import ( "github.com/conformal/gotk3/gtk" "runtime" ) const HomePage HTMLPageDescription = "https://www.duckduckgo.com/lite" const ( defaultWinWidth = 1024 defaultWinHeight = 768 ) // RunGUI initializes GTK, creates the toplevel window and all child widgets, // opens the pages for the default session, and runs the Glib main event loop. // This function blocks until the toplevel window is destroyed and the event // loop exits. func RunGUI() { gtk.Init(nil) window, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) window.Connect("destroy", func() { gtk.MainQuit() }) window.SetDefaultGeometry(defaultWinWidth, defaultWinHeight) window.Show() session := []PageDescription{HomePage} pm := NewPageManager(session) window.Add(pm) pm.Show() gtk.Main() } func main() { runtime.GOMAXPROCS(runtime.NumCPU()) RunProfiler("localhost:7070") RunGUI() }
Fix equality statement to use === rather than ==.
Application.Services.factory('watcher', function () { var watcherService = {}; watcherService.watch = function (scope, variable, fn) { scope.$watch(variable, function (newval, oldval) { if (!newval && !oldval) { return; } else if (newval === "" && oldval) { fn(oldval); } else { fn(newval); } }); }; return watcherService; });
Application.Services.factory('watcher', function () { var watcherService = {}; watcherService.watch = function (scope, variable, fn) { scope.$watch(variable, function (newval, oldval) { if (!newval && !oldval) { return; } else if (newval == "" && oldval) { fn(oldval); } else { fn(newval); } }); }; return watcherService; });
Use transfer to xml in refactor script
<?php require_once(__DIR__ . '/../vendor/autoload.php'); spl_autoload_register(function ($class) { $class = str_replace(['ReneFactor', '\\'], ['', DIRECTORY_SEPARATOR], $class); $classPath = __DIR__ . DIRECTORY_SEPARATOR . $class . '.php'; require_once $classPath; }); use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Logger\ConsoleLogger; $consoleLogger = new ConsoleLogger( new ConsoleOutput(OutputInterface::VERBOSITY_DEBUG) ); $consoleLogger->info('starting refactoring'); $refactor = new \ReneFactor\TransferToXml($consoleLogger); $refactor->refactor(); $refactor = new \ReneFactor\TransferAccess($consoleLogger); //$refactor->refactor(); $refactor = new \ReneFactor\EntityAccess($consoleLogger); //$refactor->refactor();
<?php require_once(__DIR__ . '/../vendor/autoload.php'); spl_autoload_register(function ($class) { $class = str_replace(['ReneFactor', '\\'], ['', DIRECTORY_SEPARATOR], $class); $classPath = __DIR__ . DIRECTORY_SEPARATOR . $class . '.php'; require_once $classPath; }); use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Logger\ConsoleLogger; $consoleLogger = new ConsoleLogger( new ConsoleOutput(OutputInterface::VERBOSITY_DEBUG) ); $consoleLogger->info('starting refactoring'); $refactor = new \ReneFactor\TransferAccess($consoleLogger); $refactor->refactor(); $refactor = new \ReneFactor\EntityAccess($consoleLogger); //$refactor->refactor();
784: Remove the type field as its not required.
const config = require('../../../knexfile').web const knex = require('knex')(config) module.exports = function (id) { var table = 'team_caseload_overview' var whereObject = {} if (id !== undefined) { whereObject.id = id } return knex(table) .where(whereObject) .select('name', 'grade_code AS gradeCode', 'untiered', 'd2', 'd1', 'c2', 'c1', 'b2', 'b1', 'a', 'total_cases AS totalCases', 'link_id AS linkId') .then(function (results) { return results }) }
const config = require('../../../knexfile').web const knex = require('knex')(config) module.exports = function (id, type) { var table = 'team_caseload_overview' var whereObject = {} if (id !== undefined) { whereObject.id = id } return knex(table) .where(whereObject) .select('name', 'grade_code AS gradeCode', 'untiered', 'd2', 'd1', 'c2', 'c1', 'b2', 'b1', 'a', 'total_cases AS totalCases', 'link_id AS linkId') .then(function (results) { return results }) }
chore: Add a 10s timeout to reachable-url
#!/usr/bin/env node 'use strict'; var stdin = process.openStdin(); var async = require('async'); var reachableUrl = require('reachable-url') if (require.main === module) { main(); } else { module.exports = resolveUrls; } function main() { stdin.setEncoding('utf8'); stdin.on('data', function(err, data) { if(err) { return console.error(err); } console.log(JSON.stringify(resolveUrls(JSON.parse(data)), null, 4)); }); } function resolveUrls(urls, cb) { async.mapLimit(urls, 20, resolveUrl, function(err, d) { if(err) { return cb(err); } cb(null, d.filter(id)); }); } function resolveUrl(d, cb) { reachableUrl(d.url, { timeout: 10000 }).then(({ url }) => { d.url = url cb(null, d) }).catch(err => { console.error(err) cb(); }) } function id(a) {return a;}
#!/usr/bin/env node 'use strict'; var stdin = process.openStdin(); var async = require('async'); var reachableUrl = require('reachable-url') if (require.main === module) { main(); } else { module.exports = resolveUrls; } function main() { stdin.setEncoding('utf8'); stdin.on('data', function(err, data) { if(err) { return console.error(err); } console.log(JSON.stringify(resolveUrls(JSON.parse(data)), null, 4)); }); } function resolveUrls(urls, cb) { async.mapLimit(urls, 20, resolveUrl, function(err, d) { if(err) { return cb(err); } cb(null, d.filter(id)); }); } function resolveUrl(d, cb) { reachableUrl(d.url).then(({ url }) => { d.url = url cb(null, d) }).catch(err => { console.error(err) cb(); }) } function id(a) {return a;}
Make key_sizes a frozenset, since these are/should be immutable
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function class AES(object): name = "AES" block_size = 128 key_sizes = frozenset([128, 192, 256]) def __init__(self, key): super(AES, self).__init__() self.key = key # Verify that the key size matches the expected key size if self.key_size not in self.key_sizes: raise ValueError("Invalid key size ({0}) for {1}".format( self.key_size, self.name )) @property def key_size(self): return len(self.key) * 8
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function class AES(object): name = "AES" block_size = 128 key_sizes = set([128, 192, 256]) def __init__(self, key): super(AES, self).__init__() self.key = key # Verify that the key size matches the expected key size if self.key_size not in self.key_sizes: raise ValueError("Invalid key size ({0}) for {1}".format( self.key_size, self.name )) @property def key_size(self): return len(self.key) * 8
Disable SSL in database connection for now
package db import ( "database/sql" "fmt" "github.com/rafaeljusto/cctldstats/config" ) // Connection database connection. var Connection *sql.DB // Connect performs the database connection. Today the following databases are supported: mysql and postgres func Connect() (err error) { var connParams string switch config.CCTLDStats.Database.Kind { case "mysql": connParams = fmt.Sprintf("%s:%s@tcp(%s)/%s", config.CCTLDStats.Database.Username, config.CCTLDStats.Database.Password, config.CCTLDStats.Database.Host, config.CCTLDStats.Database.Name, ) case "postgres": connParams = fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", config.CCTLDStats.Database.Username, config.CCTLDStats.Database.Password, config.CCTLDStats.Database.Host, config.CCTLDStats.Database.Name, ) } Connection, err = sql.Open(config.CCTLDStats.Database.Kind, connParams) return }
package db import ( "database/sql" "fmt" "github.com/rafaeljusto/cctldstats/config" ) // Connection database connection. var Connection *sql.DB // Connect performs the database connection. Today the following databases are supported: mysql and postgres func Connect() (err error) { var connParams string switch config.CCTLDStats.Database.Kind { case "mysql": connParams = fmt.Sprintf("%s:%s@tcp(%s)/%s", config.CCTLDStats.Database.Username, config.CCTLDStats.Database.Password, config.CCTLDStats.Database.Host, config.CCTLDStats.Database.Name, ) case "postgres": connParams = fmt.Sprintf("postgres://%s:%s@%s/%s", config.CCTLDStats.Database.Username, config.CCTLDStats.Database.Password, config.CCTLDStats.Database.Host, config.CCTLDStats.Database.Name, ) } Connection, err = sql.Open(config.CCTLDStats.Database.Kind, connParams) return }
Fix for Authentication scenario to correctly use self.clients Scenario has recently been refactored, self.clients in Scenario now takes the name of the CLI client. During the refactoring, the Authenticate scenario was not correctly updated, which causes the authentication scenario to fail. This patch fixes that. Change-Id: I546c0846e00a5285f0d47bc80b6304a53cc566ff Closes-Bug: #1291386
# Copyright 2014 Red Hat, Inc. <http://www.redhat.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.benchmark.scenarios import base class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): self.clients("keystone")
# Copyright 2014 Red Hat, Inc. <http://www.redhat.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.benchmark.scenarios import base from rally import osclients class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): keystone_endpoint = self.clients("endpoint") cl = osclients.Clients(keystone_endpoint) cl.get_keystone_client()
Allow empty strings as instructions
from django.db import models from experiment_session.models import ExperimentSession from django.core.validators import MinValueValidator class Experiment(models.Model): LIGHTOFF_FIXED = 'fixed' LIGHTOFF_WAITING = 'waiting' _LIGHTOFF_CHOICES = ( (LIGHTOFF_FIXED, 'Fixed'), (LIGHTOFF_WAITING, 'Waiting') ) AUDIO_NONE = 'none' AUDIO_BEEP = 'beep' _AUDIO_CHOICES = ( (AUDIO_NONE, 'None'), (AUDIO_BEEP, 'Audible beep on error') ) name = models.CharField(unique=True, max_length=255) lightoffmode = models.CharField( choices=_LIGHTOFF_CHOICES, max_length=30 ) lightofftimeout = models.IntegerField(validators=(MinValueValidator(0),)) audiomode = models.CharField( choices=_AUDIO_CHOICES, max_length=30 ) repeatscount = models.IntegerField( validators=( MinValueValidator(1), ) ) createdon = models.DateTimeField(auto_now_add=True, editable=False) traininglength = models.IntegerField(validators=(MinValueValidator(0),)) instructions = models.CharField(max_length=10000, blank=True) def __str__(self): return self.name
from django.db import models from experiment_session.models import ExperimentSession from django.core.validators import MinValueValidator class Experiment(models.Model): LIGHTOFF_FIXED = 'fixed' LIGHTOFF_WAITING = 'waiting' _LIGHTOFF_CHOICES = ( (LIGHTOFF_FIXED, 'Fixed'), (LIGHTOFF_WAITING, 'Waiting') ) AUDIO_NONE = 'none' AUDIO_BEEP = 'beep' _AUDIO_CHOICES = ( (AUDIO_NONE, 'None'), (AUDIO_BEEP, 'Audible beep on error') ) name = models.CharField(unique=True, max_length=255) lightoffmode = models.CharField( choices=_LIGHTOFF_CHOICES, max_length=30 ) lightofftimeout = models.IntegerField(validators=(MinValueValidator(0),)) audiomode = models.CharField( choices=_AUDIO_CHOICES, max_length=30 ) repeatscount = models.IntegerField( validators=( MinValueValidator(1), ) ) createdon = models.DateTimeField(auto_now_add=True, editable=False) traininglength = models.IntegerField(validators=(MinValueValidator(0),)) instructions = models.CharField(max_length=10000, default='') def __str__(self): return self.name
Make stetho agent when install stetho
# Copyright 2015 UnitedStack, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from setuptools import setup, find_packages setup(name='stetho', version="0.1.0", packages = find_packages(), zip_safe = False, description = "stetho", author = "UnitedStackSDN", author_email = "unitedstack-sdn@googlegroups.com", license = "APL", keywords = ("stetho", "egg"), platforms = "Independant", url = "https://www.ustack.com", entry_points={ 'console_scripts': [ 'stetho = stetho.stethoclient.shell:main', 'stetho-agent = stetho.agent.agent:main', ] } )
# Copyright 2015 UnitedStack, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from setuptools import setup, find_packages setup(name='stetho', version="0.1.0", packages = find_packages(), zip_safe = False, description = "stetho", author = "UnitedStackSDN", author_email = "unitedstack-sdn@googlegroups.com", license = "APL", keywords = ("stetho", "egg"), platforms = "Independant", url = "https://www.ustack.com", entry_points={ 'console_scripts': [ 'stetho = stetho.stethoclient.shell:main' ] } )
Fix in ModuleRegistry to properly disable module without unloading them
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.impl.sensor.v4l; import org.sensorhub.api.sensor.SensorConfig; /** * <p> * Configuration class for the generic Video4Linux camera driver * </p> * * @author Alex Robin <alex.robin@sensiasoftware.com> * @since Sep 6, 2013 */ public class V4LCameraConfig extends SensorConfig { /** * Name of video device to use (e.g. /dev/video0) */ public String deviceName = "/dev/video0"; /** * Maximum number of frames that can be kept in storage * (These last N frames will be stored in memory) */ public int frameStorageCapacity; /** * Default camera params to use on startup * These can then be changed with the control interface */ public V4LCameraParams defaultParams = new V4LCameraParams(); }
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.impl.sensor.v4l; import org.sensorhub.api.sensor.SensorConfig; /** * <p> * Configuration class for the generic Video4Linux camera driver * </p> * * @author Alex Robin <alex.robin@sensiasoftware.com> * @since Sep 6, 2013 */ public class V4LCameraConfig extends SensorConfig { /** * Name of video device to use * example: /dev/video0 */ public String deviceName; /** * Maximum number of frames that can be kept in storage * (These last N frames will be stored in memory) */ public int frameStorageCapacity; /** * Default camera params to use on startup * These can then be changed with the control interface */ public V4LCameraParams defaultParams = new V4LCameraParams(); }
Return the right URL when a file is posted
# -*- coding: utf-8 -*- # vim: set ts=4 from django.forms import ModelForm from django.http import Http404, HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from Artifactor.models import Artifact def index(request): artifacts = Artifact.objects.all() return render_to_response('Artifactor/index.html', {'artifacts': artifacts}, context_instance=RequestContext(request)) class ArtifactForm(ModelForm): class Meta: model = Artifact fields = ('path',) @csrf_exempt def post(request): if request.method == 'POST': form = ArtifactForm(request.POST, request.FILES) if form.is_valid(): artifact = form.save() return HttpResponse(artifact.path.url, content_type='text/plain') else: raise Http404
# -*- coding: utf-8 -*- # vim: set ts=4 from django.forms import ModelForm from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from Artifactor.models import Artifact def index(request): artifacts = Artifact.objects.all() return render_to_response('Artifactor/index.html', {'artifacts': artifacts}, context_instance=RequestContext(request)) class ArtifactForm(ModelForm): class Meta: model = Artifact fields = ('path',) @csrf_exempt def post(request): if request.method == 'POST': form = ArtifactForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: raise Http404
Use command's hash code method
package tests; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import com.github.sormuras.bach.Command; import org.junit.jupiter.api.Test; import tests.util.Print; class CommandTests { @Test void withoutArguments() { var command = Command.of("name"); assertEquals("name", command.name()); var commandLine = command.toString(); assertEquals("name", commandLine); assertEquals(Command.builder("name").build().toString(), commandLine); } @Test void withArguments() { var command = Command.builder("name").with(1).with("2", 3, 4).build(); assertEquals("name", command.name()); assertEquals("name 1 2 3 4", command.toString()); assertEquals(Command.of("name", 1, 2, 3, 4).hashCode(), command.hashCode()); } @Test void toCommandReturnsItself() { var expected = Command.of("name"); assertSame(expected, expected.toCommand()); } @Test void toCommandReturnsInstanceOfCommand() { assertEquals(Command.of("print"), new Print().toCommand()); assertEquals(Command.of("print", "message"), new Print("message").toCommand()); } }
package tests; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import com.github.sormuras.bach.Command; import org.junit.jupiter.api.Test; import tests.util.Print; class CommandTests { @Test void withoutArguments() { var command = Command.of("name"); assertEquals("name", command.name()); var commandLine = command.toString(); assertEquals("name", commandLine); assertEquals(Command.builder("name").build().toString(), commandLine); } @Test void withArguments() { var command = Command.builder("name").with(1).with("2", 3, 4).build(); assertEquals("name", command.name()); assertEquals("name 1 2 3 4", command.toString()); assertEquals(Command.of("name", 1, 2, 3, 4).toString(), command.toString()); } @Test void toCommandReturnsItself() { var expected = Command.of("name"); assertSame(expected, expected.toCommand()); } @Test void toCommandReturnsInstanceOfCommand() { assertEquals(Command.of("print"), new Print().toCommand()); assertEquals(Command.of("print", "message"), new Print("message").toCommand()); } }
Fix url when using cdnUrl with S3. Null url was incorrectly used as path
<?php namespace FoF\Upload\Adapters; use FoF\Upload\Contracts\UploadAdapter; use FoF\Upload\File; use FoF\Upload\Helpers\Settings; use Illuminate\Support\Arr; class AwsS3 extends Flysystem implements UploadAdapter { protected function generateUrl(File $file) { /** @var Settings $settings */ $settings = app()->make(Settings::class); $cdnUrl = $settings->get('cdnUrl'); if (!$cdnUrl) { $region = $this->adapter->getClient()->getRegion(); $bucket = $this->adapter->getBucket(); $cdnUrl = sprintf('https://%s.s3.%s.amazonaws.com', $bucket, $region ?: 'us-east-1'); } $file->url = sprintf('%s/%s', $cdnUrl, Arr::get($this->meta, 'path', $file->path)); } }
<?php namespace FoF\Upload\Adapters; use FoF\Upload\Contracts\UploadAdapter; use FoF\Upload\File; use FoF\Upload\Helpers\Settings; use Illuminate\Support\Arr; class AwsS3 extends Flysystem implements UploadAdapter { protected function generateUrl(File $file) { /** @var Settings $settings */ $settings = app()->make(Settings::class); if ($cdnUrl = $settings->get('cdnUrl')) { $file->url = sprintf('%s/%s', $cdnUrl, $file->url); } else { $region = $this->adapter->getClient()->getRegion(); $bucket = $this->adapter->getBucket(); $baseUrl = sprintf('https://%s.s3.%s.amazonaws.com/', $bucket, $region ?: 'us-east-1'); $file->url = sprintf( $baseUrl . '%s', Arr::get($this->meta, 'path', $file->path) ); } } }
Change sleep function to the end to do repeat everytime
# coding=utf8 # 31.220.16.242 # 216.58.222.46 import socket import time import webbrowser def checkdns(): print time.ctime() retorno = True try: ip = socket.gethostbyname('google.com') print ("O IP do host verificado é: " + ip) if ip == "216.58.22.46": retorno = False url = 'http://www.google.com.br/' webbrowser.open_new_tab(url) else: print "DNS ainda não atualizado. Aguardando 30s." except socket.gaierror: print "Nenhum host definido para o domínio. Aguardando 30s." return retorno condicao = True while condicao: condicao = checkdns() time.sleep( 30 )
# coding=utf8 # 31.220.16.242 # 216.58.222.46 import socket import time import webbrowser def checkdns(): print time.ctime() retorno = True try: ip = socket.gethostbyname('google.com') print ("O IP do host verificado é: " + ip) if ip == "216.58.222.46": retorno = False url = 'http://www.google.com.br/' webbrowser.open_new_tab(url) else: print "DNS ainda não atualizado. Aguardando 30s." time.sleep( 30 ) except socket.gaierror: print "Nenhum host definido para o domínio. Aguardando 30s." time.sleep( 30 ) return retorno condicao = True while condicao: condicao = checkdns()
Add teardown function as well
import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): # Make sure the expected files don't exist yet for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_created(self): self.assertFalse(os.path.exists("test_sequences")) self.assertFalse(os.path.exists("test_words")) generate_files([], sequences_fname="test_sequences", words_fname="test_words") self.assertTrue(os.path.exists("test_sequences")) self.assertTrue(os.path.exists("test_words")) def tearDown(self): # So as not to leave a mess for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) if __name__ == '__main__': unittest.main()
import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_created(self): self.assertFalse(os.path.exists("test_sequences")) self.assertFalse(os.path.exists("test_words")) generate_files([], sequences_fname="test_sequences", words_fname="test_words") self.assertTrue(os.path.exists("test_sequences")) self.assertTrue(os.path.exists("test_words")) if __name__ == '__main__': unittest.main()
Update maintainer to Blanc Ltd
#!/usr/bin/env python from setuptools import find_packages, setup # Use quickphotos.VERSION for version numbers version_tuple = __import__('quickphotos').VERSION version = '.'.join([str(v) for v in version_tuple]) setup( name='django-quick-photos', version=version, description='Latest Photos from Instagram for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-quick-photos', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], install_requires=[ 'python-instagram>=0.8.0', ], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], license='BSD-2', )
#!/usr/bin/env python from setuptools import find_packages, setup # Use quickphotos.VERSION for version numbers version_tuple = __import__('quickphotos').VERSION version = '.'.join([str(v) for v in version_tuple]) setup( name='django-quick-photos', version=version, description='Latest Photos from Instagram for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-quick-photos', maintainer='Alex Tomkins', maintainer_email='alex@blanc.ltd.uk', platforms=['any'], install_requires=[ 'python-instagram>=0.8.0', ], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], license='BSD-2', )
Fix return of Terminal instance when term method accept string
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return self.get_term(term) def get_term(self, term=None): res = super().get_term(StringGrammar.__to_string_arr(term)) if isinstance(term, str): return res[0] return res def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term))
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return super().term(StringGrammar.__to_string_arr(term)) def get_term(self, term=None): res = super().get_term(StringGrammar.__to_string_arr(term)) if isinstance(term, str): return res[0] return res def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term))
Fix up mixpanel course tracking
from modules.mixpanel.mixpanel import track_event_mixpanel from modules.decorators import view, query, event_handler import re SINGLE_PAGES_TO_TRACK = ['/', '/dashboard', '/create_account'] COURSE_PAGES_TO_TRACK = ['/courses', '/about'] @event_handler() def single_page_track_event(fs, db, response): for resp in response: if resp['event_type'] in SINGLE_PAGES_TO_TRACK: user = resp["username"] track_event_mixpanel(resp['event_type'],{'user' : user, 'distinct_id' : user}) @event_handler() def course_track_event(fs,db,response): for resp in response: for regex in COURSE_PAGES_TO_TRACK: match = re.search(regex, resp['event_type']) user = resp["username"] if match is not None: split_url = resp['event_type'].split("/") org = split_url[2] course = split_url[3] track_event_mixpanel(regex,{'user' : user, 'distinct_id' : user, 'full_url' : resp['event_type'], 'course' : course, 'org' : org})
from modules.mixpanel.mixpanel import track_event_mixpanel from modules.decorators import view, query, event_handler import re SINGLE_PAGES_TO_TRACK = ['/', '/dashboard', '/create_account'] REGEX_PAGES_TO_TRACK = ['/course', '/about'] @event_handler() def single_page_track_event(fs, db, response): for resp in response: if resp['event_type'] in SINGLE_PAGES_TO_TRACK: user = resp["username"] track_event_mixpanel(resp['event_type'],{'user' : user, 'distinct_id' : user}) @event_handler() def regex_track_event(fs,db,response): for rep in response: for regex in REGEX_PAGES_TO_TRACK: match = re.search(regex, resp['event_type']) if match is not None: track_event_mixpanel(regex,{'user' : user, 'distinct_id' : user, 'full_url' : resp['event_type']})
Remove foreign keys as Laravel cant detect class
<?php /* * This file is part of Laravel CrowdAuth * * (c) Daniel McAssey <hello@glokon.me> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateCrowdgroupCrowduserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('crowdgroup_crowduser', function(Blueprint $table) { $table->increments('id'); $table->integer('crowd_group_id')->unsigned()->index(); $table->integer('crowd_user_id')->unsigned()->index(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('crowdgroup_crowduser'); } }
<?php /* * This file is part of Laravel CrowdAuth * * (c) Daniel McAssey <hello@glokon.me> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateCrowdgroupCrowduserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('crowdgroup_crowduser', function(Blueprint $table) { $table->increments('id'); $table->integer('crowd_group_id')->unsigned()->index(); $table->integer('crowd_user_id')->unsigned()->index(); $table->timestamps(); }); Schema::table('crowdgroup_crowduser', function(Blueprint $table) { $table->foreign('crowd_group_id')->references('id')->on('crowd_groups')->onDelete('cascade'); $table->foreign('crowd_user_id')->references('id')->on('crowd_users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('crowdgroup_crowduser'); } }
tools: Fix Python 3 incompatibility for building with Eclipse on Windows
#!/usr/bin/env python # # Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths # to Windows paths, for Eclipse from __future__ import print_function, division import sys import subprocess import os.path import re UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+') paths = {} def check_path(path): try: return paths[path] except KeyError: pass paths[path] = path # cache as failed, replace with success if it works try: winpath = subprocess.check_output(["cygpath", "-w", path]).decode().strip() except subprocess.CalledProcessError: return path # something went wrong running cygpath, assume this is not a path! if not os.path.exists(winpath): return path # not actually a valid path winpath = winpath.replace("\\", "/") # make consistent with forward-slashes used elsewhere paths[path] = winpath return winpath def main(): print("Running make in '%s'" % check_path(os.getcwd())) make = subprocess.Popen(["make"] + sys.argv[1:] + ["BATCH_BUILD=1"], stdout=subprocess.PIPE) for line in iter(make.stdout.readline, ''): line = re.sub(UNIX_PATH_RE, lambda m: check_path(m.group(0)), line) print(line.rstrip()) sys.exit(make.wait()) if __name__ == "__main__": main()
#!/usr/bin/env python # # Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths # to Windows paths, for Eclipse from __future__ import print_function, division import sys import subprocess import os.path import re UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+') paths = {} def check_path(path): try: return paths[path] except KeyError: pass paths[path] = path # cache as failed, replace with success if it works try: winpath = subprocess.check_output(["cygpath", "-w", path]).strip() except subprocess.CalledProcessError: return path # something went wrong running cygpath, assume this is not a path! if not os.path.exists(winpath): return path # not actually a valid path winpath = winpath.replace("\\", "/") # make consistent with forward-slashes used elsewhere paths[path] = winpath return winpath def main(): print("Running make in '%s'" % check_path(os.getcwd())) make = subprocess.Popen(["make"] + sys.argv[1:] + ["BATCH_BUILD=1"], stdout=subprocess.PIPE) for line in iter(make.stdout.readline, ''): line = re.sub(UNIX_PATH_RE, lambda m: check_path(m.group(0)), line) print(line.rstrip()) sys.exit(make.wait()) if __name__ == "__main__": main()
Fix Test by ensuring non-interactivity
<?php /* * This file is part of the kreait eZ Publish Migrations Bundle. * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. */ namespace Kreait\EzPublish\MigrationsBundle\Tests\Command; use Kreait\EzPublish\MigrationsBundle\Command\VersionCommand; use Kreait\EzPublish\MigrationsBundle\Tests\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** * @group commands */ class VersionCommandTest extends TestCase { public function testExecuteAddVersion() { $versionString = $this->generateMigrationAndReturnVersionString(); $command = new VersionCommand(); $this->application->add($command); $tester = new CommandTester($command); $tester->execute( [ 'command' => $command->getName(), 'version' => $versionString, '--add' => true, '--no-interaction' => true, ], [ 'interactive' => false, ] ); $output = $tester->getDisplay(); $this->assertNotEmpty($output); } }
<?php /* * This file is part of the kreait eZ Publish Migrations Bundle. * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. */ namespace Kreait\EzPublish\MigrationsBundle\Tests\Command; use Kreait\EzPublish\MigrationsBundle\Command\VersionCommand; use Kreait\EzPublish\MigrationsBundle\Tests\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** * @group commands */ class VersionCommandTest extends TestCase { public function testExecuteAddVersion() { $versionString = $this->generateMigrationAndReturnVersionString(); $command = new VersionCommand(); $this->application->add($command); $tester = new CommandTester($command); $tester->execute( [ 'command' => $command->getName(), 'version' => $versionString, '--add' => true, '--no-interaction' => true, ] ); $output = $tester->getDisplay(); $this->assertEmpty($output); } }
Revert "Temporarily disallow rule cloning (for benchmarks)" This reverts commit 15c01bdcc559e04fad09f19672e7306b3e316f2a.
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import org.metaborg.meta.lang.dynsem.interpreter.DynSemLanguage; import org.metaborg.meta.lang.dynsem.interpreter.nodes.DynSemRootNode; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.source.SourceSection; public abstract class Rule extends DynSemRootNode { private final DynSemLanguage lang; public Rule(DynSemLanguage lang, SourceSection source, FrameDescriptor fd) { super(lang, source, fd); this.lang = lang; } public Rule(DynSemLanguage lang, SourceSection source) { this(lang, source, null); } protected DynSemLanguage language() { return lang; } @Override public abstract RuleResult execute(VirtualFrame frame); @Override public boolean isCloningAllowed() { return true; } @Override protected boolean isCloneUninitializedSupported() { return true; } @Override protected abstract Rule cloneUninitialized(); public Rule makeUninitializedClone() { return cloneUninitialized(); } }
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import org.metaborg.meta.lang.dynsem.interpreter.DynSemLanguage; import org.metaborg.meta.lang.dynsem.interpreter.nodes.DynSemRootNode; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.source.SourceSection; public abstract class Rule extends DynSemRootNode { private final DynSemLanguage lang; public Rule(DynSemLanguage lang, SourceSection source, FrameDescriptor fd) { super(lang, source, fd); this.lang = lang; } public Rule(DynSemLanguage lang, SourceSection source) { this(lang, source, null); } protected DynSemLanguage language() { return lang; } @Override public abstract RuleResult execute(VirtualFrame frame); @Override public boolean isCloningAllowed() { return false; } @Override protected boolean isCloneUninitializedSupported() { return false; } @Override protected abstract Rule cloneUninitialized(); public Rule makeUninitializedClone() { return cloneUninitialized(); } }
Fix route binding for nested recipes
// This file defines all routes and function handling these routes. // All routes are accessible using GET and POST methods. const routes = { '/item': require('../controllers/items/byId.js'), '/item/:id': require('../controllers/items/byId.js'), '/items': require('../controllers/items/byIds.js'), '/items/all': require('../controllers/items/all.js'), '/items/all-prices': require('../controllers/items/allPrices.js'), '/items/all-values': require('../controllers/items/allValues.js'), '/items/categories': require('../controllers/items/categories.js'), '/items/autocomplete': require('../controllers/items/autocomplete.js'), '/items/by-name': require('../controllers/items/byName.js'), '/items/by-skin': require('../controllers/items/bySkin.js'), '/items/query': require('../controllers/items/query.js'), '/items/:ids': require('../controllers/items/byIds.js'), '/skins/resolve': require('../controllers/skins/resolve.js'), '/skins/prices': require('../controllers/skins/prices.js'), '/recipe/nested/:ids': require('../controllers/recipes/nested.js'), '/gems/history': require('../controllers/gems/history.js') } module.exports = routes
// This file defines all routes and function handling these routes. // All routes are accessible using GET and POST methods. const routes = { '/item': require('../controllers/items/byId.js'), '/item/:id': require('../controllers/items/byId.js'), '/items': require('../controllers/items/byIds.js'), '/items/all': require('../controllers/items/all.js'), '/items/all-prices': require('../controllers/items/allPrices.js'), '/items/all-values': require('../controllers/items/allValues.js'), '/items/categories': require('../controllers/items/categories.js'), '/items/autocomplete': require('../controllers/items/autocomplete.js'), '/items/by-name': require('../controllers/items/byName.js'), '/items/by-skin': require('../controllers/items/bySkin.js'), '/items/query': require('../controllers/items/query.js'), '/items/:ids': require('../controllers/items/byIds.js'), '/skins/resolve': require('../controllers/skins/resolve.js'), '/skins/prices': require('../controllers/skins/prices.js'), '/recipe/nested/:id': require('../controllers/recipes/nested.js'), '/gems/history': require('../controllers/gems/history.js') } module.exports = routes
Fix for missing default in currency filter
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value, currency=None): """ Format decimal value as currency """ if currency is None: currency = settings.OSCAR_DEFAULT_CURRENCY try: value = D(value) except (TypeError, InvalidOperation): return "" # Using Babel's currency formatting # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency OSCAR_CURRENCY_FORMAT = getattr(settings, 'OSCAR_CURRENCY_FORMAT', None) kwargs = { 'currency': currency, 'locale': to_locale(get_language() or settings.LANGUAGE_CODE) } if isinstance(OSCAR_CURRENCY_FORMAT, dict): kwargs.update(OSCAR_CURRENCY_FORMAT.get(currency, {})) else: kwargs['format'] = OSCAR_CURRENCY_FORMAT return format_currency(value, **kwargs)
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value, currency=None): """ Format decimal value as currency """ try: value = D(value) except (TypeError, InvalidOperation): return "" # Using Babel's currency formatting # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency OSCAR_CURRENCY_FORMAT = getattr(settings, 'OSCAR_CURRENCY_FORMAT', None) kwargs = { 'currency': currency or settings.OSCAR_DEFAULT_CURRENCY, 'locale': to_locale(get_language() or settings.LANGUAGE_CODE) } if isinstance(OSCAR_CURRENCY_FORMAT, dict): kwargs.update(OSCAR_CURRENCY_FORMAT.get(currency, {})) else: kwargs['format'] = OSCAR_CURRENCY_FORMAT return format_currency(value, **kwargs)
Update to the new drive state
'use strict'; var should = require('should'); var config = require('../config/configuration.js'); var retrieve = require('../lib/provider-google-drive/helpers/retrieve.js'); describe("Retrieve files", function () { it("should list files when no id passed and return the id of the last document", function(done) { retrieve(config.test_refresh_token, null, config, function(err, files, lastId) { if(err) { throw err; } files.should.have.lengthOf(4); should.exist(files[0]); lastId.should.equal("82"); files[0].should.have.property('id', '1wnEFyXM4bSaSqMORS0NycszCse9dJvhYoiZnITRMeCE'); files[0].should.have.property('title', 'Test'); files[0].should.have.property('mimeType', 'application/vnd.google-apps.document'); done(); }); }); it("should list files from a given id", function(done) { retrieve(config.test_refresh_token, "44", config, function(err, files, lastId) { if(err) { throw err; } files.length.should.equal(4); done(); }); }); });
'use strict'; var should = require('should'); var config = require('../config/configuration.js'); var retrieve = require('../lib/provider-google-drive/helpers/retrieve.js'); describe("Retrieve files", function () { it("should list files when no id passed and return the id of the last document", function(done) { retrieve(config.test_refresh_token, null, config, function(err, files, lastId) { if(err) { throw err; } files.should.have.lengthOf(4); should.exist(files[0]); lastId.should.equal("49"); files[0].should.have.property('id', '1wnEFyXM4bSaSqMORS0NycszCse9dJvhYoiZnITRMeCE'); files[0].should.have.property('title', 'Test'); files[0].should.have.property('mimeType', 'application/vnd.google-apps.document'); done(); }); }); it("should list files from a given id", function(done) { retrieve(config.test_refresh_token, "44", config, function(err, files, lastId) { if(err) { throw err; } files.length.should.equal(3); done(); }); }); });
Update icons div to h4
import React from 'react'; import WeatherIcons from '../weather_icons/WeatherIcons'; const TenDay = ({ tenDayForecast }) => { if(!tenDayForecast) { return( <div></div> ) } const forecastArray = tenDayForecast.simpleforecast.forecastday; const icons = new WeatherIcons(); const tenDayDataLoop = forecastArray.map((day, i) => { return( <div className='ten-day-data' key={i}> <h4 className='ten-day-day ten-day'>{day.date.weekday_short}</h4> <h4 className={`ten-day-icon ${icons[day.icon]}`}></h4> <h4 className='ten-day-lo ten-day'>{day.low.fahrenheit}°</h4> <h4 className='ten-day-hi ten-day'>{day.high.fahrenheit}°</h4> </div> ); }) return( <section> {tenDayDataLoop} </section> ) }; export default TenDay;
import React from 'react'; import WeatherIcons from '../weather_icons/WeatherIcons'; const TenDay = ({ tenDayForecast }) => { if(!tenDayForecast) { return( <div></div> ) } const forecastArray = tenDayForecast.simpleforecast.forecastday; const icons = new WeatherIcons(); const tenDayDataLoop = forecastArray.map((day, i) => { return( <div className='ten-day-data' key={i}> <h4 className='ten-day-day ten-day'>{day.date.weekday_short}</h4> <div className={`ten-day-icon ${icons[day.icon]}`}></div> <h4 className='ten-day-lo ten-day'>{day.low.fahrenheit}°</h4> <h4 className='ten-day-hi ten-day'>{day.high.fahrenheit}°</h4> </div> ); }) return( <section> {tenDayDataLoop} </section> ) }; export default TenDay;
Replace local tile URL with Chattanooga Public Library map tiles on GitHub.
var southWest = L.latLng(34.9816, -85.4719); var northEast = L.latLng(35.217, -85.0462); var center = L.latLng(35.0657, -85.241); var bounds = L.latLngBounds(southWest, northEast); var map = L.map('map', { maxZoom: 18, minZoom: 11, maxBounds: bounds, center: center, zoom: 12 }); L.tileLayer('http://chattanoogapubliclibrary.github.io/cpd-zones-tiles/tiles/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Zone data &copy; City of Chattanooga, Imagery © <a href="http://mapbox.com">Mapbox</a>'}).addTo(map); r
var southWest = L.latLng(34.9816, -85.4719); var northEast = L.latLng(35.217, -85.0462); var center = L.latLng(35.0657, -85.241); var bounds = L.latLngBounds(southWest, northEast); var map = L.map('map', { maxZoom: 18, minZoom: 11, maxBounds: bounds, center: center, zoom: 12 }); L.tileLayer('static/tiles/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Zone data &copy; City of Chattanooga, Imagery © <a href="http://mapbox.com">Mapbox</a>'}).addTo(map); r
Add OK reaction to reload command
import discord from discord.ext import commands class Owner: """Admin-only commands that make the bot dynamic.""" def __init__(self, bot): self.bot = bot @commands.command() @commands.is_owner() async def close(self, ctx: commands.Context): """Closes the bot safely. Can only be used by the owner.""" await self.bot.logout() @commands.command() @commands.is_owner() async def status(self, ctx: commands.Context, *, status: str): """Changes the bot's status. Can only be used by the owner.""" await self.bot.change_presence(activity=discord.Game(name=status)) @commands.command(name="reload") @commands.is_owner() async def _reload(self, ctx, *, ext: str = None): """Reloads a module. Can only be used by the owner.""" if ext: self.bot.unload_extension(ext) self.bot.load_extension(ext) else: for m in self.bot.initial_extensions: self.bot.unload_extension(m) self.bot.load_extension(m) await ctx.message.add_reaction(self.bot.emoji_rustok) def setup(bot): bot.add_cog(Owner(bot))
import discord from discord.ext import commands class Owner: """Admin-only commands that make the bot dynamic.""" def __init__(self, bot): self.bot = bot @commands.command() @commands.is_owner() async def close(self, ctx: commands.Context): """Closes the bot safely. Can only be used by the owner.""" await self.bot.logout() @commands.command() @commands.is_owner() async def status(self, ctx: commands.Context, *, status: str): """Changes the bot's status. Can only be used by the owner.""" await self.bot.change_presence(activity=discord.Game(name=status)) @commands.command(name="reload") @commands.is_owner() async def _reload(self, ctx, *, ext: str = None): """Reloads a module. Can only be used by the owner.""" if ext: self.bot.unload_extension(ext) self.bot.load_extension(ext) else: for m in self.bot.initial_extensions: self.bot.unload_extension(m) self.bot.load_extension(m) def setup(bot): bot.add_cog(Owner(bot))
Remove test of built-in "NotImplementedError" exception.
import unittest from pymodbus3.exceptions import * class SimpleExceptionsTest(unittest.TestCase): """ This is the unittest for the pymodbus3.exceptions module """ def setUp(self): """ Initializes the test environment """ self.exceptions = [ ModbusException("bad base"), ModbusIOException("bad register"), ParameterException("bad parameter"), ConnectionException("bad connection"), ] def tearDown(self): """ Cleans up the test environment """ pass def test_exceptions(self): """ Test all module exceptions """ for ex in self.exceptions: try: raise ex except ModbusException as ex: self.assertTrue("Modbus Error:" in str(ex)) pass else: self.fail("Excepted a ModbusExceptions") #---------------------------------------------------------------------------# # Main #---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main()
import unittest from pymodbus3.exceptions import * class SimpleExceptionsTest(unittest.TestCase): """ This is the unittest for the pymodbus3.exceptions module """ def setUp(self): """ Initializes the test environment """ self.exceptions = [ ModbusException("bad base"), ModbusIOException("bad register"), ParameterException("bad parameter"), NotImplementedError("bad function"), ConnectionException("bad connection"), ] def tearDown(self): """ Cleans up the test environment """ pass def test_exceptions(self): """ Test all module exceptions """ for ex in self.exceptions: try: raise ex except ModbusException as ex: self.assertTrue("Modbus Error:" in str(ex)) pass else: self.fail("Excepted a ModbusExceptions") #---------------------------------------------------------------------------# # Main #---------------------------------------------------------------------------# if __name__ == "__main__": unittest.main()
Add method for instrument bank
#import pygame.midi.Output from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb) def set_instrument_bank(self, bank, channel): assert (0 <= channel <= 15) assert bank <= 127 self.write_short(0xB0 + channel, 0x00, bank)
#import pygame.midi.Output from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb)
Use watchify instead of grunt-contrib-watch for faster watched builds.
module.exports = function (grunt) { 'use strict'; grunt.loadNpmTasks('grunt-browserify'); // Project configuration. grunt.initConfig({ browserify: { options: { browserifyOptions: { debug: true // Ask for source maps }, // Don't ignore transpilation in node_modules ignore: false, transform: ['babelify'] }, package: { files: { 'dist/basic-web-components.js': 'components/**/*.js' } }, watch: { files: { 'dist/basic-web-components.js': 'components/**/*.js' }, options: { keepAlive: true, watch: true } } } }); grunt.registerTask('default', ['build']); grunt.registerTask('build', ['browserify:package']); grunt.registerTask('watch', ['browserify:watch']); };
module.exports = function (grunt) { 'use strict'; grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-watch'); // Project configuration. grunt.initConfig({ browserify: { options: { browserifyOptions: { debug: true // Ask for source maps }, // Don't ignore transpilation in node_modules ignore: false, transform: ['babelify'] }, dist: { files: { 'dist/basic-web-components.js': 'components/**/*.js' } } }, watch: { scripts: { files: [ 'components/**/*.js', 'mixins/*.js' ], tasks: ['build'] } } }); grunt.registerTask('default', ['build']); grunt.registerTask('build', ['browserify']); };
Return an array instead of a json file
'use strict'; const fs = require('fs'); const dss = require('dss'); const glob = require('glob'); class Doki { constructor(files) { this.files = files; this.parsedArray = []; } parse(destFile, options) { let files; options || {}; if (Array.isArray(this.files)) { files = this.files; } else { files = glob.sync(this.files); } // Check if has any file if (files.length === 0) { console.error(`Has no file in ${this.files}!`); process.exit(); } files.forEach((file) => { let fileContent = fs.readFileSync(file); dss.parse(fileContent, options, (parsedObject) => { this.parsedArray.push(parsedObject.blocks[0]); }); }); return this.parsedArray; } parser(name, cb) { dss.parser(name, ( i, line, block ) => cb(i, line, block)); } } module.exports = Doki;
'use strict'; const fs = require('fs'); const dss = require('dss'); const glob = require('glob'); class Doki { constructor(files) { this.files = files; this.parsedArray = []; } parse(destFile, options) { let files; options || {}; if (Array.isArray(this.files)) { files = this.files; } else { files = glob.sync(this.files); } // Check if has any file if (files.length === 0) { console.error(`Has no file in ${this.files}!`); process.exit(); } files.forEach((file) => { let fileContent = fs.readFileSync(file); dss.parse(fileContent, options, (parsedObject) => { this.parsedArray.push(parsedObject.blocks[0]); fs.writeFileSync(destFile, JSON.stringify(this.parsedArray)); }); }); } parser(name, cb) { dss.parser(name, ( i, line, block ) => cb(i, line, block)); } } module.exports = Doki;