text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Refactor functions & add params
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: # Do 1 more read if chunksize > filesize cont = False chunksize = filesize partnum = partnum + 1 tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) chunk = __read_write_block(fromfile, chunksize, tofile) chunksize *= 2 #### Private methods def __read_write_block(fromfile, n, tofile, offset = 0): stream = open(fromfile, 'rb') chunk = stream.read(n) stream.close() if not chunk: return fileobj = open(tofile, 'wb') fileobj.write(chunk) fileobj.close() return fileobj
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: cont = False chunksize = filesize chunk = __read_write_block(fromfile, chunksize) if not chunk: break partnum = partnum + 1 filename = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() chunksize *= 2 #### Private methods def __read_write_block(f, n): stream = open(f, 'rb') chunk = stream.read(n) stream.close() return chunk
Reset output store if pane is closed
/* @flow */ import { CompositeDisposable, Disposable } from "atom"; import ResizeObserver from "resize-observer-polyfill"; import React from "react"; import { reactFactory, OUTPUT_AREA_URI } from "./../utils"; import typeof store from "../store"; import OutputArea from "./../components/output-area"; export default class OutputPane { element = document.createElement("div"); disposer = new CompositeDisposable(); constructor(store: store) { this.element.classList.add("hydrogen", "watch-sidebar"); // HACK: Dispatch a window resize Event for the slider history to recompute // We should use native ResizeObserver once Atom ships with a newer version of Electron // Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62 const resizeObserver = new ResizeObserver(this.resize); resizeObserver.observe(this.element); this.disposer.add( new Disposable(() => { if (store.kernel) store.kernel.outputStore.clear(); }) ); reactFactory( <OutputArea store={store} />, this.element, null, this.disposer ); } resize = () => { window.dispatchEvent(new Event("resize")); }; getTitle = () => "Hydrogen Output Area"; getURI = () => OUTPUT_AREA_URI; getDefaultLocation = () => "right"; getAllowedLocations = () => ["left", "right", "bottom"]; destroy() { this.disposer.dispose(); this.element.remove(); } }
/* @flow */ import { CompositeDisposable } from "atom"; import ResizeObserver from "resize-observer-polyfill"; import React from "react"; import { reactFactory, OUTPUT_AREA_URI } from "./../utils"; import typeof store from "../store"; import OutputArea from "./../components/output-area"; export default class OutputPane { element = document.createElement("div"); disposer = new CompositeDisposable(); constructor(store: store) { this.element.classList.add("hydrogen", "watch-sidebar"); // HACK: Dispatch a window resize Event for the slider history to recompute // We should use native ResizeObserver once Atom ships with a newer version of Electron // Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62 const resizeObserver = new ResizeObserver(this.resize); resizeObserver.observe(this.element); reactFactory( <OutputArea store={store} />, this.element, null, this.disposer ); } resize = () => { window.dispatchEvent(new Event("resize")); }; getTitle = () => "Hydrogen Output Area"; getURI = () => OUTPUT_AREA_URI; getDefaultLocation = () => "right"; getAllowedLocations = () => ["left", "right", "bottom"]; destroy() { this.disposer.dispose(); this.element.remove(); } }
Simplify the request to Vimeo. We can either make a user request or album request.
// Define VimeoRequest var VimeoRequest = (function () { var getData = function(type, id, callback) { Zepto.ajax( { url: vimeoAPIRequestURL(type, id), dataType: 'jsonp', type: 'GET', cache: false, success: function (result) { callback(result); } } ); } var vimeoAPIRequestURL = function(type, id) { switch (type) { case 'user': return 'http://vimeo.com/api/v2/' + id + '/videos.json'; break; case 'album': return 'http://vimeo.com/api/v2/album/' + id + '/videos.json'; break; default: break; } } return { getData : getData } })();
// Define VimeoAjaxRequest var VimeoAjaxRequest = (function () { var fetchVideoData = function(vimeo_id, callback) { Zepto.ajax( { url: VimeoAjaxRequest.vimeoVideoAPIUrl(vimeo_id), dataType: 'jsonp', type: 'GET', cache: false, success: function (result) { callback(result[0]); } } ); } return { fetchVideoData : fetchVideoData, vimeoVideoAPIUrl: function(vimeo_id) { return 'http://vimeo.com/api/v2/video/' + vimeo_id + '.json'; }, getThumbnail: function(vimeo_id) { VimeoAjaxRequest.fetchVideoData(vimeo_id, function(response) { return response.thumbnail_medium; }); } } })();
Increase role removal timeout because bugs
module.exports = { handler: (msg, answer) => { if (msg.guild === undefined) return; const colorName = answer.rawArguments; if (colorName === '') { msg.reply('You must specify a colour. Use `bottie colours` to get a list of them.'); return; } const client = msg.client; const role = client.roleManager.getRoleByName(msg.guild, colorName); if (!role) { msg.reply(`The colour \`${colorName}\` does not exist!`); return; } msg.member.addRole(role) .then((member) => { msg.reply(`Enjoy your new colour ${role}!`); setTimeout(() => { const colorRoles = client.roleManager.filterColorRoles(member.roles, role); if (colorRoles.size === 0) return; member.removeRoles(colorRoles) .catch(e => msg.reply(`I couldn't remove your old colours. Reason: ${e}`)); }, 1000); }) .catch((error) => { msg.reply(`I couldn't give you the colour ${role}! Maybe I don't have permissions to manage that role.\n${error}`); }); }, cmd: 'colour', aliases: ['color'], args: ['colour name'], };
module.exports = { handler: (msg, answer) => { if (msg.guild === undefined) return; const colorName = answer.rawArguments; if (colorName === '') { msg.reply('You must specify a colour. Use `bottie colours` to get a list of them.'); return; } const client = msg.client; const role = client.roleManager.getRoleByName(msg.guild, colorName); if (!role) { msg.reply(`The colour \`${colorName}\` does not exist!`); return; } msg.member.addRole(role) .then((member) => { msg.reply(`Enjoy your new colour ${role}!`); setTimeout(() => { const colorRoles = client.roleManager.filterColorRoles(member.roles, role); if (colorRoles.size === 0) return; member.removeRoles(colorRoles) .catch(e => msg.reply(`I couldn't remove your old colours. Reason: ${e}`)); }, 500); }) .catch((error) => { msg.reply(`I couldn't give you the colour ${role}! Maybe I don't have permissions to manage that role.\n${error}`); }); }, cmd: 'colour', aliases: ['color'], args: ['colour name'], };
Add a rudimentary test for `bail`
'use strict'; var gulp = require('gulp'); var istanbul = require('gulp-istanbul'); var tapColorize = require('tap-colorize'); var tape = require('../'); gulp.task('test', function() { return gulp.src('fixtures/test/*.js') .pipe(tape({ bail: true, reporter: tapColorize() })); }); gulp.task('istanbul', function(cb) { gulp.src('fixtures/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', function() { gulp.src('fixtures/test/*.js') .on('error', cb) .on('end', cb) .pipe(tape()) .pipe(istanbul.writeReports({ reporters: ['lcov', 'text'] })) .pipe(istanbul.enforceThresholds({ thresholds: { global: { statements: 83, functions: 90, branches: 75, lines: 83, }, }, })); }); }); gulp.task('watch', function() { gulp.watch('fixtures/test/*.js', ['test']); });
'use strict'; var gulp = require('gulp'); var istanbul = require('gulp-istanbul'); var tapColorize = require('tap-colorize'); var tape = require('../'); gulp.task('test', function() { return gulp.src('fixtures/test/*.js') .pipe(tape({ reporter: tapColorize() })); }); gulp.task('istanbul', function(cb) { gulp.src('fixtures/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', function() { gulp.src('fixtures/test/*.js') .on('error', cb) .on('end', cb) .pipe(tape()) .pipe(istanbul.writeReports({ reporters: ['lcov', 'text'] })) .pipe(istanbul.enforceThresholds({ thresholds: { global: { statements: 83, functions: 90, branches: 75, lines: 83, }, }, })); }); });
Fix page boundary hit detection
import BaseRoute from '../_base'; export default BaseRoute.extend({ model: function() { return this.modelFor('page'); }, setupController: function(controller, page) { this.set('title', [page.get('treatise.title'), page.get('title')].join(' - ')); controller.set('controllers.page.boundsRect', page.get('bounds')); this._super(controller, page); }, actions: { // Hooks the page click event to navigate to the clicked section image pageClick: function(logicalPoint) { var sections = this.modelFor('page').get('sections'), x = logicalPoint.x, y = logicalPoint.y, section = sections.find(function(section) { var bounds = section.get('osBounds'); return (x >= bounds.x && x < bounds.x + bounds.width) && (y >= bounds.y && y < bounds.y + bounds.height); }); if(section) { this.transitionTo('page.section', section.get('page'), section.get('sortOrder')); } return false; } } });
import BaseRoute from '../_base'; export default BaseRoute.extend({ model: function() { return this.modelFor('page'); }, setupController: function(controller, page) { this.set('title', [page.get('treatise.title'), page.get('title')].join(' - ')); controller.set('controllers.page.boundsRect', page.get('bounds')); this._super(controller, page); }, actions: { // Hooks the page click event to navigate to the clicked section image pageClick: function(logicalPoint) { var sections = this.modelFor('page').get('sections'), x = logicalPoint.x, y = logicalPoint.y, section = sections.find(function(section) { var bounds = section.get('bounds'); return (x >= bounds.x && x < bounds.x + bounds.width) && (y >= bounds.y && y < bounds.y + bounds.height); }); if(section) { this.transitionTo('page.section', section.get('page'), section.get('sortOrder')); } return false; } } });
Fix really strange bug about conflicting models The bug: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>.) ... ERROR ====================================================================== ERROR: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>.) ---------------------------------------------------------------------- Traceback (most recent call last): eggs/nose-1.3.7-py2.7.egg/nose/loader.py|523| in makeTest return self._makeTest(obj, parent) eggs/nose-1.3.7-py2.7.egg/nose/loader.py|568| in _makeTest obj = transplant_class(obj, parent.__name__) eggs/nose-1.3.7-py2.7.egg/nose/util.py|642| in transplant_class class C(cls): eggs/Django-1.8.5-py2.7.egg/django/db/models/base.py|309| in __new__ new_class._meta.apps.register_model(new_class._meta.app_label, new_class) eggs/Django-1.8.5-py2.7.egg/django/apps/registry.py|221| in register_model (model_name, app_label, app_models[model_name], model)) RuntimeError: Conflicting 'c' models in application 'nose': <class 'manoseimas.compatibility_test.admin.TestGroup'> and <class 'nose.util.C'>. Have no idea what is going on here, but it seems related to this bug report: https://code.djangoproject.com/ticket/22280 To reproduce this bug it is enough to add this line: from manoseimas.compatibility_test.models import TestGroup to `manoseimas/compatibility_test/admin.py`, some how it conflicts with `nose`, but I'm not sure what `nose` has to do with Django apps and models? Anyway changing the way how `TestGroup` is imported fixes the bug.
from django.contrib import admin from manoseimas.compatibility_test import models class VotingInline(admin.TabularInline): model = models.TopicVoting raw_id_fields = [ 'voting', ] class ArgumentInline(admin.TabularInline): model = models.Argument class TopicAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [ ArgumentInline, VotingInline ] class TestGroupInline(admin.TabularInline): model = models.TestGroup class CompatTestAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [TestGroupInline] class TestGroupAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(models.CompatTest, CompatTestAdmin) admin.site.register(models.Topic, TopicAdmin) admin.site.register(models.TestGroup, TestGroupAdmin)
from django.contrib import admin from manoseimas.compatibility_test.models import CompatTest from manoseimas.compatibility_test.models import Topic from manoseimas.compatibility_test.models import TopicVoting from manoseimas.compatibility_test.models import Argument from manoseimas.compatibility_test.models import TestGroup class VotingInline(admin.TabularInline): model = TopicVoting raw_id_fields = [ 'voting', ] class ArgumentInline(admin.TabularInline): model = Argument class TopicAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [ ArgumentInline, VotingInline ] class TestGroupInline(admin.TabularInline): model = TestGroup class CompatTestAdmin(admin.ModelAdmin): list_display = ('name', 'description') list_filter = ('name',) inlines = [TestGroupInline] class TestGroupAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(CompatTest, CompatTestAdmin) admin.site.register(Topic, TopicAdmin) admin.site.register(TestGroup, TestGroupAdmin)
Change CodeStyling for more consistency - 2 empty lines after usestatement - No empty line after variable typedefinition
<?php namespace Becklyn\RadBundle\Entity\Extension; use Doctrine\ORM\Mapping as ORM; /** * */ trait EntityTimestamps { /** * @var \DateTime * @ORM\Column(name="time_created", type="datetime") */ private $timeCreated; /** * @var \DateTime|null * @ORM\Column(name="time_modified", type="datetime", nullable=true) */ private $timeModified; /** * @return \DateTime */ public function getTimeCreated () { return $this->timeCreated; } /** * @return \DateTime|null */ public function getTimeModified () { return $this->timeModified; } /** * @param \DateTime $timeModified */ public function setTimeModified (\DateTime $timeModified) { $this->timeModified = $timeModified; } }
<?php namespace Becklyn\RadBundle\Entity\Extension; use Doctrine\ORM\Mapping as ORM; /** * */ trait EntityTimestamps { /** * @var \DateTime * * @ORM\Column(name="time_created", type="datetime") */ private $timeCreated; /** * @var \DateTime|null * * @ORM\Column(name="time_modified", type="datetime", nullable=true) */ private $timeModified; /** * @return \DateTime */ public function getTimeCreated () { return $this->timeCreated; } /** * @return \DateTime|null */ public function getTimeModified () { return $this->timeModified; } /** * @param \DateTime $timeModified */ public function setTimeModified (\DateTime $timeModified) { $this->timeModified = $timeModified; } }
task.tests: Fix reference to python binary It was trying to use `python` as opposed to `python3`. Signed-off-by: Zack Cerza <d7cdf09fc0f0426e98c9978ee42da5d61fa54986@redhat.com>
import logging import pytest from io import StringIO from teuthology.exceptions import CommandFailedError log = logging.getLogger(__name__) class TestRun(object): """ Tests to see if we can make remote procedure calls to the current cluster """ def test_command_failed_label(self, ctx, config): result = "" try: ctx.cluster.run( args=["python3", "-c", "assert False"], label="working as expected, nothing to see here" ) except CommandFailedError as e: result = str(e) assert "working as expected" in result def test_command_failed_no_label(self, ctx, config): with pytest.raises(CommandFailedError): ctx.cluster.run( args=["python3", "-c", "assert False"], ) def test_command_success(self, ctx, config): result = StringIO() ctx.cluster.run( args=["python3", "-c", "print('hi')"], stdout=result ) assert result.getvalue().strip() == "hi"
import logging import pytest from io import StringIO from teuthology.exceptions import CommandFailedError log = logging.getLogger(__name__) class TestRun(object): """ Tests to see if we can make remote procedure calls to the current cluster """ def test_command_failed_label(self, ctx, config): result = "" try: ctx.cluster.run( args=["python", "-c", "assert False"], label="working as expected, nothing to see here" ) except CommandFailedError as e: result = str(e) assert "working as expected" in result def test_command_failed_no_label(self, ctx, config): with pytest.raises(CommandFailedError): ctx.cluster.run( args=["python", "-c", "assert False"], ) def test_command_success(self, ctx, config): result = StringIO() ctx.cluster.run( args=["python", "-c", "print('hi')"], stdout=result ) assert result.getvalue().strip() == "hi"
Add grunt test task for build
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), karma: { options: { files: [ 'test/support/test-runner.js', {pattern: 'src/**/*.js', included: false}, {pattern: 'test/**/*.js', included: false}, {pattern: 'bower_components/**/*.js', included: false} ], frameworks: ['requirejs', 'jasmine'] }, unit: { browsers: ['PhantomJS'], singleRun: true }, debug: { browsers: ['Chrome'] } } }); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('test', ['karma:unit']); grunt.registerTask('default', ['test']); };
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), karma: { options: { files: [ 'test/support/test-runner.js', {pattern: 'src/**/*.js', included: false}, {pattern: 'test/**/*.js', included: false}, {pattern: 'bower_components/**/*.js', included: false} ], frameworks: ['requirejs', 'jasmine'] }, unit: { browsers: ['PhantomJS'], singleRun: true }, debug: { browsers: ['Chrome'] } } }); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('default', ['karma:unit']); };
Update references to fix Language selection
class Cookie { static initialize(prefix) { this._prefix = prefix; } /* static set prefix(prefix) { this._prefix = prefix; } static get prefix( ) { return this._prefix; } */ static get(cookie) { let cookies = decodeURIComponent(document.cookie).split(";"); for(let i = 0; i < cookies.length; i++) { let selection = cookies[i]; while(selection.charAt(0) === " ") selection = selection.substring(1); if(selection.indexOf(this._prefix + "_" + cookie + "=") === 0) { return selection.substring((this._prefix + "_" + cookie + "=").length, selection.length); } } return false; } static set(cookie, value) { let date = new Date( ); date.setTime(date.getTime( ) + 3600 * 3600); document.cookie = this._prefix + "_" + cookie + "=" + value + "; " + date.toUTCString( ) + "; path=/"; } static remove(cookie) { let date = new Date( ); date.setTime(date.getTime( ) - 3600 * 3600); document.cookie = this._prefix + "_" + cookie + "= ; " + date.toUTCString( ) + "; path=/"; } }
class Cookie { static initialize(prefix) { this._prefix = prefix; } /* static set prefix(prefix) { this._prefix = prefix; } static get prefix( ) { return this._prefix; } */ static get(cookie) { let cookies = decodeURIComponent(document.cookie).split(";"); for(let i = 0; i < cookies.length; i++) { let selection = cookies[i]; while(selection.charAt(0) === " ") selection = selection.substring(1); if(selection.indexOf(this.prefix + "_" + cookie + "=") === 0) { return selection.substring((this.prefix + "_" + cookie + "=").length, selection.length); } } return false; } static set(cookie, value) { let date = new Date( ); date.setTime(date.getTime( ) + 3600 * 3600); document.cookie = this.prefix + "_" + cookie + "=" + value + "; " + date.toUTCString( ) + "; path=/"; } static remove(cookie) { let date = new Date( ); date.setTime(date.getTime( ) - 3600 * 3600); document.cookie = this.prefix + "_" + cookie + "= ; " + date.toUTCString( ) + "; path=/"; } }
Fix "Interface `io\streams\SocketOutputStream` not found
<?php namespace peer; /** * OutputStream that reads from a socket */ class SocketOutputStream extends \lang\Object implements \io\streams\OutputStream { protected $socket= null; /** * Constructor * * @param peer.Socket socket */ public function __construct(Socket $socket) { $this->socket= $socket; $this->socket->isConnected() || $this->socket->connect(); } /** * Write a string * * @param var arg */ public function write($arg) { $this->socket->write($arg); } /** * Flush this buffer * */ public function flush() { // NOOP, sockets cannot be flushed } /** * Close this buffer * */ public function close() { $this->socket->isConnected() && $this->socket->close(); } /** * Creates a string representation of this output strean * * @return string */ public function toString() { return nameof($this).'<'.$this->socket->toString().'>'; } }
<?php namespace peer; /** * OutputStream that reads from a socket */ class SocketOutputStream extends \lang\Object implements \io\streams\SocketOutputStream { protected $socket= null; /** * Constructor * * @param peer.Socket socket */ public function __construct(Socket $socket) { $this->socket= $socket; $this->socket->isConnected() || $this->socket->connect(); } /** * Write a string * * @param var arg */ public function write($arg) { $this->socket->write($arg); } /** * Flush this buffer * */ public function flush() { // NOOP, sockets cannot be flushed } /** * Close this buffer * */ public function close() { $this->socket->isConnected() && $this->socket->close(); } /** * Creates a string representation of this output strean * * @return string */ public function toString() { return nameof($this).'<'.$this->socket->toString().'>'; } }
Fix bug when magic method doesn't found any of properties
<?php /** * Created by PhpStorm. * User: xandros15 * Date: 2016-06-19 * Time: 17:22 */ namespace Xandros15\SlimPagination; use Slim\Http\Request; use Slim\Router; /** * @property Request request * @property Router router * @property int page * @property string name */ abstract class Page { /** @var array */ private $params; public function __construct(array $params) { $this->params = $params; } public function __get(string $name) { if (isset($this->params[$name])) { return $this->params[$name]; } throw new \InvalidArgumentException('Property `' . __CLASS__ . '::' . $name . '` doesn\'t exist'); } }
<?php /** * Created by PhpStorm. * User: xandros15 * Date: 2016-06-19 * Time: 17:22 */ namespace Xandros15\SlimPagination; use Slim\Http\Request; use Slim\Router; /** * @property Request request * @property Router router * @property int page * @property string name */ abstract class Page { /** @var array */ private $params; public function __construct(array $params) { $this->params = $params; } public function __get(string $name) { if (isset($params[$name])) { return $params[$name]; } throw new \InvalidArgumentException('Property `' . __CLASS__ . '::' . $name . '` doesn\'t exist'); } }
Use Ember.K instead of defining our own empty function
import Ember from 'ember'; var mixpanel = window.mixpanel; export default Ember.Mixin.create({ content: mixpanel, people: function() { return Ember.ObjectProxy.extend({ content: function() { if (mixpanel) { return mixpanel.people; } }.property(), set: function() { if (!this.get('content')) { return; } return this.get('content')['set'](arguments); }, unknownProperty: function(key) { if (!this.get('content')) { return Ember.K; } return this.get('content')[key].bind(this.get('content')); } }).create(); }.property(), unknownProperty: function(key) { if (!this.content) { return Ember.K; } var f = this._super(key); if (f) { return f.bind(this.content); } return f; } });
import Ember from 'ember'; var mixpanel = window.mixpanel; export default Ember.Mixin.create({ content: mixpanel, people: function() { return Ember.ObjectProxy.extend({ content: function() { if (mixpanel) { return mixpanel.people; } }.property(), set: function() { if (!this.get('content')) { return; } return this.get('content')['set'](arguments); }, unknownProperty: function(key) { if (!this.get('content')) { return function() {}; } return this.get('content')[key].bind(this.get('content')); } }).create(); }.property(), unknownProperty: function(key) { if (!this.content) { return function() {}; } var f = this._super(key); if (f) { return f.bind(this.content); } return f; } });
Fix BufferLoader for negative offset
package pack import ( "errors" "restic/backend" ) // Loader loads data from somewhere at a given offset. In contrast to // io.ReaderAt, off may be negative, in which case it references a position // relative to the end of the file (similar to Seek()). type Loader interface { Load(p []byte, off int64) (int, error) } // BackendLoader creates a Loader from a Backend and a Handle. type BackendLoader struct { Backend backend.Backend Handle backend.Handle } // Load returns data at the given offset. func (l BackendLoader) Load(p []byte, off int64) (int, error) { return l.Backend.Load(l.Handle, p, off) } // BufferLoader allows using a buffer as a Loader. type BufferLoader []byte // Load returns data at the given offset. func (b BufferLoader) Load(p []byte, off int64) (int, error) { switch { case off > int64(len(b)): return 0, errors.New("offset is larger than data") case off < -int64(len(b)): off = 0 case off < 0: off = int64(len(b)) + off } b = b[off:] return copy(p, b), nil }
package pack import ( "errors" "restic/backend" ) // Loader loads data from somewhere at a given offset. In contrast to // io.ReaderAt, off may be negative, in which case it references a position // relative to the end of the file (similar to Seek()). type Loader interface { Load(p []byte, off int64) (int, error) } // BackendLoader creates a Loader from a Backend and a Handle. type BackendLoader struct { Backend backend.Backend Handle backend.Handle } // Load returns data at the given offset. func (l BackendLoader) Load(p []byte, off int64) (int, error) { return l.Backend.Load(l.Handle, p, off) } // BufferLoader allows using a buffer as a Loader. type BufferLoader []byte // Load returns data at the given offset. func (b BufferLoader) Load(p []byte, off int64) (int, error) { switch { case off > int64(len(b)): return 0, errors.New("offset is larger than data") case off < -int64(len(b)): return 0, errors.New("offset starts before the beginning of the data") case off < 0: off = int64(len(b)) + off } b = b[off:] return copy(p, b), nil }
Return 409 for duplicate activity logging.
#!/usr/bin/env python from tastypie import fields from tastypie.authorization import DjangoAuthorization from tastypie.exceptions import ImmediateHttpResponse from tastypie.http import HttpConflict from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer from django.db import IntegrityError from panda.models import ActivityLog class ActivityLogResource(PandaModelResource): """ API resource for DataUploads. """ from panda.api.users import UserResource creator = fields.ForeignKey(UserResource, 'user', full=True) class Meta: queryset = ActivityLog.objects.all() resource_name = 'activity_log' allowed_methods = ['get', 'post'] authentication = PandaApiKeyAuthentication() authorization = DjangoAuthorization() serializer = PandaSerializer() def obj_create(self, bundle, request=None, **kwargs): """ Create an activity log for the accessing user. """ try: bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs) except IntegrityError: raise ImmediateHttpResponse(response=HttpConflict('Activity has already been recorded.')) return bundle
#!/usr/bin/env python from tastypie import fields from tastypie.authorization import DjangoAuthorization from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer from panda.models import ActivityLog class ActivityLogResource(PandaModelResource): """ API resource for DataUploads. """ from panda.api.users import UserResource creator = fields.ForeignKey(UserResource, 'user', full=True) class Meta: queryset = ActivityLog.objects.all() resource_name = 'activity_log' allowed_methods = ['get', 'post'] authentication = PandaApiKeyAuthentication() authorization = DjangoAuthorization() serializer = PandaSerializer() def obj_create(self, bundle, request=None, **kwargs): """ Create an activity log for the accessing user. """ bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs) return bundle
Fix package.json location in getVersion
#!/usr/bin/env node var http = require('http'), docopt = require('docopt').docopt, rosters = {}; var doc = "Usage:\n\ main.js [--roster ROSTER]\n\ main.js -h | --help\n\ main.js --version\n\ Options:\n\ -h --help Show this screen.\n\ --roster ROSTER Name of the roster module you would like to scrape.\n --version Show version." var options = docopt(doc, {help: true, version: getVersion()}); function getVersion(){ var pjson = require('../package.json'); return pjson.version }; console.log(options); /* http.get("url", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); */
#!/usr/bin/env node var http = require('http'), docopt = require('docopt').docopt, rosters = {}; var doc = "Usage:\n\ main.js [--roster ROSTER]\n\ main.js -h | --help\n\ main.js --version\n\ Options:\n\ -h --help Show this screen.\n\ --roster ROSTER Name of the roster module you would like to scrape.\n --version Show version." var options = docopt(doc, {help: true, version: getVersion()}); function getVersion(){ var pjson = require('./package.json'); return pjson.version }; console.log(options); /* http.get("url", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); */
Fix goog.require for XhrIoPool use
goog.require('goog.net.XhrIoPool'); var xhrIoPool; /** * * @param {string} dataUrl The url to request */ function getData(dataUrl) { log('Sending simple request for [' + dataUrl + ']'); if (!xhrIoPool) { xhrIoPool = new goog.net.XhrIoPool(); } xhrIoPool.getObject(onXhrRetrieved, dataUrl); function onXhrRetrieved(xhrRetrieved) { goog.events.listen(xhrRetrieved, goog.net.EventType.COMPLETE, function() { var obj = this.getResponseJson(); log('Received Json data object with title property of "' + obj['title'] + '"'); alert(obj['content']); goog.events.unlisten(xhrRetrieved, goog.net.EventType.COMPLETE); xhrIoPool.releaseObject(xhrRetrieved); }); xhrRetrieved.send(dataUrl); } } /** * Basic logging to an element called "log". * * @param {string} msg Message to display on page */ function log(msg) { document.getElementById('log').appendChild(document.createTextNode(msg)); document.getElementById('log').appendChild(document.createElement('br')); }
goog.require('goog.net.XhrIo'); var xhrIoPool; /** * Retrieve Json data using XhrIo's static send() method * * @param {string} dataUrl The url to request */ function getData(dataUrl) { log('Sending simple request for [' + dataUrl + ']'); if (!xhrIoPool) { xhrIoPool = new goog.net.XhrIoPool(); } xhrIoPool.getObject(onXhrRetrieved, dataUrl); function onXhrRetrieved(xhrRetrieved) { goog.events.listen(xhrRetrieved, goog.net.EventType.COMPLETE, function() { var obj = this.getResponseJson(); log('Received Json data object with title property of "' + obj['title'] + '"'); alert(obj['content']); }); xhrRetrieved.send(dataUrl); goog.events.unlisten(xhrRetrieved, goog.net.EventType.COMPLETE); xhrIoPool.releaseObject(xhrRetrieved); } } /** * Basic logging to an element called "log". * * @param {string} msg Message to display on page */ function log(msg) { document.getElementById('log').appendChild(document.createTextNode(msg)); document.getElementById('log').appendChild(document.createElement('br')); }
Fix a crash if there is no ~/.python/rc.py
import vx import math import os import sys _tick_functions = [] def _register_tick_function(f, front=False): if front: _tick_functions.insert(0, f) else: _tick_functions.append(f) def _tick(): for f in _tick_functions: f() vx.my_vx = _tick vx.register_tick_function = _register_tick_function vx.files = sys.argv[1:] import utils import scheduler import keybindings import windows import prompt def _default_start(): if len(vx.files) == 0: win = vx.window(vx.rows, vx.cols, 0, 0) win.blank() win.focus() else: d = math.floor(vx.rows / (len(vx.files))) y = 0 for f in vx.files: win = vx.window(d, vx.cols, y, 0) win.attach_file(f) y += d win.focus() vx.default_start = _default_start sys.path.append(os.path.expanduser('~/.python')) try: import rc except ImportError: pass # just means there was no ~/.python/rc module
import vx import math import os import sys _tick_functions = [] def _register_tick_function(f, front=False): if front: _tick_functions.insert(0, f) else: _tick_functions.append(f) def _tick(): for f in _tick_functions: f() vx.my_vx = _tick vx.register_tick_function = _register_tick_function vx.files = sys.argv[1:] import utils import scheduler import keybindings import windows import prompt def _default_start(): if len(vx.files) == 0: win = vx.window(vx.rows, vx.cols, 0, 0) win.blank() win.focus() else: d = math.floor(vx.rows / (len(vx.files))) y = 0 for f in vx.files: win = vx.window(d, vx.cols, y, 0) win.attach_file(f) y += d win.focus() vx.default_start = _default_start sys.path.append(os.path.expanduser('~/.python')) import rc
Remove loading class when finished loading.
$().ready(() => { loadContentSection().then(() =>{ $('body').removeClass('loading'); }); }); $("body").on('click', '.keyword', function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $("body").on('click', ".close", function(event) { event.stopPropagation(); $(".extended").removeClass("extended"); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); $("body").on('click', ".active .item", function() { $(".item").off("click"); const url = $(this).attr("data-url"); window.location.href = url; }); $("body").on('click', '.level-name', function() { const isThisExtended = $(this).parent().hasClass("extended"); $(".extended").removeClass("extended"); if (!isThisExtended) { $(this).parent().addClass("extended"); } });
$().ready(loadContentSection); $("body").on('click', '.keyword', function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $("body").on('click', ".close", function(event) { event.stopPropagation(); $(".extended").removeClass("extended"); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); $("body").on('click', ".active .item", function() { $(".item").off("click"); const url = $(this).attr("data-url"); window.location.href = url; }); $("body").on('click', '.level-name', function() { const isThisExtended = $(this).parent().hasClass("extended"); $(".extended").removeClass("extended"); if (!isThisExtended) { $(this).parent().addClass("extended"); } });
Update safeLoad to load to fix errer: Function yaml.safeLoad is removed in js-yaml 4. Use yaml.load instead, which is now safe by default.
// Common configuration for webpacker loaded from config/webpacker.yml const { join, resolve } = require('path') const { env } = require('process') const { load } = require('js-yaml') const { readFileSync } = require('fs') const configPath = resolve('config', 'webpacker.yml') const loadersDir = join(__dirname, 'loaders') const settings = load(readFileSync(configPath), 'utf8')[env.NODE_ENV] function removeOuterSlashes(string) { return string.replace(/^\/*/, '').replace(/\/*$/, '') } function formatPublicPath(host = '', path = '') { let formattedHost = removeOuterSlashes(host) if (formattedHost && !/^http/i.test(formattedHost)) { formattedHost = `//${formattedHost}` } const formattedPath = removeOuterSlashes(path) return `${formattedHost}/${formattedPath}/` } const output = { path: resolve('public', settings.public_output_path), publicPath: formatPublicPath(env.ASSET_HOST, settings.public_output_path) } module.exports = { settings, env, loadersDir, output }
// Common configuration for webpacker loaded from config/webpacker.yml const { join, resolve } = require('path') const { env } = require('process') const { safeLoad } = require('js-yaml') const { readFileSync } = require('fs') const configPath = resolve('config', 'webpacker.yml') const loadersDir = join(__dirname, 'loaders') const settings = safeLoad(readFileSync(configPath), 'utf8')[env.NODE_ENV] function removeOuterSlashes(string) { return string.replace(/^\/*/, '').replace(/\/*$/, '') } function formatPublicPath(host = '', path = '') { let formattedHost = removeOuterSlashes(host) if (formattedHost && !/^http/i.test(formattedHost)) { formattedHost = `//${formattedHost}` } const formattedPath = removeOuterSlashes(path) return `${formattedHost}/${formattedPath}/` } const output = { path: resolve('public', settings.public_output_path), publicPath: formatPublicPath(env.ASSET_HOST, settings.public_output_path) } module.exports = { settings, env, loadersDir, output }
Fix the mispelling of the addObservers method
/* var Entry = function(title, content, tags, observers) { this.title = title; this.content = content; this.tags = tags; // TODO esto lo vamos a hacer asi al final ?? */ var Entry = function() { this.title = null; this.content = null; this.tags = null; this.comments = []; this.likes = 0; this.observers = []; }; Entry.prototype.comment = function(user, text) { var c = new Comment(user, text); this.comments.push(c); }; Entry.prototype.like = function() { this.likes++; }; Entry.prototype.update = function(title, content, tags) { this.title = title; this.content = content; this.tags = tags; for (var o in this.observers) { o.notify(); } }; Entry.prototype.addObservers = function(obs) { this.observers.push(obs); }; /* Entry.prototype.destroy = function() { delete this; // Mirar si esto es correcto o no, aunque fijandolo a null se borra la ref }; */
/* var Entry = function(title, content, tags, observers) { this.title = title; this.content = content; this.tags = tags; // TODO esto lo vamos a hacer asi al final ?? */ var Entry = function() { this.title = null; this.content = null; this.tags = null; this.comments = []; this.likes = 0; this.observers = []; }; Entry.prototype.comment = function(user, text) { var c = new Comment(user, text); this.comments.push(c); }; Entry.prototype.like = function() { this.likes++; }; Entry.prototype.update = function(title, content, tags) { this.title = title; this.content = content; this.tags = tags; for (var o in this.observers) { o.notify(); } }; Entry.prototype.addObserver = function(obs) { this.observers.push(obs); }; /* Entry.prototype.destroy = function() { delete this; // Mirar si esto es correcto o no, aunque fijandolo a null se borra la ref }; */
Fix error `cannot read split of undefined`
(function () { var options = (function () { // Holy shit var optionsArray var result = {} try { optionsArray = location.href.split('?')[1].split('#')[0].split('=') } catch (e) { return {} } optionsArray.forEach(function (value, index) { // 0 is a property name and 1 the value of 0 if (index % 2 === 1) { return } result[value] = optionsArray[index + 1] }); return result }()) var toLoadSrc; if (options.ionic === 'build') { toLoadSrc = 'lib/ionic/local/ionic.bundle.js' } else if (options.ionic === 'local' || !options.ionic) { toLoadSrc = 'lib/ionic/js/ionic.bundle.js' } else { // Use options.ionic as ionic version toLoadSrc = '//code.ionicframework.com/' + options.ionic + '/js/ionic.bundle.min.js' } console.log('Ionic From') console.log(toLoadSrc) document.write('<script src="'+ toLoadSrc +'"></script>') }())
(function () { var options = (function () { // Holy shit var optionsArray = location.href.split('?')[1].split('#')[0].split('=') var result = {} optionsArray.forEach(function (value, index) { // 0 is a property name and 1 the value of 0 if (index % 2 === 1) { return } result[value] = optionsArray[index + 1] }); return result }()) var toLoadSrc; if (options.ionic === 'build') { toLoadSrc = 'lib/ionic/local/ionic.bundle.js' } else if (options.ionic === 'local' || !options.ionic) { toLoadSrc = 'lib/ionic/js/ionic.bundle.js' } else { // Use options.ionic as ionic version toLoadSrc = '//code.ionicframework.com/' + options.ionic + '/js/ionic.bundle.min.js' } console.log('Ionic From') console.log(toLoadSrc) document.write('<script src="'+ toLoadSrc +'"></script>') }())
Fix initial buf variable to act as an array
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i]
Fix PSR compliance in test files.
<?php /** * @package BC Security */ namespace BlueChip\Security\Tests\Cases; use BlueChip\Security\Plugin; class PluginTest extends \BlueChip\Security\Tests\TestCase { /** * @var \BlueChip\Security\Plugin */ protected $bc_security; /** * Setup test. */ public function setUp() { global $wpdb; parent::setUp(); $this->bc_security = new Plugin('', $wpdb); } /** * Test class instances. */ public function test_instances() { $this->assertInstanceOf(Plugin::class, $this->bc_security); $this->assertInstanceOf(\wpdb::class, $this->readAttribute($this->bc_security, 'wpdb')); } }
<?php /** * @package BC Security */ namespace BlueChip\Security\Tests\Cases; use BlueChip\Security\Plugin; class PluginTest extends \BlueChip\Security\Tests\TestCase { /** * @var \BlueChip\Security\Plugin */ protected $bc_security; /** * Setup test. */ public function setUp() { global $wpdb; parent::setUp(); $this->bc_security = new Plugin('', $wpdb); } /** * Test class instances. */ function test_instances() { $this->assertInstanceOf(Plugin::class, $this->bc_security); $this->assertInstanceOf(\wpdb::class, $this->readAttribute($this->bc_security, 'wpdb')); } }
Add type=message for high priority notifications
var request = require('request'); var url = require('url'); var messageJson = function (token, message, cb) { if (!token) { cb(new Error('Needs token')); return; } var result = {'token':token, 'type': 'message'}; if (message) { result.message = message; } cb(null,result); }; module.exports.sendMessage = function (endpoint, token, message, cb) { var urlObject = url.parse(endpoint); if (urlObject.protocol !== 'https:') { cb(new Error('Requires https')); return; } messageJson(token,message,function(err,result){ if (err) { cb(err); return; } request.post(endpoint,{ formData:result, json:true },function(err, res, body){ cb(err,res); }); }); }; module.exports.messageJson = messageJson;
var request = require('request'); var url = require('url'); var messageJson = function (token, message, cb) { if (!token) { cb(new Error('Needs token')); return; } var result = {'token':token}; if (message) { result.message = message; } cb(null,result); }; module.exports.sendMessage = function (endpoint, token, message, cb) { var urlObject = url.parse(endpoint); if (urlObject.protocol !== 'https:') { cb(new Error('Requires https')); return; } messageJson(token,message,function(err,result){ if (err) { cb(err); return; } request.post(endpoint,{ formData:result, json:true },function(err, res, body){ cb(err,res); }); }); }; module.exports.messageJson = messageJson;
Set the default block set to basic
<?php namespace Concrete\Package\CkeditorContent\Block\CkeditorContent; use \Concrete\Core\Block\BlockController; use Loader; use Core; class Controller extends BlockController { protected $btName = 'Content (CKEditor)'; protected $btTable = 'btCKEditorContent'; protected $btCacheBlockOutput = true; protected $btCacheBlockOutputOnPost = true; protected $btCacheBlockOutputForRegisteredUsers = false; protected $btSupportsInlineEdit = true; protected $btSupportsInlineAdd = true; protected $btDefaultSet = 'basic'; public function getSearchableContent() { return $this->content; } public function getBlockTypeName() { return t($this->btName); } public function getBlockTypeDescription() { return t("A content block based on CKEditor"); } public function save($args) { parent::save($args); } public function add(){ $this->requireAsset('ckeditor'); } public function edit() { $this->requireAsset('ckeditor'); } }
<?php namespace Concrete\Package\CkeditorContent\Block\CkeditorContent; use \Concrete\Core\Block\BlockController; use Loader; use Core; class Controller extends BlockController { protected $btName = 'Content (CKEditor)'; protected $btTable = 'btCKEditorContent'; protected $btCacheBlockOutput = true; protected $btCacheBlockOutputOnPost = true; protected $btCacheBlockOutputForRegisteredUsers = false; protected $btSupportsInlineEdit = true; protected $btSupportsInlineAdd = true; public function getSearchableContent() { return $this->content; } public function getBlockTypeName() { return t($this->btName); } public function getBlockTypeDescription() { return t("A content block based on CKEditor"); } public function save($args) { parent::save($args); } public function add(){ $this->requireAsset('ckeditor'); } public function edit() { $this->requireAsset('ckeditor'); } }
Move social widgets to the top
<div id="sidebar" class="x2"> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-teaser--bolshaya-medvedica'); ?> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-social--twitter'); ?> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-social--vk'); ?> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-social--facebook'); ?> <?php if ( !is_tag('juno') ) get_template_part('widget', 'sidebar-posts--juno'); ?> <?php if ( !is_tag('rasskazy-o-zvezdah') ) get_template_part('widget', 'sidebar-posts--stars-stories'); ?> <?php if ( !is_tag('rasskazy-o-sozvezdiyah') ) get_template_part('widget', 'sidebar-posts--constellations-stories'); ?> <?php if ( !is_home() && !is_category('wiki') ) get_template_part('widget', 'sidebar-wiki'); ?> </div>
<div id="sidebar" class="x2"> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-teaser--bolshaya-medvedica'); ?> <?php if ( !is_tag('juno') ) get_template_part('widget', 'sidebar-posts--juno'); ?> <?php if ( !is_tag('rasskazy-o-zvezdah') ) get_template_part('widget', 'sidebar-posts--stars-stories'); ?> <?php if ( !is_tag('rasskazy-o-sozvezdiyah') ) get_template_part('widget', 'sidebar-posts--constellations-stories'); ?> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-social--twitter'); ?> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-social--vk'); ?> <?php if ( !is_search() ) get_template_part('widget', 'sidebar-social--facebook'); ?> <?php if ( !is_home() && !is_category('wiki') ) get_template_part('widget', 'sidebar-wiki'); ?> </div>
Remove incorrect JSON struct tag
/* package proto defines a set of structures used to negotiate an update between an an application (the client) and an Equinox update service. */ package proto import "time" type PatchKind string const ( PatchNone PatchKind = "none" PatchBSDiff PatchKind = "bsdiff" ) type Request struct { AppID string `json:"app_id"` Channel string `json:"channel"` OS string `json:"os"` Arch string `json:"arch"` GoARM string `json:"goarm"` TargetVersion string `json:"target_version"` CurrentVersion string `json:"current_version"` CurrentSHA256 string `json:"current_sha256"` } type Response struct { Available bool `json:"available"` DownloadURL string `json:"download_url"` Checksum string `json:"checksum"` Signature string `json:"signature"` Patch PatchKind `json:"patch_type"` Version string `json:"version"` Release Release `json:"release"` } type Release struct { Title string `json:"title"` Version string `json:"version"` Description string `json:"description"` CreateDate time.Time `json:"create_date"` }
/* package proto defines a set of structures used to negotiate an update between an an application (the client) and an Equinox update service. */ package proto import "time" type PatchKind string const ( PatchNone PatchKind = "none" PatchBSDiff PatchKind = "bsdiff" ) type Request struct { AppID string `json:"app_id"` Channel string `json:"channel"` OS string `json:"os"` Arch string `json:"arch"` GoARM string `json:"goarm"` TargetVersion string `json:"target_version"` CurrentVersion string `json:"current_version"` CurrentSHA256 string `json:"current_sha256"` } type Response struct { Available bool `json:"available"` DownloadURL string `json:"download_url"` Checksum string `json:"checksum"` Signature string `json:"signature"` Patch PatchKind `json:"patch_type,string"` Version string `json:"version"` Release Release `json:"release"` } type Release struct { Title string `json:"title"` Version string `json:"version"` Description string `json:"description"` CreateDate time.Time `json:"create_date"` }
Add unrate action to rating.
package com.jakewharton.trakt.enumerations; import java.util.HashMap; import java.util.Map; import com.jakewharton.trakt.TraktEnumeration; public enum Rating implements TraktEnumeration { Love("love"), Hate("hate"), Unrate("unrate"); private final String value; private Rating(String value) { this.value = value; } @Override public String toString() { return this.value; } private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); static { for (Rating via : Rating.values()) { STRING_MAPPING.put(via.toString().toUpperCase(), via); } } public static Rating fromValue(String value) { return STRING_MAPPING.get(value.toUpperCase()); } }
package com.jakewharton.trakt.enumerations; import java.util.HashMap; import java.util.Map; import com.jakewharton.trakt.TraktEnumeration; public enum Rating implements TraktEnumeration { Love("love"), Hate("hate"); private final String value; private Rating(String value) { this.value = value; } @Override public String toString() { return this.value; } private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); static { for (Rating via : Rating.values()) { STRING_MAPPING.put(via.toString().toUpperCase(), via); } } public static Rating fromValue(String value) { return STRING_MAPPING.get(value.toUpperCase()); } }
Reduce array length for easier inspection
'use strict'; var round = require( '@stdlib/math/base/special/round' ); var randu = require( '@stdlib/math/base/random/randu' ); var daxpy = require( './../lib' ).wasm(); var xbytes; var ybytes; var x; var y; var i; // Allocate space on the heap: xbytes = daxpy.malloc( 10 * 8 ); // 8 bytes per double ybytes = daxpy.malloc( 10 * 8 ); // Create Float64Array views: x = new Float64Array( xbytes.buffer, xbytes.byteOffset, 10 ); y = new Float64Array( ybytes.buffer, ybytes.byteOffset, 10 ); // Set data on the heap... for ( i = 0; i < x.length; i++ ) { x[ i ] = round( randu()*100.0 ); y[ i ] = round( randu()*10.0 ); } console.log( x ); console.log( y ); daxpy( x.length, 5.0, xbytes, 1, ybytes, -1 ); console.log( y ); // Free allocated memory: daxpy.free( xbytes ); daxpy.free( ybytes );
'use strict'; var round = require( '@stdlib/math/base/special/round' ); var randu = require( '@stdlib/math/base/random/randu' ); var daxpy = require( './../lib' ).wasm(); var xbytes; var ybytes; var x; var y; var i; // Allocate space on the heap: xbytes = daxpy.malloc( 100 * 8 ); // 8 bytes per double ybytes = daxpy.malloc( 100 * 8 ); // Create Float64Array views: x = new Float64Array( xbytes.buffer, xbytes.byteOffset, 100 ); y = new Float64Array( ybytes.buffer, ybytes.byteOffset, 100 ); // Set data on the heap... for ( i = 0; i < x.length; i++ ) { x[ i ] = round( randu()*100.0 ); y[ i ] = round( randu()*10.0 ); } console.log( x ); console.log( y ); daxpy( x.length, 5.0, xbytes, 1, ybytes, -1 ); console.log( y ); // Free allocated memory: daxpy.free( xbytes ); daxpy.free( ybytes );
Add additional logging to display progression
<?php require __DIR__ . '/../vendor/autoload.php'; use Curl\MultiCurl; $multi_curl = new MultiCurl(); $multi_curl->beforeSend(function ($instance) { echo 'about to make request ' . $instance->id . ': "' . $instance->url . '".' . "\n"; }); $multi_curl->success(function ($instance) use (&$request_count, $multi_curl) { echo 'call to "' . $instance->url . '" was successful.' . "\n"; // Stop pending requests and attempt to stop active requests after the first // successful request. $multi_curl->stop(); }); $multi_curl->error(function ($instance) { echo 'call to "' . $instance->url . '" was unsuccessful.' . "\n"; }); // Count the number of completed requests. $request_count = 0; $multi_curl->complete(function ($instance) use (&$request_count) { echo 'call to "' . $instance->url . '" completed.' . "\n"; $request_count += 1; }); $multi_curl->addGet('https://httpbin.org/delay/4'); $multi_curl->addGet('https://httpbin.org/delay/1'); $multi_curl->addGet('https://httpbin.org/delay/3'); $multi_curl->addGet('https://httpbin.org/delay/2'); $multi_curl->start(); assert($request_count === 1);
<?php require __DIR__ . '/../vendor/autoload.php'; use Curl\MultiCurl; $multi_curl = new MultiCurl(); // Count the number of completed requests. $request_count = 0; $multi_curl->complete(function ($instance) use (&$request_count) { $request_count += 1; }); $multi_curl->success(function ($instance) use (&$request_count, $multi_curl) { echo 'call to "' . $instance->url . '" was successful.' . "\n"; // Stop pending requests and attempt to stop active requests after the first // successful request. $multi_curl->stop(); }); $multi_curl->addGet('https://httpbin.org/delay/4'); $multi_curl->addGet('https://httpbin.org/delay/1'); $multi_curl->addGet('https://httpbin.org/delay/3'); $multi_curl->addGet('https://httpbin.org/delay/2'); $multi_curl->start(); assert($request_count === 1);
Access code button in row widget is now secondary
<div class="pure-g centered-row"> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <?php echo _('If you do not want to check in, you can still use the access code!') ; ?> <p> <p> <?php echo _('Just ask our staff about the Wi-Fi.') ; ?> <p> </div> </div> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <a href="<?php echo $retry_url; ?>" class="pure-button button-secondary"> <i class="fa fa-play fa-lg"></i> <?php echo _('Enter access code'); ?> </a> </p> </div> </div> </div>
<div class="pure-g centered-row"> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <?php echo _('If you do not want to check in, you can still use the access code!') ; ?> <p> <p> <?php echo _('Just ask our staff about the Wi-Fi.') ; ?> <p> </div> </div> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <a href="<?php echo $retry_url; ?>" class="pure-button pure-button-primary"> <i class="fa fa-play fa-lg"></i> <?php echo _('Enter access code'); ?> </a> </p> </div> </div> </div>
Add array of sheet types
<?php namespace RadDB\Console\Commands; use Illuminate\Console\Command; class ImportDataPage extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:name'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Array of spreadsheet types * * @var array */ protected $sheetType = [ "RAD", "FLUORO", "MAMMO_HOL", "MAMMO_SIE", "SBB", ]; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // } }
<?php namespace RadDB\Console\Commands; use Illuminate\Console\Command; class ImportDataPage extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:name'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // } }
Replace short array syntax to compatible with PHP 5.3
<?php namespace HieuLe\BodyClasses; class Body { /** * Internal classes * * @var array */ protected $classes = array(); /** * Append new class * * @param string|array $classes */ public function addClasses($classes) { if (!is_array($classes)) { $classes = array($classes); } foreach ($classes as $class) { $this->classes[] = $class; } $this->classes = array_unique($this->classes); } /** * Get all internal classes as a string * * @return string */ public function getClasses() { return implode(' ', $this->classes); } /** * Get the internal class array * * @return array */ public function getClassArray() { return $this->classes; } }
<?php namespace HieuLe\BodyClasses; class Body { /** * Internal classes * * @var array */ protected $classes = []; /** * Append new class * * @param string|array $classes */ public function addClasses($classes) { if (!is_array($classes)) { $classes = [$classes]; } foreach ($classes as $class) { $this->classes[] = $class; } $this->classes = array_unique($this->classes); } /** * Get all internal classes as a string * * @return string */ public function getClasses() { return implode(' ', $this->classes); } /** * Get the internal class array * * @return array */ public function getClassArray() { return $this->classes; } }
Exclude tests folder from package
from setuptools import find_packages, setup version = '6.5.1' extras_require = { 'images': [ 'Pillow>=2.8.1,<2.9', ], } setup( name='incuna-test-utils', packages=find_packages(exclude=['tests']), include_package_data=True, version=version, description='Custom TestCases and other test helpers for Django apps', long_description=open('README.md').read(), author='Incuna', author_email='admin@incuna.com', url='https://github.com/incuna/incuna-test-utils/', install_requires=[], extras_require=extras_require, zip_safe=False, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Testing', ], )
from setuptools import find_packages, setup version = '6.5.1' extras_require = { 'images': [ 'Pillow>=2.8.1,<2.9', ], } setup( name='incuna-test-utils', packages=find_packages(), include_package_data=True, version=version, description='Custom TestCases and other test helpers for Django apps', long_description=open('README.md').read(), author='Incuna', author_email='admin@incuna.com', url='https://github.com/incuna/incuna-test-utils/', install_requires=[], extras_require=extras_require, zip_safe=False, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Testing', ], )
Return the stream from all tasks so deps work.
var gulp = require('gulp'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var sass = require('gulp-sass'); gulp.task('scripts', function() { return gulp.src(['resources/public/js/lib/*.js']) .pipe(uglify()) .pipe(gulp.dest('resources/public/js')); }); gulp.task('copy', function() { return gulp.src('bower_components/normalize-css/normalize.css') .pipe(rename('_normalize.scss')) .pipe(gulp.dest('bower_components/normalize-css')); }); gulp.task('styles', ['copy'], function() { var opts = { outputStyle: 'compressed', includePaths: [ 'bower_components/bourbon/app/assets/stylesheets', 'bower_components/sass-mediaqueries', 'bower_components/normalize-css' ] }; return gulp.src('scss/style.scss') .pipe(sass(opts)) .pipe(gulp.dest('resources/public/css')); }); gulp.task('watch', function() { gulp.watch('scss/**/*.scss', ['styles']); }); gulp.task('build', ['scripts', 'copy', 'styles']); gulp.task('default', ['build', 'watch']);
var gulp = require('gulp'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var sass = require('gulp-sass'); gulp.task('scripts', function() { return gulp.src(['resources/public/js/lib/*.js']) .pipe(uglify()) .pipe(gulp.dest('resources/public/js')); }); gulp.task('copy', function() { gulp.src('bower_components/normalize-css/normalize.css') .pipe(rename('_normalize.scss')) .pipe(gulp.dest('bower_components/normalize-css')); }); gulp.task('styles', ['copy'], function() { var opts = { outputStyle: 'compressed', includePaths: [ 'bower_components/bourbon/app/assets/stylesheets', 'bower_components/sass-mediaqueries', 'bower_components/normalize-css' ] }; gulp.src('scss/style.scss') .pipe(sass(opts)) .pipe(gulp.dest('resources/public/css')); }); gulp.task('watch', function() { gulp.watch('scss/**/*.scss', ['styles']); }); gulp.task('build', ['scripts', 'copy', 'styles']); gulp.task('default', ['build', 'watch']);
Add cache busting hash to scripts, etc. For cache busting we can simply append the hash that Webpack generates on each build to the scripts, stylesheets, etc. that it outputs. Actually the 'html-webpack-plugin' makes this laughably easy to do here by adding the 'hash' option.
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: path.resolve('js', 'index.js'), output: { path: path.resolve('BuildOutput'), filename: '[name].js' }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: '/node_modules/' }, { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ] } ] }, resolve: { extensions: ['.js', '.jsx'] }, plugins: [ new HtmlWebpackPlugin({ title: 'Tauranga Web Meetup Webpack Demo', hash: true, template: path.resolve('Index.html') }) ], devtool: 'source-map' }
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: path.resolve('js', 'index.js'), output: { path: path.resolve('BuildOutput'), filename: '[name].js' }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: '/node_modules/' }, { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ] } ] }, resolve: { extensions: ['.js', '.jsx'] }, plugins: [ new HtmlWebpackPlugin({ title: 'Tauranga Web Meetup Webpack Demo', template: path.resolve('Index.html') }) ], devtool: 'source-map' }
Comment out CopyR test for now.
#!/usr/bin/env python __author__ = 'Shyue Ping Ong' __copyright__ = 'Copyright 2014, The Materials Virtual Lab' __version__ = '0.1' __maintainer__ = 'Shyue Ping Ong' __email__ = 'ongsp@ucsd.edu' __date__ = '1/24/14' import unittest import os import shutil from monty.shutil import copy_r # class CopyRTest(unittest.TestCase): # # def setUp(self): # os.mkdir("cpr_src") # with open(os.path.join("cpr_src", "test"), "w") as f: # f.write("what") # # def test_recursive_copy(self): # copy_r(".", "cpr_dst") # self.assertTrue(os.path.exists(os.path.join("cpr_dst", "cpr_src", # "test"))) # # def tearDown(self): # shutil.rmtree("cpr_src") # shutil.rmtree("cpr_dst") if __name__ == "__main__": unittest.main()
#!/usr/bin/env python __author__ = 'Shyue Ping Ong' __copyright__ = 'Copyright 2014, The Materials Virtual Lab' __version__ = '0.1' __maintainer__ = 'Shyue Ping Ong' __email__ = 'ongsp@ucsd.edu' __date__ = '1/24/14' import unittest import os import shutil from monty.shutil import copy_r class CopyRTest(unittest.TestCase): def setUp(self): os.mkdir("cpr_src") with open(os.path.join("cpr_src", "test"), "w") as f: f.write("what") def test_recursive_copy(self): copy_r(".", "cpr_dst") self.assertTrue(os.path.exists(os.path.join("cpr_dst", "cpr_src", "test"))) def tearDown(self): shutil.rmtree("cpr_src") shutil.rmtree("cpr_dst") if __name__ == "__main__": unittest.main()
Fix cells switching order on doublesplit Thanks to @Luka967 Fixes #644 and #289
var Cell = require('./Cell'); function PlayerCell() { Cell.apply(this, Array.prototype.slice.call(arguments)); this.cellType = 0; this._canRemerge = false; } module.exports = PlayerCell; PlayerCell.prototype = new Cell(); // Main Functions PlayerCell.prototype.canEat = function (cell) { return true; // player cell can eat anyone }; PlayerCell.prototype.getSpeed = function (dist) { var speed = 2.2 * Math.pow(this._size, -0.439); speed *= 40 * this.gameServer.config.playerSpeed; return Math.min(dist, speed) / dist; }; PlayerCell.prototype.onAdd = function (gameServer) { // Add to player nodes list this.gameServer.nodesPlayer.unshift(this); }; PlayerCell.prototype.onRemove = function (gameServer) { // Remove from player cell list var index = this.owner.cells.indexOf(this); if (index != -1) this.owner.cells.splice(index, 1); index = this.gameServer.nodesPlayer.indexOf(this); if (index != -1) this.gameServer.nodesPlayer.splice(index, 1); };
var Cell = require('./Cell'); function PlayerCell() { Cell.apply(this, Array.prototype.slice.call(arguments)); this.cellType = 0; this._canRemerge = false; } module.exports = PlayerCell; PlayerCell.prototype = new Cell(); // Main Functions PlayerCell.prototype.canEat = function (cell) { return true; // player cell can eat anyone }; PlayerCell.prototype.getSpeed = function (dist) { var speed = 2.2 * Math.pow(this._size, -0.439); speed *= 40 * this.gameServer.config.playerSpeed; return Math.min(dist, speed) / dist; }; PlayerCell.prototype.onAdd = function (gameServer) { // Add to player nodes list this.gameServer.nodesPlayer.push(this); }; PlayerCell.prototype.onRemove = function (gameServer) { // Remove from player cell list var index = this.owner.cells.indexOf(this); if (index != -1) this.owner.cells.splice(index, 1); index = this.gameServer.nodesPlayer.indexOf(this); if (index != -1) this.gameServer.nodesPlayer.splice(index, 1); };
Fix the devserver default address setting name.
# # Include your development machines hostnames here. # # NOTE: this is not strictly needed, as Django doesn't enforce # the check if DEBUG==True. But Just in case you wanted to disable # it temporarily, this could be a good thing to have your hostname # here. # # If you connect via http://localhost:8000/, everything is already OK. TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.debug', ) ALLOWED_HOSTS += [ 'localhost', 'chani.licorn.org', 'leto.licorn.org', 'gurney.licorn.org' ] INSTALLED_APPS += ('django_nose', 'devserver', ) DEVSERVER_DEFAULT_ADDR = '0.0.0.0' DEVSERVER_DEFAULT_PORT = 8000 TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
# # Include your development machines hostnames here. # # NOTE: this is not strictly needed, as Django doesn't enforce # the check if DEBUG==True. But Just in case you wanted to disable # it temporarily, this could be a good thing to have your hostname # here. # # If you connect via http://localhost:8000/, everything is already OK. TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.debug', ) ALLOWED_HOSTS += [ 'localhost', 'chani.licorn.org', 'leto.licorn.org', 'gurney.licorn.org' ] INSTALLED_APPS += ('django_nose', 'devserver', ) DEVSERVER_DEFAULT_ADDRESS = '0.0.0.0' DEVSERVER_DEFAULT_PORT = 8000 TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
Correct button text in functional test
from django_webtest import WebTest from bs4 import BeautifulSoup from django.contrib.admin.models import User class NomnomTest(WebTest): fixtures = ['users.json',] def test_can_access_nomnom(self): # An administrator visits the admin site response = self.app.get('/admin/') soup = BeautifulSoup('<html>%s' % response.html) title = soup.find('title') self.assertEqual('Log in | Django site admin', title.text) # As a non-staff user, I cannot access nomnom's import page nomnom_auth_groups = self.app.get('/nomnom/auth/group/import/') self.assertContains(nomnom_auth_groups, text='id="login-form"', status_code=200) # As an administrator, I can click the Import button so that I can # import files. user = self.app.get('/admin/auth/user/', user="admin") assert 'Import Users' in user.click('Import users') # As an administrator, I can click the Export button so that I can # export files. # user = self.app.get('/admin/auth/user') # assert 'Export Users' in user.click('Export users') self.fail('TODO')
from django_webtest import WebTest from bs4 import BeautifulSoup from django.contrib.admin.models import User class NomnomTest(WebTest): fixtures = ['users.json',] def test_can_access_nomnom(self): # An administrator visits the admin site response = self.app.get('/admin/') soup = BeautifulSoup('<html>%s' % response.html) title = soup.find('title') self.assertEqual('Log in | Django site admin', title.text) # As a non-staff user, I cannot access nomnom's import page nomnom_auth_groups = self.app.get('/nomnom/auth/group/import/') self.assertContains(nomnom_auth_groups, text='id="login-form"', status_code=200) # As an administrator, I can click the Import button so that I can # import files. user = self.app.get('/admin/auth/user/', user="admin") assert 'NomNom Users' in user.click('Import users') # As an administrator, I can click the Export button so that I can # export files. # user = self.app.get('/admin/auth/user') # assert 'Export Users' in user.click('Export users') self.fail('TODO')
Use first cli input es project name without specifying it explicitly
#!/usr/bin/env node const args = require(`args`); const ncp = require(`ncp`); const path = require(`path`); const replaceRecursive = require(`../lib/replace-recursive.js`); args.option( `project-name`, `Directory and package name for the new avalanche powered project.`, `New Project` ); const options = args.parse(process.argv); let projectName = options.projectName; if (process.argv[2].substring(0, 1) !== `-`) { projectName = process.argv[2]; } const projectNameCleaned = projectName .toLowerCase() .split(` `) .join(`-`); const replacements = [ { regex: `PROJECT-NAME-CLEANED`, replacement: projectNameCleaned, }, { regex: `PROJECT-NAME`, replacement: projectName, }, ]; const packagePath = path.resolve(__dirname, `../`); const source = path.join(packagePath, `templates`, `default`); const destination = path.join(process.cwd(), projectNameCleaned); ncp(source, destination, (error) => { if (error) throw error; replaceRecursive(replacements, destination); // eslint-disable-next-line no-console console.info(`Created a new avalanche project "${projectName}" in ${destination}.`); });
#!/usr/bin/env node const args = require(`args`); const ncp = require(`ncp`); const path = require(`path`); const replaceRecursive = require(`../lib/replace-recursive.js`); args.option( `project-name`, `Directory and package name for the new avalanche powered project.`, `New Project` ); const options = args.parse(process.argv); const projectName = options.projectName; const projectNameCleaned = projectName .toLowerCase() .split(` `) .join(`-`); const replacements = [ { regex: `PROJECT-NAME-CLEANED`, replacement: projectNameCleaned, }, { regex: `PROJECT-NAME`, replacement: projectName, }, ]; const packagePath = path.resolve(__dirname, `../`); const source = path.join(packagePath, `templates`, `default`); const destination = path.join(process.cwd(), projectNameCleaned); ncp(source, destination, (error) => { if (error) throw error; replaceRecursive(replacements, destination); // eslint-disable-next-line no-console console.info(`Created a new avalanche project "${projectName}" in ${destination}.`); });
Fix issue with conflated pmxbot.logging
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab from __future__ import absolute_import import socket import logging as _logging from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) config['logs URL'] = 'http://' + socket.getfqdn() config['log level'] = _logging.INFO "The config object"
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab from __future__ import absolute_import import socket import logging from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) config['logs URL'] = 'http://' + socket.getfqdn() config['log level'] = logging.INFO "The config object"
Add description for iOS in facade
'''UniqueID facade. Returns the following depending on the platform: * **Android**: Android ID * **OS X**: Serial number of the device * **Linux**: Serial number using lshw * **Windows**: MachineGUID from regkey * **iOS**: UUID Simple Example -------------- To get the unique ID:: >>> from plyer import uniqueid >>> uniqueid.id '1b1a7a4958e2a845' .. versionadded:: 1.2.0 .. versionchanged:: 1.2.4 On Android returns Android ID instead of IMEI. ''' class UniqueID(object): ''' UniqueID facade. ''' @property def id(self): ''' Property that returns the unique id of the platform. ''' return self.get_uid() def get_uid(self): return self._get_uid() # private def _get_uid(self, **kwargs): raise NotImplementedError()
'''UniqueID facade. Returns the following depending on the platform: * **Android**: Android ID * **OS X**: Serial number of the device * **Linux**: Serial number using lshw * **Windows**: MachineGUID from regkey Simple Example -------------- To get the unique ID:: >>> from plyer import uniqueid >>> uniqueid.id '1b1a7a4958e2a845' .. versionadded:: 1.2.0 .. versionchanged:: 1.2.4 On Android returns Android ID instead of IMEI. ''' class UniqueID(object): ''' UniqueID facade. ''' @property def id(self): ''' Property that returns the unique id of the platform. ''' return self.get_uid() def get_uid(self): return self._get_uid() # private def _get_uid(self, **kwargs): raise NotImplementedError()
Add description field to TenantSerializer This might be just an oversight. Other data models do include the description in their serialisers. The API produces the description field with this change.
from rest_framework import serializers from extras.api.serializers import CustomFieldSerializer from tenancy.models import Tenant, TenantGroup # # Tenant groups # class TenantGroupSerializer(serializers.ModelSerializer): class Meta: model = TenantGroup fields = ['id', 'name', 'slug'] class TenantGroupNestedSerializer(TenantGroupSerializer): class Meta(TenantGroupSerializer.Meta): pass # # Tenants # class TenantSerializer(CustomFieldSerializer, serializers.ModelSerializer): group = TenantGroupNestedSerializer() class Meta: model = Tenant fields = ['id', 'name', 'slug', 'group', 'description', 'comments', 'custom_fields'] class TenantNestedSerializer(TenantSerializer): class Meta(TenantSerializer.Meta): fields = ['id', 'name', 'slug']
from rest_framework import serializers from extras.api.serializers import CustomFieldSerializer from tenancy.models import Tenant, TenantGroup # # Tenant groups # class TenantGroupSerializer(serializers.ModelSerializer): class Meta: model = TenantGroup fields = ['id', 'name', 'slug'] class TenantGroupNestedSerializer(TenantGroupSerializer): class Meta(TenantGroupSerializer.Meta): pass # # Tenants # class TenantSerializer(CustomFieldSerializer, serializers.ModelSerializer): group = TenantGroupNestedSerializer() class Meta: model = Tenant fields = ['id', 'name', 'slug', 'group', 'comments', 'custom_fields'] class TenantNestedSerializer(TenantSerializer): class Meta(TenantSerializer.Meta): fields = ['id', 'name', 'slug']
Add sqlalchemy to the test dependencines
from setuptools import setup, find_packages import os version = '0.0.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' setup(name='filedepot', version=version, description="Toolkit for storing files and attachments in web applications", long_description=README, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Environment :: Web Environment", "Topic :: Software Development :: Libraries :: Python Modules", "Programming Language :: Python :: 3", "Programming Language :: Python :: 2" ], keywords='storage files s3 gridfs mongodb aws sqlalchemy wsgi', author='Alessandro Molina', author_email='alessandro.molina@axant.it', url='https://github.com/amol-/depot', license='MIT', packages=find_packages(exclude=['ez_setup']), include_package_data=True, tests_require = ['mock', 'pymongo >= 2.7', 'boto', 'sqlalchemy'], test_suite='nose.collector', zip_safe=False, )
from setuptools import setup, find_packages import os version = '0.0.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' setup(name='filedepot', version=version, description="Toolkit for storing files and attachments in web applications", long_description=README, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Environment :: Web Environment", "Topic :: Software Development :: Libraries :: Python Modules", "Programming Language :: Python :: 3", "Programming Language :: Python :: 2" ], keywords='storage files s3 gridfs mongodb aws sqlalchemy wsgi', author='Alessandro Molina', author_email='alessandro.molina@axant.it', url='https://github.com/amol-/depot', license='MIT', packages=find_packages(exclude=['ez_setup']), include_package_data=True, tests_require = ['mock', 'pymongo >= 2.7', 'boto'], test_suite='nose.collector', zip_safe=False, )
Fix signalError, it needs to be function to be "lazily" evaluated and not throw Error immediately when called
import {Option} from 'giftbox'; const lists = { 1: { id: 1, name: 'work items', items: [ { id: 11, title: 'learn graphql basics', completed: false }, { id: 12, title: 'master more details of graphql', completed: false } ] }, 2: { id: 2, name: 'house items', items: [ { id: 21, title: 'pick up laundry', completed: false }, { id: 22, title: 'wash the dishes', completed: true }, { id: 23, title: 'go to gym', completed: false } ] } }; function signalError(msg) { return () => { throw new Error(msg) } } const storageOps = { findList(id) { return lists[id] ? lists[id] : signalError(`Could not find list ${id}`); }, markItemAsCompleted(listId, itemId) { return Option(lists[listId]).flatMap(list => Option(list.items.find(item => item.id === itemId))) .map(item => { item.completed = true; return item; }) .getOrElse(signalError(`Could not find todo item ${itemId} on list ${listId}`)) } }; export default storageOps;
import {Option} from 'giftbox'; const lists = { 1: { id: 1, name: 'work items', items: [ { id: 11, title: 'learn graphql basics', completed: false }, { id: 12, title: 'master more details of graphql', completed: false } ] }, 2: { id: 2, name: 'house items', items: [ { id: 21, title: 'pick up laundry', completed: false }, { id: 22, title: 'wash the dishes', completed: true }, { id: 23, title: 'go to gym', completed: false } ] } }; function signalError(msg) { throw new Error(msg) } const storageOps = { findList(id) { return lists[id] ? lists[id] : signalError(`Could not find list ${id}`); }, markItemAsCompleted(listId, itemId) { return Option(lists[listId]).flatMap(list => Option(list.items.find(item => item.id === itemId))) .map(item => { item.completed = true; return item; }) .getOrElse(signalError(`Could not find todo item ${itemId} on list ${listId}`)) } }; export default storageOps;
Remove duplicated js include for select2
//= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require lodash //= require handlebars.runtime // To use placeholders in inputs in browsers that do not support it // natively yet. //= require jquery/jquery.placeholder // Notifications (flash messages). //= require jquery/jquery.noty // To crop logos. //= require jquery/jquery.Jcrop // Used internally in the chat. //= require jquery/jquery.autosize // For modals. //= require bootstrap/bootstrap-modal //= require bootstrap/bootstrap-modalmanager // Used in crop, modals and possibly other places. Grep for `ajaxForm` // and `ajaxSubmit`. //= require jquery/jquery.form // Use to search for models (e.g. users) dynamically. // require select2 // require select2_locale_pt-BR // Use for XMPP in the chat. //= require strophe //= require i18n/translations // TODO: remove this dependecy, this is only used in attachments now and // can be easily replaced by standard jquery methods. //= require jquery/jquery.livequery // 'base' HAS to be the first one included //= require ./app/application/base //= require_tree ./templates //= require_tree ./app/application/ //= require_tree ./app/_all/
//= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require lodash //= require handlebars.runtime // Use to search for models (e.g. users) dynamically. //= require select2 //= require select2_locale_pt-BR // To use placeholders in inputs in browsers that do not support it // natively yet. //= require jquery/jquery.placeholder // Notifications (flash messages). //= require jquery/jquery.noty // To crop logos. //= require jquery/jquery.Jcrop // Used internally in the chat. //= require jquery/jquery.autosize // For modals. //= require bootstrap/bootstrap-modal //= require bootstrap/bootstrap-modalmanager // Used in crop, modals and possibly other places. Grep for `ajaxForm` // and `ajaxSubmit`. //= require jquery/jquery.form //= require select2 // Use for XMPP in the chat. //= require strophe //= require i18n/translations // TODO: remove this dependecy, this is only used in attachments now and // can be easily replaced by standard jquery methods. //= require jquery/jquery.livequery // 'base' HAS to be the first one included //= require ./app/application/base //= require_tree ./templates //= require_tree ./app/application/ //= require_tree ./app/_all/
Add container div for two-column layout
<?php /** * The template used for displaying page content * */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header --> <div class="entry-content-container"> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentyfifteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>', 'pagelink' => '<span class="screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>%', 'separator' => '<span class="screen-reader-text">, </span>', ) ); ?> </div><!-- .entry-content --> <nav class="entry-nav"> <ul class="page-menu"> <!-- insert --> </ul> </nav> </div><!-- .entry-content-container --> </article><!-- #post-## -->
<?php /** * The template used for displaying page content * */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentyfifteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>', 'pagelink' => '<span class="screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>%', 'separator' => '<span class="screen-reader-text">, </span>', ) ); ?> </div><!-- .entry-content --> </article><!-- #post-## -->
Fix a backward compatibility bug between Java 10 and Java 8.
package utilities; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; public class IoUtil { private static final int INPUT_STREAM_BUFFER_SIZE = 64; private IoUtil() {} /** * Read all content from an input stream to a byte array. * This does not close the input channel after reading. The caller * is responsible for doing that. */ public static byte[] streamToBytes(InputStream in) throws IOException { ReadableByteChannel channel = Channels.newChannel(in); ByteBuffer byteBuffer = ByteBuffer.allocate(INPUT_STREAM_BUFFER_SIZE); ByteArrayOutputStream bout = new ByteArrayOutputStream(); WritableByteChannel outChannel = Channels.newChannel(bout); while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) { // Casting is necessary here. // Similar fix in https://jira.mongodb.org/browse/JAVA-2559 // https://community.blynk.cc/t/java-error-on-remote-server-startup/17957/7 ((Buffer) byteBuffer).flip(); // Make buffer ready for write. outChannel.write(byteBuffer); byteBuffer.compact(); // Make buffer ready for reading. } outChannel.close(); return bout.toByteArray(); } }
package utilities; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; public class IoUtil { private static final int INPUT_STREAM_BUFFER_SIZE = 64; private IoUtil() {} /** * Read all content from an input stream to a byte array. * This does not close the input channel after reading. The caller * is responsible for doing that. */ public static byte[] streamToBytes(InputStream in) throws IOException { ReadableByteChannel channel = Channels.newChannel(in); ByteBuffer byteBuffer = ByteBuffer.allocate(INPUT_STREAM_BUFFER_SIZE); ByteArrayOutputStream bout = new ByteArrayOutputStream(); WritableByteChannel outChannel = Channels.newChannel(bout); while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) { byteBuffer.flip(); // Make buffer ready for write. outChannel.write(byteBuffer); byteBuffer.compact(); // Make buffer ready for reading. } outChannel.close(); return bout.toByteArray(); } }
Remove Object.assign for node v0.12 compatibility
var path = require("path"); var express = require("express"); var webpack = require("webpack"); var merge = require("lodash/object/merge"); var config = merge({}, require("./webpack.docs.config")); config.devtool = "cheap-module-eval-source-map"; config.entry.unshift("webpack-hot-middleware/client"); config.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ); var app = express(); var compiler = webpack(config); app.use(require("webpack-dev-middleware")(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(require("webpack-hot-middleware")(compiler)); app.use(express.static("docs")); app.listen(8080, "localhost", function(err) { if (err) { console.log(err); return; } console.log("Listening at http://localhost:8080"); });
var path = require("path"); var express = require("express"); var webpack = require("webpack"); var config = Object.assign({}, require("./webpack.docs.config")); config.devtool = "cheap-module-eval-source-map"; config.entry.unshift("webpack-hot-middleware/client"); config.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ); var app = express(); var compiler = webpack(config); app.use(require("webpack-dev-middleware")(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(require("webpack-hot-middleware")(compiler)); app.use(express.static("docs")); app.listen(8080, "localhost", function(err) { if (err) { console.log(err); return; } console.log("Listening at http://localhost:8080"); });
Update moving average tests to show floating point truncation
package com.easternedgerobotics.rov.math; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; @SuppressWarnings("checkstyle:MagicNumber") public final class MovingAverageTest { @Test public final void averageCalculationDoesReturnTheCorrectResult() { final TestScheduler scheduler = new TestScheduler(); final TestSubject<Float> numbers = TestSubject.create(scheduler); final TestSubscriber<Float> subscriber = new TestSubscriber<>(); MovingAverage.from(numbers, 2).subscribe(subscriber); numbers.onNext(1.5f); scheduler.triggerActions(); subscriber.assertValueCount(1); subscriber.assertValue(1.5f); numbers.onNext(8.5f); scheduler.triggerActions(); subscriber.assertValueCount(2); subscriber.assertValues(1.5f, 8.5f); numbers.onNext(21.5f); scheduler.triggerActions(); subscriber.assertValueCount(3); subscriber.assertValues(1.5f, 8.5f, 15f); numbers.onNext(41.5f); scheduler.triggerActions(); subscriber.assertValueCount(4); subscriber.assertValues(1f, 5f, 14.5f, 30f); } }
package com.easternedgerobotics.rov.math; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; @SuppressWarnings("checkstyle:MagicNumber") public final class MovingAverageTest { @Test public final void averageCalculationDoesReturnTheCorrectResult() { final TestScheduler scheduler = new TestScheduler(); final TestSubject<Float> numbers = TestSubject.create(scheduler); final TestSubscriber<Float> subscriber = new TestSubscriber<>(); MovingAverage.from(numbers, 2).subscribe(subscriber); numbers.onNext(1f); scheduler.triggerActions(); subscriber.assertValueCount(1); subscriber.assertValue(1f); numbers.onNext(9f); scheduler.triggerActions(); subscriber.assertValueCount(2); subscriber.assertValues(1f, 5f); numbers.onNext(20f); scheduler.triggerActions(); subscriber.assertValueCount(3); subscriber.assertValues(1f, 5f, 14.5f); numbers.onNext(40f); scheduler.triggerActions(); subscriber.assertValueCount(4); subscriber.assertValues(1f, 5f, 14.5f, 30f); } }
Use tuples for internal type lists in the array API These are easier for type checkers to handle.
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype('int8') int16 = np.dtype('int16') int32 = np.dtype('int32') int64 = np.dtype('int64') uint8 = np.dtype('uint8') uint16 = np.dtype('uint16') uint32 = np.dtype('uint32') uint64 = np.dtype('uint64') float32 = np.dtype('float32') float64 = np.dtype('float64') # Note: This name is changed bool = np.dtype('bool') _all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool) _boolean_dtypes = (bool) _floating_dtypes = (float32, float64) _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) _integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64) _numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype('int8') int16 = np.dtype('int16') int32 = np.dtype('int32') int64 = np.dtype('int64') uint8 = np.dtype('uint8') uint16 = np.dtype('uint16') uint32 = np.dtype('uint32') uint64 = np.dtype('uint64') float32 = np.dtype('float32') float64 = np.dtype('float64') # Note: This name is changed bool = np.dtype('bool') _all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool] _boolean_dtypes = [bool] _floating_dtypes = [float32, float64] _integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64] _integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64] _numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
Allow user to edit card id when card has fields
import { action } from '@ember/object'; import CardManipulator from './card-manipulator'; import { schedule } from '@ember/runloop'; export default class CardCreator extends CardManipulator { constructor(...args) { super(...args); /* Remove `hide-in-percy` css selectors from places where we display card IDs once we remove this */ let defaultCardId = `new-card-${Math.floor(Math.random() * 1e7)}`; this.updateCardId(defaultCardId); this.cardId = defaultCardId; } @action updateCardId(id) { let newCard = this.data.createCard(`local-hub::${id}`, this.args.adoptedFrom); if (this.card) { for (let field of this.card.fields.filter(i => !i.isAdopted)) { newCard.addField(field); } } this.card = newCard; /* FIXME: THIS IS A COMPLETE HACK. This problem should go away once we clarify how card ids and names work. See: https://github.com/cardstack/cardstack/issues/1150 */ schedule('afterRender', this, function() { document.querySelector('#card__id').focus(); }); } }
import { action } from '@ember/object'; import CardManipulator from './card-manipulator'; export default class CardCreator extends CardManipulator { constructor(...args) { super(...args); /* Remove `hide-in-percy` css selectors from places where we display card IDs once we remove this */ let defaultCardId = `new-card-${Math.floor(Math.random() * 1e7)}`; this.updateCardId(defaultCardId); this.cardId = defaultCardId; } @action updateCardId(id) { let newCard = this.data.createCard(`local-hub::${id}`, this.args.adoptedFrom); if (this.card) { for (let field of this.card.fields.filter(i => !i.isAdopted)) { newCard.addField(field); } } this.card = newCard; } }
Make JumboFieldsWorkflow fail if no env var If SIMPLEFLOW_JUMBO_FIELDS_BUCKET is not set, the example doesn't work; make this clear. Signed-off-by: Yves Bastide <3b1fe340dba76bf37270abad774f327f50b5e1d8@botify.com>
from __future__ import print_function import os from simpleflow import Workflow, activity @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): if 'SIMPLEFLOW_JUMBO_FIELDS_BUCKET' not in os.environ: print("Please define SIMPLEFLOW_JUMBO_FIELDS_BUCKET to run this example (see README.rst).") raise ValueError() long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
from __future__ import print_function import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
Test that $.create makes a div by default Adds a test for #13
describe("$.create", function() { it("creates an element and sets properties on it", function() { var element = $.create("article", { className: "wide" }); expect(element).to.be.an.instanceOf(Element); expect(element.className).to.be.equal("wide"); expect(element.tagName).to.be.equal("ARTICLE"); }); it("returns a text node when called with only a string", function() { var text = $.create("Lorem Ipsom dolor sit amet"); expect(text).to.be.an.instanceOf(Text); }); describe("passed only an object", function() { it("creates an element and sets the properties on it", function() { var element = $.create({ tag: "span" }); expect(element).to.be.an.instanceOf(Element); expect(element.tagName).to.be.equal("SPAN"); }); it("creates a div by default", function() { var element = $.create({}); expect(element.tagName).to.be.equal("DIV"); }); }); it("creates a div when there are no arguments", function() { var element = $.create(); expect(element.tagName).to.be.equal("DIV"); }); });
describe("$.create", function() { it("creates an element and sets properties on it", function() { var element = $.create("article", { className: "wide" }); expect(element).to.be.an.instanceOf(Element); expect(element.className).to.be.equal("wide"); expect(element.tagName).to.be.equal("ARTICLE"); }); it("returns a text node when called with only a string", function() { var text = $.create("Lorem Ipsom dolor sit amet"); expect(text).to.be.an.instanceOf(Text); }); describe("passed only an object", function() { it("creates an element and sets the properties on it", function() { var element = $.create({ tag: "span" }); expect(element).to.be.an.instanceOf(Element); expect(element.tagName).to.be.equal("SPAN"); }); it("creates a div by default", function() { var element = $.create({}); expect(element.tagName).to.be.equal("DIV"); }); }); });
Add aria attributes to the badge element
<?php use BearFramework\App; $app = App::get(); echo '<html><head>'; echo '<link rel="client-packages-prepare" name="users">'; echo '<style>.ivopetkov-users-badge{cursor:pointer;width:48px;height:48px;position:fixed;z-index:1000000;top:14px;right:14px;border-radius:2px;background-color:black;box-shadow:0 1px 2px 0px rgba(0,0,0,0.2);background-size:cover;background-position:center center;}</style>'; echo '</head><body>'; $styles = 'background-image:url(' . $app->currentUser->getImageUrl(100) . ');'; $onClick = 'clientPackages.get("users").then(function(users){users.openPreview("' . $app->currentUser->provider . '","' . $app->currentUser->id . '");});'; echo '<div class="ivopetkov-users-badge" role="button" tabindex="0" onkeydown="if(event.keyCode===13){this.click();}" style="' . htmlentities($styles) . '" onclick="' . htmlentities($onClick) . '"></div>'; echo '</body></html>';
<?php use BearFramework\App; $app = App::get(); echo '<html><head>'; echo '<link rel="client-packages-prepare" name="users">'; echo '<style>.ivopetkov-users-badge{cursor:pointer;width:48px;height:48px;position:fixed;z-index:1000000;top:14px;right:14px;border-radius:2px;background-color:black;box-shadow:0 1px 2px 0px rgba(0,0,0,0.2);background-size:cover;background-position:center center;}</style>'; echo '</head><body>'; $styles = 'background-image:url(' . $app->currentUser->getImageUrl(100) . ');'; $onClick = 'clientPackages.get("users").then(function(users){users.openPreview("' . $app->currentUser->provider . '","' . $app->currentUser->id . '");});'; echo '<div class="ivopetkov-users-badge" style="' . htmlentities($styles) . '" onclick="' . htmlentities($onClick) . '"></div>'; echo '</body></html>';
Add some defaults for prop types
import {Map} from 'immutable'; export default function buildProps(propsDefinition, allProps = false) { const props = {} Map(propsDefinition).map((data, prop) => { if (data.defaultValue) props[prop] = data.defaultValue.computed ? data.defaultValue.value : eval(`(${data.defaultValue.value})`) // eslint-disable-line no-eval else if (allProps || data.required || data.type.name === 'func') props[prop] = calculateProp(data.type, prop) }) return props } function calculateProp(type, prop) { switch (type.name) { case 'any': return `ANY ${prop}` case 'node': return `NODE ${prop}` case 'string': return `${prop}` case 'bool': return true case 'number': return 1 case 'array': return [] case 'object': return {} case 'func': return eval(`[function () { document.dispatchEvent(new BluekitEvent('functionTriggered', {detail: {prop: "${prop}"}})) }][0]`) // eslint-disable-line no-eval case 'enum': return type.value[0].value.replace(/'/g, '') case 'shape': return Map(type.value) .map((subType, name) => calculateProp(subType, name)) .toJS() case 'arrayOf': return [calculateProp(type.value, prop)] } return null }
import {Map} from 'immutable'; export default function buildProps(propsDefinition, allProps = false) { const props = {} Map(propsDefinition).map((data, prop) => { if (data.defaultValue) props[prop] = data.defaultValue.computed ? data.defaultValue.value : eval(`(${data.defaultValue.value})`) // eslint-disable-line no-eval else if (allProps || data.required || data.type.name === 'func') props[prop] = calculateProp(data.type, prop) }) return props } function calculateProp(type, prop) { switch (type.name) { case 'any': return 'Default ANY' case 'node': return 'Default NODE' case 'string': return `Default string ${prop}` case 'bool': return true case 'number': return 1 case 'func': return eval(`[function () { document.dispatchEvent(new BluekitEvent('functionTriggered', {detail: {prop: "${prop}"}})) }][0]`) // eslint-disable-line no-eval case 'enum': return type.value[0].value.replace(/'/g, '') case 'shape': return Map(type.value) .map((subType, name) => calculateProp(subType, name)) .toJS() case 'arrayOf': return [calculateProp(type.value, prop)] } return null }
Use from to import rather than rename
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) str = type('') import pytest from gpiozero.cli import pinout def test_args_incorrect(): with pytest.raises(SystemExit) as ex: pinout.parse_args(['--nonexistentarg']) assert ex.value.code == 2 def test_args_color(): args = pinout.parse_args([]) assert args.color is None args = pinout.parse_args(['--color']) assert args.color is True args = pinout.parse_args(['--monochrome']) assert args.color is False def test_args_revision(): args = pinout.parse_args(['--revision', '000d']) assert args.revision == '000d' def test_help(capsys): with pytest.raises(SystemExit) as ex: pinout.parse_args(['--help']) out, err = capsys.readouterr() assert 'GPIO pinout' in out assert ex.value.code == 0
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) str = type('') import pytest import gpiozero.cli.pinout as pinout def test_args_incorrect(): with pytest.raises(SystemExit) as ex: pinout.parse_args(['--nonexistentarg']) assert ex.value.code == 2 def test_args_color(): args = pinout.parse_args([]) assert args.color is None args = pinout.parse_args(['--color']) assert args.color is True args = pinout.parse_args(['--monochrome']) assert args.color is False def test_args_revision(): args = pinout.parse_args(['--revision', '000d']) assert args.revision == '000d' def test_help(capsys): with pytest.raises(SystemExit) as ex: pinout.parse_args(['--help']) out, err = capsys.readouterr() assert 'GPIO pinout' in out assert ex.value.code == 0
Change the content field in table Snippet string => text
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateSnippetTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('snippets', function (Blueprint $table) { $table->increments('id'); $table->string('description'); $table->text('content'); $table->boolean('public'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('snippets'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSnippetTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('snippets', function (Blueprint $table) { $table->increments('id'); $table->string('description'); $table->string('content'); $table->boolean('public'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('snippets'); } }
Add failure message when MPD path is not found
var Q = require('Q'), childProcess = require('child_process'); function processPath(exec) { var exec = exec || Q.denodeify(childProcess.exec); var deferred = Q.defer(); function handleDone(stdout, stderr) { var location = stdout[0].trim().replace(/\n$/, ''); deferred.resolve(location); } function handleError(error) { deferred.reject(error); } exec('which mpd').done(handleDone, handleError); return deferred.promise; } function create(configFilepath, spawn) { var spawn = spawn || childProcess.spawn; var dfd = Q.defer(); this.processPath().then(function (path) { var mpdProcess = spawn(path, [configFilepath, '--no-daemon']); mpdProcess.stdout.on('data', function (data) { dfd.resolve(); }); mpdProcess.on('error', function (error) { dfd.reject(); }); }, function() { dfd.reject('Could not find MPD binary'); }); return dfd.promise; } module.exports = { processPath: processPath, create: create };
var Q = require('Q'), childProcess = require('child_process'); function processPath(exec) { var exec = exec || Q.denodeify(childProcess.exec); var deferred = Q.defer(); function handleDone(stdout, stderr) { var location = stdout[0].trim().replace(/\n$/, ''); deferred.resolve(location); } function handleError(error) { deferred.reject(error); } exec('which mpd').done(handleDone, handleError); return deferred.promise; } function create(configFilepath, spawn) { var spawn = spawn || childProcess.spawn; var dfd = Q.defer(); this.processPath().then(function (path) { var mpdProcess = spawn(path, [configFilepath, '--no-daemon']); mpdProcess.stdout.on('data', function (data) { dfd.resolve(); }); mpdProcess.on('error', function (error) { dfd.reject(); }); }, function() { dfd.reject(); }); return dfd.promise; } module.exports = { processPath: processPath, create: create };
XTARCHCOMPONENT-1: Create a Maven Archetype to make it easy to create XWiki Components * Fixed invalid package git-svn-id: ffe117d4700a1f5efb0d898519c0bde20828e3e5@32897 f329d543-caf0-0310-9063-dda96c69346f
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package ${package}; import org.junit.Assert; import org.junit.Test; import ${package}.internal.DefaultHelloWorld; import org.xwiki.test.AbstractMockingComponentTestCase; import org.xwiki.test.annotation.MockingRequirement; /** * Tests for the {@link HelloWorld} component. * * @version $Id$ */ public class HelloWorldTest extends AbstractMockingComponentTestCase { @MockingRequirement private DefaultHelloWorld hw; @Test public void testSayHello() { Assert.assertEquals("Hello", hw.sayHello()); } }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package ${package}; import org.junit.Assert; import org.junit.Test; import org.vma.internal.DefaultHelloWorld; import org.xwiki.test.AbstractMockingComponentTestCase; import org.xwiki.test.annotation.MockingRequirement; /** * Tests for the {@link HelloWorld} component. * * @version $Id$ */ public class HelloWorldTest extends AbstractMockingComponentTestCase { @MockingRequirement private DefaultHelloWorld hw; @Test public void testSayHello() { Assert.assertEquals("Hello", hw.sayHello()); } }
Update due to KnpMenuBundle changes
<?php namespace Admingenerator\GeneratorBundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Router; class DefaultMenuBuilder { private $factory; /** * @param \Knp\Menu\FactoryInterface $factory */ public function __construct(FactoryInterface $factory) { $this->factory = $factory; } /** * @param Request $request * @param Router $router */ public function createAdminMenu(Request $request) { $menu = $this->factory->createItem('root', array('childrenAttributes' => array('id' => 'main_navigation', 'class'=>'menu') ) ); $menu->setCurrentUri($request->getRequestUri()); $help = $menu->addChild('Overwrite this menu', array('uri' => '#')); $help->setLinkAttributes(array('class'=>'sub main')); $help->addChild('Configure menu class', array('uri' => 'https://github.com/knplabs/KnpMenuBundle/blob/master/Resources/doc/index.md')); $help->addChild('Configure php class to use', array('uri' => 'https://github.com/cedriclombardot/AdmingeneratorGeneratorBundle/blob/master/Resources/doc/change-the-menu-class.markdown')); return $menu; } }
<?php namespace Admingenerator\GeneratorBundle\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Router; class DefaultMenuBuilder { private $factory; /** * @param \Knp\Menu\FactoryInterface $factory */ public function __construct(FactoryInterface $factory) { $this->factory = $factory; } /** * @param Request $request * @param Router $router */ public function createAdminMenu(Request $request) { $menu = $this->factory->createItem('root'); $menu->setCurrentUri($request->getRequestUri()); $menu->setAttributes(array('id' => 'main_navigation', 'class'=>'menu')); $help = $menu->addChild('Overwrite this menu', array('uri' => '#')); $help->setLinkAttributes(array('class'=>'sub main')); $help->addChild('Configure menu class', array('uri' => 'https://github.com/knplabs/KnpMenuBundle/blob/master/Resources/doc/index.md')); $help->addChild('Configure php class to use', array('uri' => 'https://github.com/cedriclombardot/AdmingeneratorGeneratorBundle/blob/master/Resources/doc/change-the-menu-class.markdown')); return $menu; } }
Handle temp directory with absolute path
_VERSION = 'CVS' import os _TEMP_DIR = os.path.join(os.getcwd(), '.SloppyCell') import logging logging.basicConfig() logger = logging.getLogger('__init__') # Check for debugging option. I tried using optparse for this, but ran into # issues with ipython and mpirun, both of which pollute sys.argv. import sys for arg in sys.argv: if arg.startswith('--debugSC'): words = arg.split('=') import Utility if len(words) == 2: Utility.enable_debugging_msgs(words[1]) else: Utility.enable_debugging_msgs(None) currdir = os.getcwd() try: import pypar os.chdir(currdir) HAVE_PYPAR = True num_procs = pypar.size() my_rank = pypar.rank() my_host = pypar.get_processor_name() import atexit atexit.register(pypar.finalize) except ImportError: os.chdir(currdir) HAVE_PYPAR = False num_procs = 1 my_rank = 0 import socket my_host = socket.gethostname() logger.debug('Node %i is on host %s.' % (my_rank, my_host)) if my_rank == 0 and not os.path.isdir(_TEMP_DIR): os.mkdir(_TEMP_DIR) import OldScipySupport
_VERSION = 'CVS' _TEMP_DIR = '.SloppyCell' import logging logging.basicConfig() logger = logging.getLogger('__init__') # Check for debugging option. I tried using optparse for this, but ran into # issues with ipython and mpirun, both of which pollute sys.argv. import sys for arg in sys.argv: if arg.startswith('--debugSC'): words = arg.split('=') import Utility if len(words) == 2: Utility.enable_debugging_msgs(words[1]) else: Utility.enable_debugging_msgs(None) import os currdir = os.getcwd() try: import pypar os.chdir(currdir) HAVE_PYPAR = True num_procs = pypar.size() my_rank = pypar.rank() my_host = pypar.get_processor_name() import atexit atexit.register(pypar.finalize) except ImportError: os.chdir(currdir) HAVE_PYPAR = False num_procs = 1 my_rank = 0 import socket my_host = socket.gethostname() logger.debug('Node %i is on host %s.' % (my_rank, my_host)) import os if my_rank == 0 and not os.path.isdir(_TEMP_DIR): os.mkdir(_TEMP_DIR) import OldScipySupport
Add trove classifiers specifying Python 3 support.
#!/usr/bin/env python """Distutils installer for extras.""" from setuptools import setup import os.path import extras testtools_cmd = extras.try_import('testtools.TestCommand') def get_version(): """Return the version of extras that we are building.""" version = '.'.join( str(component) for component in extras.__version__[0:3]) return version def get_long_description(): readme_path = os.path.join( os.path.dirname(__file__), 'README.rst') return open(readme_path).read() cmdclass = {} if testtools_cmd is not None: cmdclass['test'] = testtools_cmd setup(name='extras', author='Testing cabal', author_email='testtools-dev@lists.launchpad.net', url='https://github.com/testing-cabal/extras', description=('Useful extra bits for Python - things that shold be ' 'in the standard library'), long_description=get_long_description(), version=get_version(), classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", ], packages=[ 'extras', 'extras.tests', ], cmdclass=cmdclass)
#!/usr/bin/env python """Distutils installer for extras.""" from setuptools import setup import os.path import extras testtools_cmd = extras.try_import('testtools.TestCommand') def get_version(): """Return the version of extras that we are building.""" version = '.'.join( str(component) for component in extras.__version__[0:3]) return version def get_long_description(): readme_path = os.path.join( os.path.dirname(__file__), 'README.rst') return open(readme_path).read() cmdclass = {} if testtools_cmd is not None: cmdclass['test'] = testtools_cmd setup(name='extras', author='Testing cabal', author_email='testtools-dev@lists.launchpad.net', url='https://github.com/testing-cabal/extras', description=('Useful extra bits for Python - things that shold be ' 'in the standard library'), long_description=get_long_description(), version=get_version(), classifiers=["License :: OSI Approved :: MIT License"], packages=[ 'extras', 'extras.tests', ], cmdclass=cmdclass)
Change the copy-pasted test suite title
describe('public browser API', function () { 'use strict'; var assert = require('assert'), bro = require('jsdom-test-browser'), api = require('../index'), browserApi = require('../browser'); assert(bro); describe('just as the full API', function () { it('provides the React class', function () { assert.strictEqual(browserApi.Klass, api.Klass); }); it('provides the model class', function () { assert.strictEqual(browserApi.Model, api.Model); }); it('provides the environment class', function () { assert.strictEqual(browserApi.Environment, api.Environment); }); }); it('exports no intlMessages', function () { assert.strictEqual(typeof browserApi.intlMessages, 'undefined'); }); });
describe('index (public API)', function () { 'use strict'; var assert = require('assert'), bro = require('jsdom-test-browser'), api = require('../index'), browserApi = require('../browser'); assert(bro); describe('just as the full API', function () { it('provides the React class', function () { assert.strictEqual(browserApi.Klass, api.Klass); }); it('provides the model class', function () { assert.strictEqual(browserApi.Model, api.Model); }); it('provides the environment class', function () { assert.strictEqual(browserApi.Environment, api.Environment); }); }); it('exports no intlMessages', function () { assert.strictEqual(typeof browserApi.intlMessages, 'undefined'); }); });
Use primitive command state for EditInlineCommand.
import Command from './Command' class EditInlineNodeCommand extends Command { constructor(...args) { super(...args) if (!this.config.nodeType) { throw new Error('Every AnnotationCommand must have a nodeType') } } getCommandState(params) { let sel = params.selection let newState = { disabled: true, active: false } let annos = this._getAnnotationsForSelection(params) if (annos.length === 1 && annos[0].getSelection().equals(sel)) { newState.disabled = false newState.nodeId = annos[0].id } return newState } execute(params) { // eslint-disable-line } _getAnnotationsForSelection(params) { return params.selectionState.getAnnotationsForType(this.config.nodeType) } } export default EditInlineNodeCommand
import Command from './Command' class EditInlineNodeCommand extends Command { constructor(...args) { super(...args) if (!this.config.nodeType) { throw new Error('Every AnnotationCommand must have a nodeType') } } getCommandState(params) { let sel = params.selection let newState = { disabled: true, active: false } let annos = this._getAnnotationsForSelection(params) if (annos.length === 1 && annos[0].getSelection().equals(sel)) { newState.disabled = false newState.node = annos[0] } return newState } execute(params) { // eslint-disable-line } _getAnnotationsForSelection(params) { return params.selectionState.getAnnotationsForType(this.config.nodeType) } } export default EditInlineNodeCommand
Handle case of client closing conn before worker replies
<?php require 'vendor/autoload.php'; $loop = new React\EventLoop\StreamSelectLoop(); $socket = new React\Socket\Server($loop); $http = new React\Http\Server($socket); $context = new React\ZMQ\Context($loop); $dealer = $context->getSocket(ZMQ::SOCKET_DEALER); $dealer->bind('tcp://127.0.0.1:4444'); $conns = new ArrayObject(); $dealer->on('message', function ($msg) use ($conns) { list($hash, $blank, $data) = $msg; if (!isset($conns[$hash])) { return; } $response = $conns[$hash]; $response->writeHead(); $response->end($data); }); $http->on('request', function ($request, $response) use ($dealer, $conns) { $hash = spl_object_hash($request); $conns[$hash] = $response; $request->on('end', function () use ($conns, $hash) { unset($conns[$hash]); }); $dealer->send(array( $hash, '', $request->getPath() )); }); $socket->listen(8080); $loop->run();
<?php require 'vendor/autoload.php'; $loop = new React\EventLoop\StreamSelectLoop(); $socket = new React\Socket\Server($loop); $http = new React\Http\Server($socket); $context = new React\ZMQ\Context($loop); $dealer = $context->getSocket(ZMQ::SOCKET_DEALER); $dealer->bind('tcp://127.0.0.1:4444'); $conns = new ArrayObject(); $dealer->on('message', function ($msg) use ($conns) { list($hash, $blank, $data) = $msg; $response = $conns[$hash]; $response->writeHead(); $response->end($data); }); $http->on('request', function ($request, $response) use ($dealer, $conns) { $hash = spl_object_hash($request); $conns[$hash] = $response; $request->on('end', function () use ($conns, $hash) { unset($conns[$hash]); }); $dealer->send(array( $hash, '', $request->getPath() )); }); $socket->listen(8080); $loop->run();
Fix bug in matching regexp for request url
var ClientRequest = require('http').ClientRequest, querystring = require('querystring'), url = require('url'), inherit = require('../utils').inherit; module.exports = Request; function Request(request){ var parsed = url.parse(request.url, true); this.url = request.url.replace(/^http(s)?:\/\/([^\/]*)/,''); this.headers = request.headers; this.method = request.method.toLowerCase(); this.pathname = parsed.pathname; this.hash = parsed.hash; this.params = parsed.query; this.data = this.body = querystring.parse(request.post); this.files = request.files; } inherit(Request, ClientRequest, [ function param(index){ return this.params[index]; }, function post(index){ return this.data[index]; }, function get(key){ return this.headers[key]; } ]);
var ClientRequest = require('http').ClientRequest, querystring = require('querystring'), url = require('url'), inherit = require('../utils').inherit; module.exports = Request; function Request(request){ var parsed = url.parse(request.url, true); this.url = request.url.replace(/^http(s)?:\/\/([^\/]*)\/$/,''); this.headers = request.headers; this.method = request.method.toLowerCase(); this.pathname = parsed.pathname; this.hash = parsed.hash; this.params = parsed.query; this.data = this.body = querystring.parse(request.post); this.files = request.files; } inherit(Request, ClientRequest, [ function param(index){ return this.params[index]; }, function post(index){ return this.data[index]; }, function get(key){ return this.headers[key]; } ]);
Add logger to env loader
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> import os import logging logger = logging.getLogger() from dotenv import load_dotenv, get_key, set_key, unset_key from cfn_detect import load_cfn_outputs def load_envs(path): """Recursively load .env files starting from `path` Usage: from your Lambda function, call load_envs with the value __file__ to give it the current location as a place to start looking for .env files. import serverless_helpers serverless_helpers.load_envs(__file__) Given the path "foo/bar/myfile.py" and a directory structure like: foo \---.env \---bar \---.env \---myfile.py Values from foo/bar/.env and foo/.env will both be loaded, but values in foo/bar/.env will take precedence over values from foo/.env """ import os path = os.path.abspath(path) path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key from cfn_detect import load_cfn_outputs def load_envs(path): """Recursively load .env files starting from `path` Usage: from your Lambda function, call load_envs with the value __file__ to give it the current location as a place to start looking for .env files. import serverless_helpers serverless_helpers.load_envs(__file__) Given the path "foo/bar/myfile.py" and a directory structure like: foo \---.env \---bar \---.env \---myfile.py Values from foo/bar/.env and foo/.env will both be loaded, but values in foo/bar/.env will take precedence over values from foo/.env """ import os path = os.path.abspath(path) path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
Revert "[HACK TEST] Rename package for now and try with a registered account for testpypi" This reverts commit 3cc3b07dcbe7faac91cf42b40c7ebd4375c4f93d.
# Copyright 2015 datawire. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = [ "__title__", "__version__", "__summary__", "__uri__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = 'datawire-quarkdev' __version__ = '0.5.2' __summary__ = "Quark: an IDL for high level (micro)service interfaces" __uri__ = "http://datawire.github.io/quark/" __author__ = "datawire.io" __email__ = "hello@datawire.io" __license__ = "Apache License, Version 2.0" __copyright__ = "2016 %s" % __author__
# Copyright 2015 datawire. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = [ "__title__", "__version__", "__summary__", "__uri__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = 'datawire-quarkdev-bozzo' __version__ = '0.5.2' __summary__ = "Quark: an IDL for high level (micro)service interfaces" __uri__ = "http://datawire.github.io/quark/" __author__ = "datawire.io" __email__ = "hello@datawire.io" __license__ = "Apache License, Version 2.0" __copyright__ = "2016 %s" % __author__
Change nsinit root to /var/run/nsinit Signed-off-by: Michael Crosby <951f4c7b5d47e32d0112c78d14a98eaa23e6b5ef@gmail.com>
package main import ( "os" log "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" ) func main() { app := cli.NewApp() app.Name = "nsinit" app.Version = "2" app.Author = "libcontainer maintainers" app.Flags = []cli.Flag{ cli.StringFlag{Name: "root", Value: "/var/run/nsinit", Usage: "root directory for containers"}, cli.StringFlag{Name: "log-file", Value: "", Usage: "set the log file to output logs to"}, cli.BoolFlag{Name: "debug", Usage: "enable debug output in the logs"}, } app.Commands = []cli.Command{ configCommand, execCommand, initCommand, oomCommand, pauseCommand, statsCommand, unpauseCommand, stateCommand, } app.Before = func(context *cli.Context) error { if context.GlobalBool("debug") { log.SetLevel(log.DebugLevel) } if path := context.GlobalString("log-file"); path != "" { f, err := os.Create(path) if err != nil { return err } log.SetOutput(f) } return nil } if err := app.Run(os.Args); err != nil { log.Fatal(err) } }
package main import ( "os" log "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" ) func main() { app := cli.NewApp() app.Name = "nsinit" app.Version = "2" app.Author = "libcontainer maintainers" app.Flags = []cli.Flag{ cli.StringFlag{Name: "root", Value: ".", Usage: "root directory for containers"}, cli.StringFlag{Name: "log-file", Value: "", Usage: "set the log file to output logs to"}, cli.BoolFlag{Name: "debug", Usage: "enable debug output in the logs"}, } app.Commands = []cli.Command{ configCommand, execCommand, initCommand, oomCommand, pauseCommand, statsCommand, unpauseCommand, stateCommand, } app.Before = func(context *cli.Context) error { if context.GlobalBool("debug") { log.SetLevel(log.DebugLevel) } if path := context.GlobalString("log-file"); path != "" { f, err := os.Create(path) if err != nil { return err } log.SetOutput(f) } return nil } if err := app.Run(os.Args); err != nil { log.Fatal(err) } }
Fix prefix in environment variable that contains SH's key
import imp, os, netrc, ConfigParser SCRAPY_CFG_FILE = os.path.expanduser("~/.scrapy.cfg") NETRC_FILE = os.path.expanduser('~/.netrc') def missing_modules(*modules): """Receives a list of module names and returns those which are missing""" missing = [] for module_name in modules: try: imp.find_module(module_name) except ImportError: missing.append(module_name) return missing def find_api_key(): """Finds and returns the Scrapy Cloud APIKEY""" key = os.getenv("SHUB_APIKEY") if not key: key = get_key_netrc() return key def get_key_netrc(): """Gets the key from the netrc file""" try: info = netrc.netrc() except IOError: return try: key, account, password = info.authenticators("scrapinghub.com") except TypeError: return if key: return key
import imp, os, netrc, ConfigParser SCRAPY_CFG_FILE = os.path.expanduser("~/.scrapy.cfg") NETRC_FILE = os.path.expanduser('~/.netrc') def missing_modules(*modules): """Receives a list of module names and returns those which are missing""" missing = [] for module_name in modules: try: imp.find_module(module_name) except ImportError: missing.append(module_name) return missing def find_api_key(): """Finds and returns the Scrapy Cloud APIKEY""" key = os.getenv("SH_APIKEY") if not key: key = get_key_netrc() return key def get_key_netrc(): """Gets the key from the netrc file""" try: info = netrc.netrc() except IOError: return try: key, account, password = info.authenticators("scrapinghub.com") except TypeError: return if key: return key
Add route for individual quote
from flask import render_template, g from porick import app, model @app.route('/') def landing_page(): return render_template('/index.html') @app.route('/browse') @app.route('/browse/<int:quote_id>') @app.route('/browse/<area>') @app.route('/browse/<area>/page/<page>') def browse(area=None, page=None): raise NotImplementedError() @app.route('/browse/tags') @app.route('/browse/tags/<tag>') @app.route('/browse/tags/<tag>/page/<page>') def browse_by_tags(tag=None, page=None): raise NotImplementedError() @app.route('/search') @app.route('/search/<term>') @app.route('/search/<term>/page/<page>') def search(term=None, page=None): raise NotImplementedError() @app.route('/create') def new_quote(): raise NotImplementedError() @app.route('/signup') def create_account(): raise NotImplementedError() @app.route('/login') def login(): raise NotImplementedError() @app.route('/logout') def logout(): raise NotImplementedError() @app.route('/reset_password') def reset_password(): raise NotImplementedError()
from flask import render_template, g from porick import app, model @app.route('/') def landing_page(): return render_template('/index.html') @app.route('/browse') @app.route('/browse/<area>') @app.route('/browse/<area>/page/<page>') def browse(area=None, page=None): raise NotImplementedError() @app.route('/browse/tags') @app.route('/browse/tags/<tag>') @app.route('/browse/tags/<tag>/page/<page>') def browse_by_tags(tag=None, page=None): raise NotImplementedError() @app.route('/search') @app.route('/search/<term>') @app.route('/search/<term>/page/<page>') def search(term=None, page=None): raise NotImplementedError() @app.route('/create') def new_quote(): raise NotImplementedError() @app.route('/signup') def create_account(): raise NotImplementedError() @app.route('/login') def login(): raise NotImplementedError() @app.route('/logout') def logout(): raise NotImplementedError() @app.route('/reset_password') def reset_password(): raise NotImplementedError()
Include integrator modules for KPP and SMVGEAR
# compatibility with both python 2 and 3 from __future__ import print_function import numpy as np # AC_tools modules from . AC_time import * from . core import * from . generic import * from . GEOSChem_bpch import * from . GEOSChem_nc import * from . KPP import * from . planeflight import * from . plotting_REDUNDENT import * from . plotting import * from . SMVGEAR import * from . variables import * """ AC_tools is a module of functions started by Tomas, and contributed to by others in the Evans' group, and hopefully maintained by the Group. To access the help, from python or ipython, type help(AC_tools) to get general help To get more detailed help from a module for example, type help(AC_tools.AC_time.py) If you find missing documentation any thing is unclear in any of this, please request a git push to github. """ # Setup logging for module import logging level = logging.DEBUG FORMAT = "%(levelname)8s - %(message)s @---> %(filename)s:%(lineno)s %(funcName)s()" logging.basicConfig(filename='AC_tools.log', filemode='w', level=level, format=FORMAT) logging.getLogger().setLevel(level) # Import submodules here for easier access
# compatibility with both python 2 and 3 from __future__ import print_function from . plotting_REDUNDENT import * from . plotting import * from . variables import * from . AC_time import * from . planeflight import * from . generic import * from . core import * from . GEOSChem_bpch import * from . GEOSChem_nc import * import numpy as np """ AC_tools is a module of functions started by Tomas, and contributed to by others in the Evans' group, and hopefully maintained by the Group. To access the help, from python or ipython, type help(AC_tools) to get general help To get more detailed help from a module for example, type help(AC_tools.AC_time.py) If you find missing documentation any thing is unclear in any of this, please request a git push to github. """ # Setup logging for module import logging level = logging.DEBUG FORMAT = "%(levelname)8s - %(message)s @---> %(filename)s:%(lineno)s %(funcName)s()" logging.basicConfig(filename='AC_tools.log', filemode='w', level=level, format=FORMAT) logging.getLogger().setLevel(level) # Import submodules here for easier access
Put quick check so we don't load course modules on init unless we're actually running in Django
""" Module that provides a connection to the ModuleStore specified in the django settings. Passes settings.MODULESTORE as kwargs to MongoModuleStore """ from __future__ import absolute_import from importlib import import_module from os import environ from django.conf import settings _MODULESTORES = {} FUNCTION_KEYS = ['render_template'] def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def modulestore(name='default'): global _MODULESTORES if name not in _MODULESTORES: class_ = load_function(settings.MODULESTORE[name]['ENGINE']) options = {} options.update(settings.MODULESTORE[name]['OPTIONS']) for key in FUNCTION_KEYS: if key in options: options[key] = load_function(options[key]) _MODULESTORES[name] = class_( **options ) return _MODULESTORES[name] if 'DJANGO_SETTINGS_MODULE' in environ: # Initialize the modulestores immediately for store_name in settings.MODULESTORE: modulestore(store_name)
""" Module that provides a connection to the ModuleStore specified in the django settings. Passes settings.MODULESTORE as kwargs to MongoModuleStore """ from __future__ import absolute_import from importlib import import_module from django.conf import settings _MODULESTORES = {} FUNCTION_KEYS = ['render_template'] def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def modulestore(name='default'): global _MODULESTORES if name not in _MODULESTORES: class_ = load_function(settings.MODULESTORE[name]['ENGINE']) options = {} options.update(settings.MODULESTORE[name]['OPTIONS']) for key in FUNCTION_KEYS: if key in options: options[key] = load_function(options[key]) _MODULESTORES[name] = class_( **options ) return _MODULESTORES[name] # Initialize the modulestores immediately for store_name in settings.MODULESTORE: modulestore(store_name)
Remove 401 status code to log out user
import axios from 'axios'; import { browserHistory } from 'react-router' import config from '../config'; const baseUrl = config.baseUrl; const getToken = () => { return localStorage.getItem('jwt'); }; const getConfig = function () { const token = getToken(); return token ? { headers: { Authorization: `JWT ${token}` } } : {}; }; export default { get: (path) => { return axios.get(`${baseUrl}${path}`, getConfig()); }, post: (path, payload) => { return axios.post(`${baseUrl}${path}`, payload, getConfig()); }, getToken: getToken, setToken: (token) => { localStorage.setItem('jwt', token); }, destroyToken: () => { localStorage.removeItem('jwt'); } }
import axios from 'axios'; import { browserHistory } from 'react-router' import config from '../config'; const baseUrl = config.baseUrl; const onErrorHandler = error => { if (error.response) { if (error.response.status === 401) { browserHistory.push('/logout'); } } }; const getToken = () => { return localStorage.getItem('jwt'); }; const getConfig = function () { const token = getToken(); return token ? { headers: { Authorization: `JWT ${token}` } } : {}; }; export default { get: (path) => { return axios.get(`${baseUrl}${path}`, getConfig()) .catch(onErrorHandler); }, post: (path, payload) => { return axios.post(`${baseUrl}${path}`, payload, getConfig()) .catch(onErrorHandler); }, getToken: getToken, setToken: (token) => { localStorage.setItem('jwt', token); }, destroyToken: () => { localStorage.removeItem('jwt'); } }
Update test data importer script.
#!/usr/bin/env python # Script to import some test data into the db. Usually we should get a warning # due to the bad formatting of the date, which is missing the time zone flag. # Copy and execute this directly into the django shell. from sest.models import * # from datetime import datetime u = User.objects.create(username="test", email="test@example.com") # c = Channel(title="test", user=u, 12345678, datetime.now()) c = Channel.objects.create(user=u, number_fields=2) c.fieldmetadata_set.create(field_no=1, encoding='float') c.fieldmetadata_set.create(field_no=2, encoding='float') with open("sample_without_header.csv") as fo: for line in fo: line = line.strip().split(',') dt, _id, t, h = line # dt = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S UTC') t, h = float(t), float(h) # r = Record.objects.create(channel=c, insertion_time=dt, id=_id) r = Record.objects.create(channel=c, id=_id) r.field_set.create(field_no=1, val=t) r.field_set.create(field_no=2, val=h)
#!/usr/bin/env python # Script to import some test data into the db. Usually we should get a warning # due to the bad formatting of the date, which is missing the time zone flag. # Copy and execute this directly into the django shell. from sest.models import * from datetime import datetime u = User.objects.create(username="test", email="test@example.com") # c = Channel(title="test", user=u, 12345678, datetime.now()) c = Channel.objects.create(user=u, number_fields=2) c.fieldmetadata_set.create(field_no=1, encoding='float') c.fieldmetadata_set.create(field_no=2, encoding='float') with open("sample_without_header.csv") as fo: for line in fo: line = line.strip().split(',') dt, _id, t, h = line dt = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S UTC') t, h = float(t), float(h) r = Record.objects.create(channel=c, insertion_time=dt, id=_id) r.field_set.create(field_no=1, val=t) r.field_set.create(field_no=2, val=h)
Return to 1 decimal place
'use strict'; module.exports = { isHttp2(page) { return (page.connectionType === 'h2' || page.connectionType === 'spdy'); }, /** * Get the hostname from a URL string. * @param {string} url The URL like https://www.example.com/hepp * @returns {string} the hostname */ getHostname(url) { if (!url) return ''; let hostname = url.split('/')[2]; return (hostname && hostname.split(':')[0]) || ''; }, /** * Convert bytes to human readable. * @param {Number} bytes * @returns {String} human readable file size */ formatBytes(bytes) { var sizes = ['B', 'kB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0 B'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1000))); return Math.round(bytes / Math.pow(1000, i) * 10) / 10 + ' ' + sizes[i]; } };
'use strict'; module.exports = { isHttp2(page) { return (page.connectionType === 'h2' || page.connectionType === 'spdy'); }, /** * Get the hostname from a URL string. * @param {string} url The URL like https://www.example.com/hepp * @returns {string} the hostname */ getHostname(url) { if (!url) return ''; let hostname = url.split('/')[2]; return (hostname && hostname.split(':')[0]) || ''; }, /** * Convert bytes to human readable. * @param {Number} bytes * @returns {String} human readable file size */ formatBytes(bytes) { var sizes = ['B', 'kB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0 B'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1000))); return Math.round(bytes / Math.pow(1000, i), 2) + ' ' + sizes[i]; } };
Clean up sitemap URL handling.
from django.contrib.sitemaps import Sitemap from django.db.models import get_models from mezzanine.core.models import Displayable class DisplayableSitemap(Sitemap): """ Sitemap class for Django's sitemaps framework that returns all published items for models that subclass ``Displayable``. """ def items(self): """ Return all published items for models that subclass ``Displayable``. """ items = {} for model in get_models(): if issubclass(model, Displayable): for item in model.objects.published(): items[item.get_absolute_url()] = item return items.values()
from django.contrib.sitemaps import Sitemap from django.db.models import get_models from mezzanine.core.models import Displayable class DisplayableSitemap(Sitemap): """ Sitemap class for Django's sitemaps framework that returns all published items for models that subclass ``Displayable``. """ def items(self): """ Return all published items for models that subclass ``Displayable``. """ items = [] item_urls = set() for model in get_models(): if issubclass(model, Displayable): for item in model.objects.published(): url = item.get_absolute_url() # check if the url of that item was already seen # (this might happen for Page items and subclasses of Page like RichTextPage) if not url in item_urls: items.append(item) item_urls.add(url) return items
Fix Webpack Tapable deprecation warning
const gulp = require('gulp'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const compress = require('compression'); const browserSync = require('browser-sync'); const config = require('../config'); const webpackConfig = require('../config/webpack.config'); module.exports = function serve(done) { const tasks = require('../utils/getTasks'); // eslint-disable-line global-require const compiler = webpack(webpackConfig); compiler.hooks.done.tap({ name: 'BrowserSync' }, () => { browserSync.reload(); }); const middleware = [compress()]; if (config.publicPath) { middleware.push(webpackDevMiddleware(compiler, { publicPath: webpackConfig.output.publicPath, logLevel: 'silent', noInfo: true, })); } browserSync({ ...config.browserSync, middleware }); if (!config.publicPath) { gulp.watch(`${config.source}/${config.scripts.path}/**`, tasks.scripts); } gulp.watch(`${config.source}/${config.styles.path}/**`, tasks.styles); gulp.watch(`${config.source}/${config.icons.path}/**`, tasks.icons); gulp.watch(`${config.source}/${config.images.path}/**`, tasks.images); gulp.watch(config.files(config), tasks.static); done(); };
const gulp = require('gulp'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const compress = require('compression'); const browserSync = require('browser-sync'); const config = require('../config'); const webpackConfig = require('../config/webpack.config'); module.exports = function serve(done) { const tasks = require('../utils/getTasks'); // eslint-disable-line global-require const compiler = webpack(webpackConfig); compiler.plugin('done', () => { browserSync.reload(); }); const middleware = [compress()]; if (config.publicPath) { middleware.push(webpackDevMiddleware(compiler, { publicPath: webpackConfig.output.publicPath, logLevel: 'silent', noInfo: true, })); } browserSync({ ...config.browserSync, middleware }); if (!config.publicPath) { gulp.watch(`${config.source}/${config.scripts.path}/**`, tasks.scripts); } gulp.watch(`${config.source}/${config.styles.path}/**`, tasks.styles); gulp.watch(`${config.source}/${config.icons.path}/**`, tasks.icons); gulp.watch(`${config.source}/${config.images.path}/**`, tasks.images); gulp.watch(config.files(config), tasks.static); done(); };
Document new evil magic, and add required var.
# Mnemosyne configuration # ======================= # # This file is a Python script. When run, the following variables will be # defined for you; you may change or add to them as you see fit. # # * ``entries_dir``: a Maildir containing all the blog entries. # * ``layout_dir``: the blog's layout, as a skeleton directory tree. # * ``style_dir``: empy styles used for filling layout templates. # * ``output_dir``: location where we will write the generated pages. # # These will be $HOME/Mnemosyne/{entries,layout,style,htdocs} respectively. # # * ``locals``: a dict of default local variables passed to all templates. # # This will contain the keys __version__, __url__, __author__, and __email__. # # * ``MnemosyneEntry``: a class used to represent each entry passed to the # templates. # # If you wish to extend this class, you may define a new class ``Entry`` here, # using ``MnemosyneEntry`` as its base class. Any methods with a name of the # form ``get_ATTRIBUTE`` will be used to provide e.ATTRIBUTE at runtime. locals['blogname'] = 'Example Blog' locals['base'] = 'http://example.invalid' class Entry: def get_organization(self): return self.m.get('Organization')
# Mnemosyne configuration # ======================= # # This file is a Python script. When run, the following variables will be # defined for you; you may change or add to them as you see fit. # # ``entries_dir``: a Maildir containing all the blog entries. # ``layout_dir``: the blog's layout, as a skeleton directory tree. # ``style_dir``: empy styles used for filling layout templates. # ``output_dir``: location where we will write the generated pages. # # These will be $HOME/Mnemosyne/{entries,layout,style,htdocs} respectively. # # ``vars``: a dict of default local variables passed to all templates. # # This will contain the keys __version__, __url__, __author__, and __email__. # # You may also define functions here to add 'magic' attributes to each entry. # A function with a name of the form ``make_MAGIC`` (which takes a single # argument, the entry) will be used to create an attribute ``e._MAGIC`` for # each entry ``e``. Either a single value or a list of values may be returned. # # In your layout, a file or directory name containing ``__MAGIC__`` will then # be evaluated once for each value ``make_MAGIC`` returns, with the entries # for which ``make_MAGIC`` returns that value or a list containing it. vars['blogname'] = 'Example Blog' class Entry: def get_organization(self): return self.m.get('Organization')
Correct return handling for authentication middleware function
const listenerUser = require ('./listenerUser'); const listenerApp = require ('./listenerApp'); // Initialize routes. function init (app) { listenerUser.init (); listenerApp.init (); app.post ('/api/login', listenerUser.login); app.post ('/api/logout', listenerUser.logout); app.get ('/api/verifylogin', listenerUser.verifyLogin); app.post ('/api/register', listenerUser.register); app.get ('/api/profile', isAuthenticated, listenerUser.getProfile); app.post ('/api/profile', isAuthenticated, listenerUser.updateProfile); app.get ('/api/polls', listenerApp.getPolls); app.get ('/api/polls/:_id', isAuthenticated, listenerApp.getPoll); app.post ('/api/polls', isAuthenticated, listenerApp.addPoll); app.post ('/api/polls/:_id', isAuthenticated, listenerApp.updatePoll); app.delete ('/api/polls/:_id', isAuthenticated, listenerApp.deletePoll); app.post ('/api/polls/:_id/votes/:choice', listenerApp.vote); } // authenticate, if passing continue, otherwise return 401 (auth failure) function isAuthenticated (req, res, next) { if (req.isAuthenticated ()) { return next (); } else { return res.status (401).json ({}); } } exports.init = init;
const listenerUser = require ('./listenerUser'); const listenerApp = require ('./listenerApp'); // Initialize routes. function init (app) { listenerUser.init (); listenerApp.init (); app.post ('/api/login', listenerUser.login); app.post ('/api/logout', listenerUser.logout); app.get ('/api/verifylogin', listenerUser.verifyLogin); app.post ('/api/register', listenerUser.register); app.get ('/api/profile', isAuthenticated, listenerUser.getProfile); app.post ('/api/profile', isAuthenticated, listenerUser.updateProfile); app.get ('/api/polls', listenerApp.getPolls); app.get ('/api/polls/:_id', isAuthenticated, listenerApp.getPoll); app.post ('/api/polls', isAuthenticated, listenerApp.addPoll); app.post ('/api/polls/:_id', isAuthenticated, listenerApp.updatePoll); app.delete ('/api/polls/:_id', isAuthenticated, listenerApp.deletePoll); app.post ('/api/polls/:_id/votes/:choice', listenerApp.vote); } // authenticate, if passing continue, otherwise return 401 (auth failure) function isAuthenticated (req, res, next) { if (req.isAuthenticated ()) { next (); } res.status (401).json ({}); } exports.init = init;
Revert "version 0.7.3 - fix DateFields" This reverts commit ea9568f0c30cb0bffeaeb0bd4dd809a724f535ce.
# encoding: utf-8 import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django_hstore_flattenfields', version='0.7.2', description='Django with dynamic fields in hstore', author=u'Iuri Diniz', author_email='iuridiniz@gmail.com', maintainer=u'Luís Araújo', maintainer_email='caitifbrito@gmail.com', url='https://github.com/multmeio/django-hstore-flattenfields', packages=find_packages( exclude=['example', 'example.*']), # long_description=read('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], zip_safe=False, install_requires=[ 'Django==1.4.3', 'django-orm-extensions==3.0b3', ] )
# encoding: utf-8 import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django_hstore_flattenfields', version='0.7.3', description='Django with dynamic fields in hstore', author=u'Iuri Diniz', author_email='iuridiniz@gmail.com', maintainer=u'Luís Araújo', maintainer_email='caitifbrito@gmail.com', url='https://github.com/multmeio/django-hstore-flattenfields', packages=find_packages( exclude=['example', 'example.*']), # long_description=read('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], zip_safe=False, install_requires=[ 'Django==1.4.3', 'django-orm-extensions==3.0b3', ] )
Make it work with PHP 8.0 method_exists requires first parameter to be object or string now and won't accept a null parameter
<?php namespace Adldap\Laravel\Validation\Rules; use Adldap\Laravel\Events\AuthenticatedModelTrashed; use Illuminate\Support\Facades\Event; class DenyTrashed extends Rule { /** * {@inheritdoc} */ public function isValid() { if ($this->isTrashed()) { Event::dispatch( new AuthenticatedModelTrashed($this->user, $this->model) ); return false; } return true; } /** * Determines if the current model is trashed. * * @return bool */ protected function isTrashed() { if ($this->model) { return method_exists($this->model, 'trashed') && $this->model->trashed(); } return false; } }
<?php namespace Adldap\Laravel\Validation\Rules; use Adldap\Laravel\Events\AuthenticatedModelTrashed; use Illuminate\Support\Facades\Event; class DenyTrashed extends Rule { /** * {@inheritdoc} */ public function isValid() { if ($this->isTrashed()) { Event::dispatch( new AuthenticatedModelTrashed($this->user, $this->model) ); return false; } return true; } /** * Determines if the current model is trashed. * * @return bool */ protected function isTrashed() { return method_exists($this->model, 'trashed') && $this->model->trashed(); } }
Edit ESLint config: Double quotes, multiline comma-dangle, React support
module.exports = { env: { browser: true, es6: true }, extends: "eslint:recommended", parserOptions: { ecmaFeatures: { experimentalObjectRestSpread: true, jsx: true }, sourceType: "module" }, plugins: ["react"], rules: { camelcase: "error", "comma-dangle": ["error", "only-multiline"], "comma-style": ["error", "last"], eqeqeq: "error", indent: ["error", 2, { VariableDeclarator: 2 }], "linebreak-style": ["error", "unix"], "no-eq-null": "error", "no-extra-parens": "error", "no-extra-semi": "error", "no-lonely-if": "error", "no-multi-spaces": 0, "no-nested-ternary": "error", "no-param-reassign": "error", "no-self-compare": "error", "no-shadow": "error", "no-throw-literal": "error", "no-undef": "error", "no-underscore-dangle": 0, "no-void": "error", quotes: ["error", "double"], semi: ["error", "always"] } };
/*eslint-env node*/ module.exports = { parserOptions: { ecmaVersion: 6, sourceType: "module" }, env: { browser: true }, rules: { camelcase: 2, "comma-dangle": [2, "never"], "comma-style": [2, "last"], eqeqeq: 2, indent: [2, 2, { VariableDeclarator: 2 }], "no-eq-null": 2, "no-extra-parens": 2, "no-extra-semi": 2, "no-lonely-if": 2, "no-multi-spaces": 0, "no-nested-ternary": 2, "no-param-reassign": 2, "no-self-compare": 2, "no-shadow": 2, "no-throw-literal": 2, "no-undef": 2, "no-underscore-dangle": 0, "no-void": 2, quotes: [2, "single"], semi: [2, "always"] } };
Add crash prevention when a name not does not have a patient event
import Realm from 'realm'; export class NameNote extends Realm.Object { get data() { try { return JSON.parse(this._data); } catch { // swallow error, return a default return null; } } // Will throw if newValue is unable to be stringified set data(newValue) { this._data = JSON.stringify(newValue); } get patientEventID() { return this.patientEvent?.id; } toObject() { return { id: this.id, entryDate: this.entryDate.getTime(), data: this.data, nameID: this.name.id, patientEventID: this.patientEvent?.id, }; } } NameNote.schema = { name: 'NameNote', primaryKey: 'id', properties: { id: 'string', entryDate: { type: 'date', default: new Date() }, _data: { type: 'string', optional: true }, name: 'Name', patientEvent: 'PatientEvent', }, }; export default NameNote;
import Realm from 'realm'; export class NameNote extends Realm.Object { get data() { try { return JSON.parse(this._data); } catch { // swallow error, return a default return null; } } // Will throw if newValue is unable to be stringified set data(newValue) { this._data = JSON.stringify(newValue); } get patientEventID() { return this.patientEvent?.id; } toObject() { return { id: this.id, entryDate: this.entryDate.getTime(), data: this.data, nameID: this.name.id, patientEventID: this.patientEvent.id, }; } } NameNote.schema = { name: 'NameNote', primaryKey: 'id', properties: { id: 'string', entryDate: { type: 'date', default: new Date() }, _data: { type: 'string', optional: true }, name: 'Name', patientEvent: 'PatientEvent', }, }; export default NameNote;
BUGFIX: Make sure to livequery the migrate button...
/** * jQuery functionality used on the external content admin page */ ;(function ($, pt) { $().ready(function () { // bind the upload form $('#Form_EditForm_Migrate').livequery(function () { $(this).click(function () { // we don't want this to be submitted via the edit form, as we want to do an ajax postback for this // and not tie up the response. var form = $(this).parents('form'); // wrap it all up and post away! var params = form.serializeArray(); var postParams = {}; $.each(params, function (index) { postParams[this.name] = this.value; }); postParams['action_migrate'] = true; statusMessage('Importing ...', 2); $.post(form.attr('action'), postParams, function (data) { if (data) { var response = $.parseJSON(data); if (response && response.status) { statusMessage(response.message, 'good'); } else { statusMessage("There was a problem with the import"); } } // reset the base form if (pt) { pt(form.attr('id')).resetElements(); } }); return false; }); }); }); })(jQuery, $);
/** * jQuery functionality used on the external content admin page */ ;(function ($, pt) { $().ready(function () { // bind the upload form $('#Form_EditForm_Migrate').click(function () { // we don't want this to be submitted via the edit form, as we want to do an ajax postback for this // and not tie up the response. var form = $(this).parents('form'); // wrap it all up and post away! var params = form.serializeArray(); var postParams = {}; $.each(params, function (index) { postParams[this.name] = this.value; }); postParams['action_migrate'] = true; statusMessage('Importing ...', 2); $.post(form.attr('action'), postParams, function (data) { if (data) { var response = $.parseJSON(data); if (response && response.status) { statusMessage(response.message, 'good'); } else { statusMessage("There was a problem with the import"); } } // reset the base form if (pt) { pt(form.attr('id')).resetElements(); } }); return false; }); }); })(jQuery, $);
Fix broken webpack ES3 support WebPack now has the screw_ie8 default. This isn't acceptable for a module that is to be used as a general basis for other software. Also, Redux, which this module is designed to extend, does support IE8 as well.
'use strict'; var webpack = require('webpack'); var env = process.env.NODE_ENV; var config = { module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'] } ] }, output: { library: 'ReduxSchema', libraryTarget: 'umd' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env) }) ] }; if (env === 'production') { config.plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { pure_getters: false, unsafe: false, unsafe_comps: false, warnings: false, screw_ie8: false }, mangle: { screw_ie8: false }, output: { screw_ie8: false } }) ) } module.exports = config;
'use strict'; var webpack = require('webpack'); var env = process.env.NODE_ENV; var config = { module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'] } ] }, output: { library: 'ReduxSchema', libraryTarget: 'umd' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env) }) ] }; if (env === 'production') { config.plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { pure_getters: false, unsafe: false, unsafe_comps: false, warnings: false } }) ) } module.exports = config;
Rename the configuration task to services.
import del from 'del'; import path from 'path'; import gulp from 'gulp'; import eslint from 'gulp-eslint'; import babel from 'gulp-babel'; import writeFile from './build/write-file'; import generateRoutes from './src/routes/generate'; import './build/azure'; gulp.task('clean', ['azure:clean'], () => del(['dist'])); gulp.task('lint', () => gulp.src(['gulpfile.js', 'src/**/*.js', 'test/**/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError())); gulp.task('transform', ['clean'], () => gulp.src('src/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist'))); gulp.task('services', ['clean'], () => writeFile( path.resolve(__dirname, './dist/services/configuration.json'), '{}')); gulp.task('routes', ['clean'], () => writeFile( path.resolve(__dirname, './dist/routes/routes.json'), JSON.stringify({ routes: generateRoutes() }))); gulp.task('build', [ 'lint', 'routes', 'services', 'transform', ]);
import del from 'del'; import path from 'path'; import gulp from 'gulp'; import eslint from 'gulp-eslint'; import babel from 'gulp-babel'; import writeFile from './build/write-file'; import generateRoutes from './src/routes/generate'; import './build/azure'; gulp.task('clean', ['azure:clean'], () => del(['dist'])); gulp.task('lint', () => gulp.src(['gulpfile.js', 'src/**/*.js', 'test/**/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError())); gulp.task('transform', ['clean'], () => gulp.src('src/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist'))); gulp.task('configuration', ['clean'], () => writeFile( path.resolve(__dirname, './dist/services/configuration.json'), '{}')); gulp.task('routes', ['clean'], () => writeFile( path.resolve(__dirname, './dist/routes/routes.json'), JSON.stringify({ routes: generateRoutes() }))); gulp.task('build', [ 'lint', 'routes', 'transform', 'configuration', ]);
Remove useless JS referencing explorer
$(function() { $('.nav-main .submenu-trigger').on('click', function() { if ($(this).closest('li').find('.nav-submenu').length) { // Close other active submenus first, if any if ($('.nav-wrapper.submenu-active').length && !$(this).closest('li').hasClass('submenu-active')) { $('.nav-main .submenu-active, .nav-wrapper').removeClass('submenu-active'); } $(this).closest('li').toggleClass('submenu-active'); $('.nav-wrapper').toggleClass('submenu-active'); return false; } }); $(document).on('keydown click', function(e) { if ($('.nav-wrapper.submenu-active').length && (e.keyCode == 27 || !e.keyCode)) { $('.nav-main .submenu-active, .nav-wrapper').removeClass('submenu-active'); } }); });
$(function() { var $explorer = $('#explorer'); $('.nav-main .submenu-trigger').on('click', function() { if ($(this).closest('li').find('.nav-submenu').length) { // Close other active submenus first, if any if ($('.nav-wrapper.submenu-active').length && !$(this).closest('li').hasClass('submenu-active')) { $('.nav-main .submenu-active, .nav-wrapper').removeClass('submenu-active'); } $(this).closest('li').toggleClass('submenu-active'); $('.nav-wrapper').toggleClass('submenu-active'); return false; } }); $(document).on('keydown click', function(e) { if ($('.nav-wrapper.submenu-active').length && (e.keyCode == 27 || !e.keyCode)) { $('.nav-main .submenu-active, .nav-wrapper').removeClass('submenu-active'); } }); });
Move button to top nav bar Change styling to match Toggl color scheme
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; togglbutton.render('#layout-container:not(.toggl)', {observe: true}, function (elem) { var link, description, project = $('.objectlink.breadcrumb-link.first-item', elem).textContent; description = function(){ var delimiter = ' > ', w_type = window.location.pathname.split('/')[1], w_id = $('#layout-content').innerHTML.split('detailObjID":"')[1].split('"')[0], w_name = $('.detail-name-edit', elem).textContent; return w_type + delimiter + w_name + delimiter + w_id; }; link = togglbutton.createTimerLink({ className: 'attask', description: description, projectName: project }); var t_style = document.createElement("style"); t_style.innerHTML = ".toggl-button{height: 62px;line-height: 62px;background-color:#333;background-position: 1em 50%;padding: 0 1em 0 2.75em;transition: all 0.5s ease;}#nav-toggl{height: 62px; vertical-align: middle; } .toggl-button:hover{background-color:#000 !important;} .toggl-button.active{background-color:#000;}"; document.head.appendChild(t_style); var t_container = document.createElement("li"); t_container.id = "nav-toggl"; t_container.className = "navbar-item"; t_container.appendChild(link); var navgroup = document.querySelector('.navbar-item-group.right'); navgroup.insertBefore(t_container, navgroup.children[0]); });
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; togglbutton.render('#layout-container:not(.toggl)', {observe: true}, function (elem) { var link, description, project = $('.objectlink.breadcrumb-link.first-item', elem).textContent; description = function(){ var delimiter = ' > ', w_type = window.location.pathname.split('/')[1], w_id = $('#layout-content').innerHTML.split('detailObjID":"')[1].split('"')[0], w_name = $('.detail-name-edit', elem).textContent; return w_type + delimiter + w_name + delimiter + w_id; }; link = togglbutton.createTimerLink({ className: 'attask', description: description, projectName: project }); link.style.float = 'right'; $('.user-actions').appendChild(link); });
Update the comment ranges to reflect the new replacements.
import getFreeBinding from '../utils/getFreeBinding'; /** * Convert binary existential operators, e.g. `a ? b` into `if` expressions * using unary existential operators, e.g. `if a? then a else b`. * * @param {Object} node * @param {MagicString} patcher */ export default function preprocessBinaryExistentialOperator(node, patcher) { if (node.type === 'ExistsOp') { // e.g. `if a? then a else b` // ^^^ patcher.insert(node.range[0], 'if '); if (node.left.type === 'Identifier') { // e.g. `a ? b` -> `if a? then a else b` // ^^^^^ ^^^^^^^^^^^^^^^^ patcher.replace(node.range[0], node.range[1], `${node.left.raw}? then ${node.left.raw} else ${node.right.raw}`); } else { let tmp = getFreeBinding(node.scope); // e.g. `@a ? @b` -> `if (ref = @a)? then ref else @b` // ^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ patcher.replace(node.range[0], node.range[1], `(${tmp} = ${node.left.raw})? then ${tmp} else ${node.right.raw}`); } return true; } }
import getFreeBinding from '../utils/getFreeBinding'; /** * Convert binary existential operators, e.g. `a ? b` into `if` expressions * using unary existential operators, e.g. `if a? then a else b`. * * @param {Object} node * @param {MagicString} patcher */ export default function preprocessBinaryExistentialOperator(node, patcher) { if (node.type === 'ExistsOp') { // e.g. `if a? then a else b` // ^^^ patcher.insert(node.range[0], 'if '); if (node.left.type === 'Identifier') { // e.g. `a ? b` -> `if a? then a else b` // ^^^ ^^^^^^^^^^^^^^ patcher.replace(node.range[0], node.range[1], `${node.left.raw}? then ${node.left.raw} else ${node.right.raw}`); } else { let tmp = getFreeBinding(node.scope); // e.g. `@a ? @b` -> `if (ref = @a)? then ref else @b` // ^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ patcher.replace(node.range[0], node.range[1], `(${tmp} = ${node.left.raw})? then ${tmp} else ${node.right.raw}`); } return true; } }
Fix up ICIJ loader as-is
import io from csv import DictReader from zipfile import ZipFile from normality import slugify, stringify from dataset.chunked import ChunkedInsert def load_file(context, zip, name): fh = zip.open(name) _, section, _ = name.rsplit(".", 2) table_name = "%s_%s" % (context.crawler.name, section) table = context.datastore[table_name] table.drop() fh = io.TextIOWrapper(fh) reader = DictReader(fh, delimiter=",", quotechar='"') chunk = ChunkedInsert(table) for i, row in enumerate(reader, 1): row = {slugify(k, sep="_"): stringify(v) for (k, v) in row.items()} chunk.insert(row) chunk.flush() context.log.info("Done [%s]: %s rows...", table_name, i) def load(context, data): with context.http.rehash(data) as result: with ZipFile(result.file_path, "r") as zip: for name in zip.namelist(): load_file(context, zip, name)
from normality import slugify, stringify from csv import DictReader from zipfile import ZipFile def load_file(context, zip, name): fh = zip.open(name) _, section, _ = name.rsplit(".", 2) table_name = "%s_%s" % (context.crawler.name, section) table = context.datastore[table_name] table.drop() reader = DictReader(fh, delimiter=",", quotechar='"') chunk = [] for i, row in enumerate(reader, 1): row = {slugify(k, sep="_"): stringify(v) for (k, v) in row.items()} chunk.append(row) if len(chunk) >= 20000: context.log.info("Loaded [%s]: %s rows...", table_name, i) table.insert_many(chunk) chunk = [] if len(chunk): table.insert_many(chunk) context.log.info("Done [%s]: %s rows...", table_name, i) def load(context, data): with context.http.rehash(data) as result: with ZipFile(result.file_path, "r") as zip: for name in zip.namelist(): load_file(context, zip, name)
Add PickleDecoder to the public API
__version__ = '1.16.14' from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, StaticIdProvider, \ KeyBuilder, StringDelimitedKeyBuilder, Database, FileSystemDatabase, \ InMemoryDatabase from datawriter import DataWriter from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder, PickleDecoder from lmdbstore import LmdbDatabase from objectstore import ObjectStoreDatabase from persistence import PersistenceSettings from iteratornode import IteratorNode from eventlog import EventLog, RedisChannel try: from nmpy import NumpyEncoder, PackedNumpyEncoder, StreamingNumpyDecoder, \ BaseNumpyDecoder, NumpyMetaData, NumpyFeature except ImportError: pass
__version__ = '1.16.14' from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, StaticIdProvider, \ KeyBuilder, StringDelimitedKeyBuilder, Database, FileSystemDatabase, \ InMemoryDatabase from datawriter import DataWriter from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from objectstore import ObjectStoreDatabase from persistence import PersistenceSettings from iteratornode import IteratorNode from eventlog import EventLog, RedisChannel try: from nmpy import NumpyEncoder, PackedNumpyEncoder, StreamingNumpyDecoder, \ BaseNumpyDecoder, NumpyMetaData, NumpyFeature except ImportError: pass
Add exitOnError as optional parameter
const Assert = require('assert'); const FS = require('fs'); const Winston = require('winston'); const Factory = require('./lib/factory'); var exceptionLogger; function isString(str) { return typeof str === 'string'; } module.exports = function (namespace) { var level; Assert(namespace && isString(namespace), 'must provide namespace'); level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env return Factory(namespace, level, !exceptionLogger); }; module.exports.writeExceptions = function (path, exitOnError) { Assert(path && isString(path), 'must provide a file path'); // TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0 FS.appendFileSync(path, ''); // eslint-disable-line no-sync exceptionLogger = new Winston.Logger({ transports: [ new Winston.transports.File({ exitOnError: exitOnError, filename: path, handleExceptions: true, humanReadableUnhandledException: true }) ] }); };
const Assert = require('assert'); const FS = require('fs'); const Winston = require('winston'); const Factory = require('./lib/factory'); var exceptionLogger; function isString(str) { return typeof str === 'string'; } module.exports = function (namespace) { var level; Assert(namespace && isString(namespace), 'must provide namespace'); level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env return Factory(namespace, level, !exceptionLogger); }; module.exports.writeExceptions = function (path) { Assert(path && isString(path), 'must provide a file path'); // TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0 FS.appendFileSync(path, ''); // eslint-disable-line no-sync exceptionLogger = new Winston.Logger({ transports: [ new Winston.transports.File({ exitOnError: true, filename: path, handleExceptions: true, humanReadableUnhandledException: true }) ] }); };
Make post creation work again.
(function(config, models, views, routers, utils, templates) { views.NewPost = Backbone.View.extend({ id: 'new_post', events: { 'submit #new_post_form': 'createPost' }, createPost: function() { var that = this; var filename = this.$('.filename').val(); var title = this.$('.title').val(); var subtitle = this.$('.subtitle').val(); var metadata = { title: title, subtitle: subtitle, published: false }; savePost(app.state.user, app.state.repo, app.state.branch, app.state.path, filename, _.toYAML(metadata), '', 'Created ' +filename, function(err) { router.navigate(app.state.user + '/' + app.state.repo + '/' + app.state.branch + '/' + app.state.path + '/' + filename, true); }); return false; }, initialize: function(options) { }, render: function() { $(this.el).html(templates.new_post(this.model)); return this; } }); }).apply(this, window.args);
(function(config, models, views, routers, utils, templates) { views.NewPost = Backbone.View.extend({ id: 'new_post', events: { 'submit #new_post_form': 'createPost' }, createPost: function() { var that = this; var filename = this.$('.filename').val(); var title = this.$('.title').val(); var subtitle = this.$('.subtitle').val(); // TODO: make this smart // No assumptions on the repository layout should be made var metadata = { title: title, category: 'blog', subtitle: subtitle, hidden: true }; savePost(app.state.user, app.state.repo, app.state.branch, app.state.path, filename, metadata, '', 'Created ' +filename, function(err) { router.navigate(app.state.user + '/' + app.state.repo + '/' + app.state.branch + '/' + app.state.path + '/' + filename, true); }); return false; }, initialize: function(options) { }, render: function() { $(this.el).html(templates.new_post(this.model)); return this; } }); }).apply(this, window.args);
Simplify adding spaces and add time/space complexity
"""Codewars: Draw stairs 8 kyu URL: https://www.codewars.com/kata/draw-stairs/ Given a number n, draw stairs using the letter "I", n tall and n wide, with the tallest in the top left. For example n = 3 result in "I\n I\n I", or printed: I I I Another example, a 7-step stairs should be drawn like this: I I I I I I I """ def draw_stairs(n): """ Time complexity: O(n^2). Space complexity: O(n). """ stairs = [] for i in range(n): # Append (i - 1) spaces. stairs.append(' ' * i) # Append stair I. stairs.append('I') # Append change line if not the last line. if i != n - 1: stairs.append('\n') return ''.join(stairs) def main(): # Output: "I\n I\n I" n = 3 print draw_stairs(n) # Output: "I\n I\n I\n I\n I\n I\n I\n I" n = 7 print draw_stairs(n) if __name__ == '__main__': main()
"""Codewars: Draw stairs 8 kyu URL: https://www.codewars.com/kata/draw-stairs/ Given a number n, draw stairs using the letter "I", n tall and n wide, with the tallest in the top left. For example n = 3 result in "I\n I\n I", or printed: I I I Another example, a 7-step stairs should be drawn like this: I I I I I I I """ def draw_stairs(n): stairs = [] for i in range(n): # Append (i - 1) spaces. for _ in range(i): stairs.append(' ') # Append stair I. stairs.append('I') # Append change line if not the last line. if i != n - 1: stairs.append('\n') return ''.join(stairs) def main(): # Output: "I\n I\n I" n = 3 print draw_stairs(n) # Output: "I\n I\n I\n I\n I\n I\n I\n I" n = 7 print draw_stairs(n) if __name__ == '__main__': main()
Add persistance class for ConfigSchema.
# Licensed to the StackStorm, Inc ('StackStorm') 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. from st2common.models.db.pack import pack_access from st2common.persistence import base __all__ = [ 'Pack', 'ConfigSchema' ] class Pack(base.Access): impl = pack_access @classmethod def _get_impl(cls): return cls.impl class ConfigSchema(base.Access): impl = pack_access @classmethod def _get_impl(cls): return cls.impl
# Licensed to the StackStorm, Inc ('StackStorm') 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. from st2common.models.db.pack import pack_access from st2common.persistence import base __all__ = [ 'Pack' ] class Pack(base.Access): impl = pack_access @classmethod def _get_impl(cls): return cls.impl