text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Allow `willLintPaths` and `didLintPaths` to be overridden Summary: I'm not sure if the upstream will be interested in this change, but we are writing a linter which works by running an external command on the entire repository. This can't be done with `ArcanistExternalLinter` at the moment, which meant that we ended up copy-pasting most of `ArcanistFutureLinter`. This would be a lot easier if we could override `willLintPaths` and `didLintPaths`, but these methods are currently marked as `final`. An alternative solution would be some sort of `ArcanistLinter::transformPath` method. Test Plan: N/A Reviewers: epriestley, #blessed_reviewers Reviewed By: epriestley, #blessed_reviewers Subscribers: faulconbridge, Korvin Differential Revision: https://secure.phabricator.com/D19630
<?php abstract class ArcanistFutureLinter extends ArcanistLinter { private $futures; abstract protected function buildFutures(array $paths); abstract protected function resolveFuture($path, Future $future); final protected function getFuturesLimit() { return 8; } public function willLintPaths(array $paths) { $limit = $this->getFuturesLimit(); $this->futures = id(new FutureIterator(array()))->limit($limit); foreach ($this->buildFutures($paths) as $path => $future) { $this->futures->addFuture($future, $path); } } final public function lintPath($path) { return; } public function didLintPaths(array $paths) { if (!$this->futures) { return; } $map = array(); foreach ($this->futures as $path => $future) { $this->setActivePath($path); $this->resolveFuture($path, $future); $map[$path] = $future; } $this->futures = array(); $this->didResolveLinterFutures($map); } /** * Hook for cleaning up resources. * * This is invoked after a block of futures resolve, and allows linters to * discard or clean up any shared resources they no longer need. * * @param map<string, Future> Map of paths to resolved futures. * @return void */ protected function didResolveLinterFutures(array $futures) { return; } }
<?php abstract class ArcanistFutureLinter extends ArcanistLinter { private $futures; abstract protected function buildFutures(array $paths); abstract protected function resolveFuture($path, Future $future); final protected function getFuturesLimit() { return 8; } final public function willLintPaths(array $paths) { $limit = $this->getFuturesLimit(); $this->futures = id(new FutureIterator(array()))->limit($limit); foreach ($this->buildFutures($paths) as $path => $future) { $this->futures->addFuture($future, $path); } } final public function lintPath($path) { return; } final public function didLintPaths(array $paths) { if (!$this->futures) { return; } $map = array(); foreach ($this->futures as $path => $future) { $this->setActivePath($path); $this->resolveFuture($path, $future); $map[$path] = $future; } $this->futures = array(); $this->didResolveLinterFutures($map); } /** * Hook for cleaning up resources. * * This is invoked after a block of futures resolve, and allows linters to * discard or clean up any shared resources they no longer need. * * @param map<string, Future> Map of paths to resolved futures. * @return void */ protected function didResolveLinterFutures(array $futures) { return; } }
Add build to gulp serve task dependencies.
var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var config = require('../config'); gulp.task('watch', ['scripts:watch', 'sass:watch', 'templates:watch', 'views:watch']); gulp.task('build', ['browserify:build', 'scripts:build', 'sass:build', 'templates:build', 'views:build']); gulp.task('lint', ['scripts:lint']); gulp.task('clean', ['browserify:clean', 'scripts:clean', 'sass:clean', 'templates:clean']); gulp.task('serve', config.production ? ['build'] : ['build', 'watch'], function () { $.connect.server({ root: config.serve.root, livereload: !config.production, port: config.serve.port }); }); gulp.task('default', ['serve']);
var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var config = require('../config'); gulp.task('watch', ['browserify:build', 'scripts:watch', 'sass:watch', 'templates:watch', 'views:watch']); gulp.task('build', ['browserify:build', 'scripts:build', 'sass:build', 'templates:build', 'views:build']); gulp.task('lint', ['scripts:lint']); gulp.task('clean', ['browserify:clean', 'scripts:clean', 'sass:clean', 'templates:clean']); gulp.task('serve', config.production ? null : ['watch'], function () { $.connect.server({ root: config.serve.root, livereload: !config.production, port: config.serve.port }); }); gulp.task('default', ['serve']);
Fix packmeteor meteor package for meteor 0.9.2
var crypto = Npm.require('crypto'); var fs = Npm.require('fs'); var path = Npm.require('path'); var beforeFiles = []; var afterFiles = []; Packmeteor = { config: function(options) { }, addFile: function(url, before) { if (before) { beforeFiles.push(url); } else { afterFiles.push(url); } } }; WebApp.connectHandlers.use(function(req, res, next) { if (req.url !== '/packmeteor.manifest') { return next(); } var manifest = '#PACKMETEOR\n'; manifest += '/' + '\n'; _.each(WebApp.clientPrograms['web.browser'].manifest, function (resource) { if (resource.where === 'client') { var url = resource.url.split('?')[0]; manifest += url + '\n'; } }); manifest += '#BEFORE\n'; _.each(beforeFiles, function (url) { manifest += url + '\n'; }); manifest += '#AFTER\n'; _.each(afterFiles, function (url) { manifest += url + '\n'; }); // content length needs to be based on bytes var body = new Buffer(manifest); res.setHeader('Content-Type', 'text/plain'); res.setHeader('Content-Length', body.length); return res.end(body); });
var crypto = Npm.require('crypto'); var fs = Npm.require('fs'); var path = Npm.require('path'); var beforeFiles = []; var afterFiles = []; Packmeteor = { config: function(options) { }, addFile: function(url, before) { if (before) { beforeFiles.push(url); } else { afterFiles.push(url); } } }; WebApp.connectHandlers.use(function(req, res, next) { if (req.url !== '/packmeteor.manifest') { return next(); } var manifest = '#PACKMETEOR\n'; manifest += '/' + '\n'; _.each(WebApp.clientProgram.manifest, function (resource) { if (resource.where === 'client') { var url = resource.url.split('?')[0]; manifest += url + '\n'; } }); manifest += '#BEFORE\n'; _.each(beforeFiles, function (url) { manifest += url + '\n'; }); manifest += '#AFTER\n'; _.each(afterFiles, function (url) { manifest += url + '\n'; }); // content length needs to be based on bytes var body = new Buffer(manifest); res.setHeader('Content-Type', 'text/plain'); res.setHeader('Content-Length', body.length); return res.end(body); });
Fix let/var in occurencecounter hash
/** * Convert a string to a number * @param {string} str * @returns {number} the hashed string * @see https://stackoverflow.com/a/51276700 */ function hash(str) { const prime = 403 let hash = 167 for (let i = 0; i < str.length; i++) { hash = hash ^ str.charCodeAt(i) hash *= prime } return hash } export class OccurrenceCounter { constructor() { this._items = Object.create(null) } /** * Converting the CSS string to an integer because this collection potentially * becomes very large and storing the values as integers saves 10-70% * * @see https://github.com/projectwallace/css-analyzer/pull/242 * @param {string} item * @returns {number} the count for this item */ push(item) { const key = hash(item) if (this._items[key]) return this._items[key] = 1 } count() { return Object.keys(this._items).length } }
/** * Convert a string to a number * @param {string} str * @returns {number} the hashed string * @see https://stackoverflow.com/a/51276700 */ function hash(str) { let hash = 0x811c9dc5 var prime = 0x000193 for (let i = 0; i < str.length; i++) { hash = hash ^ str.charCodeAt(i) hash *= prime } return hash } export class OccurrenceCounter { constructor() { this._items = Object.create(null) } /** * Converting the CSS string to an integer because this collection potentially * becomes very large and storing the values as integers saves 10-70% * * @see https://github.com/projectwallace/css-analyzer/pull/242 * @param {string} item * @returns {number} the count for this item */ push(item) { const key = hash(item) if (this._items[key]) { return this._items[key]++ } return this._items[key] = 1 } count() { return Object.keys(this._items).length } }
Make words optional for get_doc
# coding: utf-8 from __future__ import unicode_literals from ..tokens import Doc from ..attrs import ORTH, POS, HEAD, DEP def get_doc(vocab, words=[], tags=None, heads=None, deps=None): """Create Doc object from given vocab, words and annotations.""" tags = tags or [''] * len(words) heads = heads or [0] * len(words) deps = deps or [''] * len(words) doc = Doc(vocab, words=words) attrs = doc.to_array([POS, HEAD, DEP]) for i, (tag, head, dep) in enumerate(zip(tags, heads, deps)): attrs[i, 0] = doc.vocab.strings[tag] attrs[i, 1] = head attrs[i, 2] = doc.vocab.strings[dep] doc.from_array([POS, HEAD, DEP], attrs) return doc
# coding: utf-8 from __future__ import unicode_literals from ..tokens import Doc from ..attrs import ORTH, POS, HEAD, DEP def get_doc(vocab, words, tags=None, heads=None, deps=None): """Create Doc object from given vocab, words and annotations.""" tags = tags or [''] * len(words) heads = heads or [0] * len(words) deps = deps or [''] * len(words) doc = Doc(vocab, words=words) attrs = doc.to_array([POS, HEAD, DEP]) for i, (tag, head, dep) in enumerate(zip(tags, heads, deps)): attrs[i, 0] = doc.vocab.strings[tag] attrs[i, 1] = head attrs[i, 2] = doc.vocab.strings[dep] doc.from_array([POS, HEAD, DEP], attrs) return doc
Hide search saving buttons for now
App.Search.SearchPanelUi = Ext.extend(Ext.form.FormPanel, { title: 'Search criteria', labelWidth: 100, labelAlign: 'left', layout: 'form', tbar: { xtype: 'toolbar', items: [{ text: 'Add language', icon: urlRoot + 'images/add.png', cls: 'x-btn-text-icon', ref: '../addLanguageButton' //}, '-', { //text: 'Save search', //icon: urlRoot + 'images/disk.png' //}, { //text: 'Saved searches', //icon: urlRoot + 'images/folder_explore.png' }, '-', { text: 'Reset form', icon: urlRoot + 'images/cancel.png' }, '-', { text: '<b>Search</b>', icon: urlRoot + 'images/zoom.png' }] }, initComponent: function() { App.Search.SearchPanelUi.superclass.initComponent.call(this); this.setupSubcomponents(); }, /* Setup */ setupSubcomponents: function() { this.addLanguageButton.on('click', this.onAddLanguageClicked, this); }, /* Event handlers */ onAddLanguageClicked: function() { alert('hei'); } });
App.Search.SearchPanelUi = Ext.extend(Ext.form.FormPanel, { title: 'Search criteria', labelWidth: 100, labelAlign: 'left', layout: 'form', tbar: { xtype: 'toolbar', items: [{ text: 'Add language', icon: urlRoot + 'images/add.png', cls: 'x-btn-text-icon', ref: '../addLanguageButton' }, '-', { text: 'Save search', icon: urlRoot + 'images/disk.png' }, { text: 'Saved searches', icon: urlRoot + 'images/folder_explore.png' }, '-', { text: 'Reset form', icon: urlRoot + 'images/cancel.png' }, '-', { text: '<b>Search</b>', icon: urlRoot + 'images/zoom.png' }] }, initComponent: function() { App.Search.SearchPanelUi.superclass.initComponent.call(this); this.setupSubcomponents(); }, /* Setup */ setupSubcomponents: function() { this.addLanguageButton.on('click', this.onAddLanguageClicked, this); }, /* Event handlers */ onAddLanguageClicked: function() { alert('hei'); } });
Bugfix: Make sure ``grunt`` can access ``bower_components``. Since the components are installed inside the assets directory grunt needs to be told where it can import them.
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { options: { includePaths: ['us_ignite/assets/bower_components/foundation/scss'] }, dist: { options: { outputStyle: 'compressed' }, files: { 'us_ignite/assets/css/app.css': 'scss/app.scss' } } }, watch: { grunt: { files: ['Gruntfile.js'] }, sass: { files: 'scss/**/*.scss', tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('build', ['sass']); grunt.registerTask('default', ['build','watch']); }
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { options: { includePaths: ['bower_components/foundation/scss'] }, dist: { options: { outputStyle: 'compressed' }, files: { 'us_ignite/assets/css/app.css': 'scss/app.scss' } } }, watch: { grunt: { files: ['Gruntfile.js'] }, sass: { files: 'scss/**/*.scss', tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('build', ['sass']); grunt.registerTask('default', ['build','watch']); }
Revert "Bump Python binding to 0.4.0" This reverts commit d46e582186ee0fdc30f52319b2bb2cfca1a7d59b.
from setuptools import setup, find_packages with open('README.md') as file: long_description = file.read() setup( name="circllhist", long_description=long_description, long_description_content_type='text/markdown', version="0.3.2", description="OpenHistogram log-linear histogram library", maintainer="Circonus Packaging", maintainer_email="packaging@circonus.com", url="https://github.com/openhistogram/libcircllhist", install_requires=['cffi'], packages=['circllhist'], classifiers=[ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", "Operating System :: POSIX" ], python_requires=">=2.7", )
from setuptools import setup, find_packages with open('README.md') as file: long_description = file.read() setup( name="circllhist", long_description=long_description, long_description_content_type='text/markdown', version="0.4.0", description="OpenHistogram log-linear histogram library", maintainer="Circonus Packaging", maintainer_email="packaging@circonus.com", url="https://github.com/openhistogram/libcircllhist", install_requires=['cffi'], packages=['circllhist'], classifiers=[ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", "Operating System :: POSIX" ], python_requires=">=2.7", )
Change default playlist name scheme
import m from 'mithril'; import R from 'ramda'; import Velocity from 'velocity-animate'; import Promise from 'bluebird'; import io from 'socket.io-client'; import { Head, Spotify } from '../components'; import { setPlaylist } from './RestRequests'; const registerSpotify = () => Spotify.getAuthorization(); const hookUpThemSweetSockets = socket => { socket.on('addSong', data => Spotify.addSong(data.uriList, data.playlist)); socket.on('removeSong', data => Spotify.removeSong(data.uris, data.playlist)); socket.on('makePlaylist', ({ user }) => Spotify.makePlaylist('Mixta-' + user) .then(({ id }) => setPlaylist(user, id))); }; // VIEW MODEL // VIEWS const view = () => <html> <Head /> <body> <div config={registerSpotify}></div> </body> </html>; // CONTROLLER const controller = () => { const socket = io.connect('http://localhost:3001'); socket.on('connect', () => console.log('Hooked on sockets worked for me!')); hookUpThemSweetSockets(socket); }; // EXPORT export default { view, controller, };
import m from 'mithril'; import R from 'ramda'; import Velocity from 'velocity-animate'; import Promise from 'bluebird'; import io from 'socket.io-client'; import { Head, Spotify } from '../components'; import { setPlaylist } from './RestRequests'; const registerSpotify = () => Spotify.getAuthorization(); const hookUpThemSweetSockets = socket => { socket.on('addSong', data => Spotify.addSong(data.uriList, data.playlist)); socket.on('removeSong', data => Spotify.removeSong(data.uris, data.playlist)); socket.on('makePlaylist', ({ user }) => Spotify.makePlaylist('mix-' + user) .then(({ id }) => setPlaylist(user, id))); }; // VIEW MODEL // VIEWS const view = () => <html> <Head /> <body> <div config={registerSpotify}></div> </body> </html>; // CONTROLLER const controller = () => { const socket = io.connect('http://localhost:3001'); socket.on('connect', () => console.log('Hooked on sockets worked for me!')); hookUpThemSweetSockets(socket); }; // EXPORT export default { view, controller, };
Comment out full if clause, not just body
<?php use Cake\Core\Plugin; $findRoot = function ($root) { do { $lastRoot = $root; $root = dirname($root); if (is_dir($root . '/vendor/cakephp/cakephp')) { return $root; } } while ($root !== $lastRoot); throw new \Exception('Cannot find the root of the application, unable to run tests'); }; $root = $findRoot(__FILE__); unset($findRoot); chdir($root); //if (file_exists($root . '/config/bootstrap.php')) { // require $root . '/config/bootstrap.php'; // return; //} require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php'; $loader = require $root . '/vendor/autoload.php'; $loader->setPsr4('Cake\\', './vendor/cakephp/cakephp/src'); $loader->setPsr4('Cake\Test\\', './vendor/cakephp/cakephp/tests'); $loader->setPsr4('Burzum\Imagine\\', './vendor/burzum/cakephp-imagine-plugin/src'); Plugin::load('Burzum/FileStorage', [ 'path' => dirname(__FILE__, 2) . DS, //'autoload' => true, //'bootstrap' => true ]); Plugin::load('Burzum/Imagine', [ 'path' => dirname(__FILE__, 2) . DS, 'autoload' => true, 'bootstrap' => true ]);
<?php use Cake\Core\Plugin; $findRoot = function ($root) { do { $lastRoot = $root; $root = dirname($root); if (is_dir($root . '/vendor/cakephp/cakephp')) { return $root; } } while ($root !== $lastRoot); throw new \Exception('Cannot find the root of the application, unable to run tests'); }; $root = $findRoot(__FILE__); unset($findRoot); chdir($root); if (file_exists($root . '/config/bootstrap.php')) { //require $root . '/config/bootstrap.php'; //return; } require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php'; $loader = require $root . '/vendor/autoload.php'; $loader->setPsr4('Cake\\', './vendor/cakephp/cakephp/src'); $loader->setPsr4('Cake\Test\\', './vendor/cakephp/cakephp/tests'); $loader->setPsr4('Burzum\Imagine\\', './vendor/burzum/cakephp-imagine-plugin/src'); Plugin::load('Burzum/FileStorage', [ 'path' => dirname(__FILE__, 2) . DS, //'autoload' => true, //'bootstrap' => true ]); Plugin::load('Burzum/Imagine', [ 'path' => dirname(__FILE__, 2) . DS, 'autoload' => true, 'bootstrap' => true ]);
Add some sleep in tests to not exceed allowed request limits
import pytest from pynoaa import PyNOAA from time import sleep noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ") @pytest.mark.parametrize('startdate,locationid',( ['1994-05-20',None], [None,['FIPS:36','FIPS:37']], )) def test_datasets(startdate, locationid): datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid) results = datasets["results"] assert datasets["metadata"]["resultset"]["limit"] == 1 assert results[0]["id"] == "GHCND" sleep(0.2) @pytest.mark.parametrize('fun,id',( ['datasets','NEXRAD2',], ['datacategories','ANNPRCP',], ['datatypes','ANN-DUTR-NORMAL',], ['locationcategories','CNTRY',], ['locations','CITY:AG000007',], ['stations','COOP:010148',], )) def test_id(fun, id): results = getattr(noaa, fun)(id=id) assert results["id"] == id sleep(0.2)
import pytest from pynoaa import PyNOAA noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ") @pytest.mark.parametrize('startdate,locationid',( ['1994-05-20',None], [None,['FIPS:36','FIPS:37']], )) def test_datasets(startdate, locationid): datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid) results = datasets["results"] assert datasets["metadata"]["resultset"]["limit"] == 1 assert results[0]["id"] == "GHCND" @pytest.mark.parametrize('fun,id',( ['datasets','NEXRAD2',], ['datacategories','ANNPRCP',], ['datatypes','ANN-DUTR-NORMAL',], ['locationcategories','CNTRY',], ['locations','CITY:AG000007',], ['stations','COOP:010148',], )) def test_id(fun, id): results = getattr(noaa, fun)(id=id) assert results["id"] == id
Reset fellow server js file
'use strict'; var users = require('../../app/controllers/users'); var fellows = require('../../app/controllers/fellows'); module.exports = function(app) { // Setting up the bootcamp api app.route('/camps') .get(fellows.list_camp); // login and authorization required // .post(fellows.create_camp); //by admin app.route('/camps/:campId') .get(fellows.read_camp) // login and authorization required .put(fellows.update_camp) // login and authorization required .delete(fellows.delete_camp); // login and authorization required app.route('/camps/:campId/fellows'); //.get(fellows.list_applicant) // login and authorization required // .post(fellows.create_applicant); //by admin app.route('/camps/:campId/fellows/:fellowId') .get(fellows.read_applicant) // login and authorization required .delete(fellows.delete_applicant); // login and authorization required by admin // Finish by binding the fellow middleware app.param('fellowId', fellows.fellowByID); };
'use strict'; var users = require('../../app/controllers/users'); var fellows = require('../../app/controllers/fellows'); module.exports = function(app) { // Setting up the bootcamp api app.route('/camps') <<<<<<< HEAD .get(fellows.list_camp) // login and authorization required ======= .get(fellows.list_camp); // login and authorization required >>>>>>> d27202af5ed201b57b4a5a78a95f3bdc88556d1a // .post(fellows.create_camp); //by admin app.route('/camps/:campId') .get(fellows.read_camp) // login and authorization required .put(fellows.update_camp) // login and authorization required .delete(fellows.delete_camp); // login and authorization required app.route('/camps/:campId/fellows'); //.get(fellows.list_applicant) // login and authorization required // .post(fellows.create_applicant); //by admin app.route('/camps/:campId/fellows/:fellowId') .get(fellows.read_applicant) // login and authorization required .delete(fellows.delete_applicant); // login and authorization required by admin // Finish by binding the fellow middleware app.param('fellowId', fellows.fellowByID); };
Fix to only match '>' at the beginning of a line Which was the intention with the '\n' in the pattern before, but I had made it optional for the common case of the '>' being at the beginning of the message, which of course had the side effect of allowing the '>' to be matched anywhere (bleh). Now, with a MULTLINE-mode regexp and '^' in the pattern, the '>' will only be treated as significant at the beginning of a line, (preceded by optional whitespace).
from __future__ import unicode_literals import re crontable = [] outputs = [] state = {} class ClueState: def __init__(self): self.count = 0 self.clue = '' def process_message(data): channel = data['channel'] if channel not in state.keys(): state[channel] = ClueState() st = state[channel] # Count the number of messages we have seen in this channel since # stony last repeated a clue. st.count = st.count + 1 if re.search("^\s*&gt;", data['text'], re.MULTILINE): st.clue = data['text'] st.count = 1 else: if st.count % 10 == 0: outputs.append([channel, st.clue])
from __future__ import unicode_literals import re crontable = [] outputs = [] state = {} class ClueState: def __init__(self): self.count = 0 self.clue = '' def process_message(data): channel = data['channel'] if channel not in state.keys(): state[channel] = ClueState() st = state[channel] # Count the number of messages we have seen in this channel since # stony last repeated a clue. st.count = st.count + 1 if re.search("\n?\s*&gt;", data['text']): st.clue = data['text'] st.count = 1 else: if st.count % 10 == 0: outputs.append([channel, st.clue])
Update return type in setup() Signed-off-by: Ghazanfar Mir <a14a6de1517ea7407ff078dd52990c3cb073b27a@gmail.com>
<?php namespace GhazanfarMir\CompaniesHouse\Tests\Features; use PHPUnit\Framework\TestCase; use GhazanfarMir\CompaniesHouse\Http\Client; use GhazanfarMir\CompaniesHouse\CompaniesHouse; abstract class CompaniesHouseBaseTest extends TestCase { /** * @var string */ protected $api_key = 'IvSp6uE13FPbE8iDPx6Yey9aQ64jH3Cvm18eAE_N'; /** * @var string */ protected $base_uri = 'https://api.companieshouse.gov.uk/'; /** * @var */ protected $client; /** * @var */ protected $api; /** * @var */ protected $platform; /** * @test */ public function setUp(): void { parent::setUp(); $this->client = new Client($this->base_uri, $this->api_key); $this->api = new CompaniesHouse($this->client); $this->platform = getenv('PLATFORM'); } }
<?php namespace GhazanfarMir\CompaniesHouse\Tests\Features; use PHPUnit\Framework\TestCase; use GhazanfarMir\CompaniesHouse\Http\Client; use GhazanfarMir\CompaniesHouse\CompaniesHouse; abstract class CompaniesHouseBaseTest extends TestCase { /** * @var string */ protected $api_key = 'IvSp6uE13FPbE8iDPx6Yey9aQ64jH3Cvm18eAE_N'; /** * @var string */ protected $base_uri = 'https://api.companieshouse.gov.uk/'; /** * @var */ protected $client; /** * @var */ protected $api; /** * @var */ protected $platform; /** * @test */ public function setUp() { parent::setUp(); $this->client = new Client($this->base_uri, $this->api_key); $this->api = new CompaniesHouse($this->client); $this->platform = getenv('PLATFORM'); } }
Fix for not filling associated object unless they had ID fields. If I'm not misunderstanding, the intended behavior is to be able to populate completely new records as well. The fill was left inside the identifier column conditions which meant unless you set them you couldn't create a new record.
<?php namespace Tenet\Filter; abstract class AbstractAssociationFilter { /** * @todo refactor this... it can be better for scalar vs array * @todo rename the object var in the checks */ protected function makeObject($accessor, $object, $target, $data) { $manager = $accessor->getObjectManager(); $metadata = $manager->getClassMetadata($target); $identifiers = $metadata->getIdentifierFieldNames($object); // handle object of type target if ($data instanceof $target) { return $data; } // handle scalar identifier if (is_scalar($data) && count($identifiers) === 1) { return $manager->find($target, $data) ?: new $target; } $object = new $target; // handle keyed identifier(s) if (is_array($data)) { // get array of identifier data passed in $ids = array_filter(array_intersect_key($data, array_flip($identifiers)), function($v) { return ($v === '' || $v === null) ? false : true; }); // if all identifiers are present, try to find the object if (count($ids) === count($identifiers)) { $exiting_record = $manager->find($target, $ids); if ($existing_record) { $object = $exiting_record; } } $accessor->fill($object, $data); } return $object; } }
<?php namespace Tenet\Filter; abstract class AbstractAssociationFilter { /** * @todo refactor this... it can be better for scalar vs array * @todo rename the object var in the checks */ protected function makeObject($accessor, $object, $target, $data) { $manager = $accessor->getObjectManager(); $metadata = $manager->getClassMetadata($target); $identifiers = $metadata->getIdentifierFieldNames($object); // handle object of type target if ($data instanceof $target) { return $data; } // handle scalar identifier if (is_scalar($data) && count($identifiers) === 1) { return $manager->find($target, $data) ?: new $target; } // handle keyed identifier(s) if (is_array($data)) { // get array of identifier data passed in $ids = array_filter(array_intersect_key($data, array_flip($identifiers)), function($v) { return ($v === '' || $v === null) ? false : true; }); // if all identifiers are present, try to find the object if (count($ids) === count($identifiers)) { $object = $manager->find($target, $ids) ?: new $target; return $accessor->fill($object, $data); } } return new $target; } }
Remove white background in high level element
import React from 'react'; import PrimaryNav from '../../components/PrimaryNav'; import {ReactRouter, Router, Link, withRouter} from 'react-router'; class Layout extends React.Component { onHelpClick(e) { e.preventDefault(); this.props.router.push('/createWorkshop'); } render () { return ( <div> <PrimaryNav /> <div id="Page"> {this.props.children} </div> </div> ); } } export default withRouter(Layout);
import React from 'react'; import PrimaryNav from '../../components/PrimaryNav'; import {ReactRouter, Router, Link, withRouter} from 'react-router'; class Layout extends React.Component { onHelpClick(e) { e.preventDefault(); this.props.router.push('/createWorkshop'); } render () { const styleItUpStooge = { backgroundColor: '#FAFAFA', }; return ( <div style={styleItUpStooge}> <PrimaryNav /> <div id="Page"> {this.props.children} </div> </div> ); } } export default withRouter(Layout);
Update tests to correspond with flake8
import logging import unittest import six if six.PY3: from unittest import mock else: import mock from engineio import async_eventlet class TestServer(unittest.TestCase): def setUp(self): logging.getLogger('engineio').setLevel(logging.NOTSET) @mock.patch('engineio.async_eventlet._WebSocketWSGI.__call__', return_value='data') def test_wsgi_call(self, _WebSocketWSGI): _WebSocketWSGI.__call__ = lambda e, s: 'data' environ = {"eventlet.input": None} start_response = "bar" wsgi = async_eventlet.WebSocketWSGI(None) self.assertEqual(wsgi(environ, start_response), 'data')
import logging import unittest import six if six.PY3: from unittest import mock else: import mock from engineio import async_eventlet class TestServer(unittest.TestCase): def setUp(self): logging.getLogger('engineio').setLevel(logging.NOTSET) @mock.patch('engineio.async_eventlet._WebSocketWSGI.__call__', return_value='data') def test_wsgi_call(self, _WebSocketWSGI): _WebSocketWSGI.__call__ = lambda e,s: 'data' environ = {"eventlet.input": None} start_response = "bar" wsgi = async_eventlet.WebSocketWSGI(None) self.assertEqual(wsgi(environ, start_response), 'data')
:new: Move DOM Updates to attachedCallback of BottomTab
'use strict'; class BottomTab extends HTMLElement{ constructor(Content){ this.innerHTML = Content } attachedCallback() { this.active = false this.visibility = false this.classList.add('linter-tab') this.countSpan = document.createElement('span') this.countSpan.classList.add('count') this.countSpan.textContent = '0' this.appendChild(document.createTextNode(' ')) this.appendChild(this.countSpan) } get active() { return this._active } set active(value) { this._active = value if (value) { this.classList.add('active') } else { this.classList.remove('active') } } set count(value) { this.countSpan.textContent = value } set visibility(value){ this._visibility = value if(value){ this.removeAttribute('hidden') } else { this.setAttribute('hidden', true) } } get visibility(){ return this._visibility } } module.exports = BottomTab = document.registerElement('linter-bottom-tab', { prototype: BottomTab.prototype })
'use strict'; class BottomTab extends HTMLElement{ initialize(Content, onClick) { this._active = false this._visibility = true this.innerHTML = Content this.classList.add('linter-tab') this.countSpan = document.createElement('span') this.countSpan.classList.add('count') this.countSpan.textContent = '0' this.appendChild(document.createTextNode(' ')) this.appendChild(this.countSpan) this.addEventListener('click', onClick) } get active() { return this._active } set active(value) { this._active = value if (value) { this.classList.add('active') } else { this.classList.remove('active') } } set count(value) { this.countSpan.textContent = value } set visibility(value){ this._visibility = value if(value){ this.removeAttribute('hidden') } else { this.setAttribute('hidden', true) } } get visibility(){ return this._visibility } } module.exports = BottomTab = document.registerElement('linter-bottom-tab', { prototype: BottomTab.prototype })
Remove runtime dep on python-pbr, python-d2to1 Requires RPM spec to fill in REDHATCINDERVERSION.
# Copyright 2011 OpenStack Foundation # # 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. CINDER_VENDOR = "OpenStack Foundation" CINDER_PRODUCT = "OpenStack Cinder" CINDER_PACKAGE = None # OS distro package version suffix loaded = False class VersionInfo: version = "REDHATCINDERVERSION" release = "REDHATCINDERRELEASE" def release_string(self): return '%s-%s' % (self.version, self.release) def version_string(self): return self.version version_info = VersionInfo() version_string = version_info.version_string
# Copyright 2011 OpenStack Foundation # # 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 pbr import version as pbr_version CINDER_VENDOR = "OpenStack Foundation" CINDER_PRODUCT = "OpenStack Cinder" CINDER_PACKAGE = None # OS distro package version suffix loaded = False version_info = pbr_version.VersionInfo('cinder') version_string = version_info.version_string
Move ContentSearcher HTML-parsing to separate function
import cheerio from 'cheerio'; import Core from './core'; import RefResult from './ref-result.js'; class ContentSearcher { search(queryStr) { let searchURL = `${this.constructor.baseSearchURL}`; return Core.getHTML(searchURL, {q: queryStr, version_id: 111}).then((html) => { let results = this.parseResults(html); if (results.length > 0) { return Promise.resolve(results); } else { return Promise.reject(); } }); } // Parse the content search results from the given HTML string parseResults(html) { let $ = cheerio.load(html); let $references = $('li.reference'); let results = []; $references.each((r, reference) => { let $reference = $(reference); results.push(new RefResult({ title: $reference.find('h3').text().trim(), subtitle: $reference.find('p').text().trim(), uid: $reference.find('a').prop('href').match(Core.refUIDPattern)[0] })); }); return results; } } ContentSearcher.baseSearchURL = 'https://www.bible.com/search/bible'; export default ContentSearcher;
import cheerio from 'cheerio'; import Core from './core'; import RefResult from './ref-result.js'; class ContentSearcher { search(queryStr) { let searchURL = `${this.constructor.baseSearchURL}`; return Core.getHTML(searchURL, {q: queryStr, version_id: 111}).then((html) => { let $ = cheerio.load(html); let $references = $('li.reference'); let results = []; $references.each((r, reference) => { let $reference = $(reference); results.push(new RefResult({ title: $reference.find('h3').text().trim(), subtitle: $reference.find('p').text().trim(), uid: $reference.find('a').prop('href').match(Core.refUIDPattern)[0] })); }); if (results.length > 0) { return Promise.resolve(results); } else { return Promise.reject(); } }); } } ContentSearcher.baseSearchURL = 'https://www.bible.com/search/bible'; export default ContentSearcher;
Fix missing part upload just change config because session id always change for every request
<?php return [ /** * The storage config */ "storage" => [ /** * Returns the folder name of the chunks. The location is in storage/app/{folder_name} */ "chunks" => "chunks", "disk" => "local" ], "clear" => [ /** * How old chunks we should delete */ "timestamp" => "-3 HOURS", "schedule" => [ "enabled" => true, "cron" => "0 */1 * * * *" // run every hour ] ], "chunk" => [ // setup for the chunk naming setup to ensure same name upload at same time "name" => [ "use" => [ "session" => false, // should the chunk name use the session id? The uploader muset send cookie!, "browser" => true // instead of session we can use the ip and browser? ] ] ] ];
<?php return [ /** * The storage config */ "storage" => [ /** * Returns the folder name of the chunks. The location is in storage/app/{folder_name} */ "chunks" => "chunks", "disk" => "local" ], "clear" => [ /** * How old chunks we should delete */ "timestamp" => "-3 HOURS", "schedule" => [ "enabled" => true, "cron" => "0 */1 * * * *" // run every hour ] ], "chunk" => [ // setup for the chunk naming setup to ensure same name upload at same time "name" => [ "use" => [ "session" => true, // should the chunk name use the session id? The uploader muset send cookie!, "browser" => false // instead of session we can use the ip and browser? ] ] ] ];
Update test class with getExternalContext. git-svn-id: 1a1fa68050bcaed5349a5b70a2a7ea3fbc73e3e8@949908 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j; import org.apache.logging.log4j.spi.LoggerContext; /** * */ public class SimpleLoggerContext implements LoggerContext { private Logger logger = new SimpleLogger(); public Logger getLogger(String name) { return logger; } public boolean hasLogger(String name) { return false; } public Object getExternalContext() { return null; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j; import org.apache.logging.log4j.spi.LoggerContext; /** * */ public class SimpleLoggerContext implements LoggerContext { private Logger logger = new SimpleLogger(); public Logger getLogger(String name) { return logger; } public boolean hasLogger(String name) { return false; } }
Create Node class; construct insert method
#!/usr/bin/env python class Node(object): def __init__(self, data, nextNode=None): self.data = data self.nextNode = nextNode class LinkedList(object): def __init__(self, firstNode=None): self.firstNode = firstNode def insert(self, newNode): # insert newNode at beginning of list if not self.firstNode: self.firstNode = newNode else: newNode.nextNode = self.firstNode self.firstNode = newNode def pop(self): # pops first value from list and returns it pass def size(self): # returns length of list pass def search(self, val): # return node containing 'val' in list, if present (else None) pass def remove(self, node): # remove node from list, wherever it might be pass def display(self): # print list as python tuple literal # (bonus points if you make it appear like "(12, 'sam', 32, 'fred')") for node in self: print self.firstNode
#!/usr/bin/env python class SinglyLinked(object): def __init__(self): pass def insert(self, val): # insert val at beginning of list pass def pop(self): # pops first value from list and returns it pass def size(self): # returns length of list pass def search(self, val): # return node containing 'val' in list, if present (else None) pass def remove(self, node): # remove node from list, wherever it might be pass def print_(self): # print list as python tuple literal # (bonus points if you make it appear like "(12, 'sam', 32, 'fred')") pass
Add failing test for calling set on arrays There seems to be a bug here. Enable pending test by changing `xit` to `it`.
describe("$.set", function() { it("exists", function() { expect($.set).to.exist; }); it("sets options on the provided subject", function() { var element = $.set(document.createElement("nav"), { style: { color: "red" } }); expect(element).to.exist; expect(element.style.color).to.equal("red"); }); it("can be called on elements", function() { var element = document.createElement("nav"); element._.set({className: "main-navigation"}); expect(element.className).to.equal("main-navigation"); }); xit("can be called on arrays", function() { var list = [ document.createElement("li"), document.createElement("li"), document.createElement("li") ]; list._.set({className: "list-part"}); list.forEach(function(item) { expect(item.className).to.equal("list-part"); }); }); it("sets other options as properties or attributes on the subject", function() { var element = $.set(document.createElement("input"), { id: "the-main-one", type: "text", disabled: true }); expect(element.id).to.equal("the-main-one"); expect(element.disabled).to.be.true; expect(element.type).to.equal("text"); }); });
describe("$.set", function() { it("exists", function() { expect($.set).to.exist; }); it("sets options on the provided subject", function() { var element = $.set(document.createElement("nav"), { style: { color: "red" } }); expect(element).to.exist; expect(element.style.color).to.equal("red"); }); it("can be called on elements", function() { var element = document.createElement("nav"); element._.set({className: "main-navigation"}); expect(element.className).to.equal("main-navigation"); }); it("sets other options as properties or attributes on the subject", function() { var element = $.set(document.createElement("input"), { id: "the-main-one", type: "text", disabled: true }); expect(element.id).to.equal("the-main-one"); expect(element.disabled).to.be.true; expect(element.type).to.equal("text"); }); });
Hide ember.js output from Travis.ci tests.
import os import subprocess import sys import threading import time from .run import Command as RunserverCommand class Command(RunserverCommand): def run_tests(self): env = os.environ.copy() env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001' return subprocess.call( [ 'python', 'manage.py', 'test', 'taskmanager', ], env=env, ) def handle(self, *args, **kwargs): fnull = open(os.devnull, 'w') ember = threading.Thread( target=self.run_ember, kwargs={ 'stdout': fnull, 'stderr': subprocess.STDOUT } ) ember.daemon = True ember.start() time.sleep(10) sys.exit(self.run_tests())
import os import subprocess import sys import threading import time from .run import Command as RunserverCommand class Command(RunserverCommand): def run_tests(self): env = os.environ.copy() env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001' return subprocess.call( [ 'python', 'manage.py', 'test', 'taskmanager', ], env=env, ) def handle(self, *args, **kwargs): fnull = open(os.devnull, 'w') ember = threading.Thread( target=self.run_ember, #kwargs={ # 'stdout': fnull, # 'stderr': subprocess.STDOUT #} ) ember.daemon = True ember.start() time.sleep(10) sys.exit(self.run_tests())
Fix recommended songs in wishes to public only
<?php namespace App\Model\Query; use App\Model\Entity\Song; use Kdyby\Doctrine\QueryBuilder; use Kdyby\Doctrine\QueryObject; use Kdyby\Persistence\Queryable; /** * Performs search for public songs which metadata contains search string. * @author Tomáš Jirásek */ class SongPublicSearchQuery extends QueryObject { /** @var string */ private $search; /** * @param string $search */ public function __construct($search) { $this->search = $search; } /** * @param Queryable $repository * @return QueryBuilder */ protected function doCreateQuery(Queryable $repository) { return $repository->createQueryBuilder() ->select('s') ->from(Song::class, 's') ->orWhere('s.title LIKE :query') ->orWhere('s.author LIKE :query') ->orWhere('s.originalAuthor LIKE :query') ->andWhere('s.public = 1') ->setParameter('query', "%$this->search%") ->orderBy('s.title'); } }
<?php namespace App\Model\Query; use App\Model\Entity\Song; use Kdyby\Doctrine\QueryBuilder; use Kdyby\Doctrine\QueryObject; use Kdyby\Persistence\Queryable; /** * Performs search for public songs which metadata contains search string. * @author Tomáš Jirásek */ class SongPublicSearchQuery extends QueryObject { /** @var string */ private $search; /** * @param string $search */ public function __construct($search) { $this->search = $search; } /** * @param Queryable $repository * @return QueryBuilder */ protected function doCreateQuery(Queryable $repository) { return $repository->createQueryBuilder() ->select('s') ->from(Song::class, 's') ->orWhere('s.title LIKE :query') ->orWhere('s.author LIKE :query') ->orWhere('s.originalAuthor LIKE :query') ->setParameter('query', "%$this->search%") ->orderBy('s.title'); } }
Add Ties to Overall stats
import dedent from 'dedent-js'; const formatOverallStats = (data, battletag, gameMode) => { const stats = data['stats'][gameMode]['overall_stats']; const moreStats = data['stats'][gameMode]['game_stats']; let level = stats['level']; let competitiveStats; if (typeof stats['prestige'] === 'number') { level += (stats['prestige'] * 100); } if (gameMode === 'competitive') { const winRate = ((stats['wins'] / stats['games']) * 100).toFixed(2); competitiveStats = dedent` \n- Losses: ${stats['losses'] || 0} - Ties: ${stats['ties'] || 0} - Win Rate: ${winRate || 0}% - Games: ${stats['games'] || 0}`; } return dedent`*${battletag}*'s Overall Stats: - Level: ${level || 0} - Rating: ${stats['comprank'] || 0} - Wins: ${stats['wins'] || 0}${competitiveStats || ''} - K/D Ratio: ${moreStats['kpd'] || 0} - Cards: ${moreStats['cards'] || 0} - Medals: ${moreStats['medals'] || 0} - Gold: ${moreStats['medals_gold'] || 0} - Silver: ${moreStats['medals_silver'] || 0} - Bronze: ${moreStats['medals_bronze'] || 0}`; }; export default formatOverallStats;
import dedent from 'dedent-js'; const formatOverallStats = (data, battletag, gameMode) => { const stats = data['stats'][gameMode]['overall_stats']; const moreStats = data['stats'][gameMode]['game_stats']; let level = stats['level']; let competitiveStats; if (typeof stats['prestige'] === 'number') { level += (stats['prestige'] * 100); } if (gameMode === 'competitive') { const winRate = ((stats['wins'] / stats['games']) * 100).toFixed(2); competitiveStats = dedent` \n- Losses: ${stats['losses'] || 0} - Win Rate: ${winRate || 0}% - Games: ${stats['games'] || 0}`; } return dedent`*${battletag}*'s Overall Stats: - Level: ${level || 0} - Rating: ${stats['comprank'] || 0} - Wins: ${stats['wins'] || 0}${competitiveStats || ''} - K/D Ratio: ${moreStats['kpd'] || 0} - Cards: ${moreStats['cards'] || 0} - Medals: ${moreStats['medals'] || 0} - Gold: ${moreStats['medals_gold'] || 0} - Silver: ${moreStats['medals_silver'] || 0} - Bronze: ${moreStats['medals_bronze'] || 0}`; }; export default formatOverallStats;
Fix string type comparison for py2
import six from tilezilla import sensors def test_friendly_names_data(): # Test this variable is dict # Should contain [SENSOR (str)]:[MAPPING (dict)] # where: # MAPPING is a dict of [friendly_name (str)]:[band id (int)] assert isinstance(sensors.SENSOR_FRIENDLY_NAMES, dict) sensor_names = ['TM', 'ETM+', 'MSS', 'OLI_TIRS'] # ... for name in sensor_names: assert name in sensors.SENSOR_FRIENDLY_NAMES for name, mapping in six.iteritems(sensors.SENSOR_FRIENDLY_NAMES): for band_name, band_idx in six.iteritems(mapping): assert isinstance(band_name, six.string_types) assert isinstance(band_idx, int)
import pytest import six from tilezilla import sensors def test_friendly_names_data(): # Test this variable is dict # Should contain [SENSOR (str)]:[MAPPING (dict)] # where: # MAPPING is a dict of [friendly_name (str)]:[band id (int)] assert isinstance(sensors.SENSOR_FRIENDLY_NAMES, dict) sensor_names = ['TM', 'ETM+', 'MSS', 'OLI_TIRS'] # ... for name in sensor_names: assert name in sensors.SENSOR_FRIENDLY_NAMES for name, mapping in six.iteritems(sensors.SENSOR_FRIENDLY_NAMES): for band_name, band_idx in six.iteritems(mapping): assert isinstance(band_name, str) assert isinstance(band_idx, int)
Fix solution for challenge 32
// Challenge 32 - Break HMAC-SHA1 with a slightly less artificial timing leak // http://cryptopals.com/sets/4/challenges/32 package cryptopals import ( "crypto/sha1" "net/http" "time" ) type challenge32 struct { } func (challenge32) ForgeHmacSHA1SignaturePrecise(addr, file string) []byte { sig := make([]byte, sha1.Size) x := challenge31{} for i := 0; i < len(sig); i++ { var valBest byte var timeBest time.Duration for j := 0; j < 256; j++ { sig[i] = byte(j) url := x.buildURL(addr, file, sig) fastest := time.Hour for k := 0; k < 10; k++ { start := time.Now() resp, _ := http.Get(url) elapsed := time.Since(start) resp.Body.Close() if elapsed < fastest { fastest = elapsed } } if fastest > timeBest { valBest = byte(j) timeBest = fastest } } sig[i] = valBest } return sig }
// Challenge 32 - Break HMAC-SHA1 with a slightly less artificial timing leak // http://cryptopals.com/sets/4/challenges/32 package cryptopals import ( "crypto/sha1" "net/http" "time" ) type challenge32 struct { } func (challenge32) ForgeHmacSHA1SignaturePrecise(addr, file string) []byte { sig := make([]byte, sha1.Size) x := challenge31{} for i := 0; i < len(sig); i++ { var valBest byte var timeBest time.Duration for j := 0; j < 256; j++ { sig[i] = byte(j) url := x.buildURL(addr, file, sig) start := time.Now() for k := 0; k < 15; k++ { resp, _ := http.Get(url) resp.Body.Close() } elapsed := time.Since(start) if elapsed > timeBest { valBest = byte(j) timeBest = elapsed } } sig[i] = valBest } return sig }
Remove discriminator's from player names The widget API seems to always set discriminator to 0000
const Core = require('./core'); class Discord extends Core { constructor() { super(); this.dnsResolver = { resolve: function(address) {return {address: address} } }; } async run(state) { this.usedTcp = true; const raw = await this.request({ uri: 'https://discordapp.com/api/guilds/' + this.options.address + '/widget.json', }); const json = JSON.parse(raw); state.name = json.name; if (json.instant_invite) { state.connect = json.instant_invite; } else { state.connect = 'https://discordapp.com/channels/' + this.options.address } state.players = json.members.map(v => { return { name: v.username, team: v.status } }); state.maxplayers = json.presence_count; state.raw = json; } } module.exports = Discord;
const Core = require('./core'); class Discord extends Core { constructor() { super(); this.dnsResolver = { resolve: function(address) {return {address: address} } }; } async run(state) { this.usedTcp = true; const raw = await this.request({ uri: 'https://discordapp.com/api/guilds/' + this.options.address + '/widget.json', }); const json = JSON.parse(raw); state.name = json.name; if (json.instant_invite) { state.connect = json.instant_invite; } else { state.connect = 'https://discordapp.com/channels/' + this.options.address } state.players = json.members.map(v => { return { name: v.username + '#' + v.discriminator, username: v.username, discriminator: v.discriminator, team: v.status } }); state.maxplayers = json.presence_count; state.raw = json; } } module.exports = Discord;
Disable password change on the client
(function() { 'use strict'; angular .module('sentryApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider.state('password', { parent: 'account', url: '/password', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'Password' }, views: { 'content@': { templateUrl: 'app/account/password/password.html', controller: 'PasswordController', controllerAs: 'vm' } } }); } })();
(function() { 'use strict'; angular .module('sentryApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider.state('password', { parent: 'account', url: '/password', data: { authorities: ['ROLE_USER'], pageTitle: 'Password' }, views: { 'content@': { templateUrl: 'app/account/password/password.html', controller: 'PasswordController', controllerAs: 'vm' } } }); } })();
Add font family in finals HTML documents
<?php require_once 'MdCompile.php'; define ('ACTION', $_POST['_action']); switch (ACTION) { case 'get': echo json_encode( array ( 'markdown' => file_get_contents('../courses/Markdown/'.$_POST['name'].'.md'), 'html' => file_get_contents('../courses/HTML/'.$_POST['name'].'.html') ) ); break; case 'create': $compiled = parseMD($_POST['content']); file_put_contents('../courses/Markdown/'.$_POST['name'].'.md', $_POST['content']); file_put_contents('../courses/HTML/'.$_POST['name'].'.html', '<!doctype html><html><head><title>'.$_POST['name'].' - CollegeEditor</title><meta charset="utf-8" /></head><body style="font-family:helvetica,verdana;">'.$compiled.'</body></html>'); echo json_encode( array ( 'compiled' => $compiled ) ); break; case 'delete': unlink('../courses/Markdown/'.$_POST['name'].'.md'); break; default: header('HTTP/1.1 403 Forbidden'); exit(); break; } ?>
<?php require_once 'MdCompile.php'; define ('ACTION', $_POST['_action']); switch (ACTION) { case 'get': echo json_encode( array ( 'markdown' => file_get_contents('../courses/Markdown/'.$_POST['name'].'.md'), 'html' => file_get_contents('../courses/HTML/'.$_POST['name'].'.html') ) ); break; case 'create': $compiled = parseMD($_POST['content']); file_put_contents('../courses/Markdown/'.$_POST['name'].'.md', $_POST['content']); file_put_contents('../courses/HTML/'.$_POST['name'].'.html', '<!doctype html><html><head><title>'.$_POST['name'].' - CollegeEditor</title><meta charset="utf-8" /></head><body>'.$compiled.'</body></html>'); echo json_encode( array ( 'compiled' => $compiled ) ); break; case 'delete': unlink('../courses/Markdown/'.$_POST['name'].'.md'); break; default: header('HTTP/1.1 403 Forbidden'); exit(); break; } ?>
Add TODO and clean up render function [#OSF-5081]
import re from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer class JSONAPIRenderer(JSONRenderer): format = "jsonapi" media_type = 'application/vnd.api+json' def render(self, data, accepted_media_type=None, renderer_context=None): # TODO: There should be a way to do this that is conditional on esi being requested and # TODO: In such a way that it doesn't use regex unless there's absolutely no other way. initial_rendering = super(JSONAPIRenderer, self).render(data, accepted_media_type, renderer_context) augmented_rendering = re.sub(r'"<esi:include src=\\"(.*?)\\"\/>"', r'<esi:include src="\1"/>', initial_rendering) return augmented_rendering class BrowsableAPIRendererNoForms(BrowsableAPIRenderer): """ Renders browsable API but omits HTML forms """ def get_context(self, *args, **kwargs): context = super(BrowsableAPIRendererNoForms, self).get_context(*args, **kwargs) unwanted_forms = ('put_form', 'post_form', 'delete_form', 'raw_data_put_form', 'raw_data_post_form', 'raw_data_patch_form', 'raw_data_put_or_patch_form') for form in unwanted_forms: del context[form] return context
import re from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer class JSONAPIRenderer(JSONRenderer): format = "jsonapi" media_type = 'application/vnd.api+json' def render(self, data, accepted_media_type=None, renderer_context=None): stuff = super(JSONAPIRenderer, self).render(data, accepted_media_type, renderer_context) new_stuff = re.sub(r'"<esi:include src=\\"(.*?)\\"\/>"', r'<esi:include src="\1"/>', stuff) return new_stuff class BrowsableAPIRendererNoForms(BrowsableAPIRenderer): """ Renders browsable API but omits HTML forms """ def get_context(self, *args, **kwargs): context = super(BrowsableAPIRendererNoForms, self).get_context(*args, **kwargs) unwanted_forms = ('put_form', 'post_form', 'delete_form', 'raw_data_put_form', 'raw_data_post_form', 'raw_data_patch_form', 'raw_data_put_or_patch_form') for form in unwanted_forms: del context[form] return context
Simplify dateFns locale data handling + add map Previously cached it internally, but the import() gets cached anyway.
import Vue from 'vue' import distanceInWords from 'date-fns/distance_in_words' // https://date-fns.org/v1.29.0/docs/I18n const localeMap = { zh: 'zh_tw', } export default new Vue({ data: { locale: 'en', localeData: null, now: new Date(), }, created () { setInterval(() => { this.now = new Date() }, 10 * 1000) }, watch: { async locale (locale) { this.localeData = await import(`date-fns/locale/${localeMap[locale] || locale}`) }, }, methods: { distanceInWordsToNow (date, options = {}) { if (options.disallowFuture && date > this.now) date = this.now return distanceInWords(this.now, date, { locale: this.localeData, ...options }) }, }, })
import Vue from 'vue' import distanceInWords from 'date-fns/distance_in_words' export default new Vue({ data: { locale: 'en', loadedLocale: 'en', locales: {}, now: new Date(), }, created () { setInterval(() => { this.now = new Date() }, 10 * 1000) }, watch: { async locale (locale) { if (locale === 'zh') locale = 'zh_tw' // https://date-fns.org/v1.29.0/docs/I18n Vue.set(this.locales, this.locale, await import(`date-fns/locale/${locale}`)) this.loadedLocale = this.locale }, }, methods: { distanceInWordsToNow (date, options = {}) { if (options.disallowFuture && date > this.now) date = this.now return distanceInWords(this.now, date, { locale: this.locales[this.loadedLocale], ...options }) }, }, })
Make completion work more logically.
#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var tab = require('tabalot'); var noop = function() {} var homedir = path.resolve(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.grunt-init'); if (process.argv.indexOf('completion') !== -1 && process.argv.indexOf('--') === -1) { process.argv.push('--bin'); process.argv.push('grunt-init'); process.argv.push('--completion'); process.argv.push('grunt-init-completion'); } tab() ('--help', '-h') ('--no-color') ('--debug', '-d') ('--stack') ('--force', '-f') ('--no-write') ('--verbose', '-v') ('--version', '-V') (function(callback) { fs.readdir(path.join(homedir), function(err, files) { if (err) callback(err); files = files.filter(function(file) { return fs.statSync(path.join(homedir, file)).isDirectory(); }); if (files.length) return callback(null, files, { exitCode:15, }); callback(); }); }) (noop) tab.parse();
#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var tab = require('tabalot'); var noop = function() {} var homedir = path.resolve(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.grunt-init'); if (process.argv.indexOf('completion') !== -1 && process.argv.indexOf('--') === -1) { process.argv.push('--bin'); process.argv.push('grunt-init'); process.argv.push('--completion'); process.argv.push('grunt-init-completion'); } tab() ('--help', '-h') ('--no-color') ('--debug', '-d') ('--stack') ('--force', '-f') ('--no-write') ('--verbose', '-v') ('--version', '-V') fs.readdir(path.join(homedir), function(err, files) { if (err) process.exit(2); files = files.filter(function(file) { return fs.statSync(path.join(homedir, file)).isDirectory(); }); files.forEach(function(file) { tab(file)(noop); }); tab.parse(); });
Revert Authorizer back to taking a context
package auth import ( "time" "golang.org/x/net/context" ) // AuthenticationProvider provides helper methods to convert tokens to sessions // using our own internal authorization services type AuthenticationProvider interface { // MarshalSession into wire format for transmission between services MarshalSession(s Session) ([]byte, error) // UnmarshalSession from wire format used during transmission between services UnmarshalSession(b []byte) (Session, error) // RecoverSession from a given access token, converting this into a session RecoverSession(ctx context.Context, accessToken string) (Session, error) } // Session represents an OAuth access token along with expiry information, // user and client information type Session interface { AccessToken() string RefreshToken() string Expiry() time.Time // @todo add Signature() string User() User Client() Client } // Authorizer provides an interface to validate authorization credentials // for access to resources, eg. oauth scopes, or other access control type Authorizer func(ctx context.Context) error // User represents the resource owner ie. an end-user of the application type User interface { ID() string Scopes() []string } // Client represents the application making a request on behalf of a User type Client interface { ID() string Scopes() []string }
package auth import ( "time" "github.com/b2aio/typhon/server" "golang.org/x/net/context" ) // AuthenticationProvider provides helper methods to convert tokens to sessions // using our own internal authorization services type AuthenticationProvider interface { // MarshalSession into wire format for transmission between services MarshalSession(s Session) ([]byte, error) // UnmarshalSession from wire format used during transmission between services UnmarshalSession(b []byte) (Session, error) // RecoverSession from a given access token, converting this into a session RecoverSession(ctx context.Context, accessToken string) (Session, error) } // Session represents an OAuth access token along with expiry information, // user and client information type Session interface { AccessToken() string RefreshToken() string Expiry() time.Time // @todo add Signature() string User() User Client() Client } // Authorizer provides an interface to validate authorization credentials // for access to resources, eg. oauth scopes, or other access control type Authorizer func(ctx server.Request) error // User represents the resource owner ie. an end-user of the application type User interface { ID() string Scopes() []string } // Client represents the application making a request on behalf of a User type Client interface { ID() string Scopes() []string }
Replace anonymous type with lambda pr-link: Alluxio/alluxio#8648 change-id: cid-50ff894a3d0e24b07fe4fb2585530b5032008f0b
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.multi.process; import alluxio.util.CommonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.concurrent.ThreadSafe; /** * Utility methods for external test cluster classes. */ @ThreadSafe public final class Utils { private static final Logger LOG = LoggerFactory.getLogger(Utils.class); /** * Launches a thread to terminate the current process after the specified period has elapsed. * * @param lifetimeMs the time to wait before terminating the current process */ public static void limitLife(final long lifetimeMs) { new Thread(() -> { CommonUtils.sleepMs(lifetimeMs); LOG.info("Process has timed out after {}ms, exiting now", lifetimeMs); System.exit(-1); }, "life-limiter").start(); } private Utils() {} // Not intended for instantiation. }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.multi.process; import alluxio.util.CommonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.concurrent.ThreadSafe; /** * Utility methods for external test cluster classes. */ @ThreadSafe public final class Utils { private static final Logger LOG = LoggerFactory.getLogger(Utils.class); /** * Launches a thread to terminate the current process after the specified period has elapsed. * * @param lifetimeMs the time to wait before terminating the current process */ public static void limitLife(final long lifetimeMs) { new Thread(new Runnable() { @Override public void run() { CommonUtils.sleepMs(lifetimeMs); LOG.info("Process has timed out after {}ms, exiting now", lifetimeMs); System.exit(-1); } }, "life-limiter").start(); } private Utils() {} // Not intended for instantiation. }
Fix for webpack output location on CI server
const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); module.exports = { // webpack folder's entry js - excluded from jekll's build process. entry: './webpack/entry.js', output: { // we're going to put the generated file in the assets folder so jekyll will grab it. path: path.resolve(__dirname, './assets/js/'), filename: 'bundle.js', }, stats: { assets: true, children: false, chunks: false, errors: true, errorDetails: true, modules: false, timings: true, colors: true, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { js: 'babel?presets[]=es2015', }, }, }, { test: /\.js?$/, exclude: /(node_modules)/, loader: 'babel-loader', }, ], }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', }, extensions: ['*', '.js', '.vue', '.json'], }, plugins: [ new VueLoaderPlugin(), ], };
const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); module.exports = { // webpack folder's entry js - excluded from jekll's build process. entry: './webpack/entry.js', output: { // we're going to put the generated file in the assets folder so jekyll will grab it. path: path.resolve(__dirname, 'assets/js/'), filename: 'bundle.js', }, stats: { assets: true, children: false, chunks: false, errors: true, errorDetails: true, modules: false, timings: true, colors: true, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { js: 'babel?presets[]=es2015', }, }, }, { test: /\.js?$/, exclude: /(node_modules)/, loader: 'babel-loader', }, ], }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', }, extensions: ['*', '.js', '.vue', '.json'], }, plugins: [ new VueLoaderPlugin(), ], };
Move var declarations to the top.
'use strict'; var assert = require('assert'), Batch = require('batch'), getStylesData = require('style-data'), getStylesheetList = require('list-stylesheets'), getHrefContent = require('href-content'); module.exports = function (html, options, callback) { var batch = new Batch(), data = getStylesheetList(html, options); batch.push(function (cb) { getStylesData(data.html, options, cb); }); if (data.hrefs.length) { assert.ok(options.url, 'options.url is required'); } data.hrefs.forEach(function (stylesheetHref) { batch.push(function (cb) { getHrefContent(stylesheetHref, options.url, cb); }); }); batch.end(function (err, results) { var stylesData, css; if (err) { return callback(err); } stylesData = results.shift(); results.forEach(function (content) { stylesData.css.push(content); }); css = stylesData.css.join('\n'); callback(null, stylesData.html, css); }); };
'use strict'; var assert = require('assert'), Batch = require('batch'), getStylesData = require('style-data'), getStylesheetList = require('list-stylesheets'), getHrefContent = require('href-content'); module.exports = function (html, options, callback) { var batch = new Batch(), data = getStylesheetList(html, options); batch.push(function (cb) { getStylesData(data.html, options, cb); }); if (data.hrefs.length) { assert.ok(options.url, 'options.url is required'); } data.hrefs.forEach(function (stylesheetHref) { batch.push(function (cb) { getHrefContent(stylesheetHref, options.url, cb); }); }); batch.end(function (err, results) { if (err) { return callback(err); } var stylesData = results.shift(), css; results.forEach(function (content) { stylesData.css.push(content); }); css = stylesData.css.join('\n'); callback(null, stylesData.html, css); }); };
Fix problem with sites that blocks bots
""" Validator functions """ from urllib import request from urllib.error import HTTPError from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" try: online_resource = request.urlopen(url) except HTTPError as exception: if exception.code == 410: raise ValidationError("Online document was removed.") # This is the code returned by Google Drive elif exception.code == 403: req = request.Request(url, headers={'User-Agent' : "lowFAT"}) online_resource = request.urlopen(req) else: raise ValidationError("Error! HTTP status code is {}.".format(exception.code)) # Need to test if website didn't redirect the request to another resource. if url != online_resource.geturl() or online_resource.getcode() != 200: raise ValidationError("Can't access online document.") def pdf(value): """Check if filename looks like a PDF file.""" filename = value.name.lower() if not filename.endswith(".pdf"): raise ValidationError("File name doesn't look to be a PDF file.") try: pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable except: raise ValidationError("File doesn't look to be a PDF file.")
""" Validator functions """ from urllib import request from urllib.error import HTTPError from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" try: online_resource = request.urlopen(url) except HTTPError as exception: if exception.code == 410: raise ValidationError("Online document was removed.") # This is the code returned by Google Drive # Need to test if website didn't redirect the request to another resource. if url != online_resource.geturl() or online_resource.getcode() != 200: raise ValidationError("Can't access online document.") def pdf(value): """Check if filename looks like a PDF file.""" filename = value.name.lower() if not filename.endswith(".pdf"): raise ValidationError("File name doesn't look to be a PDF file.") try: pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable except: raise ValidationError("File doesn't look to be a PDF file.")
Make sure deprecated ConfigureClientView event still works
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Http\Controller; use Flarum\Event\ConfigureClientView; use Flarum\Event\ConfigureWebApp; use Flarum\Http\WebApp\AbstractWebApp; use Illuminate\Contracts\Events\Dispatcher; use Psr\Http\Message\ServerRequestInterface as Request; abstract class AbstractWebAppController extends AbstractHtmlController { /** * @var AbstractWebApp */ protected $webApp; /** * @var Dispatcher */ protected $events; /** * {@inheritdoc} */ public function render(Request $request) { $view = $this->getView($request); $this->events->fire( new ConfigureClientView($this, $view, $request) ); $this->events->fire( new ConfigureWebApp($this, $view, $request) ); return $view->render($request); } /** * @param Request $request * @return \Flarum\Http\WebApp\WebAppView */ protected function getView(Request $request) { return $this->webApp->getView(); } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Http\Controller; use Flarum\Event\ConfigureWebApp; use Flarum\Http\WebApp\AbstractWebApp; use Illuminate\Contracts\Events\Dispatcher; use Psr\Http\Message\ServerRequestInterface as Request; abstract class AbstractWebAppController extends AbstractHtmlController { /** * @var AbstractWebApp */ protected $webApp; /** * @var Dispatcher */ protected $events; /** * {@inheritdoc} */ public function render(Request $request) { $view = $this->getView($request); $this->events->fire( new ConfigureWebApp($this, $view, $request) ); return $view->render($request); } /** * @param Request $request * @return \Flarum\Http\WebApp\WebAppView */ protected function getView(Request $request) { return $this->webApp->getView(); } }
Refactor to flatten if statements
package com.nickww.finitefield; import static com.nickww.finitefield.FiniteByteField.*; import java.util.List; final class XorChecksumVector extends ChecksumVector { @Override public byte[] withChecksums(byte[] data) { if(data.length < 1) throw new IllegalArgumentException("Data array must have at least one element"); byte[] checksummed = new byte[data.length + 1]; System.arraycopy(data, 0, checksummed, 0, data.length); checksummed[checksummed.length - 1] = add(data); return checksummed; } @Override public byte[] solveMissingValues(Byte[] dataWithChecksums) { if(dataWithChecksums.length < 2) throw new IllegalArgumentException("Array too small to include both data and checksums."); byte[] data = super.copy(dataWithChecksums, dataWithChecksums.length - 1); List<Integer> nullIndices = super.missingIndices(dataWithChecksums); if(nullIndices.size() > 1) throw new IllegalArgumentException("Too many missing values - can only handle 1"); if(!nullIndices.isEmpty() && nullIndices.get(0) != data.length) data[nullIndices.get(0)] = add(dataWithChecksums[dataWithChecksums.length - 1], add(data)); return data; } }
package com.nickww.finitefield; import static com.nickww.finitefield.FiniteByteField.*; import java.util.List; final class XorChecksumVector extends ChecksumVector { @Override public byte[] withChecksums(byte[] data) { if(data.length < 1) throw new IllegalArgumentException("Data array must have at least one element"); byte[] checksummed = new byte[data.length + 1]; System.arraycopy(data, 0, checksummed, 0, data.length); checksummed[checksummed.length - 1] = add(data); return checksummed; } @Override public byte[] solveMissingValues(Byte[] dataWithChecksums) { if(dataWithChecksums.length < 2) throw new IllegalArgumentException("Array too small to include both data and checksums."); byte[] data = super.copy(dataWithChecksums, dataWithChecksums.length - 1); List<Integer> nullIndices = super.missingIndices(dataWithChecksums); if(!nullIndices.isEmpty() && nullIndices.get(0) != data.length) { if(nullIndices.size() > 1) throw new IllegalArgumentException("Too many missing values - can only handle 1"); else data[nullIndices.get(0)] = add(dataWithChecksums[dataWithChecksums.length - 1], add(data)); } return data; } }
Fix bug `No module named yaml`
#!/usr/bin/env python # coding: utf-8 import os import re from setuptools import setup, find_packages def load_required_modules(): with open(os.path.join(os.path.dirname(__file__), "requirements.txt")) as f: return [line.strip() for line in f.read().strip().split(os.linesep) if line.strip()] setup( name='dictmixin', __version__=re.search( r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]', # It excludes inline comment too open('dictmixin/__init__.py').read()).group(1), description='Parsing mixin which converts `data class instance`, `dict object`, and `json string` each other.', license='MIT', author='tadashi-aikawa', author_email='syou.maman@gmail.com', maintainer='tadashi-aikawa', maintainer_email='tadashi-aikawa', url='https://github.com/tadashi-aikawa/dictmixin.git', keywords='dict json convert parse each other', packages=find_packages(exclude=['tests*']), install_requires=load_required_modules(), classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
#!/usr/bin/env python # coding: utf-8 import re from setuptools import setup, find_packages setup( name='dictmixin', __version__=re.search( r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]', # It excludes inline comment too open('dictmixin/__init__.py').read()).group(1), description='Parsing mixin which converts `data class instance`, `dict object`, and `json string` each other.', license='MIT', author='tadashi-aikawa', author_email='syou.maman@gmail.com', maintainer='tadashi-aikawa', maintainer_email='tadashi-aikawa', url='https://github.com/tadashi-aikawa/dictmixin.git', keywords='dict json convert parse each other', packages=find_packages(exclude=['tests*']), install_requires=[], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Fix total lines at end
/** * Generate a blob link. * @param {string} file - File name * @param {string} contents - Contents of the file * @param {string} title - The title of the new issue * @param {string} sha - Commit where this todo was introduced * @param {object} config - Config object * @returns {string} - GitHub blob link */ module.exports = function generateBlobLink (context, file, contents, title, sha, config) { const regexFlags = config.caseSensitive ? 'g' : 'gi' const re = new RegExp(`${config.keyword}\\s${title}`, regexFlags) const {repo, owner} = context.repo() const lines = contents.split(/\r\n|\r|\n/) const totalLines = lines.length const start = lines.findIndex(line => line.search(re) > -1) + 1 let end = start + config.blobLines // If the proposed end of range is past the last line of the file // make the end the last line of the file. if (totalLines < end) { end = totalLines - 1 } let range = `L${start}-L${end}` // Cut off blob line if the issue-to-be is on the last line if (totalLines === start || config.blobLines === 1) { range = `L${start}` } return `https://github.com/${owner}/${repo}/blob/${sha}/${file}#${range}` }
/** * Generate a blob link. * @param {string} file - File name * @param {string} contents - Contents of the file * @param {string} title - The title of the new issue * @param {string} sha - Commit where this todo was introduced * @param {object} config - Config object * @returns {string} - GitHub blob link */ module.exports = function generateBlobLink (context, file, contents, title, sha, config) { const regexFlags = config.caseSensitive ? 'g' : 'gi' const re = new RegExp(`${config.keyword}\\s${title}`, regexFlags) const {repo, owner} = context.repo() const lines = contents.split(/\r\n|\r|\n/) const totalLines = lines.length const start = lines.findIndex(line => line.search(re) > -1) + 1 let end = start + config.blobLines // If the proposed end of range is past the last line of the file // make the end the last line of the file. if (totalLines < end) { end = totalLines } let range = `L${start}-L${end}` // Cut off blob line if the issue-to-be is on the last line if (totalLines === start || config.blobLines === 1) { range = `L${start}` } return `https://github.com/${owner}/${repo}/blob/${sha}/${file}#${range}` }
Move "you can close this window" to newline Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl> * * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ style('core', 'login/authpicker'); /** @var array $_ */ ?> <div class="picker-window"> <h2><?php p($l->t('Account connected')) ?></h2> <p class="info"> <?php p($l->t('Your client should now be connected!')) ?><br/> <?php p($l->t('You can close this window.')) ?> </p> <br/> </div>
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl> * * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ style('core', 'login/authpicker'); /** @var array $_ */ ?> <div class="picker-window"> <h2><?php p($l->t('Account connected')) ?></h2> <p class="info"> <?php print_unescaped($l->t('Your client should now be connected! You can close this window.')) ?> </p> <br/> </div>
Fix extension path of apollo-client-devtools in packaged app
import path from 'path'; import { BrowserWindow } from 'electron'; export default async () => { if (process.env.NODE_ENV === 'development') { const installer = require('electron-devtools-installer'); // eslint-disable-line const extensions = ['REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS']; const forceDownload = !!process.env.UPGRADE_EXTENSIONS; for (const name of extensions) { try { await installer.default(installer[name], forceDownload); } catch (e) {} // eslint-disable-line } BrowserWindow.addDevToolsExtension(path.resolve('dist/devtools-helper/')); BrowserWindow.addDevToolsExtension( path.join(__dirname, '../node_modules/apollo-client-devtools/shells/webextension/') ); } else { BrowserWindow.addDevToolsExtension(path.join(__dirname, 'devtools-helper/')); BrowserWindow.addDevToolsExtension( path.join(__dirname, 'node_modules/apollo-client-devtools/shells/webextension/') ); } };
import path from 'path'; import { BrowserWindow } from 'electron'; export default async () => { if (process.env.NODE_ENV === 'development') { const installer = require('electron-devtools-installer'); // eslint-disable-line const extensions = ['REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS']; const forceDownload = !!process.env.UPGRADE_EXTENSIONS; for (const name of extensions) { try { await installer.default(installer[name], forceDownload); } catch (e) {} // eslint-disable-line } BrowserWindow.addDevToolsExtension(path.resolve('dist/devtools-helper/')); } else { BrowserWindow.addDevToolsExtension(path.join(__dirname, 'devtools-helper/')); } BrowserWindow.addDevToolsExtension( path.resolve('node_modules/apollo-client-devtools/shells/webextension/') ); };
Enhance client testing… a little
describe('Client-side', function() { var React = require('react/addons'); var TestUtils = React.addons.TestUtils; var Router = require('react-router'); var clientRoute = require('../example-app/WikiApp').clientRoute; var serverRoute = require('../example-app/WikiApp').serverRoute; before(function() { global.document = require('jsdom').jsdom(); global.window = global.document.defaultView; }); after(function() { delete global.document; delete global.window; }); it('Renders the basic route', function () { return serverRoute('/').then(function() { return clientRoute('/').then(function (element) { TestUtils.isElement(element).should.eql(true); var node = TestUtils.renderIntoDocument(element); var matches = TestUtils.scryRenderedDOMComponentsWithClass(node, 'wiki-list'); matches[0].getDOMNode().should.be.a('object'); }); }); }); });
describe('Client-side', function() { var React = require('react/addons'); var TestUtils = React.addons.TestUtils; var Router = require('react-router'); var clientRoute = require('../example-app/WikiApp').clientRoute; before(function() { global.document = require('jsdom').jsdom(); global.window = global.document.defaultView; }); after(function() { delete global.document; delete global.window; }); it('Renders the basic route', function () { return clientRoute('/').then(function (element) { TestUtils.isElement(element).should.eql(true); var node = TestUtils.renderIntoDocument(element); var matches = TestUtils.scryRenderedDOMComponentsWithClass(node, 'wiki-list'); matches[0].getDOMNode().should.be.a('object'); }); }); });
Remove silly stylism for "( document )"
/** * Interactive features for the external menus functionality * * This piece of JS is loaded on both the list view app for the * epfl-external-menu custom post type, and in the Appearance -> Menus * screen (although at the moment it does nothing on the latter). */ /** * Activate the app on the epfl-external-menu list view screen */ function initExternalMenuList ($) { $('a.page-title-action').remove(); $('h1.wp-heading-inline').after('<button class="page-title-action">' + wp.translations.refresh_button + '</button>'); var $button = $('h1.wp-heading-inline').next(); var spinning = false; $button.click(function() { if (spinning) return; var $form = window.EPFLMenus.asWPAdminPostForm('refresh'); $form.submit(); var $spinner = $('<span class="ajax-spinner"></span>'); $button.append($spinner); spinning = true; }); } jQuery(document).ready(function($) { if (window.wp.screen.base === 'edit' && window.wp.screen.post_type === 'epfl-external-menu' ) { initExternalMenuList($); } // If you see this, nothing threw or crashed (yet). console.log('epfl-menus-admin.js is on duty.'); });
/** * Interactive features for the external menus functionality * * This piece of JS is loaded on both the list view app for the * epfl-external-menu custom post type, and in the Appearance -> Menus * screen (although at the moment it does nothing on the latter). */ /** * Activate the app on the epfl-external-menu list view screen */ function initExternalMenuList ($) { $('a.page-title-action').remove(); $('h1.wp-heading-inline').after('<button class="page-title-action">' + wp.translations.refresh_button + '</button>'); var $button = $('h1.wp-heading-inline').next(); var spinning = false; $button.click(function() { if (spinning) return; var $form = window.EPFLMenus.asWPAdminPostForm('refresh'); $form.submit(); var $spinner = $('<span class="ajax-spinner"></span>'); $button.append($spinner); spinning = true; }); } jQuery( document ).ready(function($) { if (window.wp.screen.base === 'edit' && window.wp.screen.post_type === 'epfl-external-menu' ) { initExternalMenuList($); } // If you see this, nothing threw or crashed (yet). console.log('epfl-menus-admin.js is on duty.'); });
Add reset() and fetcherOptions to second wrapper
import containerFactory from 'second-container' import Fetcher from 'second-fetcher' import Renderer from 'second-renderer' import createDehydrator from 'second-dehydrator' class Second { constructor () { this.initialised = false } init ({ VDom, VDomServer, fetcherOptions = {} }) { this.initialised = true this.fetcher = new Fetcher(fetcherOptions) this.containerFactory = containerFactory({ Component: VDom.Component, createElement: VDom.createElement, fetcher: this.fetcher }) this.dehydrate = createDehydrator(VDom.createElement) this.renderer = new Renderer({ VDom, VDomServer, componentIsReady: () => !this.fetcher.hasOutstandingRequests() }) } reset () { this.fetcher.reset() } createContainer (Component, params) { if (!this.initialised) { throw new Error('You must call second.init() before you can call second.createContainer().') } return this.containerFactory(Component, params) } render (Component, params) { if (!this.initialised) { throw new Error('You must call second.init() before you can call second.render().') } return this.renderer.render(Component, params) } renderStatic (Component, params) { if (!this.initialised) { throw new Error('You must call second.init() before you can call second.renderStatic().') } return this.renderer.renderStatic(Component, params) } } export default new Second()
import containerFactory from 'second-container' import Fetcher from 'second-fetcher' import Renderer from 'second-renderer' import createDehydrator from 'second-dehydrator' class Second { constructor () { this.initialised = false } init ({ VDom, VDomServer }) { this.initialised = true const fetcher = new Fetcher() this.containerFactory = containerFactory({ Component: VDom.Component, createElement: VDom.createElement, fetcher }) this.dehydrate = createDehydrator(VDom.createElement) this.renderer = new Renderer({ VDom, VDomServer, componentIsReady: () => !fetcher.hasOutstandingRequests() }) } createContainer (Component, params) { if (!this.initialised) { throw new Error('You must call second.init() before you can call second.createContainer().') } return this.containerFactory(Component, params) } render (Component, params) { if (!this.initialised) { throw new Error('You must call second.init() before you can call second.render().') } return this.renderer.render(Component, params) } renderStatic (Component, params) { if (!this.initialised) { throw new Error('You must call second.init() before you can call second.renderStatic().') } return this.renderer.renderStatic(Component, params) } } export default new Second()
Comment and toast delete tested
(function () { 'use strict'; angular .module('drinks', ['ngAnimate', 'toastr']) .controller('DrinksListController', DrinksListController); DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr']; function DrinksListController(DrinksService, $state, $scope, toastr) { var vm = this; vm.AddToMenu = AddToMenu; vm.mvOnMenu = mvOnMenu; vm.mvOffMenu = mvOffMenu; vm.drinks = DrinksService.query(); function AddToMenu(drink) { drink.$update(successCallback, errorCallback); function successCallback(res) { $state.go('drinks.list', { drinkId: res._id }); } function errorCallback(res) { vm.error = res.data.message; } } //Menu drink toggle notification via toastr function mvOnMenu(drink) { toastr.success( drink.drinkName + ' was added to tap!', { closeHtml: '<button></button>' } ); } function mvOffMenu(drink) { toastr.success( drink.drinkName + ' was removed from tap!' ); } } })();
(function () { 'use strict'; angular .module('drinks', ['ngAnimate', 'toastr']) .controller('DrinksListController', DrinksListController); DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr']; function DrinksListController(DrinksService, $state, $scope, toastr) { var vm = this; vm.AddToMenu = AddToMenu; vm.mvOnMenu = mvOnMenu; vm.mvOffMenu = mvOffMenu; vm.drinks = DrinksService.query(); function AddToMenu(drink) { drink.$update(successCallback, errorCallback); function successCallback(res) { $state.go('drinks.list', { drinkId: res._id }); } function errorCallback(res) { vm.error = res.data.message; } } function mvOnMenu(drink) { toastr.success(drink.drinkName + ' was added to tap!'); } function mvOffMenu(drink) { toastr.success(drink.drinkName + ' was removed from tap!'); } } })();
Extend get_channel_id_* to return the full path to the exported DBs.
import fnmatch import logging as logger import os import uuid logging = logger.getLogger(__name__) def _is_valid_hex_uuid(uuid_to_test): try: uuid_obj = uuid.UUID(uuid_to_test) except ValueError: return False return uuid_to_test == uuid_obj.hex def get_channel_id_list_from_scanning_content_database_dir(content_database_dir, return_full_dir=False): """ Returns a list of channel IDs for the channel databases that exist in a content database directory. """ db_list = fnmatch.filter(os.listdir(content_database_dir), '*.sqlite3') db_names = [db.split('.sqlite3', 1)[0] for db in db_list] valid_db_names = [name for name in db_names if _is_valid_hex_uuid(name)] invalid_db_names = set(db_names) - set(valid_db_names) if invalid_db_names: logging.warning("Ignoring databases in content database directory '{directory}' with invalid names: {names}" .format(directory=content_database_dir, names=invalid_db_names)) if not return_full_dir: return valid_db_names else: full_dir_template = os.path.join(content_database_dir, "{}.sqlite3") return [full_dir_template.format(f) for f in valid_db_names]
import fnmatch import logging as logger import os import uuid logging = logger.getLogger(__name__) def _is_valid_hex_uuid(uuid_to_test): try: uuid_obj = uuid.UUID(uuid_to_test) except ValueError: return False return uuid_to_test == uuid_obj.hex def get_channel_id_list_from_scanning_content_database_dir(content_database_dir): """ Returns a list of channel IDs for the channel databases that exist in a content database directory. """ db_list = fnmatch.filter(os.listdir(content_database_dir), '*.sqlite3') db_names = [db.split('.sqlite3', 1)[0] for db in db_list] valid_db_names = [name for name in db_names if _is_valid_hex_uuid(name)] invalid_db_names = set(db_names) - set(valid_db_names) if invalid_db_names: logging.warning("Ignoring databases in content database directory '{directory}' with invalid names: {names}" .format(directory=content_database_dir, names=invalid_db_names)) return valid_db_names
Add unhandled promise rejection handler
const Source = require("./Ship/PollSource.js"); const Connection = require("./Ship/Connection.js"); const MessageRouter = require("./Ship/MessageRouter.js"); const CommandSource = require("./Ship/CommandSource.js"); const helpCommand = require("./Ship/Commands/Help.js"); const bindOurCommands = require("./Commands.js"); const config = require("./config.json"); const connection = new Connection(config.auth.id,config.auth.key); const source = new Source(connection); const messageSource = new MessageRouter(source); let commandSource; console.log("Pinging telegram to check connection and get out username..."); connection.getMe().then(me=>{ console.log(`> Response. We are "${me.username}".`); console.log("> Binding commands to command source."); commandSource = new CommandSource(messageSource,me.username); helpCommand.bind("help",commandSource); bindOurCommands(commandSource); console.log("> Starting message source."); source.start(); }); process.on('unhandledRejection', err => { console.log(`${new Date()} WARN: Unandled error in promise:`,err); });
const Source = require("./Ship/PollSource.js"); const Connection = require("./Ship/Connection.js"); const MessageRouter = require("./Ship/MessageRouter.js"); const CommandSource = require("./Ship/CommandSource.js"); const helpCommand = require("./Ship/Commands/Help.js"); const bindOurCommands = require("./Commands.js"); const config = require("./config.json"); const connection = new Connection(config.auth.id,config.auth.key); const source = new Source(connection); const messageSource = new MessageRouter(source); let commandSource; console.log("Pinging telegram to check connection and get out username..."); connection.getMe().then(me=>{ console.log(`> Response. We are "${me.username}".`); console.log("> Binding commands to command source."); commandSource = new CommandSource(messageSource,me.username); helpCommand.bind("help",commandSource); bindOurCommands(commandSource); console.log("> Starting message source."); source.start(); });
Make a test more secure Choose a random filename to avoid overwriting a file.
from regr_test import run import os from subprocess import check_output from tempfile import NamedTemporaryFile def test_source(): var_name, var_value = 'TESTVAR', 'This is a test' with NamedTemporaryFile('w', delete=False) as f: f.write('export %s="%s"' % (var_name, var_value)) script_name = f.name env = run.source(script_name) cmd = ['/bin/bash', '-c', 'echo $%s' % var_name] stdout = check_output(cmd, env=env, universal_newlines=True) os.remove(script_name) assert stdout.strip() == var_value def test_duration(): time = 2 p = run.execute('sleep %s' % time) (duration, data) = run.monitor(p) assert abs(duration-time) < 1.0 def test_timeout(): p = run.execute('sleep 5') (duration, data) = run.monitor(p, timeout=2) assert duration is None
from regr_test import run from subprocess import check_output import os def test_source(): script = 'test_env.sh' var_name, var_value = 'TESTVAR', 'This is a test' with open(script, 'w') as f: f.write('export %s="%s"' % (var_name, var_value)) env = run.source(script) cmd = ['/bin/bash', '-c', 'echo $%s' % var_name] stdout = check_output(cmd, env=env, universal_newlines=True) os.remove(script) assert stdout.strip() == var_value def test_duration(): time = 2 p = run.execute('sleep %s' % time) (duration, data) = run.monitor(p) assert abs(duration-time) < 1.0 def test_timeout(): p = run.execute('sleep 5') (duration, data) = run.monitor(p, timeout=2) assert duration is None
Use correct class for logger
package nl.homesensors.sensortag; import net.sf.expectit.Expect; import net.sf.expectit.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; import static net.sf.expectit.matcher.Matchers.regexp; abstract class AbstractSensor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSensor.class); abstract void enableNotifications(Expect expect) throws IOException; abstract void enable(Expect expect) throws IOException; abstract void disable(Expect expect) throws IOException; String expectSuccessfulMatch(final Expect expect, final String regexp) throws IOException, SensortagException { final String value; final Result result = expect.withTimeout(25, TimeUnit.SECONDS).expect(regexp(regexp)); if (result.isSuccessful()) { value = result.group(1); } else { throw new SensortagException("No match found for regexp [" + regexp + "] in [" + result.getInput() + "]"); } return value; } void discardNotifications(final Expect expect, final String regexp) throws IOException { while(expect.withTimeout(20, TimeUnit.SECONDS).expect(regexp(regexp)).isSuccessful()) { LOG.debug("Discarding notification handle"); } } }
package nl.homesensors.sensortag; import net.sf.expectit.Expect; import net.sf.expectit.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; import static net.sf.expectit.matcher.Matchers.regexp; abstract class AbstractSensor { private static final Logger LOG = LoggerFactory.getLogger(SensorTagReader.class); abstract void enableNotifications(Expect expect) throws IOException; abstract void enable(Expect expect) throws IOException; abstract void disable(Expect expect) throws IOException; String expectSuccessfulMatch(final Expect expect, final String regexp) throws IOException, SensortagException { final String value; final Result result = expect.withTimeout(25, TimeUnit.SECONDS).expect(regexp(regexp)); if (result.isSuccessful()) { value = result.group(1); } else { throw new SensortagException("No match found for regexp [" + regexp + "] in [" + result.getInput() + "]"); } return value; } void discardNotifications(final Expect expect, final String regexp) throws IOException { while(expect.withTimeout(20, TimeUnit.SECONDS).expect(regexp(regexp)).isSuccessful()) { LOG.debug("Discarding notification handle"); } } }
Contacts: Make tmp file cleaup a bit safer.
<?php /** * ownCloud - Addressbook * * @author Thomas Tanghus * @copyright 2012 Thomas Tanghus <thomas@tanghus.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ // Check if we are a user OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('contacts'); $tmp_path = isset($_POST['tmp_path']) ? $_POST['tmp_path'] : ''; // give some time to save the photo sleep(5); if($tmp_path != '' && file_exists($tmp_path) && !is_dir($tmp_path) && dirname($tmp_path)==get_temp_dir()) { unlink($tmp_path); OCP\JSON::success(); exit(); } else { error_log('Couldn\'t find: '.$tmp_path); OCP\JSON::error(); }
<?php /** * ownCloud - Addressbook * * @author Thomas Tanghus * @copyright 2012 Thomas Tanghus <thomas@tanghus.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * TODO: Translatable strings. * Remember to delete tmp file at some point. */ // Check if we are a user OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('contacts'); $tmp_path = isset($_POST['tmp_path']) ? $_POST['tmp_path'] : ''; // give some time to save the photo sleep(5); if($tmp_path != '' && file_exists($tmp_path)) { unlink($tmp_path); OCP\JSON::success(); exit(); } else { error_log('Couldn\'t find: '.$tmp_path); OCP\JSON::error(); } ?>
Change example from Null Island to Ha Noi
var explode = require('turf-explode'); var point = require('turf-point'); /** * Calculates the centroid of a polygon Feature or * FeatureCollection using the geometric mean of all vertices. * This lessens the effect of small islands and artifacts when calculating * the centroid of a set of polygons. * * @module turf/centroid * @param {FeatureCollection} fc a {@link Feature} or FeatureCollection of any type * @return {Point} a Point showing the centroid of the input feature(s) * @example * var poly = turf.polygon([[ * [105.818939,21.004714], * [105.818939,21.061754], * [105.890007,21.061754], * [105.890007,21.004714], * [105.818939,21.004714] * ]]); * * var centroidPt = turf.centroid(poly); * * var result = turf.featurecollection([poly, centroidPt]); * * //=result */ module.exports = function(features){ var vertices = explode(features).features, xSum = 0, ySum = 0, len = vertices.length; for (var i = 0; i < len; i++) { xSum += vertices[i].geometry.coordinates[0]; ySum += vertices[i].geometry.coordinates[1]; } return point(xSum / len, ySum / len); };
var explode = require('turf-explode'); var point = require('turf-point'); /** * Calculates the centroid of a polygon Feature or * FeatureCollection using the geometric mean of all vertices. * This lessens the effect of small islands and artifacts when calculating * the centroid of a set of polygons. * * @module turf/centroid * @param {FeatureCollection} fc a {@link Feature} or FeatureCollection of any type * @return {Point} a Point showing the centroid of the input feature(s) * @example * var poly = turf.polygon([[[0,0], [0,10], [10,10] , [10,0], [0, 0]]]); * var centroidPt = turf.centroid(poly); * * var result = turf.featurecollection([poly, centroidPt]); * * //=result */ module.exports = function(features){ var vertices = explode(features).features, xSum = 0, ySum = 0, len = vertices.length; for (var i = 0; i < len; i++) { xSum += vertices[i].geometry.coordinates[0]; ySum += vertices[i].geometry.coordinates[1]; } return point(xSum / len, ySum / len); };
Add break line on clean txt files
""" Script to clean the txt generated files and kept only the 37 class: LICENSE-PLATE and set the number 0 to the class. """ import os dataset_dir = "data/dataset/" for filename in list(filter(lambda x: x[-3:] == "txt", os.listdir(dataset_dir))): with open(dataset_dir + filename, 'r') as f: content = f.read() with open(dataset_dir + filename, 'w') as f: license_plate_lines = filter(lambda x: x.split(' ')[0] == "37", content.split('\n')) for line in license_plate_lines: line = line.split(' ') line[0] = "0" line = ' '.join(line) f.write(line + '\n')
""" Script to clean the txt generated files and kept only the 37 class: LICENSE-PLATE and set the number 0 to the class. """ import os dataset_dir = "data/dataset/" for filename in list(filter(lambda x: x[-3:] == "txt", os.listdir(dataset_dir))): with open(dataset_dir + filename, 'r') as f: content = f.read() with open(dataset_dir + filename, 'w') as f: license_plate_lines = filter(lambda x: x.split(' ')[0] == "37", content.split('\n')) for line in license_plate_lines: line = line.split(' ') line[0] = "0" line = ' '.join(line) f.write(line)
Correct unicde function so UserProfile is correctly displayed in the admin form
import os import simplejson as json from django.db import models from django.contrib.auth.models import User from django_extensions.db.fields.json import JSONField from django.conf import settings from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) keyboard = JSONField(blank=True, null=True) def __unicode__(self): return u"Profile of user %s" % (self.user.username) def create_user_profile(sender, instance, created, **kwargs): if created: profile = UserProfile.objects.create(user=instance) try: # TODO Get this from database? profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR, 'accounts/keyboard.json'), 'r')) profile.save() except IOError: # If a default keyboard configuration is not provided do nothing # TODO Should this throw a configuration exception pass post_save.connect(create_user_profile, sender=User)
import os import simplejson as json from django.db import models from django.contrib.auth.models import User from django_extensions.db.fields.json import JSONField from django.conf import settings from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) keyboard = JSONField(blank=True, null=True) def __unicode__(self): return u"Profile of user: {}".format(self.user.username) def create_user_profile(sender, instance, created, **kwargs): if created: profile = UserProfile.objects.create(user=instance) try: # TODO Get this from database? profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR, 'accounts/keyboard.json'), 'r')) profile.save() except IOError: # If a default keyboard configuration is not provided do nothing # TODO Should this throw a configuration exception pass post_save.connect(create_user_profile, sender=User)
Convert entities to readable text in convos
// @flow import React from 'react' import {StyleSheet} from 'react-native' import {ListRow, Detail, Title} from '../components/list' import type {PodcastEpisode} from './types' import {fastGetTrimmedText} from '../../lib/html' import {AllHtmlEntities} from 'html-entities' const styles = StyleSheet.create({ row: { paddingTop: 5, paddingBottom: 5, }, }) type Props = { event: PodcastEpisode, onPress: PodcastEpisode => any, } const entities = new AllHtmlEntities() export class ArchivedConvocationRow extends React.PureComponent<Props> { _onPress = () => this.props.onPress(this.props.event) render() { const {event} = this.props let annotation = '' if (event.enclosure && event.enclosure.type.startsWith('audio/')) { annotation = '🎧' } else if (event.enclosure && event.enclosure.type.startsWith('video/')) { annotation = '📺' } return ( <ListRow arrowPosition="center" contentContainerStyle={styles.row} onPress={this._onPress} > <Title> {annotation} {event.title} </Title> <Detail lines={4}> {entities.decode(fastGetTrimmedText(event.description))} </Detail> </ListRow> ) } }
// @flow import React from 'react' import {StyleSheet} from 'react-native' import {ListRow, Detail, Title} from '../components/list' import type {PodcastEpisode} from './types' const styles = StyleSheet.create({ row: { paddingTop: 5, paddingBottom: 5, }, }) type Props = { event: PodcastEpisode, onPress: PodcastEpisode => any, } export class ArchivedConvocationRow extends React.PureComponent<Props> { _onPress = () => this.props.onPress(this.props.event) render() { const {event} = this.props let annotation = '' if (event.enclosure && event.enclosure.type.startsWith('audio/')) { annotation = '🎧' } else if (event.enclosure && event.enclosure.type.startsWith('video/')) { annotation = '📺' } return ( <ListRow arrowPosition="center" contentContainerStyle={styles.row} onPress={this._onPress} > <Title> {annotation} {event.title} </Title> <Detail lines={4}>{event.description}</Detail> </ListRow> ) } }
Remove default for 'cmd' flag See GitHub issue #20
package main import ( "fmt" "os" "path/filepath" rat "github.com/ericfreese/rat/lib" flag "github.com/spf13/pflag" ) var ( RatVersion = "0.0.2" ) var flags struct { cmd string mode string version bool } func init() { flag.StringVarP(&flags.cmd, "cmd", "c", "", "command to run (required)") flag.StringVarP(&flags.mode, "mode", "m", "default", "name of mode") flag.BoolVarP(&flags.version, "version", "v", false, "display version and exit") flag.Parse() } func validateFlags() bool { if len(flags.cmd) == 0 { fmt.Fprintln(os.Stderr, "flag 'cmd' is required") return false } return true } func main() { var err error if flags.version { fmt.Println(RatVersion) return } if !validateFlags() { flag.Usage() os.Exit(1) } if err = rat.Init(); err != nil { panic(err) } defer rat.Close() if config, err := os.Open(filepath.Join(rat.ConfigDir, "ratrc")); err == nil { rat.LoadConfig(config) config.Close() } rat.PushPager(rat.NewCmdPager(flags.mode, flags.cmd, rat.Context{})) rat.Run() }
package main import ( "fmt" "os" "path/filepath" rat "github.com/ericfreese/rat/lib" flag "github.com/spf13/pflag" ) var ( RatVersion = "0.0.2" ) var flags struct { cmd string mode string version bool } func init() { flag.StringVarP(&flags.cmd, "cmd", "c", "cat ~/.config/rat/ratrc", "command to run") flag.StringVarP(&flags.mode, "mode", "m", "default", "name of mode") flag.BoolVarP(&flags.version, "version", "v", false, "display version and exit") flag.Parse() } func main() { var err error if flags.version { fmt.Println(RatVersion) return } if err = rat.Init(); err != nil { panic(err) } defer rat.Close() if config, err := os.Open(filepath.Join(rat.ConfigDir, "ratrc")); err == nil { rat.LoadConfig(config) config.Close() } rat.PushPager(rat.NewCmdPager(flags.mode, flags.cmd, rat.Context{})) rat.Run() }
Include package data in builds
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name='django-afip', version='0.8.0', description='AFIP integration for django', author='Hugo Osvaldo Barrera', author_email='hbarrera@z47.io', url='https://gitlab.com/hobarrera/django-afip', license='ISC', packages=find_packages(), include_package_data=True, # long_description=open('README.rst').read(), install_requires=open('requirements.txt').read().splitlines()[:-1] + ['suds-py3==1.0.0.0'], dependency_links=( 'git+https://github.com/hobarrera/suds-py3.git#egg=suds-py3-1.0.0.0', ), use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], )
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name='django-afip', version='0.8.0', description='AFIP integration for django', author='Hugo Osvaldo Barrera', author_email='hbarrera@z47.io', url='https://gitlab.com/hobarrera/django-afip', license='ISC', packages=find_packages(), # long_description=open('README.rst').read(), install_requires=open('requirements.txt').read().splitlines()[:-1] + ['suds-py3==1.0.0.0'], dependency_links=( 'git+https://github.com/hobarrera/suds-py3.git#egg=suds-py3-1.0.0.0', ), use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], )
Update fetch config with new Syzygy location. Change-Id: Iacc2efd6974f1a161da6e33a0d25d6329fcaaf4f Reviewed-on: https://chromium-review.googlesource.com/692697 Commit-Queue: Sébastien Marchand <b98658856fe44d267ccfa37efbb15fc831b08ae9@chromium.org> Reviewed-by: Aaron Gable <bbed39beedae4cdb499af742d2fcd6c63934d93b@chromium.org> Reviewed-by: Sébastien Marchand <b98658856fe44d267ccfa37efbb15fc831b08ae9@chromium.org>
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import config_util # pylint: disable=import-error # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=no-init class Syzygy(config_util.Config): """Basic Config class for Syzygy.""" @staticmethod def fetch_spec(_props): return { 'type': 'gclient_git', 'gclient_git_spec': { 'solutions': [ { 'name' : 'src', 'url' : 'https://chromium.googlesource.com/syzygy', 'deps_file': 'DEPS', 'managed' : False, } ], }, } @staticmethod def expected_root(_props): return 'src' def main(argv=None): return Syzygy().handle_args(argv) if __name__ == '__main__': sys.exit(main(sys.argv))
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import config_util # pylint: disable=import-error # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=no-init class Syzygy(config_util.Config): """Basic Config class for Syzygy.""" @staticmethod def fetch_spec(_props): return { 'type': 'gclient_git', 'gclient_git_spec': { 'solutions': [ { 'name' : 'src', 'url' : 'https://github.com/google/syzygy.git', 'deps_file': 'DEPS', 'managed' : False, } ], }, } @staticmethod def expected_root(_props): return 'src' def main(argv=None): return Syzygy().handle_args(argv) if __name__ == '__main__': sys.exit(main(sys.argv))
mvn-scalaxb: Update WSDL integration test for 0.6.7 The generated soap.scala file is now named soap12.scala.
package org.scalaxb.maven.it; import org.junit.Test; public class ITP03WSDL extends AbstractIT { private String[] expected = new String[] { "generated/stockquote.scala", "generated/xmlprotocol.scala", "scalaxb/httpclients_dispatch.scala", "scalaxb/scalaxb.scala", "scalaxb/soap12.scala", "soapenvelope12/soapenvelope12.scala", "soapenvelope12/soapenvelope12_xmlprotocol.scala" }; @Test public void filesAreGeneratedInCorrectLocation() { assertFilesGenerated("itp03-wsdl", expected); } }
package org.scalaxb.maven.it; import org.junit.Test; public class ITP03WSDL extends AbstractIT { private String[] expected = new String[] { "generated/stockquote.scala", "generated/xmlprotocol.scala", "scalaxb/httpclients_dispatch.scala", "scalaxb/scalaxb.scala", "scalaxb/soap.scala", "soapenvelope12/soapenvelope12.scala", "soapenvelope12/soapenvelope12_xmlprotocol.scala" }; @Test public void filesAreGeneratedInCorrectLocation() { assertFilesGenerated("itp03-wsdl", expected); } }
Enable SSL for postgre connection
var fs = require("fs"); var path = require("path"); var Sequelize = require("sequelize"); var env = process.env.NODE_ENV || "development"; var sequelize = new Sequelize(process.env.DATABASE_URL, { dialect: 'postgres', dialectOptions: { ssl: true } }); var db = {}; sequelize .authenticate() .then(function (err) { console.log('Connection has been established successfully.'); }, function (err) { console.log('Unable to connect to the database:', err); }); fs .readdirSync(__dirname) .filter(function (file) { return (file.indexOf(".") !== 0) && (file !== "index.js"); }) .forEach(function (file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function (modelName) { if ("associate" in db[modelName]) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
var fs = require("fs"); var path = require("path"); var Sequelize = require("sequelize"); var env = process.env.NODE_ENV || "development"; //var config = require('../config/sequelize.json')[env]; var sequelize = new Sequelize(process.env.DATABASE_URL, { dialect: 'postgres' }); var db = {}; sequelize .authenticate() .then(function (err) { console.log('Connection has been established successfully.'); }, function (err) { console.log('Unable to connect to the database:', err); }); fs .readdirSync(__dirname) .filter(function (file) { return (file.indexOf(".") !== 0) && (file !== "index.js"); }) .forEach(function (file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function (modelName) { if ("associate" in db[modelName]) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
FEATURE: Add PHPs json_encode options to stringify eel helper
<?php namespace Neos\Eel\Helper; /* * This file is part of the Neos.Eel package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; use Neos\Eel\ProtectedContextAwareInterface; /** * JSON helpers for Eel contexts * * @Flow\Proxy(false) */ class JsonHelper implements ProtectedContextAwareInterface { /** * JSON encode the given value * * @param mixed $value * @param array $options Array of option constant names as strings * @return string */ public function stringify($value, array $options = []): string { $optionSum = array_sum(array_map('constant', $options)); return json_encode($value, $optionSum); } /** * JSON decode the given string * * @param string $json * @param boolean $associativeArrays * @return mixed */ public function parse($json, $associativeArrays = true) { return json_decode($json, $associativeArrays); } /** * All methods are considered safe * * @param string $methodName * @return boolean */ public function allowsCallOfMethod($methodName) { return true; } }
<?php namespace Neos\Eel\Helper; /* * This file is part of the Neos.Eel package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; use Neos\Eel\ProtectedContextAwareInterface; /** * JSON helpers for Eel contexts * * @Flow\Proxy(false) */ class JsonHelper implements ProtectedContextAwareInterface { /** * JSON encode the given value * * @param mixed $value * @return string */ public function stringify($value) { return json_encode($value); } /** * JSON decode the given string * * @param string $json * @param boolean $associativeArrays * @return mixed */ public function parse($json, $associativeArrays = true) { return json_decode($json, $associativeArrays); } /** * All methods are considered safe * * @param string $methodName * @return boolean */ public function allowsCallOfMethod($methodName) { return true; } }
Use new open() function on TargetInfo, in example3
import luigi import sciluigi as sl import time class T1(sl.Task): # Parameter text = luigi.Parameter() # I/O def out_data1(self): return sl.TargetInfo(self, self.text + '.txt') # TODO: Of course make the target spec into an object with "get target" method! # Implementation def run(self): with self.out_data1().open('w') as outfile: outfile.write(self.text) # ======================================================================== class Merge(sl.Task): # I/O in_data1 = None in_data2 = None def out_merged(self): return sl.TargetInfo(self, self.in_data1().path + '.merged.txt') # Implementation def run(self): with self.in_data1().open() as in1, self.in_data2().open() as in2, self.out_merged().open('w') as outfile: for row in in1: outfile.write(row+'\n') for row in in2: outfile.write(row+'\n')
import luigi import sciluigi as sl import time class T1(sl.Task): # Parameter text = luigi.Parameter() # I/O def out_data1(self): return sl.TargetInfo(self, self.text + '.txt') # TODO: Of course make the target spec into an object with "get target" method! # Implementation def run(self): with self.out_data1().target.open('w') as outfile: outfile.write(self.text) # ======================================================================== class Merge(sl.Task): # I/O in_data1 = None in_data2 = None def out_merged(self): return sl.TargetInfo(self, self.in_data1().path + '.merged.txt') # Implementation def run(self): with self.in_data1().target.open() as in1, self.in_data2().target.open() as in2, self.out_merged().target.open('w') as outfile: for row in in1: outfile.write(row+'\n') for row in in2: outfile.write(row+'\n')
Change Mongoloid cursor to return itself on rewind except of void and also accept any value in limit and then change it to number.
<?php /** * @package Billing * @copyright Copyright (C) 2012 S.D.O.C. LTD. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ class Mongodloid_Cursor implements Iterator { private $_cursor; public function __construct(MongoCursor $cursor) { $this->_cursor = $cursor; } public function count() { return $this->_cursor->count(); } public function current() { return new Mongodloid_Entity($this->_cursor->current()); } public function key() { return $this->_cursor->key(); } public function next() { return $this->_cursor->next(); } public function rewind() { $this->_cursor->rewind(); return $this; } public function valid() { return $this->_cursor->valid(); } public function sort(array $fields) { $this->_cursor->sort($fields); return $this; } public function limit($limit) { $this->_cursor->limit(intval($limit)); return $this; } }
<?php /** * @package Billing * @copyright Copyright (C) 2012 S.D.O.C. LTD. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ class Mongodloid_Cursor implements Iterator { private $_cursor; public function __construct(MongoCursor $cursor) { $this->_cursor = $cursor; } public function count() { return $this->_cursor->count(); } public function current() { return new Mongodloid_Entity($this->_cursor->current()); } public function key() { return $this->_cursor->key(); } public function next() { return $this->_cursor->next(); } public function rewind() { return $this->_cursor->rewind(); } public function valid() { return $this->_cursor->valid(); } public function sort(array $fields) { $this->_cursor->sort($fields); return $this; } public function limit(int $limit) { $this->_cursor->limit($limit); return $this; } }
Docs: Set stable version to 2.x
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from sphinx_celery import conf globals().update(conf.build_config( 'amqp', __file__, project='py-amqp', description='Python Promises', version_dev='2.1', version_stable='2.0', canonical_url='https://amqp.readthedocs.io', webdomain='celeryproject.org', github_project='celery/py-amqp', author='Ask Solem & contributors', author_name='Ask Solem', copyright='2016', publisher='Celery Project', html_logo='images/celery_128.png', html_favicon='images/favicon.ico', html_prepend_sidebars=['sidebardonations.html'], extra_extensions=[], include_intersphinx={'python', 'sphinx'}, apicheck_package='amqp', apicheck_ignore_modules=['amqp'], ))
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from sphinx_celery import conf globals().update(conf.build_config( 'amqp', __file__, project='py-amqp', description='Python Promises', version_dev='2.0', version_stable='1.4', canonical_url='https://amqp.readthedocs.io', webdomain='celeryproject.org', github_project='celery/py-amqp', author='Ask Solem & contributors', author_name='Ask Solem', copyright='2016', publisher='Celery Project', html_logo='images/celery_128.png', html_favicon='images/favicon.ico', html_prepend_sidebars=['sidebardonations.html'], extra_extensions=[], include_intersphinx={'python', 'sphinx'}, apicheck_package='amqp', apicheck_ignore_modules=['amqp'], ))
Change output_all_unitprot to allow multi ids for some proteins.
from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command from django.conf import settings from django.db import connection from django.db.models import Q from django.template.loader import render_to_string from protein.models import Protein from residue.models import ResidueGenericNumber, ResidueGenericNumberEquivalent from common import definitions from common.selection import SelectionItem from common.alignment_gpcr import Alignment import xlsxwriter, xlrd import logging, json, os class Command(BaseCommand): help = "Output all uniprot mappings" logger = logging.getLogger(__name__) def handle(self, *args, **options): #Get the proteins f = open('uniprot.json', 'w') ps = Protein.objects.filter(Q(source__name='SWISSPROT') | Q(source__name='TREMBL'),web_links__web_resource__slug='uniprot').all().prefetch_related('web_links__web_resource') print('total:',len(ps)) mapping = {} for p in ps: uniprot = p.web_links.filter(web_resource__slug='uniprot').values_list('index', flat = True) mapping[p.entry_name] = list(uniprot) json.dump(mapping,f, indent=4, separators=(',', ': ')) # print("Seqs: {}\tNot matching: {}".format(num_of_sequences, num_of_non_matching_sequences)) # open("uniprot.txt", "w").write()
from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command from django.conf import settings from django.db import connection from django.db.models import Q from django.template.loader import render_to_string from protein.models import Protein from residue.models import ResidueGenericNumber, ResidueGenericNumberEquivalent from common import definitions from common.selection import SelectionItem from common.alignment_gpcr import Alignment import xlsxwriter, xlrd import logging, json, os class Command(BaseCommand): help = "Output all uniprot mappings" logger = logging.getLogger(__name__) def handle(self, *args, **options): #Get the proteins f = open('uniprot.json', 'w') ps = Protein.objects.filter(Q(source__name='SWISSPROT') | Q(source__name='TREMBL'),web_links__web_resource__slug='uniprot').all().prefetch_related('web_links__web_resource') print('total:',len(ps)) mapping = {} for p in ps: uniprot = p.web_links.get(web_resource__slug='uniprot') mapping[p.entry_name] = uniprot.index json.dump(mapping,f, indent=4, separators=(',', ': ')) # print("Seqs: {}\tNot matching: {}".format(num_of_sequences, num_of_non_matching_sequences)) # open("uniprot.txt", "w").write()
Remove the "3" from SublimeLinter3
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.6.0' check_version = True regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)' multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.6.0' check_version = True regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)' multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
[DX] Improve autoload paths parameter name
<?php declare(strict_types=1); namespace Rector\Core\Error; use PHPStan\AnalysedCodeException; use Rector\Core\Contract\Rector\RectorInterface; use Throwable; final class ExceptionCorrector { public function matchRectorClass(Throwable $throwable): ?string { if (! isset($throwable->getTrace()[0])) { return null; } if (! isset($throwable->getTrace()[0]['class'])) { return null; } /** @var string $class */ $class = $throwable->getTrace()[0]['class']; if (! is_a($class, RectorInterface::class, true)) { return null; } return $class; } public function getAutoloadExceptionMessageAndAddLocation(AnalysedCodeException $analysedCodeException): string { return sprintf( 'Analyze error: "%s". Include your files in "$parameters->set(Option::AUTOLOAD_PATHS, [...]));" in "rector.php" config.%sSee https://github.com/rectorphp/rector#configuration', $analysedCodeException->getMessage(), PHP_EOL ); } }
<?php declare(strict_types=1); namespace Rector\Core\Error; use PHPStan\AnalysedCodeException; use Rector\Core\Contract\Rector\RectorInterface; use Throwable; final class ExceptionCorrector { public function matchRectorClass(Throwable $throwable): ?string { if (! isset($throwable->getTrace()[0])) { return null; } if (! isset($throwable->getTrace()[0]['class'])) { return null; } /** @var string $class */ $class = $throwable->getTrace()[0]['class']; if (! is_a($class, RectorInterface::class, true)) { return null; } return $class; } public function getAutoloadExceptionMessageAndAddLocation(AnalysedCodeException $analysedCodeException): string { return sprintf( 'Analyze error: "%s". Include your files in "parameters > autoload_paths".%sSee https://github.com/rectorphp/rector#configuration', $analysedCodeException->getMessage(), PHP_EOL ); } }
Load in the mockery trait
<?php namespace Bugsnag\BugsnagLaravel\Tests\Request; use Bugsnag\BugsnagLaravel\Request\LaravelRequest; use Bugsnag\BugsnagLaravel\Request\LaravelResolver; use Bugsnag\Request\NullRequest; use Bugsnag\Request\RequestInterface; use GrahamCampbell\TestBenchCore\MockeryTrait; use Illuminate\Foundation\Application; use Illuminate\Http\Request; use Mockery; use PHPUnit_Framework_TestCase as TestCase; class LaravelRequestTest extends TestCase { use MockeryTrait; public function testCanResolveNullRequest() { $resolver = new LaravelResolver($app = Mockery::mock(Application::class)); $app->shouldReceive('runningInConsole')->once()->andReturn(true); $request = $resolver->resolve(); $this->assertInstanceOf(RequestInterface::class, $request); $this->assertInstanceOf(NullRequest::class, $request); } public function testCanResolveLaravelRequest() { $resolver = new LaravelResolver($app = Mockery::mock(Application::class)); $app->shouldReceive('runningInConsole')->once()->andReturn(false); $app->shouldReceive('make')->once()->with(Request::class)->andReturn($request = Mockery::mock(Request::class)); $request = $resolver->resolve(); $this->assertInstanceOf(RequestInterface::class, $request); $this->assertInstanceOf(LaravelRequest::class, $request); } }
<?php namespace Bugsnag\BugsnagLaravel\Tests\Request; use Bugsnag\BugsnagLaravel\Request\LaravelRequest; use Bugsnag\BugsnagLaravel\Request\LaravelResolver; use Bugsnag\Request\NullRequest; use Bugsnag\Request\RequestInterface; use Illuminate\Foundation\Application; use Illuminate\Http\Request; use Mockery; use PHPUnit_Framework_TestCase as TestCase; class LaravelRequestTest extends TestCase { public function testCanResolveNullRequest() { $resolver = new LaravelResolver($app = Mockery::mock(Application::class)); $app->shouldReceive('runningInConsole')->once()->andReturn(true); $request = $resolver->resolve(); $this->assertInstanceOf(RequestInterface::class, $request); $this->assertInstanceOf(NullRequest::class, $request); } public function testCanResolveLaravelRequest() { $resolver = new LaravelResolver($app = Mockery::mock(Application::class)); $app->shouldReceive('runningInConsole')->once()->andReturn(false); $app->shouldReceive('make')->once()->with(Request::class)->andReturn($request = Mockery::mock(Request::class)); $request = $resolver->resolve(); $this->assertInstanceOf(RequestInterface::class, $request); $this->assertInstanceOf(LaravelRequest::class, $request); } }
Replace clearInterval with RequestAnimationFrame for performance
import Prop from 'props/prop'; import canvas from 'canvas'; const coords = { northEast: { x: 1, y: -1, }, southEast: { x: 1, y: 1, }, southWest: { x: -1, y: 1, }, northWest: { x: -1, y: -1, }, }; export default class Ball extends Prop { constructor() { const width = 10; const height = 10; const x = (canvas.width / 2) - (width / 2); const y = (canvas.height / 2) - (height / 2); super(x, y, width, height); } isOutOfBounds() { // This will be moved into a collision detection lib at some point. return ( this.positionY === canvas.height || this.positionY === 0 || this.positionX === canvas.width || this.positionX === 0 ); } fire() { const direction = coords.northWest; const move = () => { this.move(direction.x, direction.y); if (!this.isOutOfBounds()) { return requestAnimationFrame(move); } }; requestAnimationFrame(move); } }
import Prop from 'props/prop'; import canvas from 'canvas'; const coords = { northEast: { x: 1, y: -1, }, southEast: { x: 1, y: 1, }, southWest: { x: -1, y: 1, }, northWest: { x: -1, y: -1, }, }; export default class Ball extends Prop { constructor() { const width = 10; const height = 10; const x = (canvas.width / 2) - (width / 2); const y = (canvas.height / 2) - (height / 2); super(x, y, width, height); } isOutOfBounds() { // This will be moved into a collision detection lib at some point. return ( this.positionY === canvas.height || this.positionY === 0 || this.positionX === canvas.width || this.positionX === 0 ); } fire() { const direction = coords.northWest; const move = setInterval(() => { this.move(direction.x, direction.y); if (this.isOutOfBounds()) { console.log('Stopping ball, out of bounds'); clearInterval(move); } }, 10); } }
Use LTS endpoint on Lts explore page
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; import isEmpty from 'lodash/isEmpty'; /* @tmpfix: remove usage of indcTransform */ import indcTransform from 'utils/indctransform'; const fetchLTSInit = createAction('fetchLTSInit'); const fetchLTSReady = createAction('fetchLTSReady'); const fetchLTSFail = createAction('fetchLTSFail'); const fetchLTS = createThunkAction('fetchLTS', () => (dispatch, state) => { const { LTS } = state(); if ( LTS && (isEmpty(LTS.data) || isEmpty(LTS.data.indicators)) && !LTS.loading ) { dispatch(fetchLTSInit()); fetch('/api/v1/lts?source=LTS&filter=map') .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => indcTransform(data)) .then(data => { dispatch(fetchLTSReady(data)); }) .catch(error => { console.warn(error); dispatch(fetchLTSFail()); }); } }); export default { fetchLTS, fetchLTSInit, fetchLTSReady, fetchLTSFail };
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; import isEmpty from 'lodash/isEmpty'; /* @tmpfix: remove usage of indcTransform */ import indcTransform from 'utils/indctransform'; const fetchLTSInit = createAction('fetchLTSInit'); const fetchLTSReady = createAction('fetchLTSReady'); const fetchLTSFail = createAction('fetchLTSFail'); const fetchLTS = createThunkAction('fetchLTS', () => (dispatch, state) => { const { LTS } = state(); if ( LTS && (isEmpty(LTS.data) || isEmpty(LTS.data.indicators)) && !LTS.loading ) { dispatch(fetchLTSInit()); fetch('/api/v1/ndcs?source=LTS&filter=map') .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => indcTransform(data)) .then(data => { dispatch(fetchLTSReady(data)); }) .catch(error => { console.warn(error); dispatch(fetchLTSFail()); }); } }); export default { fetchLTS, fetchLTSInit, fetchLTSReady, fetchLTSFail };
Fix help handler for 404 message
import { getLogger } from "./logger"; const logger = getLogger(); const helpTextHandlers = { MISSING_404_TEXT: showMissing404Text }; function showMissing404Text () { logger.info(` ######################################################################################### Rendered a 404 Error but no custom 404 route detected. You can create a custom 404 handler with the following steps: 1. Create a new container that you would like to use when rendering 404 errors. > gluestick generate container RouteNotFound 2. Import this new container in the routes file along with the 'ROUTE_NAME_404_NOT_FOUND' constant. import RouteNotFound from "../containers/RouteNotFound"; import { ROUTE_NAME_404_NOT_FOUND } from "gluestick-shared"; 3. Add a new route that uses this constant and container as your very last route. <Route name={"ROUTE_NAME_404_NOT_FOUND"} path="*" component={RouteNotFound} /> ######################################################################################### `); } export default function showHelpText (key) { helpTextHandlers[key](); } export const MISSING_404_TEXT = "MISSING_404_TEXT";
import { getLogger } from "./logger"; const logger = getLogger(); const helpTextHandlers = { [MISSING_404_TEXT]: showMissing404Text }; function showMissing404Text () { logger.info(` ######################################################################################### Rendered a 404 Error but no custom 404 route detected. You can create a custom 404 handler with the following steps: 1. Create a new container that you would like to use when rendering 404 errors. > gluestick generate container RouteNotFound 2. Import this new container in the routes file along with the 'ROUTE_NAME_404_NOT_FOUND' constant. import RouteNotFound from "../containers/RouteNotFound"; import { ROUTE_NAME_404_NOT_FOUND } from "gluestick-shared"; 3. Add a new route that uses this constant and container as your very last route. <Route name={"ROUTE_NAME_404_NOT_FOUND"} path="*" component={RouteNotFound} /> ######################################################################################### `); } export default function showHelpText (key) { helpTextHandlers[key](); } export const MISSING_404_TEXT = "MISSING_404_TEXT";
Use profile id if display name is null - closes #54
'use strict'; /** * Module dependencies. */ var passport = require('passport'), refresh = require('passport-oauth2-refresh'), SpotifyStrategy = require('passport-spotify').Strategy, config = require('../config'), users = require('../../app/controllers/users.server.controller'); module.exports = function() { // Use spotify strategy var strategy = new SpotifyStrategy({ clientID: config.spotify.clientID, clientSecret: config.spotify.clientSecret, callbackURL: config.spotify.callbackURL, }, function(req, accessToken, refreshToken, profile, done) { // Set the provider data and include tokens var providerData = profile._json; /** * NOTE: There is a bug in passport where the accessToken and * refresh token and swapped. I am patching this in the strategy * so I don't have to apply this backwards logic throughout the app */ providerData.accessToken = refreshToken.access_token; providerData.refreshToken = accessToken; // Create the user OAuth profile var providerUserProfile = { displayName: profile.displayName || profile.id, username: profile.id, provider: 'spotify', providerIdentifierField: 'id', providerData: providerData }; // Save the user OAuth profile users.saveOAuthUserProfile(req, providerUserProfile, done); } ); passport.use(strategy); refresh.use(strategy); };
'use strict'; /** * Module dependencies. */ var passport = require('passport'), refresh = require('passport-oauth2-refresh'), SpotifyStrategy = require('passport-spotify').Strategy, config = require('../config'), users = require('../../app/controllers/users.server.controller'); module.exports = function() { // Use spotify strategy var strategy = new SpotifyStrategy({ clientID: config.spotify.clientID, clientSecret: config.spotify.clientSecret, callbackURL: config.spotify.callbackURL, }, function(req, accessToken, refreshToken, profile, done) { // Set the provider data and include tokens var providerData = profile._json; /** * NOTE: There is a bug in passport where the accessToken and * refresh token and swapped. I am patching this in the strategy * so I don't have to apply this backwards logic throughout the app */ providerData.accessToken = refreshToken.access_token; providerData.refreshToken = accessToken; // Create the user OAuth profile var providerUserProfile = { displayName: profile.displayName, username: profile.id, provider: 'spotify', providerIdentifierField: 'id', providerData: providerData }; // Save the user OAuth profile users.saveOAuthUserProfile(req, providerUserProfile, done); } ); passport.use(strategy); refresh.use(strategy); };
Fix server not closing on sigterm/interrupt
package main import ( "os" "os/signal" "syscall" "github.com/underlx/disturbancesmlx/discordbot" ) // DiscordBot starts the Discord bot if it is enabled in the settings func DiscordBot() { discordToken, present := secrets.Get("discordToken") if !present { discordLog.Println("Discord token not found, Discord functions disabled") return } err := discordbot.Start(rootSqalxNode, websiteURL, discordToken, discordLog, schedulesToLines, handleNewStatus) if err != nil { discordLog.Println(err) return } // Wait here until CTRL-C or other term signal is received. discordLog.Println("Bot is now running.") sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc // Cleanly close down the Discord session. discordbot.Stop() os.Exit(0) }
package main import ( "os" "os/signal" "syscall" "github.com/underlx/disturbancesmlx/discordbot" ) // DiscordBot starts the Discord bot if it is enabled in the settings func DiscordBot() { discordToken, present := secrets.Get("discordToken") if !present { discordLog.Println("Discord token not found, Discord functions disabled") return } err := discordbot.Start(rootSqalxNode, websiteURL, discordToken, discordLog, schedulesToLines, handleNewStatus) if err != nil { discordLog.Println(err) return } // Wait here until CTRL-C or other term signal is received. discordLog.Println("Bot is now running.") sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc // Cleanly close down the Discord session. discordbot.Stop() }
Update to the current location of the freetype library
package freetype import ( "github.com/golang/freetype" "image" ) var img = image.NewNRGBA64(image.Rectangle{image.Point{0, 0}, image.Point{59, 39}}) func Fuzz(data []byte) int { f, err := freetype.ParseFont(data) if err != nil { if f != nil { panic("font is not nil on error") } return 0 } ctx := freetype.NewContext() ctx.SetFont(f) ctx.SetSrc(image.Black) ctx.SetHinting(freetype.FullHinting) ctx.SetDst(img) ctx.SetDPI(51) ctx.SetFontSize(9) if _, err = ctx.DrawString("go-фузз", freetype.Pt(1, 3)); err != nil { panic(err) } return 1 }
package freetype import ( "code.google.com/p/freetype-go/freetype" "image" ) var img = image.NewNRGBA64(image.Rectangle{image.Point{0, 0}, image.Point{59, 39}}) func Fuzz(data []byte) int { f, err := freetype.ParseFont(data) if err != nil { if f != nil { panic("font is not nil on error") } return 0 } ctx := freetype.NewContext() ctx.SetFont(f) ctx.SetSrc(image.Black) ctx.SetHinting(freetype.FullHinting) ctx.SetDst(img) ctx.SetDPI(51) ctx.SetFontSize(9) if _, err = ctx.DrawString("go-фузз", freetype.Pt(1, 3)); err != nil { panic(err) } return 1 }
Allow adding error message for specified field
# coding=utf-8 from django.forms import forms class APICall(forms.Form): def __init__(self, api_key=None, *args, **kwargs): super(APICall, self).__init__(*args, **kwargs) self.api_key = api_key def add_error(self, error_msg, field_name=forms.NON_FIELD_ERRORS): # TODO: with Django master you would just raise ValidationError({field_name: error_msg}) self._errors.setdefault(field_name, self.error_class()).append(error_msg) def clean(self): for name, data in self.cleaned_data.iteritems(): setattr(self, name, data) return super(APICall, self).clean() def action(self, test): raise NotImplementedError('APIForms must implement action(self, test)')
from django.forms import forms class APICall(forms.Form): def __init__(self, api_key=None, *args, **kwargs): super(APICall, self).__init__(*args, **kwargs) self.api_key = api_key def add_error(self, error_msg): errors = self.non_field_errors() errors.append(error_msg) self._errors[forms.NON_FIELD_ERRORS] = errors def clean(self): for name, data in self.cleaned_data.iteritems(): setattr(self, name, data) return super(APICall, self).clean() def action(self, test): raise NotImplementedError('APIForms must implement action(self, test)')
Add more info about active page
<?php namespace Rudolf\Modules\Pages; use Rudolf\Modules\A_front\FController; use Rudolf\Component\Http\HttpErrorException; class Controller extends FController { public function page($sAddress) { $addressArray = explode('/', trim($sAddress, '/')); $model = new Model(); $pagesList = $model->getPagesList(); $pageId = $model->getPageIdByPath($addressArray, $pagesList); if (false === $pageId) { throw new HttpErrorException('No page found (error 404)', 404); } $pageData = $model->getPageById($pageId); $view = new View(); $view->page($pageData); $aAddress = explode('/', $sAddress); $temp = ''; foreach ($aAddress as $key => $value) { $active[] = ltrim($temp = $temp . '/' . $value, '/'); } $view->setFrontData($this->frontData, $active); $view->setBreadcrumbsData($pagesList, $aAddress); return $view->render(); } }
<?php namespace Rudolf\Modules\Pages; use Rudolf\Modules\A_front\FController; use Rudolf\Component\Http\HttpErrorException; class Controller extends FController { public function page($sAddress) { $addressArray = explode('/', trim($sAddress, '/')); $model = new Model(); $pagesList = $model->getPagesList(); $pageId = $model->getPageIdByPath($addressArray, $pagesList); if (false === $pageId) { throw new HttpErrorException('No page found (error 404)', 404); } $pageData = $model->getPageById($pageId); $view = new View(); $view->page($pageData); $aAddress = explode('/', $sAddress); $view->setFrontData($this->frontData, $aAddress[0]); $view->setBreadcrumbsData($pagesList, $aAddress); return $view->render(); } }
fix: Use new class name FileLookup See also: #72
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import GitLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = GitLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True
Add taggit and statirator.blog to INSTALLED_APPS
# Generated by statirator import os # directories setup ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}') BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}') # languages setup LANGUAGE_CODE = '{{default_lang}}' _ = lambda s:s LANGUAGES = ({% for code, name in languages %} ('{{code}}', _('{{ name }}')), {% endfor %}) ROOT_URLCONF = '{{ project_name }}.urls' TEMPLATE_DIRS = ( os.path.join(ROOT_DIR, 'templates'), ) INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.staticfiles', 'django_medusa', 'taggit', 'statirator.blog', ) MEDUSA_RENDERER_CLASS = "django_medusa.renderers.DiskStaticSiteRenderer" MEDUSA_MULTITHREAD = True MEDUSA_DEPLOY_DIR = BUILD_DIR
# Generated by statirator import os # directories setup ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}') BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}') # languages setup LANGUAGE_CODE = '{{default_lang}}' _ = lambda s:s LANGUAGES = ({% for code, name in languages %} ('{{code}}', _('{{ name }}')), {% endfor %}) ROOT_URLCONF = '{{ project_name }}.urls' TEMPLATE_DIRS = ( os.path.join(ROOT_DIR, 'templates'), ) INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.staticfiles', 'django_medusa', ) MEDUSA_RENDERER_CLASS = "django_medusa.renderers.DiskStaticSiteRenderer" MEDUSA_MULTITHREAD = True MEDUSA_DEPLOY_DIR = BUILD_DIR
Use correct argument for content type in serve view
import mimetypes from django.http import HttpResponse, HttpResponseNotModified, Http404 from django.contrib.staticfiles.views import serve as staticfiles_serve from django.views.static import was_modified_since, http_date from staticassets import finder, settings def serve(request, path, **kwargs): mimetype, encoding = mimetypes.guess_type(path) if not mimetype in settings.MIMETYPES.values(): return staticfiles_serve(request, path, **kwargs) bundle = request.GET.get('bundle') in ('1', 't', 'true') asset = finder.find(path, bundle=bundle) if not asset: raise Http404("Static asset not found") # Respect the If-Modified-Since header. modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if not was_modified_since(modified_since, asset.mtime, asset.size): return HttpResponseNotModified(content_type=asset.attributes.content_type) response = HttpResponse(asset.content, content_type=asset.attributes.content_type) response['Last-Modified'] = http_date(asset.mtime) response['Content-Length'] = asset.size return response
import mimetypes from django.http import HttpResponse, HttpResponseNotModified, Http404 from django.contrib.staticfiles.views import serve as staticfiles_serve from django.views.static import was_modified_since, http_date from staticassets import finder, settings def serve(request, path, **kwargs): mimetype, encoding = mimetypes.guess_type(path) if not mimetype in settings.MIMETYPES.values(): return staticfiles_serve(request, path, **kwargs) bundle = request.GET.get('bundle') in ('1', 't', 'true') asset = finder.find(path, bundle=bundle) if not asset: raise Http404("Static asset not found") # Respect the If-Modified-Since header. modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if not was_modified_since(modified_since, asset.mtime, asset.size): return HttpResponseNotModified(mimetype=asset.attributes.content_type) response = HttpResponse(asset.content, mimetype=asset.attributes.content_type) response['Last-Modified'] = http_date(asset.mtime) response['Content-Length'] = asset.size return response
Fix missing use in SliderBundle
<?php /** * AdminBuilderSubscriber.php * * @since 15/10/14 * @author Gerhard Seidel <gseidel.message@googlemail.com> */ namespace esperanto\SliderBundle\EventListener; use esperanto\AdminBundle\Event\RouteBuilderEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use esperanto\AdminBundle\Builder\Route\SyliusRouteBuilder; use esperanto\AdminBundle\Builder\View\ViewBuilder; use esperanto\AdminBundle\Event\BuilderEvent; use esperanto\AdminBundle\Event\MenuBuilderEvent; class AdminSliderBuilderSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'esperanto_slider.slider.build_menu' => array('onBuildMenu', 0), 'esperanto_slider.slider.build_table_route' => array('onBuildTableRoute', 0), 'esperanto_slider.slider.build_index_route' => array('onBuildIndexRoute', 0), ); } public function onBuildTableRoute(RouteBuilderEvent $event) { } public function onBuildIndexRoute(RouteBuilderEvent $event) { } public function onBuildMenu(MenuBuilderEvent $event) { $event->setBuilder(null); } }
<?php /** * AdminBuilderSubscriber.php * * @since 15/10/14 * @author Gerhard Seidel <gseidel.message@googlemail.com> */ namespace esperanto\SliderBundle\EventListener; use esperanto\AdminBundle\Event\RouteBuilderEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use esperanto\AdminBundle\Builder\Route\SyliusRouteBuilder; use esperanto\AdminBundle\Builder\View\ViewBuilder; use esperanto\AdminBundle\Event\BuilderEvent; class AdminSliderBuilderSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'esperanto_slider.slider.build_menu' => array('onBuildMenu', 0), 'esperanto_slider.slider.build_table_route' => array('onBuildTableRoute', 0), 'esperanto_slider.slider.build_index_route' => array('onBuildIndexRoute', 0), ); } public function onBuildTableRoute(RouteBuilderEvent $event) { } public function onBuildIndexRoute(RouteBuilderEvent $event) { } public function onBuildMenu(MenuBuilderEvent $event) { $event->setBuilder(null); } }
Fix setting new indices of playlist entries. * Was giving entries indices from 2...n+1, Now 1...n like you want
import Ember from 'ember'; export default Ember.Component.extend({ tagName: '', fixWidthHelper: function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; }, updateSortedOrder: function(indices) { this.beginPropertyChanges(); let tracks = this.get('model.tracks').forEach((track) => { var index = indices[track.get('id')] +1; if (track.get('index') !== index) { track.set('index',index); track.save(); } }); this.endPropertyChanges(); }, didInsertElement: function() { var component = this; Ember.$('#tracklisting').sortable({ helper: function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; }, update: function(e, ui) { let indices = {}; $(this).find('.playlistentry').each( (index, item) => { indices[$(item).data('id')] = index; }); //$(this).sortable('cancel'); component.updateSortedOrder(indices); }, }); Ember.$('#tracklisting').disableSelection(); } });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: '', fixWidthHelper: function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; }, updateSortedOrder: function(indices) { this.beginPropertyChanges(); let tracks = this.get('model.tracks').forEach((track) => { var index = indices[track.get('id')] +1; if (track.get('index') !== index) { track.set('index',index+1); track.save(); } }); this.endPropertyChanges(); }, didInsertElement: function() { var component = this; Ember.$('#tracklisting').sortable({ helper: function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; }, update: function(e, ui) { let indices = {}; $(this).find('.playlistentry').each( (index, item) => { indices[$(item).data('id')] = index; }); //$(this).sortable('cancel'); component.updateSortedOrder(indices); }, }); Ember.$('#tracklisting').disableSelection(); } });
Test getting properties as well
var jQuery = require('jquery'); var VIE = require('../vie.js'); // Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed VIE.RDFa.predicateSelector = '[property]'; exports['test inheriting subject'] = function(test) { var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); var jsonldEntities = VIE.RDFa.readEntities(html); test.equal(jsonldEntities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON"); test.equal(jsonldEntities[1]['foaf:name'], 'Albert Einstein'); test.equal(jsonldEntities[0]['dbp:conventionalLongName'], 'Federal Republic of Germany'); var backboneEntities = VIE.RDFaEntities.getInstances(html); test.equal(backboneEntities.length, 2, "This RDFa defines two entities but they don't get to Backbone"); test.equal(backboneEntities[1].get('foaf:name'), 'Albert Einstein'); test.equal(backboneEntities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany'); test.done(); };
var jQuery = require('jquery'); var VIE = require('../vie.js'); // Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed VIE.RDFa.predicateSelector = '[property]'; exports['test inheriting subject'] = function(test) { var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein<span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); var entities = VIE.RDFa.readEntities(html); test.equal(entities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON"); var entities = VIE.RDFaEntities.getInstances(html); test.equal(entities.length, 2, "This RDFa defines two entities but they don't get to Backbone"); test.done(); };
Add codegen script to package_data
#! /usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup(name='egoio', author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES', author_email='', description='ego input/output repository', version='0.3.0', url='https://github.com/openego/ego.io', packages=find_packages(), license='GNU Affero General Public License v3.0', install_requires=[ 'geoalchemy2 >= 0.3.0, <= 0.4.0', 'sqlalchemy >= 1.0.11, <= 1.1.15', 'keyring >= 4.0', 'psycopg2'], extras_require={ "sqlalchemy": 'postgresql'}, package_data={'tools': 'sqlacodegen_oedb.sh'} )
#! /usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup(name='egoio', author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES', author_email='', description='ego input/output repository', version='0.3.0', url='https://github.com/openego/ego.io', packages=find_packages(), license='GNU Affero General Public License v3.0', install_requires=[ 'geoalchemy2 >= 0.3.0, <= 0.4.0', 'sqlalchemy >= 1.0.11, <= 1.1.15', 'keyring >= 4.0', 'psycopg2'], extras_require={ "sqlalchemy": 'postgresql'} )
Add function for creating a datetime aware object
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day)
Add TODO to clean up 'departed' field
Template.home.onCreated(function () { const instance = this; // Set current Home ID from router instance.homeId = Router.current().params.homeId; // Subscribe to current home instance.subscribe('singleHome', instance.homeId); // Subscribe to Home Residents instance.subscribe('homeCurrentResidents', instance.homeId); }); Template.home.events({ 'click #edit-home': function () { // Get reference to template instance var instance = Template.instance(); // Get Home ID var homeId = instance.homeId; // Get home var home = Homes.findOne(homeId); // Show the edit home modal Modal.show('editHome', home); } }); Template.home.helpers({ 'home': function () { // Create reference to template instance var instance = Template.instance(); // Get Home ID from template instance var homeId = instance.homeId; // Return current Home return Homes.findOne(homeId); }, 'residents': function () { // Create reference to template instance var instance = Template.instance(); // Get Home ID from template instance var homeId = instance.homeId; // Return all residents for current home, sorting by first name // TODO: deprecate the departed field return Residents.find({departed: false}, {sort: {firstName: 1}}); } });
Template.home.onCreated(function () { const instance = this; // Set current Home ID from router instance.homeId = Router.current().params.homeId; // Subscribe to current home instance.subscribe('singleHome', instance.homeId); // Subscribe to Home Residents instance.subscribe('homeCurrentResidents', instance.homeId); }); Template.home.events({ 'click #edit-home': function () { // Get reference to template instance var instance = Template.instance(); // Get Home ID var homeId = instance.homeId; // Get home var home = Homes.findOne(homeId); // Show the edit home modal Modal.show('editHome', home); } }); Template.home.helpers({ 'home': function () { // Create reference to template instance var instance = Template.instance(); // Get Home ID from template instance var homeId = instance.homeId; // Return current Home return Homes.findOne(homeId); }, 'residents': function () { // Create reference to template instance var instance = Template.instance(); // Get Home ID from template instance var homeId = instance.homeId; // Return all residents for current home, sorting by first name return Residents.find({}, {sort: {firstName: 1}}); } });
Add more asserts to tests for error checking
'use strict'; var assert = require('assert'); var ControllerInterface = require('../lib/controller-interface'); describe('controller-interface', function() { beforeEach(function() { this.controllerInterface = new ControllerInterface( './test-controller.fcl'); }); it('it should give an expected output on input', function(done) { this.controllerInterface.runController([-0.4, 3.1], function(err, result) { assert.ifError(err); assertFloatEqual(result, 0.5); done(); }); }); it('it should give an expected output on input', function(done) { this.controllerInterface.runController([0.2, 1.1], function(err, result) { assert.ifError(err); assertFloatEqual(result, 1.5); done(); }); }); }); function assertFloatEqual(actual, expected) { assert(Math.abs(actual - expected) < 1e-5, 'expected ' + expected + ', got ' + actual); }
'use strict'; var assert = require('assert'); var ControllerInterface = require('../lib/controller-interface'); describe('controller-interface', function() { beforeEach(function() { this.controllerInterface = new ControllerInterface( './test-controller.fcl'); }); it('it should give an expected output on input', function(done) { this.controllerInterface.runController([-0.4, 3.1], function(err, result) { assertFloatEqual(result, 0.5); done(); }); }); it('it should give an expected output on input', function(done) { this.controllerInterface.runController([0.2, 1.1], function(err, result) { assertFloatEqual(result, 1.5); done(); }); }); }); function assertFloatEqual(actual, expected) { assert(Math.abs(actual - expected) < 1e-5, 'expected ' + expected + ', got ' + actual); }
Use airoute() to ensure redirect works correctly in multi-site setups
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; class EnsureEmailIsVerified { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $redirectToRoute * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse|null */ public function handle($request, Closure $next, $redirectToRoute = null) { if (! $request->user() || ($request->user() instanceof MustVerifyEmail && ! $request->user()->hasVerifiedEmail()) ) { $params = []; if( env( 'SHOP_MULTILOCALE' ) ) { $params['locale'] = $request->route( 'locale', $request->input( 'locale', app()->getLocale() ) ); } return $request->expectsJson() ? abort(403, 'Your email address is not verified.') : Redirect::guest(airoute($redirectToRoute ?: 'verification.notice', $params)); } return $next($request); } }
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; class EnsureEmailIsVerified { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $redirectToRoute * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse|null */ public function handle($request, Closure $next, $redirectToRoute = null) { if (! $request->user() || ($request->user() instanceof MustVerifyEmail && ! $request->user()->hasVerifiedEmail()) ) { $params = []; if( env( 'SHOP_MULTILOCALE' ) ) { $params['locale'] = $request->route( 'locale', $request->input( 'locale', app()->getLocale() ) ); } return $request->expectsJson() ? abort(403, 'Your email address is not verified.') : Redirect::guest(URL::route($redirectToRoute ?: 'verification.notice', $params)); } return $next($request); } }
Fix escape sequence formatting linter errors
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\\/'), ('\\', '\\\\'), ('/\\', '\\/\\\\'), ('\\//\\', '\\\\\\/\\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\\/\\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\\/c/d', ['ab/c', 'd']), ('ab\\//cd', ['ab/', 'cd']), ('ab/\\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
import pytest from girder.utility import path @pytest.mark.parametrize('raw,encoded', [ ('abcd', 'abcd'), ('/', '\/'), ('\\', '\\\\'), ('/\\', '\/\\\\'), ('\\//\\', '\\\\\/\/\\\\'), ('a\\\\b//c\\d', 'a\\\\\\\\b\/\/c\\\\d') ]) def testCodec(raw, encoded): assert path.encode(raw) == encoded assert path.decode(encoded) == raw @pytest.mark.parametrize('pth,tokens', [ ('abcd', ['abcd']), ('/abcd', ['', 'abcd']), ('/ab/cd/ef/gh', ['', 'ab', 'cd', 'ef', 'gh']), ('/ab/cd//', ['', 'ab', 'cd', '', '']), ('ab\\/cd', ['ab/cd']), ('ab\/c/d', ['ab/c', 'd']), ('ab\//cd', ['ab/', 'cd']), ('ab/\/cd', ['ab', '/cd']), ('ab\\\\/cd', ['ab\\', 'cd']), ('ab\\\\/\\\\cd', ['ab\\', '\\cd']), ('ab\\\\\\/\\\\cd', ['ab\\/\\cd']), ('/\\\\abcd\\\\/', ['', '\\abcd\\', '']), ('/\\\\\\\\/\\//\\\\', ['', '\\\\', '/', '\\']) ]) def testSplitAndJoin(pth, tokens): assert path.split(pth) == tokens assert path.join(tokens) == pth
Update file format version string.
/** * @author jimbo00000 */ THREE.InstancedGeometryExporter = function () {}; THREE.InstancedGeometryExporter.prototype = { constructor: THREE.InstancedGeometryExporter, parse: function ( geometry ) { var output = { metadata: { version: 4.1, type: 'InstancedGeometry3D', generator: 'InstancedGeometryExporter' } }; console.log(geometry); var cnt = geometry.maxInstancedCount; output[ 'maxInstancedCount' ] = cnt; { var attribute = 'perInstPositions'; var typedArray = geometry.attributes[ attribute ]; var array = []; for ( var i = 0, l = cnt*4; i < l; i ++ ) { array[ i ] = typedArray.array[ i ]; } output[ attribute ] = array; } { var attribute = 'perInstOrientations'; var typedArray = geometry.attributes[ attribute ]; var array = []; //for ( var i = 0, l = cnt; i < l; i ++ ) { for ( var i = 0, l = cnt*4; i < l; i ++ ) { array[ i ] = typedArray.array[ i ]; } output[ attribute ] = array; } return output; } };
/** * @author jimbo00000 */ THREE.InstancedGeometryExporter = function () {}; THREE.InstancedGeometryExporter.prototype = { constructor: THREE.InstancedGeometryExporter, parse: function ( geometry ) { var output = { metadata: { version: 4.0, type: 'InstancedGeometry', generator: 'InstancedGeometryExporter' } }; console.log(geometry); //output['fileFormatType'] = '3D instanced geomtry'; //output['fileFormatVersion'] = 0.1; var cnt = geometry.maxInstancedCount; output[ 'maxInstancedCount' ] = cnt; { var attribute = 'perInstPositions'; var typedArray = geometry.attributes[ attribute ]; var array = []; for ( var i = 0, l = cnt*4; i < l; i ++ ) { array[ i ] = typedArray.array[ i ]; } output[ attribute ] = array; } { var attribute = 'perInstOrientations'; var typedArray = geometry.attributes[ attribute ]; var array = []; //for ( var i = 0, l = cnt; i < l; i ++ ) { for ( var i = 0, l = cnt*4; i < l; i ++ ) { array[ i ] = typedArray.array[ i ]; } output[ attribute ] = array; } return output; } };
Fix module filters not working in Firefox due to having two click events
define(['backbone.marionette', 'hbs!../templates/filter'], function (Marionette, template) { 'use strict'; return Marionette.ItemView.extend({ tagName: 'label', className: 'checkbox-inline', template: template, events: { 'click :checkbox': function (event) { event.preventDefault(); this.model.toggleSelected(); }, 'click a': function (event) { event.preventDefault(); this.model.collection.selectNone(); this.model.toggleSelected(); } }, modelEvents: { 'selected deselected': 'render' } }); });
define(['backbone.marionette', 'hbs!../templates/filter'], function (Marionette, template) { 'use strict'; return Marionette.ItemView.extend({ tagName: 'label', className: 'checkbox-inline', template: template, events: { 'click :checkbox': function () { this.model.toggleSelected(); }, 'click a': function (event) { event.preventDefault(); this.model.collection.selectNone(); this.model.toggleSelected(); } }, modelEvents: { 'selected deselected': 'render' } }); });
Put a time limit on smart shutdown.
package main import ( "log" "net" "os" "os/signal" "sync" "syscall" "time" ) var listenerChan = make(chan net.Listener) var activeConnections sync.WaitGroup func init() { go watchForSIGTERM() } func watchForSIGTERM() { var listeners []net.Listener sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM) for { select { case l := <-listenerChan: listeners = append(listeners, l) case <-sigChan: log.Println("Received SIGTERM") for _, ln := range listeners { ln.Close() } if *pidfile != "" { os.Remove(*pidfile) } go func() { // Stop after 24 hours even if the connections aren't closed. time.Sleep(24 * time.Hour) os.Exit(0) }() activeConnections.Wait() os.Exit(0) } } }
package main import ( "log" "net" "os" "os/signal" "sync" "syscall" ) var listenerChan = make(chan net.Listener) var activeConnections sync.WaitGroup func init() { go watchForSIGTERM() } func watchForSIGTERM() { var listeners []net.Listener sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM) for { select { case l := <-listenerChan: listeners = append(listeners, l) case <-sigChan: log.Println("Received SIGTERM") for _, ln := range listeners { ln.Close() } if *pidfile != "" { os.Remove(*pidfile) } activeConnections.Wait() os.Exit(0) } } }
NXP-12694: Use generic resource directory finder for icon files
"""Helper to lookup UI resources from package""" import os from nxdrive.logging_config import get_logger from nxdrive.utils import find_resource_dir log = get_logger(__name__) def find_icon(icon_filename): """Find the FS path of an icon in various OS binary packages""" import nxdrive nxdrive_path = os.path.dirname(nxdrive.__file__) icons_path = os.path.join(nxdrive_path, 'data', 'icons') icons_dir = find_resource_dir('icons', icons_path) if icons_dir is None: log.warning("Could not find icon file %s as icons directory" " could not be found", icon_filename) return None icon_filepath = os.path.join(icons_dir, icon_filename) if not os.path.exists(icon_filepath): log.warning("Could not find icon file: %s", icon_filepath) return None return icon_filepath
"""Helper to lookup UI resources from package""" import re import os from nxdrive.logging_config import get_logger log = get_logger(__name__) def find_icon(icon_filename): """Find the FS path of an icon on various OS binary packages""" import nxdrive nxdrive_path = os.path.dirname(nxdrive.__file__) icons_path = os.path.join(nxdrive_path, 'data', 'icons') cxfreeze_suffix = os.path.join('library.zip', 'nxdrive') app_resources = '/Contents/Resources/' if app_resources in nxdrive_path: # OSX frozen distribution, bundled as an app icons_path = re.sub(app_resources + ".*", app_resources + 'icons', nxdrive_path) elif nxdrive_path.endswith(cxfreeze_suffix): # Frozen distribution of nxdrive, data is out of the zip icons_path = nxdrive_path.replace(cxfreeze_suffix, 'icons') if not os.path.exists(icons_path): log.warning("Could not find the icons folder at: %s", icons_path) return None icon_filepath = os.path.join(icons_path, icon_filename) if not os.path.exists(icon_filepath): log.warning("Could not find icon file: %s", icon_filepath) return None return icon_filepath
Change coordinates order to Lat,Lng to match the frontend geocoding.
#!/usr/bin/env python # -*- coding: utf-8 -*- import json, os, sys from utils.file import load_json # Parse a json-formatted input instance and produce a csv file with # all involved coordinates in Lat,Lng order. def coord_to_csv(array): return str(array[1]) + ',' + str(array[0]) + '\n' def write_to_csv(input_file): input = load_json(input_file) lines = [] for v in input['vehicles']: if 'start' in v: lines.append(coord_to_csv(v['start'])) if 'end' in v: lines.append(coord_to_csv(v['end'])) for job in input['jobs']: lines.append(coord_to_csv(job['location'])) output_name = input_file[:input_file.rfind('.json')] + '.csv' with open(output_name, 'w') as output_file: for l in lines: output_file.write(l) if __name__ == "__main__": write_to_csv(sys.argv[1])
# -*- coding: utf-8 -*- import json, os, sys from utils.file import load_json # Parse a json-formatted input instance and produce a csv file with # all involved coordinates. def coord_to_csv(array): return str(array[0]) + ',' + str(array[1]) + '\n' def write_to_csv(input_file): input = load_json(input_file) lines = [] for v in input['vehicles']: if 'start' in v: lines.append(coord_to_csv(v['start'])) if 'end' in v: lines.append(coord_to_csv(v['end'])) for job in input['jobs']: lines.append(coord_to_csv(job['location'])) output_name = input_file[:input_file.rfind('.json')] + '.csv' with open(output_name, 'w') as output_file: for l in lines: output_file.write(l) if __name__ == "__main__": write_to_csv(sys.argv[1])
Fix another spurious on quick logout
/* * Copyright (C) 2015 SUSE Linux * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ (function () { 'use strict'; angular.module('janusHangouts') .directive('jhChat', jhChatDirective); function jhChatDirective() { return { restrict: 'EA', templateUrl: 'app/components/chat/jh-chat.html', scope: { messages: '=' }, link: jhChatLink, controllerAs: 'vm', bindToController: true, controller: JhChatCtrl }; function jhChatLink(scope) { scope.$watch('vm.messages.length', function(newVal) { /* Update messages */ if (newVal !== undefined) { // Scroll to bottom of messages list. var messagesList = document.getElementById('jh-chat-messages'); setTimeout(function() { if (messagesList) { messagesList.scrollTop = messagesList.scrollHeight; } }, 100); } }); } function JhChatCtrl() {} } })();
/* * Copyright (C) 2015 SUSE Linux * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. */ (function () { 'use strict'; angular.module('janusHangouts') .directive('jhChat', jhChatDirective); function jhChatDirective() { return { restrict: 'EA', templateUrl: 'app/components/chat/jh-chat.html', scope: { messages: '=' }, link: jhChatLink, controllerAs: 'vm', bindToController: true, controller: JhChatCtrl }; function jhChatLink(scope) { scope.$watch('vm.messages.length', function(newVal) { /* Update messages */ if (newVal !== undefined) { // Scroll to bottom of messages list. var messagesList = document.getElementById('jh-chat-messages'); setTimeout(function() { messagesList.scrollTop = messagesList.scrollHeight; }, 100); } }); } function JhChatCtrl() {} } })();
Add new ViewRepository method to get all Widgets for a given Wiew
<?php namespace Victoire\Bundle\WidgetBundle\Repository; use Doctrine\ORM\EntityRepository; use Victoire\Bundle\CoreBundle\Entity\View; /** * The widget Repository. */ class WidgetRepository extends EntityRepository { /** * Get all the widget within a list of ids. * * @param array $widgetIds * * @return \Doctrine\ORM\QueryBuilder */ public function getAllIn(array $widgetIds) { return $this->createQueryBuilder('widget') ->where('widget.id IN (:map)') ->setParameter('map', $widgetIds); } /** * Find all the widgets in a list of ids. * * @param array $widgetIds * * @return multitype: */ public function findAllIn(array $widgetIds) { $qb = $this->getAllIn($widgetIds); return $qb->getQuery()->getResult(); } /** * Find all widgets for a given View. * * @param View $view * @return multitype */ public function findAllWidgetsForView(View $view) { return $this->findAllIn($view->getWidgetsIds()); } }
<?php namespace Victoire\Bundle\WidgetBundle\Repository; use Doctrine\ORM\EntityRepository; /** * The widget Repository. */ class WidgetRepository extends EntityRepository { /** * Get all the widget within a list of ids. * * @param array $widgetIds * * @return \Doctrine\ORM\QueryBuilder */ public function getAllIn(array $widgetIds) { return $this->createQueryBuilder('widget') ->where('widget.id IN (:map)') ->setParameter('map', $widgetIds); } /** * Find all the widgets in a list of ids. * * @param array $widgetIds * * @return multitype: */ public function findAllIn(array $widgetIds) { $qb = $this->getAllIn($widgetIds); return $qb->getQuery()->getResult(); } }
Move code to a db library
package main import ( "fmt" "strconv" "github.com/blockfreight/blockfreight-alpha/blockfreight/bft/leveldb" ) func main() { //db_path := "bft-db/db" db_path := "bft-db" db, err := leveldb.OpenDB(db_path) defer leveldb.CloseDB(db) leveldb.HandleError(err, "Create or Open Database") //fmt.Println("Database created / open on "+db_path) for i := 1; i <= 50000; i++ { err = leveldb.InsertBFTX(strconv.Itoa(i), "Value for "+strconv.Itoa(i), db) //leveldb.HandleError(err, "Insert data for value "+strconv.Itoa(i)) //fmt.Println("Record saved!") } //Iteration var n int n, err = leveldb.Iterate(db) leveldb.HandleError(err, "Iteration") fmt.Println("Total: "+strconv.Itoa(n)) }
package main import ( "fmt" "strconv" "github.com/blockfreight/blockfreight-alpha/blockfreight/bft/leveldb" ) func main() { //db_path := "bft-db/db" db_path := "bft-db" db, err := leveldb.OpenDB(db_path) defer leveldb.CloseDB(db) leveldb.HandleError(err, "Create or Open Database") //fmt.Println("Database created / open on "+db_path) for i := 1; i <= 50000; i++ { err = leveldb.InsertBFTX(strconv.Itoa(i), "Value for "+strconv.Itoa(i), db) //leveldb.HandleError(err, "Insert data for value "+strconv.Itoa(i)) //fmt.Println("Record saved!") } //Iteration var n int n, err = leveldb.Iterate(db) leveldb.HandleError(err, "Iteration") fmt.Println("Total: "+strconv.Itoa(n)) }