text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Move private variable to bottom of struct
package onedrive import ( "net/http" "time" ) const ( version = "0.1" baseURL = "https://api.onedrive.com/v1.0" userAgent = "github.com/ggordan/go-onedrive; version " + version ) // OneDrive is the entry point for the client. It manages the communication with // Microsoft OneDrive API type OneDrive struct { Client *http.Client // When debug is set to true, the JSON response is formatted for better readability Debug bool BaseURL string // Services Drives *DriveService Items *ItemService // Private throttle time.Time } // NewOneDrive returns a new OneDrive client to enable you to communicate with // the API func NewOneDrive(c *http.Client, debug bool) *OneDrive { drive := OneDrive{ Client: c, BaseURL: baseURL, Debug: debug, throttle: time.Now(), } drive.Drives = &DriveService{&drive} drive.Items = &ItemService{&drive} return &drive } func (od *OneDrive) throttleRequest(time time.Time) { od.throttle = time }
package onedrive import ( "net/http" "time" ) const ( version = "0.1" baseURL = "https://api.onedrive.com/v1.0" userAgent = "github.com/ggordan/go-onedrive; version " + version ) // OneDrive is the entry point for the client. It manages the communication with // Microsoft OneDrive API type OneDrive struct { Client *http.Client // When debug is set to true, the JSON response is formatted for better readability Debug bool BaseURL string throttle time.Time // Services Drives *DriveService Items *ItemService } // NewOneDrive returns a new OneDrive client to enable you to communicate with // the API func NewOneDrive(c *http.Client, debug bool) *OneDrive { drive := OneDrive{ Client: c, BaseURL: baseURL, Debug: debug, throttle: time.Now(), } drive.Drives = &DriveService{&drive} drive.Items = &ItemService{&drive} return &drive } func (od *OneDrive) throttleRequest(time time.Time) { od.throttle = time }
Introduce pause in the output so as not to overwhelm the IPC mechanism between test worker and build host.
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); Thread.sleep(5); } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); Thread.sleep(5); } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
Modify text for management command message
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.bad_redirect_text(url, e) def bad_redirect_text(self, url, exception): """ Return informational text for a URL that raised an exception. """ return """ Redirect {key} with target {target} returns {error} Edit this short URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.error_text(url, e) def error_text(self, url, exception): """ """ return """ Bad redirect target: {key} {target} returns {error} Edit this URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
Make sure we have a recipient before sending notification
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db.models.signals import post_save from notification import models as notification from ..core.models import BaseModel class Comment(BaseModel): user = models.ForeignKey('profiles.User', related_name='users') content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') comment = models.TextField() def __unicode__(self): return '{0}: {1}...'.format(self.user.first_name, self.comment[:50]) class Meta: ordering = ('date_created',) def comment_saved(sender, instance, created, **kwargs): mentor = instance.content_object.mentor protege = instance.content_object.protege meeting_url = instance.content_object.get_url_with_domain() if instance.user == mentor: recipient = protege elif instance.user == protege: recipient = mentor if created and recipient: notification.send( [recipient], 'comment', {'comment': instance, 'recipient': recipient, 'meeting_url': meeting_url}) post_save.connect(comment_saved, sender=Comment)
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db.models.signals import post_save from notification import models as notification from ..core.models import BaseModel class Comment(BaseModel): user = models.ForeignKey('profiles.User', related_name='users') content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') comment = models.TextField() def __unicode__(self): return '{0}: {1}...'.format(self.user.first_name, self.comment[:50]) class Meta: ordering = ('date_created',) def comment_saved(sender, instance, created, **kwargs): mentor = instance.content_object.mentor protege = instance.content_object.protege meeting_url = instance.content_object.get_url_with_domain() if created: if instance.user == mentor: recipient = protege elif instance.user == protege: recipient = mentor notification.send( [recipient], 'comment', {'comment': instance, 'recipient': recipient, 'meeting_url': meeting_url}) post_save.connect(comment_saved, sender=Comment)
Use unbreakable spaces in lang dropdown
import React from 'react' import PropTypes from 'prop-types' import moment from 'moment' import { translate } from 'react-i18next' import Dropdown from '../Dropdown' export class LanguageSelection extends React.PureComponent { static propTypes = { i18n: PropTypes.shape({ changeLanguage: PropTypes.func.isRequired }).isRequired } changeLanguage(language) { const { i18n } = this.props moment.locale(language) i18n.changeLanguage(language) } render() { const { i18n } = this.props return ( <Dropdown title={i18n.language === 'en' ? '🇬🇧' : '🇫🇷'}> <div onClick={() => this.changeLanguage('en')}>English 🇬🇧</div> <div onClick={() => this.changeLanguage('fr')}>Français 🇫🇷</div> </Dropdown> ) } } export default translate('Common')(LanguageSelection)
import React from 'react' import PropTypes from 'prop-types' import moment from 'moment' import { translate } from 'react-i18next' import Dropdown from '../Dropdown' export class LanguageSelection extends React.PureComponent { static propTypes = { i18n: PropTypes.shape({ changeLanguage: PropTypes.func.isRequired }).isRequired } changeLanguage(language) { const { i18n } = this.props moment.locale(language) i18n.changeLanguage(language) } render() { const { i18n } = this.props return ( <Dropdown title={i18n.language === 'en' ? '🇬🇧' : '🇫🇷'}> <div onClick={() => this.changeLanguage('en')}>English 🇬🇧</div> <div onClick={() => this.changeLanguage('fr')}>Français 🇫🇷</div> </Dropdown> ) } } export default translate('Common')(LanguageSelection)
Speed up deep copy of fields
# -*- coding: utf-8 -*- '''Abstract base classes. These are necessary to avoid circular imports between core.py and fields.py. ''' import copy class FieldABC(object): '''Abstract base class from which all Field classes inherit. ''' parent = None name = None def format(self, value): raise NotImplementedError def output(self, key, obj): raise NotImplementedError def __deepcopy__(self, memo): ret = copy.copy(self) return ret def __repr__(self): return "<{0} Field>".format(self.__class__.__name__) __str__ = __repr__ class SerializerABC(object): '''Abstract base class from which all Serializers inherit.''' @property def errors(self): raise NotImplementedError def is_valid(self, fields=None): raise NotImplementedError
# -*- coding: utf-8 -*- '''Abstract base classes. These are necessary to avoid circular imports between core.py and fields.py. ''' class FieldABC(object): '''Abstract base class from which all Field classes inherit. ''' parent = None name = None def format(self, value): raise NotImplementedError def output(self, key, obj): raise NotImplementedError def __repr__(self): return "<{0} Field>".format(self.__class__.__name__) __str__ = __repr__ class SerializerABC(object): '''Abstract base class from which all Serializers inherit.''' @property def errors(self): raise NotImplementedError def is_valid(self, fields=None): raise NotImplementedError
Use `done` callback for smooth animation
$(function() { $('.accordion_head').each( function() { $(this).after('<ul style="display: none;"></ul>'); }); $(document).on("click", '.accordion_head', function() { var ul = $(this).next(); if (ul.text() == '') { term = $(this).data('term'); $.getJSON("/children_graph?term=" + term) .done(function(data) { $.each(data, function(i,item) { ul.append('<li><div class="accordion_head" data-term="' + item.path + '"><a href="' + item.uri + '" >' + item.basename+ '</a></div><ul style="display: none;"></ul></li>'); }); ul.hide().slideToggle(); }); } else { ul.slideToggle(); } }).next().hide(); });
$(function() { $('.accordion_head').each( function() { $(this).after('<ul style="display: none;"></ul>'); }); $(document).on("click", '.accordion_head', function() { var ul = $(this).next(); if (ul.text() == '') { term = $(this).data('term'); $.getJSON("/children_graph?term=" + term, function(data) { $.each(data, function(i,item) { ul.append('<li><div class="accordion_head" data-term="' + item.path + '"><a href="' + item.uri + '" >' + item.basename+ "</a></div><ul style='dispaly: none;'><ul></li>"); }); }); ul.slideToggle(); } else { ul.slideToggle(); } }).next().hide(); });
[Acrimed] Use internal RSS 2.0 parser
<?php class AcrimedBridge extends FeedExpander { const MAINTAINER = "qwertygc"; const NAME = "Acrimed Bridge"; const URI = "http://www.acrimed.org/"; const DESCRIPTION = "Returns the newest articles."; public function collectData(){ $this->collectExpandableDatas("http://www.acrimed.org/spip.php?page=backend"); } protected function parseItem($newsItem){ $item = $this->parseRSS_2_0_Item($newsItem); $hs = new HTMLSanitizer(); $articlePage = $this->getSimpleHTMLDOM($newsItem->link); $article = $hs->sanitize($articlePage->find('article.article1', 0)->innertext); $article = HTMLSanitizer::defaultImageSrcTo($article, "http://www.acrimed.org/"); $item['content'] = $article; return $item; } public function getCacheDuration(){ return 4800; // 2 hours } }
<?php class AcrimedBridge extends FeedExpander{ const MAINTAINER = "qwertygc"; const NAME = "Acrimed Bridge"; const URI = "http://www.acrimed.org/"; const DESCRIPTION = "Returns the newest articles."; public function collectData(){ $this->collectExpandableDatas("http://www.acrimed.org/spip.php?page=backend"); } protected function parseItem($newsItem) { $hs = new HTMLSanitizer(); $namespaces = $newsItem->getNameSpaces(true); $dc = $newsItem->children($namespaces['dc']); $item = array(); $item['uri'] = trim($newsItem->link); $item['title'] = trim($newsItem->title); $item['timestamp'] = strtotime($dc->date); $articlePage = $this->getSimpleHTMLDOM($newsItem->link); $article = $hs->sanitize($articlePage->find('article.article1', 0)->innertext); $article = HTMLSanitizer::defaultImageSrcTo($article, "http://www.acrimed.org/"); $item['content'] = $article; return $item; } public function getCacheDuration(){ return 4800; // 2 hours } }
Make Google implicit grant redirect to the local Ember app
/** * This class implements authentication against google * using the client-side OAuth2 authorization flow in a popup window. */ import Oauth2Bearer from 'torii/providers/oauth2-bearer'; import {configurable} from 'torii/configuration'; var GoogleOauth2Bearer = Oauth2Bearer.extend({ name: 'google-oauth2-bearer', baseUrl: 'https://accounts.google.com/o/oauth2/auth', // additional params that this provider requires optionalUrlParams: ['scope', 'request_visible_actions'], requestVisibleActions: configurable('requestVisibleActions', ''), responseParams: ['access_token'], scope: configurable('scope', 'email'), redirectUri: configurable('redirectUri', 'http://localhost:4200/oauth2callback') }); export default GoogleOauth2Bearer;
/** * This class implements authentication against google * using the client-side OAuth2 authorization flow in a popup window. */ import Oauth2Bearer from 'torii/providers/oauth2-bearer'; import {configurable} from 'torii/configuration'; var GoogleOauth2Bearer = Oauth2Bearer.extend({ name: 'google-oauth2-bearer', baseUrl: 'https://accounts.google.com/o/oauth2/auth', // additional params that this provider requires optionalUrlParams: ['scope', 'request_visible_actions'], requestVisibleActions: configurable('requestVisibleActions', ''), responseParams: ['access_token'], scope: configurable('scope', 'email'), redirectUri: configurable('redirectUri', 'http://localhost:8000/oauth2callback') }); export default GoogleOauth2Bearer;
Fix typo in docs for /icon set.
import asyncio import io import re from plumeria.command import commands, CommandError from plumeria.message import Message from plumeria.message.image import read_image from plumeria.perms import server_admins_only from plumeria.transport.transport import ForbiddenError @commands.register('icon set', category='Management') @server_admins_only async def set_icon(message: Message): """ Set the server icon to the given image. Example:: /drawtext Hello there! | icon set Requires an input image. """ attachment = await read_image(message) if not attachment: raise CommandError("No image is available to process.") def execute(): width, height = attachment.image.size if width < 128 or height < 128: raise CommandError("Image is too small (128x128 minimum size).") buffer = io.BytesIO() attachment.image.save(buffer, "png") return buffer.getvalue() image_data = await asyncio.get_event_loop().run_in_executor(None, execute) try: await message.server.update(icon=image_data) return "Server icon updated." except ForbiddenError as e: raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
import asyncio import io import re from plumeria.command import commands, CommandError from plumeria.message import Message from plumeria.message.image import read_image from plumeria.perms import server_admins_only from plumeria.transport.transport import ForbiddenError @commands.register('icon set', category='Management') @server_admins_only async def set_icon(message: Message): """ Set the server icon to the given image. Example:: /drawtext Hello there! | set icon Requires an input image. """ attachment = await read_image(message) if not attachment: raise CommandError("No image is available to process.") def execute(): width, height = attachment.image.size if width < 128 or height < 128: raise CommandError("Image is too small (128x128 minimum size).") buffer = io.BytesIO() attachment.image.save(buffer, "png") return buffer.getvalue() image_data = await asyncio.get_event_loop().run_in_executor(None, execute) try: await message.server.update(icon=image_data) return "Server icon updated." except ForbiddenError as e: raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
Fix property fallback removes attribute
import List from './List'; class Property extends List { link(node, name, value) { const accessor = this.resolveProperty(node, name); this.engine._link(value, { value: accessor.get(), observe: accessor.set }); } resolveProperty(node, name) { if (name in node) { return { get: ()=> node[name], set: (value)=> node[name] = value }; } else { return { get: ()=> { const val = node.getAttribute(name); return val ? val : undefined; }, set: (value)=> { if (value === false || value === undefined || value === null) { node.removeAttribute(name); } else { node.setAttribute(name, value === true ? name : value); } } }; } } } export default Property;
import List from './List'; class Property extends List { link(node, name, value) { const accessor = this.resolveProperty(node, name); this.engine._link(value, { value: accessor.get(), observe: accessor.set }); } resolveProperty(node, name) { if (name in node) { return { get: ()=> node[name], set: (value)=> node[name] = value }; } else { return { get: ()=> { const val = node.getAttribute(name); return val ? val : undefined; }, set: (value)=> { if (value === false) { node.removeAttribute(name); } else { node.setAttribute(name, value === true ? name : value); } } }; } } } export default Property;
Fix initial capital domain table name
package ee.tuleva.onboarding.capital; import ee.tuleva.onboarding.user.User; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.NotBlank; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.math.BigDecimal; @Data @Builder @Entity @Table(name = "initial_capital") @AllArgsConstructor @NoArgsConstructor public class InitialCapital { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull BigDecimal amount; @NotBlank @Size(min = 3, max = 3) String currency; @OneToOne User user; }
package ee.tuleva.onboarding.capital; import ee.tuleva.onboarding.user.User; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.NotBlank; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.math.BigDecimal; @Data @Builder @Entity @Table(name = "users") @AllArgsConstructor @NoArgsConstructor public class InitialCapital { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull BigDecimal amount; @NotBlank @Size(min = 3, max = 3) String currency; @OneToOne User user; }
Change reporter style in Karma.
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['mocha', 'chai'], // reporter style reporters: [ 'dots' ], // list of files / patterns to load in the browser files: [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Firefox'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['mocha', 'chai'], // list of files / patterns to load in the browser files: [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Firefox'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
Add FIXME for delete PDF
# coding: utf8 import errno import logging import os from slugify import slugify from labonneboite.conf import settings logger = logging.getLogger('main') def get_file_path(office): file_path = "pdf/%s/%s/%s/%s.pdf" % (office.departement, office.naf, slugify(office.name.strip()[0]), office.siret) full_path = os.path.join(settings.GLOBAL_STATIC_PATH, file_path) return full_path def write_file(office, data): filename = get_file_path(office) if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise with open(filename, "w") as f: f.write(data) f.close() logger.info("wrote PDF file to %s", filename) def delete_file(office): # FIXME : Works only on one front-end... filename = get_file_path(office) if os.path.exists(filename): os.remove(filename)
# coding: utf8 import errno import logging import os from slugify import slugify from labonneboite.conf import settings logger = logging.getLogger('main') def get_file_path(office): file_path = "pdf/%s/%s/%s/%s.pdf" % (office.departement, office.naf, slugify(office.name.strip()[0]), office.siret) full_path = os.path.join(settings.GLOBAL_STATIC_PATH, file_path) return full_path def write_file(office, data): filename = get_file_path(office) if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise with open(filename, "w") as f: f.write(data) f.close() logger.info("wrote PDF file to %s", filename) def delete_file(office): filename = get_file_path(office) if os.path.exists(filename): os.remove(filename)
Add async and defer support
//= require js.cookie 'use strict'; var cookiesEu = { init: function() { var cookiesEuOKButton = document.querySelector('.js-cookies-eu-ok'); if (cookiesEuOKButton) { this.addListener(cookiesEuOKButton); } }, addListener: function(target) { // Support for IE < 9 if (target.attachEvent) { target.attachEvent('onclick', this.setCookie); } else { target.addEventListener('click', this.setCookie, false); } }, setCookie: function() { Cookies.set('cookie_eu_consented', true, { path: '/', expires: 365 }); var container = document.querySelector('.js-cookies-eu'); container.parentNode.removeChild(container); } }; (function() { var isCalled = false; function isReady() { if (isCalled) return; isCalled = true; cookiesEu.init(); } if (document.addEventListener) { document.addEventListener('DOMContentLoaded', isReady, false); } // Old browsers IE < 9 if (window.addEventListener) { window.addEventListener('load', isReady, false); } else if (window.attachEvent) { window.attachEvent('onload', isReady); } })();
//= require js.cookie 'use strict'; document.addEventListener('DOMContentLoaded', function() { var cookiesEu = { init: function() { var cookiesEuOKButton = document.querySelector('.js-cookies-eu-ok'); if (cookiesEuOKButton) { this.addListener(cookiesEuOKButton); } }, addListener: function(target) { // Support for IE < 9 if (target.attachEvent) { target.attachEvent('onclick', this.setCookie); } else { target.addEventListener('click', this.setCookie, false); } }, setCookie: function() { Cookies.set('cookie_eu_consented', true, { path: '/', expires: 365 }); var container = document.querySelector('.js-cookies-eu'); container.parentNode.removeChild(container); } } cookiesEu.init(); });
fix: Change to multiple verbose option
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo def set_logging(ctx, param, value): """Set logging level based on how many verbose flags.""" logging_level = (logging.root.getEffectiveLevel() - value * 10) or 1 logging.basicConfig(level=logging_level, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') @click.command() @click.option('-v', '--verbose', count=True, callback=set_logging, help='More verbose logging, use multiple times.') @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ log = logging.getLogger(__name__) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = [kwargs['dir']] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo @click.command() @click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True) @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') log = logging.getLogger(__name__) if kwargs['debug']: logging.root.setLevel(logging.DEBUG) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = [kwargs['dir']] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
Add != null check to avoid exceptions when teleporting unknown entity
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_7; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleEntityTeleport; import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData; import protocolsupport.protocol.utils.types.NetworkEntity; import protocolsupport.protocol.utils.types.NetworkEntityType; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class EntityTeleport extends MiddleEntityTeleport { @Override public RecyclableCollection<ClientBoundPacketData> toData(ProtocolVersion version) { NetworkEntity wentity = cache.getWatchedEntity(entityId); y *= 32; if ((wentity != null) && ((wentity.getType() == NetworkEntityType.TNT) || (wentity.getType() == NetworkEntityType.FALLING_OBJECT))) { y += 16; } ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_ENTITY_TELEPORT_ID, version); serializer.writeInt(entityId); serializer.writeInt((int) (x * 32)); serializer.writeInt((int) y); serializer.writeInt((int) (z * 32)); serializer.writeByte(yaw); serializer.writeByte(pitch); return RecyclableSingletonList.create(serializer); } }
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_7; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleEntityTeleport; import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData; import protocolsupport.protocol.utils.types.NetworkEntity; import protocolsupport.protocol.utils.types.NetworkEntityType; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class EntityTeleport extends MiddleEntityTeleport { @Override public RecyclableCollection<ClientBoundPacketData> toData(ProtocolVersion version) { NetworkEntity wentity = cache.getWatchedEntity(entityId); y *= 32; if ((wentity.getType() == NetworkEntityType.TNT) || (wentity.getType() == NetworkEntityType.FALLING_OBJECT)) { y += 16; } ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_ENTITY_TELEPORT_ID, version); serializer.writeInt(entityId); serializer.writeInt((int) (x * 32)); serializer.writeInt((int) y); serializer.writeInt((int) (z * 32)); serializer.writeByte(yaw); serializer.writeByte(pitch); return RecyclableSingletonList.create(serializer); } }
Edit Failure logging to auto-expire, and rename key to a more searchable one
<?php /** * Redis backend for storing failed Resque jobs. * * @package Resque/Failure * @author Chris Boulton <chris.boulton@interspire.com> * @copyright (c) 2010 Chris Boulton * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Failure_Redis implements Resque_Failure_Interface { /** * Initialize a failed job class and save it (where appropriate). * * @param object $payload Object containing details of the failed job. * @param object $exception Instance of the exception that was thrown by the failed job. * @param object $worker Instance of Resque_Worker that received the job. * @param string $queue The name of the queue the job was fetched from. */ public function __construct($payload, $exception, $worker, $queue) { $data = array(); $data['failed_at'] = strftime('%a %b %d %H:%M:%S %Z %Y'); $data['payload'] = $payload; $data['exception'] = get_class($exception); $data['error'] = $exception->getMessage(); $data['backtrace'] = explode("\n", $exception->getTraceAsString()); $data['worker'] = (string)$worker; $data['queue'] = $queue; Resque::Redis()->setex('failed:'.$payload['id'], 3600*14, function_exists('igbinary_serialize') ? igbinary_serialize($data) : serialize($data)); } } ?>
<?php /** * Redis backend for storing failed Resque jobs. * * @package Resque/Failure * @author Chris Boulton <chris.boulton@interspire.com> * @copyright (c) 2010 Chris Boulton * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Failure_Redis implements Resque_Failure_Interface { /** * Initialize a failed job class and save it (where appropriate). * * @param object $payload Object containing details of the failed job. * @param object $exception Instance of the exception that was thrown by the failed job. * @param object $worker Instance of Resque_Worker that received the job. * @param string $queue The name of the queue the job was fetched from. */ public function __construct($payload, $exception, $worker, $queue) { $data = new stdClass; $data->failed_at = strftime('%a %b %d %H:%M:%S %Z %Y'); $data->payload = $payload; $data->exception = get_class($exception); $data->error = $exception->getMessage(); $data->backtrace = explode("\n", $exception->getTraceAsString()); $data->worker = (string)$worker; $data->queue = $queue; $data = json_encode($data); Resque::redis()->rpush('failed', $data); } } ?>
Remove initial migration for 002
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-25 21:06 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), # ('volunteers', '0001_initial'), ] operations = [ migrations.AddField( model_name='tasktemplate', name='primary', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-25 21:06 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('volunteers', '0001_initial'), ] operations = [ migrations.AddField( model_name='tasktemplate', name='primary', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
Remove event attributes that should not be fillable.
<?php namespace Rogue\Models; use Illuminate\Database\Eloquent\Model; class Event extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['content', 'user']; /** * Attributes that can be queried when filtering. * * This array is manually maintained. It does not necessarily mean that * any of these are actual indexes on the database... but they should be! * * @var array */ public static $indexes = [ 'eventable_id', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'content' => 'array', ]; public function eventable() { return $this->morphTo(); } public function scopeForSignup($query, $id) { return $query->where('eventable_type', 'Rogue\Models\Signup') ->where('eventable_id', $id); } }
<?php namespace Rogue\Models; use Illuminate\Database\Eloquent\Model; class Event extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['eventable_id', 'eventable_type', 'content', 'user']; /** * Attributes that can be queried when filtering. * * This array is manually maintained. It does not necessarily mean that * any of these are actual indexes on the database... but they should be! * * @var array */ public static $indexes = [ 'eventable_id', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'content' => 'array', ]; public function eventable() { return $this->morphTo(); } public function scopeForSignup($query, $id) { return $query->where('eventable_type', 'Rogue\Models\Signup') ->where('eventable_id', $id); } }
Remove cb from core function
const merge = require('webpack-merge'); const concat = require('lodash/concat'); const reduce = require('lodash/reduce'); const compact = require('lodash/compact'); const isArray = require('lodash/isArray'); const isObject = require('lodash/isObject'); const config = require('./config'); const resolve = require('./resolve'); module.exports = (existingConfig = {}) => { let resolved = []; const opts = config.build(); if (!isObject(existingConfig)) { // TODO do we want to support promise based configs? throw new Error('Existing config must be an object'); } if (opts.presets) { if (!isArray(opts.presets)) { throw new Error('Presets must be an array'); } resolved = concat(resolved, resolve.presets(opts.presets)); } if (opts.plugins) { if (!isArray(opts.plugins)) { throw new Error('Plugins must be an array'); } resolved = concat(resolved, resolve.plugins(opts.plugins)); } // Clean out unresolved packages resolved = compact(resolved); const out = reduce(resolved, (acc, curr) => merge.smart(acc, curr(existingConfig)), existingConfig ); return out; };
const merge = require('webpack-merge'); const concat = require('lodash/concat'); const reduce = require('lodash/reduce'); const compact = require('lodash/compact'); const isArray = require('lodash/isArray'); const isObject = require('lodash/isObject'); const isFunction = require('lodash/isFunction'); const config = require('./config'); const resolve = require('./resolve'); module.exports = (existingConfig = {}, cb) => { let resolved = []; const opts = config.build(); if (!isObject(existingConfig)) { // TODO do we want to support promise based configs? throw new Error('Existing config must be an object'); } if (opts.presets) { if (!isArray(opts.presets)) { throw new Error('Presets must be an array'); } resolved = concat(resolved, resolve.presets(opts.presets)); } if (opts.plugins) { if (!isArray(opts.plugins)) { throw new Error('Plugins must be an array'); } resolved = concat(resolved, resolve.plugins(opts.plugins)); } // Clean out unresolved packages resolved = compact(resolved); const out = reduce(resolved, (acc, curr) => merge.smart(acc, curr(existingConfig)), existingConfig ); if (cb) { if (!isFunction(cb)) { throw new Error('Callback must be a function'); } // Make cb promise compatible via error first cb(null, out); } return out; };
Save our backtraces in a compatible manner with resque.
import sys import traceback class BaseBackend(object): """Provides a base class that custom backends can subclass. Also provides basic traceback and message parsing. The ``__init__`` takes these keyword arguments: ``exp`` -- The exception generated by your failure. ``queue`` -- The queue in which the ``Job`` was enqueued when it failed. ``payload`` -- The payload that was passed to the ``Job``. ``worker`` -- The worker that was processing the ``Job`` when it failed. """ def __init__(self, exp, queue, payload, worker=None): excc, _, tb = sys.exc_info() self._exception = excc self._traceback = traceback.format_exc() self._worker = worker self._queue = queue self._payload = payload def _parse_traceback(self, trace): """Return the given traceback string formatted for a notification.""" if not trace: return [] return trace.split('\n') def _parse_message(self, exc): """Return a message for a notification from the given exception.""" return '%s: %s' % (exc.__class__.__name__, str(exc))
import sys import traceback class BaseBackend(object): """Provides a base class that custom backends can subclass. Also provides basic traceback and message parsing. The ``__init__`` takes these keyword arguments: ``exp`` -- The exception generated by your failure. ``queue`` -- The queue in which the ``Job`` was enqueued when it failed. ``payload`` -- The payload that was passed to the ``Job``. ``worker`` -- The worker that was processing the ``Job`` when it failed. """ def __init__(self, exp, queue, payload, worker=None): excc, _, tb = sys.exc_info() self._exception = excc self._traceback = traceback.format_exc() self._worker = worker self._queue = queue self._payload = payload def _parse_traceback(self, trace): """Return the given traceback string formatted for a notification.""" return trace def _parse_message(self, exc): """Return a message for a notification from the given exception.""" return '%s: %s' % (exc.__class__.__name__, str(exc))
[security][symfony] Fix fatal error on old symfony versions. PHP Fatal error: Undefined class constant 'ABSOLUTE_URL' in ....
<?php namespace Payum\Core\Bridge\Symfony\Security; use Payum\Core\Registry\StorageRegistryInterface; use Payum\Core\Security\AbstractGenericTokenFactory; use Payum\Core\Storage\StorageInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class TokenFactory extends AbstractGenericTokenFactory { /** * @var \Symfony\Component\Routing\RouterInterface */ protected $urlGenerator; /** * @param UrlGeneratorInterface $urlGenerator * @param StorageInterface $tokenStorage * @param StorageRegistryInterface $storageRegistry * @param string $capturePath * @param string $notifyPath */ public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath) { $this->urlGenerator = $urlGenerator; parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath); } /** * @param string $path * @param array $parameters * * @return string */ protected function generateUrl($path, array $parameters = array()) { return $this->urlGenerator->generate($path, $parameters, true); } }
<?php namespace Payum\Core\Bridge\Symfony\Security; use Payum\Core\Registry\StorageRegistryInterface; use Payum\Core\Security\AbstractGenericTokenFactory; use Payum\Core\Security\TokenInterface; use Payum\Core\Storage\StorageInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class TokenFactory extends AbstractGenericTokenFactory { /** * @var \Symfony\Component\Routing\RouterInterface */ protected $urlGenerator; /** * @param UrlGeneratorInterface $urlGenerator * @param StorageInterface $tokenStorage * @param StorageRegistryInterface $storageRegistry * @param string $capturePath * @param string $notifyPath */ public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath) { $this->urlGenerator = $urlGenerator; parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath); } /** * @param string $path * @param array $parameters * * @return string */ protected function generateUrl($path, array $parameters = array()) { return $this->urlGenerator->generate($path, $parameters, UrlGeneratorInterface::ABSOLUTE_URL); } }
Use pkg_resources to read version
import pathlib import pkg_resources from mopidy import config, exceptions, ext __version__ = pkg_resources.get_distribution("Mopidy-dLeyna").version class Extension(ext.Extension): dist_name = "Mopidy-dLeyna" ext_name = "dleyna" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["upnp_browse_limit"] = config.Integer(minimum=0) schema["upnp_lookup_limit"] = config.Integer(minimum=0) schema["upnp_search_limit"] = config.Integer(minimum=0) schema["dbus_start_session"] = config.String() return schema def setup(self, registry): from .backend import dLeynaBackend registry.add("backend", dLeynaBackend) def validate_environment(self): try: import dbus # noqa except ImportError: raise exceptions.ExtensionError("Cannot import dbus")
import pathlib from mopidy import config, exceptions, ext __version__ = "1.2.2" class Extension(ext.Extension): dist_name = "Mopidy-dLeyna" ext_name = "dleyna" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["upnp_browse_limit"] = config.Integer(minimum=0) schema["upnp_lookup_limit"] = config.Integer(minimum=0) schema["upnp_search_limit"] = config.Integer(minimum=0) schema["dbus_start_session"] = config.String() return schema def setup(self, registry): from .backend import dLeynaBackend registry.add("backend", dLeynaBackend) def validate_environment(self): try: import dbus # noqa except ImportError: raise exceptions.ExtensionError("Cannot import dbus")
Revert "fixup! CLOUD-1047: Add region to resources" This reverts commit 05773b07489f247b989f30f866bcba77d9522ac8.
package resources import "github.com/aws/aws-sdk-go/service/ec2" type EC2Subnet struct { svc *ec2.EC2 id *string region *string } func (n *EC2Nuke) ListSubnets() ([]Resource, error) { params := &ec2.DescribeSubnetsInput{} resp, err := n.Service.DescribeSubnets(params) if err != nil { return nil, err } resources := make([]Resource, 0) for _, out := range resp.Subnets { resources = append(resources, &EC2Subnet{ svc: n.Service, id: out.SubnetId, region: n.Service.Config.Region, }) } return resources, nil } func (e *EC2Subnet) Remove() error { params := &ec2.DeleteSubnetInput{ SubnetId: e.id, } _, err := e.svc.DeleteSubnet(params) if err != nil { return err } return nil } func (e *EC2Subnet) String() string { return *e.id }
package resources import ( "fmt" "github.com/aws/aws-sdk-go/service/ec2" ) type EC2Subnet struct { svc *ec2.EC2 id *string region *string } func (n *EC2Nuke) ListSubnets() ([]Resource, error) { params := &ec2.DescribeSubnetsInput{} resp, err := n.Service.DescribeSubnets(params) if err != nil { return nil, err } resources := make([]Resource, 0) for _, out := range resp.Subnets { resources = append(resources, &EC2Subnet{ svc: n.Service, id: out.SubnetId, region: n.Service.Config.Region, }) } return resources, nil } func (e *EC2Subnet) Remove() error { params := &ec2.DeleteSubnetInput{ SubnetId: e.id, } _, err := e.svc.DeleteSubnet(params) if err != nil { return err } return nil } func (e *EC2Subnet) String() string { return fmt.Sprintf("%s in %s", *e.id, *e.region) }
Fix bug where it would default to a matching line number of 1.
<?php namespace pharen\debug; function convert_line_num($line_map, $errline){ foreach($line_map as $php_line=>$ph_line){ $pharen_line = $ph_line; if($php_line >= $errline){ break; } } return $pharen_line; } function generate_pharen_err($file, $line, $msg){ return "$msg in $file:$line\n"; } function error_handler($errno, $errstr, $errfile, $errline, $errctx){ $line_map = get_line_map(); $pharen_file = basename($errfile, ".php").".phn"; $pharen_line = convert_line_num($line_map, $errline); echo generate_pharen_err($pharen_file, $pharen_line, $errstr); return True; } set_error_handler('pharen\debug\error_handler');
<?php namespace pharen\debug; function convert_line_num($line_map, $errline){ $pharen_line = 1; foreach($line_map as $php_line=>$ph_line){ if($php_line >= $errline){ $pharen_line = $ph_line; break; } } return $pharen_line; } function generate_pharen_err($file, $line, $msg){ return "$msg in $file:$line\n"; } function error_handler($errno, $errstr, $errfile, $errline, $errctx){ $line_map = get_line_map(); $pharen_file = basename($errfile, ".php").".phn"; $pharen_line = convert_line_num($line_map, $errline); echo generate_pharen_err($pharen_file, $pharen_line, $errstr); return True; } set_error_handler('pharen\debug\error_handler');
Fix syntax error in `ep06`
// @license // Copyright (c) 2014 The Polymer Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@license // Copyright (c) 2014 The Polymer Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
tests: Convert ext test to pytests
from __future__ import absolute_import, unicode_literals import pytest from mopidy import config, ext @pytest.fixture def extension(): return ext.Extension() def test_dist_name_is_none(extension): assert extension.dist_name is None def test_ext_name_is_none(extension): assert extension.ext_name is None def test_version_is_none(extension): assert extension.version is None def test_get_default_config_raises_not_implemented(extension): with pytest.raises(NotImplementedError): extension.get_default_config() def test_get_config_schema_returns_extension_schema(extension): schema = extension.get_config_schema() assert isinstance(schema['enabled'], config.Boolean) def test_validate_environment_does_nothing_by_default(extension): assert extension.validate_environment() is None def test_setup_raises_not_implemented(extension): with pytest.raises(NotImplementedError): extension.setup(None)
from __future__ import absolute_import, unicode_literals import unittest from mopidy import config, ext class ExtensionTest(unittest.TestCase): def setUp(self): # noqa: N802 self.ext = ext.Extension() def test_dist_name_is_none(self): self.assertIsNone(self.ext.dist_name) def test_ext_name_is_none(self): self.assertIsNone(self.ext.ext_name) def test_version_is_none(self): self.assertIsNone(self.ext.version) def test_get_default_config_raises_not_implemented(self): with self.assertRaises(NotImplementedError): self.ext.get_default_config() def test_get_config_schema_returns_extension_schema(self): schema = self.ext.get_config_schema() self.assertIsInstance(schema['enabled'], config.Boolean) def test_validate_environment_does_nothing_by_default(self): self.assertIsNone(self.ext.validate_environment()) def test_setup_raises_not_implemented(self): with self.assertRaises(NotImplementedError): self.ext.setup(None)
Add new record to list
import { reduceApi, getBaseType } from '../../common/api' import { LIST_TODOS, VIEW_TODO, CREATE_TODO, UPDATE_TODO, DELETE_TODO, MOVE_TODO } from './actions'; export default function todoReducer(state = {todos: []}, action) { switch (getBaseType(action.type)) { case LIST_TODOS.BASE: state = reduceApi(state, action, LIST_TODOS, (data) => { return {todos: data}; }); case VIEW_TODO.BASE: state = reduceApi(state, action, VIEW_TODO, (data) => { return {todo: data}; }); case CREATE_TODO.BASE: state = reduceApi(state, action, CREATE_TODO, (data) => { return {todos: [...state.todos, data]}; }); default: return state; } }
import { reduceApi, getBaseType } from '../../common/api' import { LIST_TODOS, VIEW_TODO, CREATE_TODO, UPDATE_TODO, DELETE_TODO, MOVE_TODO } from './actions'; export default function todoReducer(state = {todos: []}, action) { switch (getBaseType(action.type)) { case LIST_TODOS.BASE: state = reduceApi(state, action, LIST_TODOS, (data) => { return {todos: data}; }); case VIEW_TODO.BASE: state = reduceApi(state, action, VIEW_TODO, (data) => { return {todo: data}; }); case CREATE_TODO.BASE: state = reduceApi(state, action, CREATE_TODO, (data) => { return {todo: data}; }); default: return state; } }
Fix invalid hostname on browser
import fetch from 'isomorphic-fetch' import url from 'url' import config from '../config' export default class APIClient { constructor({ path, method, query, body }) { const apiUrlObject = new url.Url() apiUrlObject.pathname = path apiUrlObject.protocol = (this.isServer() ? 'http' : window.location.protocol) apiUrlObject.host = (this.isServer() ? `localhost:${config.PORT}`: `${window.location.host}`) if (query) { apiUrlObject.query = query } return new Promise((resolve, reject) => { fetch(decodeURI(url.format(apiUrlObject))). then((res) => { return res.json() }). then((body) => { return resolve(body) }). catch((err) => { return reject(err) }) }) } isServer() { return ! (typeof window !== 'undefined' && window.document); } }
import fetch from 'isomorphic-fetch' import url from 'url' import config from '../config' export default class APIClient { constructor({ path, method, query, body }) { const apiUrlObject = new url.Url() delete apiUrlObject.search apiUrlObject.pathname = path apiUrlObject.protocol = (this.isServer() ? 'http' : window.location.protocol) apiUrlObject.host = (this.isServer() ? `localhost:${config.PORT}`: `${window.location.host}:${window.location.port}`) if (query) { apiUrlObject.query = query } return new Promise((resolve, reject) => { fetch(url.format(apiUrlObject)). then((res) => { return res.json() }). then((body) => { return resolve(body) }). catch((err) => { return reject(err) }) }) } isServer() { return ! (typeof window !== 'undefined' && window.document); } }
Use Urls instead of Resources for name
package main import ( "github.com/codegangsta/negroni" "github.com/gorilla/mux" "gopkg.in/unrolled/render.v1" "net/http" ) var printer = render.New(render.Options { Layout: "layout", IndentJSON: true, }) func main() { router := mux.NewRouter().StrictSlash(true) router.Path("/").HandlerFunc(HomeHandler).Name("home") urls := router.PathPrefix("/urls").Subrouter() urls.Methods("GET").Path("/").HandlerFunc(UrlsIndexHandler).Name("urls_index") app := negroni.Classic() app.UseHandler(router) app.Run(":8080") } func HomeHandler(w http.ResponseWriter, req *http.Request) { data := map[string]interface{} { "title": "Home", } printer.HTML(w, http.StatusOK, "home", data) } func UrlsIndexHandler(w http.ResponseWriter, req *http.Request) { urls := []string { "www.google.com", "www.yahoo.com", "www.cnn.com", } printer.JSON(w, http.StatusOK, map[string][]string {"urls": urls}) }
package main import ( "github.com/codegangsta/negroni" "github.com/gorilla/mux" "gopkg.in/unrolled/render.v1" "net/http" ) var printer = render.New(render.Options { Layout: "layout", IndentJSON: true, }) func main() { router := mux.NewRouter().StrictSlash(true) router.Path("/").HandlerFunc(HomeHandler).Name("home") resources := router.PathPrefix("/urls").Subrouter() resources.Methods("GET").Path("/").HandlerFunc(ResourcesIndexHandler).Name("resources_index") app := negroni.Classic() app.UseHandler(router) app.Run(":8080") } func HomeHandler(w http.ResponseWriter, req *http.Request) { data := map[string]interface{} { "title": "Home", } printer.HTML(w, http.StatusOK, "home", data) } func ResourcesIndexHandler(w http.ResponseWriter, req *http.Request) { urls := []string { "www.google.com", "www.yahoo.com", "www.cnn.com", } printer.JSON(w, http.StatusOK, map[string][]string {"urls": urls}) }
[FIX] Set last id in sequence
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## import logging import openupgradelib _logger = logging.getLogger(__name__) def migrate(cr, version): _logger.info('Migrating account_check from version %s' % version) cr.execute(""" INSERT INTO account_check ( id, create_uid, create_date, write_date, write_uid, state, number, issue_date, amount, company_id, user_id, voucher_id, clearing, bank_id, vat, type, source_partner_id, destiny_partner_id, payment_date ) SELECT id, create_uid, create_date, write_date, write_uid, state, CAST(number AS INT), date, amount, company_id, user_id, voucher_id, clearing, bank_id, vat, 'third', source_partner_id, destiny_partner_id, clearing_date FROM account_third_check """) cr.execute("select max(id) FROM account_check") take_last_check = cr.fetchall()[0][0] cr.execute("ALTER SEQUENCE account_check_id_seq RESTART WITH %s;", (take_last_check,)) pass
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## import logging import openupgradelib _logger = logging.getLogger(__name__) def migrate(cr, version): _logger.info('Migrating account_check from version %s' % version) cr.execute(""" INSERT INTO account_check ( id, create_uid, create_date, write_date, write_uid, state, number, issue_date, amount, company_id, user_id, voucher_id, clearing, bank_id, vat, type, source_partner_id, destiny_partner_id, payment_date ) SELECT id, create_uid, create_date, write_date, write_uid, state, CAST(number AS INT), date, amount, company_id, user_id, voucher_id, clearing, bank_id, vat, 'third', source_partner_id, destiny_partner_id, clearing_date FROM account_third_check """) pass
Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(200, 200) w2 = window.Window(200, 200) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
Fix ding sound's resource name
/* * Copyright (c) 2010 Célio Cidral Junior * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tomighty.sound.timer; import org.tomighty.config.Options.SoundConfig; import org.tomighty.sound.SoundSupport; public class Ding extends SoundSupport { @Override protected SoundConfig configuration() { return options().sound().ding(); } @Override protected String defaultSoundResource() { return "/deskbell.wav"; } }
/* * Copyright (c) 2010 Célio Cidral Junior * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tomighty.sound.timer; import org.tomighty.config.Options.SoundConfig; import org.tomighty.sound.SoundSupport; public class Ding extends SoundSupport { @Override protected SoundConfig configuration() { return options().sound().ding(); } @Override protected String defaultSoundResource() { return "/ding.wav"; } }
Fix printing of logged non-ascii characters webdriver seems to not handle non-ascii characters in the result of an executed script correctly (python throws an exception when printing the string). This makes them be printed correctly. R=mdjones@chromium.org Review URL: https://codereview.chromium.org/848503003
#!/usr/bin/env python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs DomDistillers jstests. This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests. This requires that the ChromeDriver executable is on the PATH and that Selenium WebDriver is installed. In addition, ChromeDriver assumes that Chrome is available at /usr/bin/google-chrome. """ import os import sys import time try: from selenium import webdriver except: print 'ERROR:' print 'Couldn\'t import webdriver. Please run `sudo ./install-build-deps.sh`.' sys.exit(1) start = time.time() test_runner = "return com.dom_distiller.client.JsTestEntry.run()"; test_html = os.path.abspath(os.path.join(os.path.dirname(__file__), "war", "test.html")) driver = webdriver.Chrome() driver.get("file://" + test_html) result = driver.execute_script(test_runner) driver.quit() end = time.time() print result['log'].encode('utf-8') print 'Tests run: %d, Failures: %d, Skipped: %d, Time elapsed: %0.3f sec' % (result['numTests'], result['failed'], result['skipped'], end - start) sys.exit(0 if result['success'] else 1)
#!/usr/bin/env python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs DomDistillers jstests. This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests. This requires that the ChromeDriver executable is on the PATH and that Selenium WebDriver is installed. In addition, ChromeDriver assumes that Chrome is available at /usr/bin/google-chrome. """ import os import sys import time try: from selenium import webdriver except: print 'ERROR:' print 'Couldn\'t import webdriver. Please run `sudo ./install-build-deps.sh`.' sys.exit(1) start = time.time() test_runner = "return com.dom_distiller.client.JsTestEntry.run()"; test_html = os.path.abspath(os.path.join(os.path.dirname(__file__), "war", "test.html")) driver = webdriver.Chrome() driver.get("file://" + test_html) result = driver.execute_script(test_runner) driver.quit() end = time.time() print result['log'] print 'Tests run: %d, Failures: %d, Skipped: %d, Time elapsed: %0.3f sec' % (result['numTests'], result['failed'], result['skipped'], end - start) sys.exit(0 if result['success'] else 1)
Configure to use PostgreSQL driver in Kohana.
<?php defined('SYSPATH') or die('No direct access allowed.'); $dbpath = getenv('DBPATH'); $dbhost = getenv('DBHOST'); $dbname = getenv('DBNAME'); $dbuser = getenv('DBUSER'); $dbpass = getenv('DBPASS'); return array( 'mysql' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "mysql:host=$dbhost;dbname=$dbname", 'username' => $dbuser, 'password' => $dbpass, ), 'charset' => 'utf8', ), 'pgsql' => array( 'type' => 'postgresql', 'connection' => array( 'hostname' => $dbhost, 'username' => $dbuser, 'password' => $dbpass, 'database' => $dbname, ), 'charset' => 'utf8', ), 'sqlite' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "sqlite:$dbpath", ), ), );
<?php defined('SYSPATH') or die('No direct access allowed.'); $dbpath = getenv('DBPATH'); $dbhost = getenv('DBHOST'); $dbname = getenv('DBNAME'); $dbuser = getenv('DBUSER'); $dbpass = getenv('DBPASS'); return array( 'mysql' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "mysql:host=$dbhost;dbname=$dbname", 'username' => $dbuser, 'password' => $dbpass, ), 'charset' => 'utf8', ), 'pgsql' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "pgsql:host=$dbhost;dbname=$dbname", 'username' => $dbuser, 'password' => $dbpass, ), 'charset' => 'utf8', ), 'sqlite' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "sqlite:$dbpath", ), ), );
Remove paragraph for less space
var ws = new WebSocket("ws://localhost:8081/"), messageList = document.getElementById("messageList"); ws.onopen = function(ev) { console.log('Connection opened.'); } ws.onclose = function(ev) { console.log('Connection closed.'); } ws.onerror = function(ev) { console.log('Error: '+ev); } ws.onmessage = function(event) { console.log("Recieved " + event.data); message = JSON.parse(event.data); messageList.innerHTML += '<div class="messageDiv"><div class="messageLeft">'+message.author+':&nbsp;</div><div class="messageCenter">'+message.body+'</div><div class="messageRight">&nbsp;('+message.TimeSent.slice(11,19)+')</div></div>'; messageList.scrollTop = messageList.scrollHeight; } var submitText = function() { text = document.getElementById("messageInput").value; document.getElementById("messageInput").value = ""; name = document.getElementById("name").value; if (name == "") name = "Anonymous"; message = JSON.stringify({author:name, body:text}); ws.send(message); }
var ws = new WebSocket("ws://localhost:8081/"), messageList = document.getElementById("messageList"); ws.onopen = function(ev) { console.log('Connection opened.'); } ws.onclose = function(ev) { console.log('Connection closed.'); } ws.onerror = function(ev) { console.log('Error: '+ev); } ws.onmessage = function(event) { console.log("Recieved " + event.data); message = JSON.parse(event.data); messageList.innerHTML += '<div class="messageDiv"><div class="messageLeft"><p>'+message.author+':&nbsp;</p></div><div class="messageCenter"><p>'+message.body+'</p></div><div class="messageRight"><p>&nbsp;('+message.TimeSent.slice(11,19)+')</p></div></div>'; messageList.scrollTop = messageList.scrollHeight; } var submitText = function() { text = document.getElementById("messageInput").value; document.getElementById("messageInput").value = ""; name = document.getElementById("name").value; if (name == "") name = "Anonymous"; message = JSON.stringify({author:name, body:text}); ws.send(message); }
Remove LIMIT for Batch Loader LIMIT doesn't exist for SQL Server, hence we need a different method to get the column count for creating Batch Loader
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.teradata.tempto.internal.fulfillment.table.jdbc; import com.teradata.tempto.query.QueryExecutor; import org.slf4j.Logger; import java.sql.JDBCType; import java.sql.SQLException; import java.util.List; import static org.slf4j.LoggerFactory.getLogger; class LoaderFactory { private static final Logger LOGGER = getLogger(LoaderFactory.class); Loader create(QueryExecutor queryExecutor, String tableName) throws SQLException { List<JDBCType> columnTypes = queryExecutor.executeQuery("SELECT * FROM " + tableName + " WHERE 1=2").getColumnTypes(); try { return new BatchLoader(queryExecutor, tableName, columnTypes.size()); } catch (SQLException sqlException) { LOGGER.warn("Unable to insert data with PreparedStatement", sqlException); return new InsertLoader(queryExecutor, tableName, columnTypes); } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.teradata.tempto.internal.fulfillment.table.jdbc; import com.teradata.tempto.query.QueryExecutor; import org.slf4j.Logger; import java.sql.JDBCType; import java.sql.SQLException; import java.util.List; import static org.slf4j.LoggerFactory.getLogger; class LoaderFactory { private static final Logger LOGGER = getLogger(LoaderFactory.class); Loader create(QueryExecutor queryExecutor, String tableName) throws SQLException { List<JDBCType> columnTypes = queryExecutor.executeQuery("SELECT * FROM " + tableName + " LIMIT 1").getColumnTypes(); try { return new BatchLoader(queryExecutor, tableName, columnTypes.size()); } catch (SQLException sqlException) { LOGGER.warn("Unable to insert data with PreparedStatement", sqlException); return new InsertLoader(queryExecutor, tableName, columnTypes); } } }
Add Polish language document strings.
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from ..structure import SectionTitles, AdmonitionTitles PL = Language('pl', 'Polski') SectionTitles( contents='Spis Treści', list_of_figures='Spis Ilustracji', list_of_tables='Spis Tabel', chapter='Rozdział', index='Skorowidz', ) in PL AdmonitionTitles( attention='Uwaga!', caution='Ostrożnie!', danger='!NIEBEZPIECZEŃSTWO!', error='Błąd', hint='Wskazówka', important='Ważne', note='Notatka', tip='Porada', warning='Ostrzeżenie', seealso='Zobacz również', ) in PL
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from ..structure import SectionTitles, AdmonitionTitles PL = Language('pl', 'Polski') SectionTitles( contents='Spis Treści', list_of_figures='Spis Ilustracji', list_of_tables='Spis Tabel', chapter='Rozdział', index='Index', ) in PL AdmonitionTitles( attention='Uwaga!', caution='Ostrzeżenie!', danger='Uwaga!', error='Błąd', hint='Wskazówka', important='Ważne', note='Uwaga', tip='Porada', warning='Ostrzeżenie', seealso='Zobacz również', ) in PL
Delete download_url. Let PyPI provide the bandwidth.
from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages version_classifiers = ['Programming Language :: Python :: %s' % version for version in ['2', '2.5', '2.6', '2.7']] other_classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Environment :: Console', 'Operating System :: OS Independent', 'Topic :: Software Development :: Testing', ] readme_file = open('README', 'rt') try: detailed_description = readme_file.read() finally: readme_file.close() setup( name="nosy", version="1.1", description="""\ Run the nose test discovery and execution tool whenever a source file is changed. """, long_description=detailed_description, author="Doug Latornell", author_email="djl@douglatornell.ca", url="http://douglatornell.ca/software/python/Nosy/", license="New BSD License", classifiers=version_classifiers + other_classifiers, packages=find_packages(), entry_points={'console_scripts':['nosy = nosy.nosy:main']} )
from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages djl_url = "http://douglatornell.ca/software/python/Nosy/" nosy_version = "1.1" version_classifiers = ['Programming Language :: Python :: %s' % version for version in ['2', '2.5', '2.6', '2.7']] other_classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Environment :: Console', 'Operating System :: OS Independent', 'Topic :: Software Development :: Testing', ] readme_file = open('README', 'rt') try: detailed_description = readme_file.read() finally: readme_file.close() setup( name="nosy", version=nosy_version, description="""\ Run the nose test discovery and execution tool whenever a source file is changed. """, long_description=detailed_description, author="Doug Latornell", author_email="djl@douglatornell.ca", url=djl_url, download_url="http://pypi.python.org/pypi/nosy", license="New BSD License", classifiers=version_classifiers + other_classifiers, packages=find_packages(), entry_points={'console_scripts':['nosy = nosy.nosy:main']} )
Allow newer versions of sklearn - this will now allow software to be compiled again on OSX. Also tested on Linux.
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="accelerometer", version="2.0", author="Aiden Doherty", author_email="aiden.doherty@bdi.ox.ac.uk", description="A package to extract meaningful health information from large accelerometer datasets e.g. how much time individuals spend in sleep, sedentary behaviour, walking and moderate intensity physical activity", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/activityMonitoring/biobankAccelerometerAnalysis", packages=setuptools.find_packages(), install_requires=[ 'argparse', 'joblib', 'matplotlib', 'numpy', 'scipy', 'pandas>=0.24', 'scikit-learn>=0.21.2', 'sphinx', 'sphinx-rtd-theme', 'statsmodels', ], classifiers=[ "Programming Language :: Python :: 3", "Operating System :: MacOS :: MacOS X", "Operating System :: Unix", ], )
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="accelerometer", version="2.0", author="Aiden Doherty", author_email="aiden.doherty@bdi.ox.ac.uk", description="A package to extract meaningful health information from large accelerometer datasets e.g. how much time individuals spend in sleep, sedentary behaviour, walking and moderate intensity physical activity", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/activityMonitoring/biobankAccelerometerAnalysis", packages=setuptools.find_packages(), install_requires=[ 'argparse', 'joblib', 'matplotlib', 'numpy', 'scipy', 'pandas>=0.24', 'scikit-learn==0.21.2', 'sphinx', 'sphinx-rtd-theme', 'statsmodels', ], classifiers=[ "Programming Language :: Python :: 3", "Operating System :: MacOS :: MacOS X", "Operating System :: Unix", ], )
Add namespace to votes app URLs
"""jay URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from django.views.generic import TemplateView from . import demo_urls from votes import urls as votes_urls urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name="base/base.html")), url(r'^demo/', include(demo_urls)), url(r'^(?P<system_name>[\w-]+)/', include(votes_urls, namespace='votes')), url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}), url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}), ]
"""jay URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from django.views.generic import TemplateView from . import demo_urls from votes import urls as votes_urls urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name="base/base.html")), url(r'^demo/', include(demo_urls)), url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)), url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}), url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}), ]
Update urlpatterns and remove old patterns pattern
from functools import wraps from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous urlpatterns = [ url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), ]
from functools import wraps from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous urlpatterns = patterns('', url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), )
Switch back to login check via location compare (where staying on login means failed login and success resulted in forward to search results)
protractor.expect = { challengeSolved: function (context) { describe('(shared)', () => { beforeEach(() => { browser.get('/#/score-board') }) it("challenge '" + context.challenge + "' should be solved on score board", () => { expect(element(by.id(context.challenge + '.solved')).getAttribute('hidden')).toBeFalsy() expect(element(by.id(context.challenge + '.notSolved')).getAttribute('hidden')).toBeTruthy() }) }) } } protractor.beforeEach = { login: function (context) { describe('(shared)', () => { beforeEach(() => { browser.get('/#/login') element(by.id('email')).sendKeys(context.email) element(by.id('password')).sendKeys(context.password) element(by.id('loginButton')).click() }) it('should have logged in user "' + context.email + '" with password "' + context.password + '"', () => { expect(browser.getCurrentUrl()).toMatch(/\/search/) // TODO Instead check for uib-tooltip of <i> with fa-user-circle }) }) } }
protractor.expect = { challengeSolved: function (context) { describe('(shared)', () => { beforeEach(() => { browser.get('/#/score-board') }) it("challenge '" + context.challenge + "' should be solved on score board", () => { expect(element(by.id(context.challenge + '.solved')).getAttribute('hidden')).toBeFalsy() expect(element(by.id(context.challenge + '.notSolved')).getAttribute('hidden')).toBeTruthy() }) }) } } protractor.beforeEach = { login: function (context) { let oldToken describe('(shared)', () => { beforeEach(() => { oldToken = localStorage.getItem('token') browser.get('/#/login') element(by.id('email')).sendKeys(context.email) element(by.id('password')).sendKeys(context.password) element(by.id('loginButton')).click() }) it('should have logged in user "' + context.email + '" with password "' + context.password + '"', () => { expect(localStorage.getItem('token')).not.toMatch(oldToken) }) }) } }
Change for 0.2 to use generic hash streams
'use strict'; var crypto = require('crypto') var Transform = require('stream').PassThrough var util = require('util') /** * Constructor * @constructor * @param {string} hash type defaults to sha1 * @param {object} options */ var SHAStream = function(hashType,options){ var that = this that.hashType = hashType || 'sha1' Transform.call(that,options) that.sum = crypto.createHash(that.hashType) that[that.hashType] = null that.on('finish',function(){ that[that.hashType] = that.sum.digest('hex') that.emit(hashType,that[that.hashType]) that.emit(that.hashType,that[that.hashType]) }) } util.inherits(SHAStream,Transform) /** * Transform data * @param {Buffer} chunk * @param {string} encoding * @param {function} done */ SHAStream.prototype._transform = function(chunk,encoding,done){ try { this.sum.update(chunk) this.push(chunk) done() } catch(e){ done(e) } } /** * Export helper * @type {SHAStream} */ module.exports = SHAStream
'use strict'; var crypto = require('crypto') var Transform = require('stream').PassThrough var util = require('util') /** * Constructor * @constructor * @param {object} options */ var SHA1Stream = function(options){ var that = this Transform.call(that,options) that.shasum = crypto.createHash('sha1') that.sha1 = null that.on('finish',function(){ that.sha1 = that.shasum.digest('hex') that.emit('sha1',that.sha1) }) } util.inherits(SHA1Stream,Transform) /** * Transform data * @param {Buffer} chunk * @param {string} encoding * @param {function} done */ SHA1Stream.prototype._transform = function(chunk,encoding,done){ try { this.shasum.update(chunk) this.push(chunk) done() } catch(e){ done(e) } } /** * Export helper * @type {SHA1Stream} */ module.exports = SHA1Stream
Rename wrapper to fix woocommerce conflict
<!doctype html> <html <?php language_attributes(); ?> class="no-js" data-logo-width="<?php echo get_theme_mod('logo_width'); ?>";> <head> <meta charset="<?php bloginfo('charset'); ?>"> <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title> <link href="//www.google-analytics.com" rel="dns-prefetch"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php wp_head(); ?> </head> <body <?php body_class( ! is_front_page() ? "not-home" : "" ); ?>> <div id="wrapper"> <div id="inner_wrapper"> <?php get_template_part('partials/page_header'); ?> <?php // get_template_part('partials/customizer_page_header'); ?>
<!doctype html> <html <?php language_attributes(); ?> class="no-js" data-logo-width="<?php echo get_theme_mod('logo_width'); ?>";> <head> <meta charset="<?php bloginfo('charset'); ?>"> <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title> <link href="//www.google-analytics.com" rel="dns-prefetch"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php wp_head(); ?> </head> <body <?php body_class( ! is_front_page() ? "not-home" : "" ); ?>> <div id="wrapper"> <div id="container"> <?php get_template_part('partials/page_header'); ?> <?php // get_template_part('partials/customizer_page_header'); ?>
Return FALSE when account is not valid
<?php namespace Shoptet\Spayd\Utilities; use Shoptet\Spayd\Exceptions; class IbanUtilities { public static function computeIBANFromCzechBankAccount(\Shoptet\Spayd\Model\CzechAccount $czechAccount) { if ($czechAccount->isValid()) { $prefix = sprintf('%06d', $czechAccount->getPrefix()); $accountNumber = sprintf('%010d', $czechAccount->getAccountNumber()); $bankCode = sprintf('%04d', $czechAccount->getBankCode()); $accountBuffer = $bankCode . $prefix . $accountNumber . $czechAccount->getNumericLanguageCode(); $checksum = sprintf('%02d', (98 - bcmod($accountBuffer, 97))); // build the IBAN number return 'CZ' . $checksum . $bankCode . $prefix . $accountNumber; } else { return FALSE; } } }
<?php namespace Shoptet\Spayd\Utilities; use Shoptet\Spayd\Exceptions; class IbanUtilities { public static function computeIBANFromCzechBankAccount(\Shoptet\Spayd\Model\CzechAccount $czechAccount) { if ($czechAccount->isValid()) { $prefix = sprintf('%06d', $czechAccount->getPrefix()); $accountNumber = sprintf('%010d', $czechAccount->getAccountNumber()); $bankCode = sprintf('%04d', $czechAccount->getBankCode()); } $accountBuffer = $bankCode . $prefix . $accountNumber . $czechAccount->getNumericLanguageCode(); $checksum = sprintf('%02d', (98 - bcmod($accountBuffer, 97))); // build the IBAN number return 'CZ' . $checksum . $bankCode . $prefix . $accountNumber; } }
Change to write to the IO18 pin
<?php if(isset($_GET['trigger']) && $_GET['trigger'] == 1) { error_reporting(E_ALL); exec('gpio -g write 18 0'); usleep(1000000); exec('gpio -g write 18 1'); } ?> <!DOCTYPE html> <html> <head> <title>Garage Opener</title> <link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" /> <link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" /> <link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone-retina-display.png" /> <link rel="stylesheet" href="css/style.css" type="text/css"> <meta name="apple-mobile-web-app-capable" content="yes"> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="js/script.js"></script> </head> <body> <div class='awrap'> <a href='/?trigger=1'></a> </div> </body> </html>
<?php if(isset($_GET['trigger']) && $_GET['trigger'] == 1) { error_reporting(E_ALL); exec('gpio write 7 0'); usleep(1000000); exec('gpio write 7 1'); } ?> <!DOCTYPE html> <html> <head> <title>Garage Opener</title> <link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" /> <link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" /> <link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone-retina-display.png" /> <link rel="stylesheet" href="css/style.css" type="text/css"> <meta name="apple-mobile-web-app-capable" content="yes"> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="js/script.js"></script> </head> <body> <div class='awrap'> <a href='/?trigger=1'></a> </div> </body> </html>
Allow the default Remarkup <p> tag to be inline-styled for mail Summary: Ref T10694. Browsers / mail clients have default `<p>` rules, particularly margin/padding. This allows the inline stuff to turn them off with explicit `"padding: 0; margin: 0;"` so it can control spacing more precisely. Test Plan: See D15857. Reviewers: chad Reviewed By: chad Maniphest Tasks: T10694 Differential Revision: https://secure.phabricator.com/D15858
<?php final class PhutilRemarkupDefaultBlockRule extends PhutilRemarkupBlockRule { public function getPriority() { return 750; } public function getMatchingLineCount(array $lines, $cursor) { return 1; } public function markupText($text, $children) { $engine = $this->getEngine(); $text = trim($text); $text = $this->applyRules($text); if ($engine->isTextMode()) { if (!$this->getEngine()->getConfig('preserve-linebreaks')) { $text = preg_replace('/ *\n */', ' ', $text); } return $text; } if ($engine->getConfig('preserve-linebreaks')) { $text = phutil_escape_html_newlines($text); } if (!strlen($text)) { return null; } $default_attributes = $engine->getConfig('default.p.attributes'); if ($default_attributes) { $attributes = $default_attributes; } else { $attributes = array(); } return phutil_tag('p', $attributes, $text); } }
<?php final class PhutilRemarkupDefaultBlockRule extends PhutilRemarkupBlockRule { public function getPriority() { return 750; } public function getMatchingLineCount(array $lines, $cursor) { return 1; } public function markupText($text, $children) { $text = trim($text); $text = $this->applyRules($text); if ($this->getEngine()->isTextMode()) { if (!$this->getEngine()->getConfig('preserve-linebreaks')) { $text = preg_replace('/ *\n */', ' ', $text); } return $text; } if ($this->getEngine()->getConfig('preserve-linebreaks')) { $text = phutil_escape_html_newlines($text); } if (!strlen($text)) { return null; } return phutil_tag('p', array(), $text); } }
Add test for the alternative --choice options
// Module dependencies var debug = require('debug')('ruche:test:cli:atlernatives'); var expect = require('chai').expect; var cli = require('../../lib/cli'); var fake = require('./util/fake'); /** * Test suite for cli:alternatives * * Compare the results of `cli.argv(command)` against expected scenarios. */ describe('cli:alternatives', function () { it('alternatives package should produce `alternatives` context', function () { var argv = fake.argv('ruche alternatives package'); var result = cli.argv(argv); expect(result.context).to.equal('alternatives'); }); it('With no package should produce `alternatives` help', function () { var argv = fake.argv('ruche alternatives'); var result = cli.argv(argv); expect(result.context).to.equal('help'); expect(result.help).to.equal('alternatives'); }); it('should be called with only one package', function () { var argv = fake.argv('ruche alternatives pack1 pack2'); var result = cli.argv(argv); expect(result.context).to.equal('help'); expect(result.help).to.equal('alternatives'); }); it('could be called with --choice option', function () { var argv = fake.argv('ruche alternatives package --choice package-1-win32'); var result = cli.argv(argv); expect(result.context).to.equal('alternatives'); expect(result.package).to.equal('package'); expect(result.choice).to.equal('package-1-win32'); }); });
// Module dependencies var debug = require('debug')('ruche:test:cli:atlernatives'); var expect = require('chai').expect; var cli = require('../../lib/cli'); var fake = require('./util/fake'); /** * Test suite for cli:alternatives * * Compare the results of `cli.argv(command)` against expected scenarios. */ describe('cli:alternatives', function () { it('alternatives package should produce `alternatives` context', function () { var argv = fake.argv('ruche alternatives package'); var result = cli.argv(argv); expect(result.context).to.equal('alternatives'); }); it('With no package should produce `alternatives` help', function () { var argv = fake.argv('ruche alternatives'); var result = cli.argv(argv); expect(result.context).to.equal('help'); expect(result.help).to.equal('alternatives'); }); it('should be called with only one package', function () { var argv = fake.argv('ruche alternatives pack1 pack2'); var result = cli.argv(argv); expect(result.context).to.equal('help'); expect(result.help).to.equal('alternatives'); }); });
Use absolute paths for dependencies
from __future__ import (unicode_literals, division, absolute_import, print_function) from reggae.build import Build, DefaultOptions from inspect import getmembers def get_build(module): builds = [v for n, v in getmembers(module) if isinstance(v, Build)] assert len(builds) == 1 return builds[0] def get_default_options(module): opts = [v for n, v in getmembers(module) if isinstance(v, DefaultOptions)] assert len(opts) == 1 or len(opts) == 0 return opts[0] if len(opts) else None def get_dependencies(module): from modulefinder import ModuleFinder import os finder = ModuleFinder() finder.run_script(module) all_module_paths = [os.path.abspath(m.__file__) for m in finder.modules.values() if m.__file__ is not None] def is_in_same_path(p): return p and os.path.dirname(p).startswith(os.path.dirname(module)) return [x for x in all_module_paths if is_in_same_path(x) and x != module]
from __future__ import (unicode_literals, division, absolute_import, print_function) from reggae.build import Build, DefaultOptions from inspect import getmembers def get_build(module): builds = [v for n, v in getmembers(module) if isinstance(v, Build)] assert len(builds) == 1 return builds[0] def get_default_options(module): opts = [v for n, v in getmembers(module) if isinstance(v, DefaultOptions)] assert len(opts) == 1 or len(opts) == 0 return opts[0] if len(opts) else None def get_dependencies(module): from modulefinder import ModuleFinder import os finder = ModuleFinder() finder.run_script(module) all_module_paths = [m.__file__ for m in finder.modules.values()] def is_in_same_path(p): return p and os.path.dirname(p).startswith(os.path.dirname(module)) return [x for x in all_module_paths if is_in_same_path(x) and x != module]
Change name to Sparkle instead of boring name before
package main import ( "encoding/json" "fmt" "net/http" "time" "github.com/gorilla/mux" ) type Sparkle struct { Sparkler string `json:"sparkler"` Sparklee string `json:"sparklee"` Reason string `json:"reason,omitempty"` Time time.Time `json:"time,omitempty"` } var sparkles []Sparkle func defaultHandler(w http.ResponseWriter, h *http.Request) { fmt.Fprint(w, "Default sparkles") } func addSparkles(w http.ResponseWriter, h *http.Request) { fmt.Fprint(w, "Add a sparkle") var s Sparkle b := json.NewDecoder(h.Body) b.Decode(&s) sparkles = append(sparkles, s) fmt.Printf("%v", sparkles) } func getSparkles(w http.ResponseWriter, h *http.Request) { fmt.Fprintf(w, "%v", sparkles) } func getSparklesForRecipient(w http.ResponseWriter, h *http.Request) { vars := mux.Vars(h) rcpt := vars["recipient"] fmt.Fprint(w, "Get sparkles for ", rcpt) }
package main import ( "encoding/json" "fmt" "net/http" "time" "github.com/gorilla/mux" ) type Request struct { SparkledBy string `json:"sparkled_by"` Recipient string `json:"recipient"` SparkledAt time.Time `json:"sparkled_at"` } func defaultHandler(w http.ResponseWriter, h *http.Request) { fmt.Fprint(w, "Default sparkles") } func addSparkles(w http.ResponseWriter, h *http.Request) { fmt.Fprint(w, "Add a sparkle") var r Request b := json.NewDecoder(h.Body) b.Decode(&r) fmt.Printf("%v", b) } func getSparkles(w http.ResponseWriter, h *http.Request) { fmt.Fprint(w, "Get top sparkles") } func getSparklesForRecipient(w http.ResponseWriter, h *http.Request) { vars := mux.Vars(h) rcpt := vars["recipient"] fmt.Fprint(w, "Get sparkles for ", rcpt) }
Fix JSON field for multiple instances
@section("field") <div id="json_{{ $field_id }}" class="field_{{ $field_name }}" style="width: 100%; height: 400px;"></div> <input name="{{ $prefixed_field_name }}" id="{{ $field_id }}" type="hidden" value="{{ $field_value }}"> @overwrite @section("footer.js") @parent <script> // create the editor var container_{{ $field_id }} = $("#json_{{ $field_id }}"); var json_field_{{ $field_id }} = $("#{{ $field_id }}"); var json_{{ $field_id }} = json_field_{{ $field_id }}.val(); var editor_{{ $field_id }} = new JSONEditor(container_{{ $field_id }}[0], { {!! app('soda.form')->buildJsParams($field_parameters) !!} }); editor_{{ $field_id }}.setText(json_{{ $field_id }}); json_field_{{ $field_id }}.closest('form').on('submit', function(e) { json_field_{{ $field_id }}.val(editor_{{ $field_id }}.getText()); }) $("#json_{{ $field_name }}").on("keydown", ".jsoneditor-field, .jsoneditor-value", function() { if(event.keyCode == 13 || event.keyCode == 9) { // enter or tab event.preventDefault(); return false; } }) </script> @stop
@section("field") <div id="json_{{ $field_id }}" class="field_{{ $field_name }}" style="width: 100%; height: 400px;"></div> <input name="{{ $prefixed_field_name }}" id="{{ $field_id }}" type="hidden" value="{{ $field_value }}"> @overwrite @section("footer.js") @parent <script> // create the editor var container = $("#json_{{ $field_id }}"); var json_field = $("#{{ $field_id }}"); var json = json_field.val(); var editor = new JSONEditor(container[0], { {!! app('soda.form')->buildJsParams($field_parameters) !!} }); editor.setText(json); json_field.closest('form').on('submit', function (e) { json_field.val(editor.getText()); }) $("#json_{{ $field_name }}").on("keydown", ".jsoneditor-field, .jsoneditor-value", function () { if (event.keyCode == 13 || event.keyCode == 9) { // enter or tab event.preventDefault(); return false; } }) </script> @stop
Remove readLine from repl:main for jar load performance output.
package ca.junctionbox.cljbuck.repl; import clojure.lang.RT; import java.io.IOException; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; public class Main { public static void main(final String[] main) throws IOException { long start = System.nanoTime(); RT.var("clojure.core", "+").invoke(1, 2, 3); long finish = System.nanoTime(); System.out.println((finish - start)); } public static void printGCStats() { long totalGarbageCollections = 0; long garbageCollectionTime = 0; for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { long count = gc.getCollectionCount(); if(count >= 0) { totalGarbageCollections += count; } long time = gc.getCollectionTime(); if(time >= 0) { garbageCollectionTime += time; } } System.out.println("Total Garbage Collections: " + totalGarbageCollections); System.out.println("Total Garbage Collection Time (ms): " + garbageCollectionTime); } }
package ca.junctionbox.cljbuck.repl; import clojure.lang.RT; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; public class Main { public static void main(final String[] main) { System.out.println("Start you're engines!"); long start = System.nanoTime(); System.out.println(RT.var("clojure.core", "+").invoke(1, 2, 3)); long finish = System.nanoTime(); System.out.println("Clojure Load: " + (finish - start) + "ns"); printGCStats(); } public static void printGCStats() { long totalGarbageCollections = 0; long garbageCollectionTime = 0; for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { long count = gc.getCollectionCount(); if(count >= 0) { totalGarbageCollections += count; } long time = gc.getCollectionTime(); if(time >= 0) { garbageCollectionTime += time; } } System.out.println("Total Garbage Collections: " + totalGarbageCollections); System.out.println("Total Garbage Collection Time (ms): " + garbageCollectionTime); } }
Append random number to the image URL, make test a bit less CPU intensive
<?php date_default_timezone_set('America/New_York'); ini_set('zlib.output_compression', 1024); ini_set('zlib.output_compression_level', 6); header('Content-Type: text/html; charset=utf-8', true); // run phpinfo ob_start();phpinfo();$contents = ob_get_clean(); // emulate slow, cpu-intensive loop for($j=0;$j<10000;$j++) { $v = ''; for($i=0;$i<20;$i++) { $v=base64_encode($v.$i.''); }} ?><!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1 id="testing">Load Balancer Testing</h1> <h2>Server address: <?php echo $_SERVER['SERVER_ADDR']; ?></h2> <p><img width="400" height="175" alt="Testing loading the image from the server" src="images/img000.jpeg?r=<?php echo mt_rand(0,999999);?>" /></p> </body> </html>
<?php date_default_timezone_set('America/New_York'); ini_set('zlib.output_compression', 1024); ini_set('zlib.output_compression_level', 6); header('Content-Type: text/html; charset=utf-8', true); // run phpinfo ob_start();phpinfo();$contents = ob_get_clean(); // emulate slow, cpu-intensive loop for($j=0;$j<100000;$j++) { $v = ''; for($i=0;$i<20;$i++) { $v=base64_encode($v.$i.''); }} ?><!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1 id="testing">Load Balancer Testing</h1> <h2>Server address: <?php echo $_SERVER['SERVER_ADDR']; ?></h2> <p><img width="400" height="175" alt="Testing loading the image from the server" src="images/img000.jpeg" /></p> </body> </html>
Fix incorrect name in comment.
# Copyright (C) 2013 Andy Balaam and The Pepper Developers # Released under the MIT License. See the file COPYING.txt for details. # I assure you before God that what I am writing to you is no lie. # Galations 1 v20 import types import abc def type_is( typ, inst ): """ Check that inst is of (exact) type typ. Throws an Assertion error if not. The arguments order is supposed to be reminiscent of C/Java style function declarations. """ # Arguably, we should allow duck typing to take its course # here - there could be some other metaclass we need to # add later, but I prefer the easier-to-understand error # message we get by checking the type. if not ( type(typ) == type or type(typ) == types.ClassType or type(typ) == abc.ABCMeta ): raise AssertionError( "Wrong arguments to type_is: the first argument must be a " + "class or type, not %s" % typ.__class__.__name__ ) if inst.__class__ != typ: raise AssertionError( "type_is check failed: expected a %s but found a %s." % ( typ.__name__, inst.__class__.__name__ ) )
# Copyright (C) 2013 Andy Balaam and The Pepper Developers # Released under the MIT License. See the file COPYING.txt for details. # I assure you before God that what I am writing to you is no lie. # Galations 1 v20 import types import abc def type_is( typ, inst ): """ Check that instance is of (exact) type typ. Throws an Assertion error if not. The arguments order is supposed to be reminiscent of C/Java style function declarations. """ # Arguably, we should allow duck typing to take its course # here - there could be some other metaclass we need to # add later, but I prefer the easier-to-understand error # message we get by checking the type. if not ( type(typ) == type or type(typ) == types.ClassType or type(typ) == abc.ABCMeta ): raise AssertionError( "Wrong arguments to type_is: the first argument must be a " + "class or type, not %s" % typ.__class__.__name__ ) if inst.__class__ != typ: raise AssertionError( "type_is check failed: expected a %s but found a %s." % ( typ.__name__, inst.__class__.__name__ ) )
Remove ontology path from request IRI correctly
package de.linkvt.bachelor.config; import de.linkvt.bachelor.web.GeneratorController; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; /** * Extracts the ontology IRI from the URL. */ @Component public class OntologyIriExtractor { public String extractGeneratorIri(String url) { String urlWithoutIdAndFilename = trimFilenameAndId(url); return removeOntologyPath(urlWithoutIdAndFilename); } public String extractOntologyIri(String url, Long generationId) { String urlWithoutFilename = trimFilenameAndId(url); return urlWithoutFilename + generationId + "/"; } private String trimFilenameAndId(String url) { return url.replaceAll("(\\d+/)?[^/]*$", ""); } private String removeOntologyPath(String url) { return StringUtils.removeEndIgnoreCase(url, GeneratorController.ONTOLOGY_PATH); } }
package de.linkvt.bachelor.config; import de.linkvt.bachelor.web.GeneratorController; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; /** * Extracts the ontology IRI from the URL. */ @Component public class OntologyIriExtractor { public String extractGeneratorIri(String url) { String urlWithoutIdAndFilename = trimFilenameAndId(url); return trimOntologyPath(urlWithoutIdAndFilename); } public String extractOntologyIri(String url, Long generationId) { String urlWithoutFilename = trimFilenameAndId(url); return urlWithoutFilename + generationId + "/"; } private String trimFilenameAndId(String url) { return url.replaceAll("(\\d+/)?[^/]*$", ""); } private String trimOntologyPath(String url) { return StringUtils.stripEnd(url, GeneratorController.ONTOLOGY_PATH); } }
Update jest diagnostics to warn only
module.exports = { globals: { "ts-jest": { diagnostics: { warnOnly: true } } }, transform: { ".ts": "ts-jest" }, testEnvironment: "node", testPathIgnorePatterns: [ "/dist/", "/node_modules/" ], moduleFileExtensions: [ "ts", "js", "json", "node" ], /* moduleNameMapper: { '^src/(.*)$': '<rootDir>/src/$1' }, */ coveragePathIgnorePatterns: [ "/dist/", "/node_modules/", "/tests/", "/index.ts" ], coverageThreshold: { global: { branches: 65, functions: 80, lines: 75, statements: 75 } }, collectCoverage: true, collectCoverageFrom: [ "src/**/*.{js,ts}", "!**/node_modules/**" ] }
module.exports = { transform: { ".ts": "ts-jest" }, testEnvironment: "node", testPathIgnorePatterns: [ "/dist/", "/node_modules/" ], moduleFileExtensions: [ "ts", "js", "json", "node" ], /* moduleNameMapper: { '^src/(.*)$': '<rootDir>/src/$1' }, */ coveragePathIgnorePatterns: [ "/dist/", "/node_modules/", "/tests/", "/index.ts" ], coverageThreshold: { global: { branches: 65, functions: 80, lines: 75, statements: 75 } }, collectCoverage: true, collectCoverageFrom: [ "src/**/*.{js,ts}", "!**/node_modules/**" ] }
Make the base test case abstract
<?php use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; abstract class RememberTestCase extends PHPUnit_Framework_TestCase { const ID = '00000000-0000-0000-0000-000000000000'; const USER_KEY = 'rememberable:37e1e4277521620256c524b5598dec2e19a04bfaf581bb9da4f83c3ad4ff7dbb7b03e7db5175eb2f3e507b4f8133fc2837eb392f7a92ce118ebff3a0e72cad9a'; /** * Is SQL allowed to be issued? * * @var bool */ protected static $sql = true; public static function setUpBeforeClass() { DB::listen(function ($query) { if (static::$sql === false) { throw new SqlIssuedException($query->sql); } }); } public function setUp() { Cache::flush(); DB::beginTransaction(); } public function tearDown() { Cache::flush(); DB::rollBack(); static::$sql = true; } }
<?php use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; class RememberTestCase extends PHPUnit_Framework_TestCase { const ID = '00000000-0000-0000-0000-000000000000'; const USER_KEY = 'rememberable:37e1e4277521620256c524b5598dec2e19a04bfaf581bb9da4f83c3ad4ff7dbb7b03e7db5175eb2f3e507b4f8133fc2837eb392f7a92ce118ebff3a0e72cad9a'; /** * Is SQL allowed to be issued? * * @var bool */ protected static $sql = true; public static function setUpBeforeClass() { DB::listen(function ($query) { if (static::$sql === false) { throw new SqlIssuedException($query->sql); } }); } public function setUp() { Cache::flush(); DB::beginTransaction(); } public function tearDown() { Cache::flush(); DB::rollBack(); static::$sql = true; } }
Apply OrderedDict changes to Bundle.
"""STIX 2 Bundle object""" from collections import OrderedDict from .base import _STIXBase from .properties import IDProperty, Property, TypeProperty class Bundle(_STIXBase): _type = 'bundle' _properties = OrderedDict() _properties = _properties.update([ ('type', TypeProperty(_type)), ('id', IDProperty(_type)), ('spec_version', Property(fixed="2.0")), ('objects', Property()), ]) def __init__(self, *args, **kwargs): # Add any positional arguments to the 'objects' kwarg. if args: if isinstance(args[0], list): kwargs['objects'] = args[0] + list(args[1:]) + kwargs.get('objects', []) else: kwargs['objects'] = list(args) + kwargs.get('objects', []) super(Bundle, self).__init__(**kwargs)
"""STIX 2 Bundle object""" from .base import _STIXBase from .properties import IDProperty, Property, TypeProperty class Bundle(_STIXBase): _type = 'bundle' _properties = { 'type': TypeProperty(_type), 'id': IDProperty(_type), 'spec_version': Property(fixed="2.0"), 'objects': Property(), } def __init__(self, *args, **kwargs): # Add any positional arguments to the 'objects' kwarg. if args: if isinstance(args[0], list): kwargs['objects'] = args[0] + list(args[1:]) + kwargs.get('objects', []) else: kwargs['objects'] = list(args) + kwargs.get('objects', []) super(Bundle, self).__init__(**kwargs)
Fix invalid tile entity error
package pokefenn.totemic.init; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntityType; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.registries.ObjectHolder; import pokefenn.totemic.Totemic; import pokefenn.totemic.tile.totem.TileTotemBase; @ObjectHolder(Totemic.MOD_ID) public final class ModTileEntities { public static final TileEntityType<TileTotemBase> totem_base = null; @SubscribeEvent public static void init(RegistryEvent.Register<TileEntityType<?>> event) { event.getRegistry().registerAll( TileEntityType.Builder.create(TileTotemBase::new, ModBlocks.getTotemBases().values().toArray(new Block[0])).build(null).setRegistryName("totem_base") ); } }
package pokefenn.totemic.init; import net.minecraft.tileentity.TileEntityType; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.registries.ObjectHolder; import pokefenn.totemic.Totemic; import pokefenn.totemic.tile.totem.TileTotemBase; @ObjectHolder(Totemic.MOD_ID) public final class ModTileEntities { public static final TileEntityType<TileTotemBase> totem_base = null; @SubscribeEvent public static void init(RegistryEvent.Register<TileEntityType<?>> event) { event.getRegistry().registerAll( TileEntityType.Builder.create(TileTotemBase::new).build(null).setRegistryName("totem_base") ); } }
Refactor num iterator for new spec :white_check_mark:
// Number iterator for iterating from 0 to Number // http://blog.getify.com/iterating-es6-numbers/comment-page-1/#comment-535319 function numberIterator({ length, increment, start }) { if (length === undefined) { length = 10; } if (increment === undefined) { increment = 1; } if (start === undefined) { start = 0; } return { [Symbol.iterator] : function() { let number, count; return { next : function() { if (count === undefined) { count = 1; number = start; return { value : number, done : false }; } else if (count < length) { count++; number += increment; return { value : number, done : false }; } else { return { done : true }; } } }; } }; } export default numberIterator;
// Number iterator for iterating from 0 to Number // http://blog.getify.com/iterating-es6-numbers/comment-page-1/#comment-535319 function numberIterator(total, increment = 1) { return { [Symbol.iterator]: function() { var i, count; return { next: function() { if (count === undefined) { i = 0; count = 1; return { value: 0, done: false }; } else if (count < total) { i += increment; count++; return { value: i, done: false }; } else { return { done: true }; } } }; } }; } export default numberIterator;
Add shebang to python server
#!/usr/bin/env python3 import socket import serial.tools.list_ports import serial ports = list(serial.tools.list_ports.comports()) arduino_port = next((port for port in ports if "Arduino" in port.description), None) arduino = serial.Serial(arduino_port[0], 9600) # print("Connecting on " + arduino_port[0]) PORT = 4242 HOST = 'localhost' server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((HOST, PORT)) server_socket.listen(5) while True: connection, address = server_socket.accept() # print("Client connected") while True: try: incoming = arduino.readline() connection.send(incoming) except: # print("Client disconnected") break
import socket import serial.tools.list_ports import serial ports = list(serial.tools.list_ports.comports()) arduino_port = next((port for port in ports if "Arduino" in port.description), None) arduino = serial.Serial(arduino_port[0], 9600) # print("Connecting on " + arduino_port[0]) PORT = 4242 HOST = 'localhost' server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((HOST, PORT)) server_socket.listen(5) while True: connection, address = server_socket.accept() # print("Client connected") while True: try: incoming = arduino.readline() connection.send(incoming) except: # print("Client disconnected") break
Add timeInfo() for conditional scales Fix quotes and remove whitespace
import fmt from "./fmt" import { log } from "fly-util" export default function () { this.on("fly_run", ({ path }) => log(`Flying with ${fmt.path}...`, path)) .on("flyfile_not_found", ({ error }) => log(`No Flyfile Error: ${fmt.error}`, error)) .on("fly_watch", () => log(`${fmt.warn}`, "Watching files...")) .on("plugin_load", ({ plugin }) => log(`Loading plugin ${fmt.name}`, plugin)) .on("plugin_error", ({ plugin, error }) => log(`${fmt.error} failed due to ${fmt.error}`, plugin, error)) .on("task_error", ({ task, error }) => log(`${fmt.error} failed due to ${fmt.error}`, task, error)) .on("task_start", ({ task }) => log(`Starting ${fmt.start}`, task)) .on("task_complete", ({ task, duration }) => { const time = timeInfo(duration) log(`Finished ${fmt.complete} in ${fmt.secs}`, task, time.duration, time.scale) }) .on("task_not_found", ({ task }) => log(`${fmt.error} not found in Flyfile.`, task)) return this } /** * conditionally format task duration * @param {Number} duration task duration in ms * @param {String} scale default scale for output * @return {Object} time information */ function timeInfo (duration, scale = "ms") { const time = duration >= 1000 ? { duration: Math.round((duration / 1000) * 10) / 10, scale: "s" } : { duration, scale } return time }
import fmt from "./fmt" import { log } from "fly-util" export default function () { this.on("fly_run", ({ path }) => log(`Flying with ${fmt.path}...`, path)) .on("flyfile_not_found", ({ error }) => log(`No Flyfile Error: ${fmt.error}`, error)) .on("fly_watch", () => log(`${fmt.warn}`, "Watching files...")) .on("plugin_load", ({ plugin }) => log(`Loading plugin ${fmt.name}`, plugin)) .on("plugin_error", ({ plugin, error }) => log(`${fmt.error} failed due to ${fmt.error}`, plugin, error)) .on("task_error", ({ task, error }) => log(`${fmt.error} failed due to ${fmt.error}`, task, error)) .on("task_start", ({ task }) => log(`Starting ${fmt.start}`, task)) .on("task_complete", ({ task, duration }) => log(`Finished ${fmt.complete} in ${fmt.secs}`, task, duration, "ms")) .on("task_not_found", ({ task }) => log(`${fmt.error} not found in Flyfile.`, task)) return this }
Use `auto_now_add` to make ACL.created_at timezone aware
# -*- coding: utf-8 -*- from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ACL(models.Model): acl_list = {} resource = models.CharField( _("Resource name"), max_length=255, db_index=True, ) display = models.CharField( _("displayed name"), max_length=255, null=True, blank=True, ) created_at = models.DateTimeField( _("Creation time"), auto_now_add=True, ) is_available = models.BooleanField( _("Is available to assign"), default=True, ) class Meta: app_label = 'yaacl' def __str__(self): if self.display: return "%s (%s)" % (self.display, self.resource) else: return self.resource
# -*- coding: utf-8 -*- from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ACL(models.Model): acl_list = {} resource = models.CharField( _("Resource name"), max_length=255, db_index=True, ) display = models.CharField( _("displayed name"), max_length=255, null=True, blank=True, ) created_at = models.DateTimeField( _("Creation time"), default=datetime.now(), ) is_available = models.BooleanField( _("Is available to assign"), default=True, ) class Meta: app_label = 'yaacl' def __str__(self): if self.display: return "%s (%s)" % (self.display, self.resource) else: return self.resource
Add browser sync support for images
var browserSync = require('browser-sync'); module.exports = function(gulp, plugins) { var paths = { 'build': [ // images that should be compressed 'assets/images/**/*' ], // destination folder 'output': 'build/img' }; gulp.task('build:img', 'compresses images and moves them to the build folder', function() { return gulp.src(paths.build) .pipe(plugins.newer(paths.output)) .pipe(plugins.image()) .pipe(gulp.dest(paths.output)) .pipe(browserSync.reload({'stream': true})) .pipe(plugins.notify({'message': 'Image minification complete', 'onLast': true})); }); gulp.task('watch:img', 'watches the source images folders and recompresses them when changed', ['build:img'], function() { gulp.watch(paths.build, ['build:img']); }); };
module.exports = function(gulp, plugins) { var paths = { 'build': [ // images that should be compressed 'assets/images/**/*' ], // destination folder 'output': 'build/img' }; gulp.task('build:img', 'compresses images and moves them to the build folder', function() { return gulp.src(paths.build) .pipe(plugins.newer(paths.output)) .pipe(plugins.image()) .pipe(gulp.dest(paths.output)); }); gulp.task('watch:img', 'watches the source images folders and recompresses them when changed', ['build:img'], function() { gulp.watch(paths.build, ['build:img']); }); };
Remove duplicate definition of reference.
package com.humbughq.android; import android.util.Log; import android.widget.TextView; class AsyncLogin extends HumbugAsyncPushTask { public AsyncLogin(HumbugActivity humbugActivity, String username, String password) { super(humbugActivity); that = humbugActivity; this.that.email = username; this.setProperty("username", username); this.setProperty("password", password); } public final void execute() { execute("api/v1/fetch_api_key"); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != null) { this.that.api_key = result.toString(); Log.i("login", "Logged in as " + this.that.api_key); this.that.openLogin(); } else { TextView errorText = (TextView) this.that .findViewById(R.id.error_text); errorText.setText("Login failed"); } } }
package com.humbughq.android; import android.util.Log; import android.widget.TextView; class AsyncLogin extends HumbugAsyncPushTask { HumbugActivity that; public AsyncLogin(HumbugActivity humbugActivity, String username, String password) { super(humbugActivity); that = humbugActivity; this.that.email = username; this.setProperty("username", username); this.setProperty("password", password); } public final void execute() { execute("api/v1/fetch_api_key"); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != null) { this.that.api_key = result.toString(); Log.i("login", "Logged in as " + this.that.api_key); this.that.openLogin(); } else { TextView errorText = (TextView) this.that .findViewById(R.id.error_text); errorText.setText("Login failed"); } } }
Rename and refactor argument tests
package com.hamishrickerby.http_server; import junit.framework.TestCase; /** * Created by rickerbh on 15/08/2016. */ public class AppArgumentsTest extends TestCase { public void testEmptyInputReturnsValidArguments() { String[] inputArgs = new String[0]; AppArguments args = new AppArguments(inputArgs); assertEquals(0, args.size()); } public void testArgumentsAreRetrieved() { String[] inputArgs = {"-p", "3000", "-d", "hello"}; AppArguments args = new AppArguments(inputArgs); assertEquals("3000", args.get("-p")); assertEquals("hello", args.get("-d")); } public void testIncompleteAndNotPresentArgumentsFailToGetRead() { String[] inputArgs = {"-p", "3000", "-d"}; AppArguments args = new AppArguments(inputArgs); assertEquals("3000", args.get("-p")); assertNull(args.get("-d")); assertNull(args.get("i-don't-exist")); } }
package com.hamishrickerby.http_server; import junit.framework.TestCase; /** * Created by rickerbh on 15/08/2016. */ public class AppArgumentsTest extends TestCase { public void testEmptyArgumentsAre0Long() { String[] inputArgs = new String[0]; AppArguments args = new AppArguments(inputArgs); assertEquals(0, args.size()); } public void testArgumentsParseCorrectly() { String[] inputArgs = {"-p", "3000", "-d", "hello"}; AppArguments args = new AppArguments(inputArgs); assertEquals("3000", args.get("-p")); assertEquals("hello", args.get("-d")); } public void testIncompleteArgumentsFailToGetRead() { String[] inputArgs = {"-p", "3000", "-d"}; AppArguments args = new AppArguments(inputArgs); assertEquals("3000", args.get("-p")); assertNull(args.get("-d")); } public void testNotPresentArgumentReturnsNull() { String[] inputArgs = {"-p", "3000"}; AppArguments args = new AppArguments(inputArgs); assertEquals("3000", args.get("-p")); assertNull(args.get("-d")); } }
Fix defaults-only middleware case, i.e. no args
var fs = require('fs'); var middleware = []; fs.readdirSync(__dirname + '/middleware').forEach(function (filename) { if (/\.js$/.test(filename)) { var name = filename.substr(0, filename.lastIndexOf('.')); middleware.push(name); exports.__defineGetter__(name, function () { return require('./middleware/' + name); }); } }); exports.defaults = function (app, overrides) { if (!app || typeof app.use !== 'function') { overrides = app; try { // make sub-app, in likeliest framework(s) app = require('express')(); } catch (e) { app = require('connect')(); } } overrides = overrides || {csp: false}; middleware.forEach(function _eachMiddleware(m) { if (overrides[m] !== false) { app.use(require('./middleware/' + m)()); } }); return app; };
var fs = require('fs'); var middleware = []; fs.readdirSync(__dirname + '/middleware').forEach(function (filename) { if (/\.js$/.test(filename)) { var name = filename.substr(0, filename.lastIndexOf('.')); middleware.push(name); exports.__defineGetter__(name, function () { return require('./middleware/' + name); }); } }); exports.defaults = function (app, overrides) { if (typeof app.use !== 'function') { overrides = app; try { // make sub-app, in likeliest framework(s) app = require('express')(); } catch (e) { app = require('connect')(); } } overrides = overrides || {csp: false}; middleware.forEach(function _eachMiddleware(m) { if (overrides[m] !== false) { app.use(require('./middleware/' + m)()); } }); return app; };
Update tilelive pool factory create method to pass errors.
var Map = require('./lib/map'), Format = require('./lib/format'), safe64 = require('./lib/safe64'); module.exports = { Map: Map, Format: Format, safe64: safe64, pool: function(datasource) { return { create: function(callback) { var resource = new Map(datasource); resource.initialize(function(err) { callback(err, resource); }); }, destroy: function(resource) { resource.destroy(); } }; }, serve: function(resource, options, callback) { resource.render(options, callback); } };
var Map = require('./lib/map'), Format = require('./lib/format'), safe64 = require('./lib/safe64'); module.exports = { Map: Map, Format: Format, safe64: safe64, pool: function(datasource) { return { create: function(callback) { var resource = new Map(datasource); resource.initialize(function(err) { if (err) throw err; callback(resource); }); }, destroy: function(resource) { resource.destroy(); } }; }, serve: function(resource, options, callback) { resource.render(options, callback); } };
Add preventDefault argument for UpfCheckbox
import Component from '@ember/component'; import { observer } from '@ember/object'; import { equal } from '@ember/object/computed'; export default Component.extend({ classNames: ['upf-checkbox'], classNameBindings: [ 'hasLabel:upf-checkbox--has-label', 'sizeSmall:upf-checkbox--sm', 'disabled:upf-checkbox--disabled' ], attributeBindings: ['data-control-name'], sizeSmall: equal('size', 'sm'), disabled: false, onValueChange: null, onToggleAttempt: null, _: observer('value', function () { if (this.onValueChange) { this.onValueChange(this.value); } }), click(e) { if (this.preventDefault) { e.preventDefault(); } e.stopPropagation(); if (this.disabled && this.onToggleAttempt) { e.preventDefault(); this.onToggleAttempt(); } } });
import Component from '@ember/component'; import { observer } from '@ember/object'; import { equal } from '@ember/object/computed'; export default Component.extend({ classNames: ['upf-checkbox'], classNameBindings: [ 'hasLabel:upf-checkbox--has-label', 'sizeSmall:upf-checkbox--sm', 'disabled:upf-checkbox--disabled' ], attributeBindings: ['data-control-name'], sizeSmall: equal('size', 'sm'), disabled: false, onValueChange: null, onToggleAttempt: null, _: observer('value', function() { if (this.onValueChange) { this.onValueChange(this.value); } }), click(e) { e.stopPropagation(); if (this.disabled && this.onToggleAttempt) { e.preventDefault(); this.onToggleAttempt(); } } });
Add read only functionnality on published node
<?php namespace PHPOrchestra\ModelBundle\EventListener; use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs; use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs; use PHPOrchestra\ModelBundle\Model\StatusInterface; use PHPOrchestra\ModelBundle\Model\StatusableInterface; /** * Class SavePublishedDocumentListener */ class SavePublishedDocumentListener { /** * @param LifecycleEventArgs $eventArgs */ public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if ($document instanceof StatusableInterface) { $status = $document->getStatus(); if (! empty($status) && $status->isPublished() && (!method_exists($document, 'isDeleted') || ! $document->isDeleted()) ) { $documentManager = $eventArgs->getDocumentManager(); $documentManager->getUnitOfWork()->detach($document); } } } }
<?php namespace PHPOrchestra\ModelBundle\EventListener; use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs; use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs; use PHPOrchestra\ModelBundle\Model\StatusInterface; use PHPOrchestra\ModelBundle\Model\StatusableInterface; /** * Class SavePublishedDocumentListener */ class SavePublishedDocumentListener { /** * @param LifecycleEventArgs $eventArgs */ public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if ($document instanceof StatusableInterface) { $status = $document->getStatus(); if (! empty($status) && $status->isPublished() && (! method_exists($document, 'isDeleted') || ! $document->isDeleted())) { $documentManager = $eventArgs->getDocumentManager(); $documentManager->getUnitOfWork()->detach($document); } } } }
Update index test case 1
/** * util/core.spec.js * * @author Rock Hu <rockia@mac.com> * @license MIT */ import Endpoints from '../../src/config/endpoints.json'; import API from '../../src/config/api.json'; var Sinon = require('sinon'); var Chai = require('chai'); var Path = require('path'); Chai.use(require('sinon-chai')); Chai.should(); var expect = Chai.expect; var index = require('../../src/index.js'); describe('index', function() { it('should return APIDriver Object', function(){ var options = { api_key: '1234', platform: 'production', region: 'NA' }; class APIDriver{}; var apidriverObj = new APIDriver(Endpoints,API,options); expect(apidriverObj).to.be.an.instanceof(APIDriver); }); });
/** * util/core.spec.js * * @author Rock Hu <rockia@mac.com> * @license MIT */ import Endpoints from '../../src/config/endpoints.json'; import API from '../../src/config/api.json'; var Sinon = require('sinon'); var Chai = require('chai'); var Path = require('path'); Chai.use(require('sinon-chai')); Chai.should(); var expect = Chai.expect; var index = require('../../src/index.js'); describe('index', function() { var options = { api_key: '1234', platform: 'production', region: 'NA' }; class APIDriver{}; var apidriverObj = new APIDriver(Endpoints,API,options); it('should return APIDriver Object', function(){ expect(apidriverObj).to.be.an.instanceof(APIDriver); }); });
Remove decorator 'skip_in_ci' from test_files Because implement stub of capture engine, 'Output slides pdf' test can run in CircleCI
import os import shutil import deck2pdf from pytest import raises from . import ( current_dir, test_dir, ) class TestForMain(object): def setUp(self): shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True) def test_help(self): raises(SystemExit, deck2pdf.main, []) raises(SystemExit, deck2pdf.main, ['-h']) def test_files(self): test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html') deck2pdf.main([test_slide_path, '-c', 'stub']) assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
import os import shutil import deck2pdf from pytest import raises from . import ( current_dir, test_dir, skip_in_ci, ) class TestForMain(object): def setUp(self): shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True) def test_help(self): raises(SystemExit, deck2pdf.main, []) raises(SystemExit, deck2pdf.main, ['-h']) @skip_in_ci def test_files(self): test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html') deck2pdf.main([test_slide_path, ]) assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
Set back number of seats when unspecified seats are reserved
'use strict'; angular.module('ticketbox.boxoffice.block', [ 'ngRoute', 'ticketbox.config', 'ticketbox.components.api', 'ticketbox.common.seatplan.handlers', 'ticketbox.components.seatplan', 'ticketbox.components.reserver', 'ticketbox.boxoffice.toolbar']) .config(function($routeProvider) { $routeProvider.when('/block/:blockId', { controller: 'BlockCtrl', templateUrl: 'boxoffice.block/boxoffice.block.html' }); }) .controller('BlockCtrl', function($scope, $routeParams, $location, Eventblock, reserver, maxNumberOfUnspecifiedSeats) { $scope.block = Eventblock.get({ 'id': $routeParams.blockId }); $scope.selectableNumbersOfUnspecifiedSeats = _.range(1, maxNumberOfUnspecifiedSeats + 1); $scope.data = { numberOfSeats: 0 }; $scope.reserveMultiple = function(block, numberOfSeats) { reserver.reserveMultiple(block.id, numberOfSeats) .then(function() { $scope.data.numberOfSeats = 0; }); } });
'use strict'; angular.module('ticketbox.boxoffice.block', [ 'ngRoute', 'ticketbox.config', 'ticketbox.components.api', 'ticketbox.common.seatplan.handlers', 'ticketbox.components.seatplan', 'ticketbox.components.reserver', 'ticketbox.boxoffice.toolbar']) .config(function($routeProvider) { $routeProvider.when('/block/:blockId', { controller: 'BlockCtrl', templateUrl: 'boxoffice.block/boxoffice.block.html' }); }) .controller('BlockCtrl', function($scope, $routeParams, $location, Eventblock, reserver, maxNumberOfUnspecifiedSeats) { $scope.block = Eventblock.get({ 'id': $routeParams.blockId }); $scope.selectableNumbersOfUnspecifiedSeats = _.range(1, maxNumberOfUnspecifiedSeats + 1); $scope.data = { numberOfSeats: 0 }; $scope.reserveMultiple = function(block, numberOfSeats) { reserver.reserveMultiple(block.id, numberOfSeats) .then(function() { $scope.data.numberOfSeats = undefined; }); } });
Add hashtag for currency name and symbol
# coding: utf-8 import os import time from twython import Twython import requests APP_KEY = os.environ.get('APP_KEY') APP_SECRET = os.environ.get('APP_SECRET') OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN') OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET') twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) def post_tweet(currency): template = """ {name} - {symbol} Price: ${price_usd} Change in 1h: {percent_change_1h}% Market cap: ${market_cap_usd} Ranking: {rank} #{name} #{symbol} """ if currency['percent_change_1h'] > 0: currency['percent_change_1h'] = '+{}'.format(currency['percent_change_1h']) twitter.update_status(status=template.format(**currency)) def main(): response = requests.get('https://api.coinmarketcap.com/v1/ticker/') for currency in sorted(response.json(), key=lambda x: x['rank'])[:10]: post_tweet(currency) time.sleep(5) if __name__ == '__main__': main()
# coding: utf-8 import os import time from twython import Twython import requests APP_KEY = os.environ.get('APP_KEY') APP_SECRET = os.environ.get('APP_SECRET') OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN') OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET') twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) def post_tweet(currency): template = """ {name} - {symbol} Price: ${price_usd} Change in 1h: {percent_change_1h}% Market cap: ${market_cap_usd} Ranking: {rank} """ if currency['percent_change_1h'] > 0: currency['percent_change_1h'] = '+{}'.format(currency['percent_change_1h']) twitter.update_status(status=template.format(**currency)) def main(): response = requests.get('https://api.coinmarketcap.com/v1/ticker/') for currency in sorted(response.json(), key=lambda x: x['rank'])[:10]: post_tweet(currency) time.sleep(5) if __name__ == '__main__': main()
Fix models path in tests
<?php if(is_dir(__DIR__ . '/../vendor')) { include(__DIR__ . '/../vendor/autoload.php'); } else { require __DIR__ . '/../src.php'; } require __DIR__ . '/TestCase.php'; require __DIR__ . '/DatabaseTestCase.php'; $models = glob(realpath(__DIR__) . '/Models/*.php'); foreach($models as $model) { include $model; } require __DIR__ . '/custom.php'; function d() { $debug = debug_backtrace(); $args = func_get_args(); $data = array( 'data' => $args, 'debug' => array( 'file' => $debug[0]['file'], 'line' => $debug[0]['line'], ) ); if(class_exists('Mindy\Helper\Dumper')) { Mindy\Helper\Dumper::dump($data, 10); } else { var_dump($data); } die(); }
<?php if(is_dir(__DIR__ . '/../vendor')) { include(__DIR__ . '/../vendor/autoload.php'); } else { require __DIR__ . '/../src.php'; } require __DIR__ . '/TestCase.php'; require __DIR__ . '/DatabaseTestCase.php'; $models = glob(realpath(__DIR__) . '/models/*.php'); foreach($models as $model) { include $model; } require __DIR__ . '/custom.php'; function d() { $debug = debug_backtrace(); $args = func_get_args(); $data = array( 'data' => $args, 'debug' => array( 'file' => $debug[0]['file'], 'line' => $debug[0]['line'], ) ); if(class_exists('Mindy\Helper\Dumper')) { Mindy\Helper\Dumper::dump($data, 10); } else { var_dump($data); } die(); }
Make api-tokens view exempt from CSRF checks
from django.http import JsonResponse from django.views.decorators.http import require_http_methods from oidc_provider.lib.utils.oauth2 import protected_resource_view from django.views.decorators.csrf import csrf_exempt from .api_tokens import get_api_tokens_by_access_token @csrf_exempt @require_http_methods(['GET', 'POST']) @protected_resource_view(['openid']) def get_api_tokens_view(request, token, *args, **kwargs): """ Get the authorized API Tokens. :type token: oidc_provider.models.Token :rtype: JsonResponse """ api_tokens = get_api_tokens_by_access_token(token, request=request) response = JsonResponse(api_tokens, status=200) response['Access-Control-Allow-Origin'] = '*' response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
from django.http import JsonResponse from django.views.decorators.http import require_http_methods from oidc_provider.lib.utils.oauth2 import protected_resource_view from .api_tokens import get_api_tokens_by_access_token @require_http_methods(['GET', 'POST']) @protected_resource_view(['openid']) def get_api_tokens_view(request, token, *args, **kwargs): """ Get the authorized API Tokens. :type token: oidc_provider.models.Token :rtype: JsonResponse """ api_tokens = get_api_tokens_by_access_token(token, request=request) response = JsonResponse(api_tokens, status=200) response['Access-Control-Allow-Origin'] = '*' response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
Fix setting loyalty_number on new customer
<? include '../scat.php'; $name= $_REQUEST['name']; $company= $_REQUEST['company']; $phone= $_REQUEST['phone']; if (empty($name) && empty($company) && empty($phone)) die_jsonp("You need to supply at least a name, company, or phone number."); $list= array(); foreach(array('name', 'company', 'address', 'email', 'phone', 'tax_id') as $field) { $list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', "; } if ($_REQUEST['phone']) { $list[]= "loyalty_number = '" . preg_replace('/[^\d]/', '', $_REQUEST['phone']) . "', "; } $fields= join('', $list); $q= "INSERT INTO person SET $fields active = 1"; $r= $db->query($q) or die_query($db, $q); echo jsonp(array('person' => $db->insert_id));
<? include '../scat.php'; $name= $_REQUEST['name']; $company= $_REQUEST['company']; $phone= $_REQUEST['phone']; if (empty($name) && empty($company) && empty($phone)) die_jsonp("You need to supply at least a name, company, or phone number."); $list= array(); foreach(array('name', 'company', 'address', 'email', 'phone', 'tax_id') as $field) { $list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', "; } if ($list['phone']) { $list['loyalty_number']= preg_replace('/[^\d]/', '', $list['phone']); } $fields= join('', $list); $q= "INSERT INTO person SET $fields active = 1"; $r= $db->query($q) or die_query($db, $q); echo jsonp(array('person' => $db->insert_id));
Prepare for y (yellow) first argument
#!/usr/bin/env python2 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width shows red/green bar to visualize return code of previous command ''' import sys if len(sys.argv) >= 2: value = int(sys.argv[1]) if value: col_char = '1' else: col_char = '2' cols_limit = int(sys.argv[2]) esc = chr(27) print (''.join(( esc, '[4', col_char, 'm', ' ' * (cols_limit - 2), esc, '[0m', ))) else: print (''' Usage: %(prog_name)s status_code number_of_columns 1. status code: 0 - OK (green color), other values - BAD (red color) 2. number of columns: the width of text console ''' % dict( prog_name=sys.argv[0], ))
#!/usr/bin/env python2 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width shows red/green bar to visualize return code of previous command ''' import sys if len(sys.argv) >= 2: value = int(sys.argv[1]) cols_limit = int(sys.argv[2]) esc = chr(27) if value: col_char = '1' else: col_char = '2' print (''.join(( esc, '[4', col_char, 'm', ' ' * (cols_limit - 2), esc, '[0m', ))) else: print (''' Usage: %(prog_name)s status_code number_of_columns 1. status code: 0 - OK (green color), other values - BAD (red color) 2. number of columns: the width of text console ''' % dict( prog_name=sys.argv[0], ))
[IMP] Test should not have wait if thy are long by default.
(function() { 'use strict'; openerp.Tour.register({ id: 'test_instance_introspection', name: 'Complete a basic order trough the Front-End', path: '/instance_introspection', mode: 'test', steps: [ { title: 'Wait for the main screen', waitFor: 'h3:contains("Addons Paths"),#accordion.results', element: '.btn-reload', }, { title: 'Load Repositories', waitFor: '#accordion.results', }, ], }); })();
(function() { 'use strict'; openerp.Tour.register({ id: 'test_instance_introspection', name: 'Complete a basic order trough the Front-End', path: '/instance_introspection', mode: 'test', steps: [ { title: 'Wait for the main screen', waitFor: 'h3:contains("Addons Paths"),#accordion.results', element: '.btn-reload', wait: 200, }, { title: 'Load Repositories', waitFor: '#accordion.results', }, ], }); })();
Update full directory for PHP include file
<?php include("/home/c0smic/secure/data_db_settings.php"); # Read GET variables $stime = $_POST['stime']; $etime = $_POST['etime']; $moves = $_POST['moves']; $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
<?php include("/secure/data_db_settings.php"); # Read GET variables $stime = $_POST['stime']; $etime = $_POST['etime']; $moves = $_POST['moves']; $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
Add instructional text to kiosk header and remove unnecessary margin shrinkage
<!DOCTYPE html> <html lang="en"> <head> @include('layouts/head') <style type="text/css"> /* Vertically center all the things - http://bit.ly/2Fm2Gpe */ html, body { width: 100%; height: 100%; } html { display: table; } body { display: table-cell; vertical-align: middle; } </style> </head> <body> @inject('request', 'Illuminate\Http\Request') <div class="container" id="app"> <div class="row"> <div class="col-12" style="text-align:center"> <h1 style="font-size: 4rem">Welcome to the Shop!</h1> <h2><em>Tap a team to record attendance</em></h2> </div> </div> <attendance-kiosk></attendance-kiosk> </div> </body> <script src="{{ mix('/js/app.js') }}"></script> @if (Session::has('sweet_alert.alert')) <script> Swal.fire({!! Session::pull('sweet_alert.alert') !!}); </script> @endif </html>
<!DOCTYPE html> <html lang="en"> <head> @include('layouts/head') <style type="text/css"> /* Vertically center all the things - http://bit.ly/2Fm2Gpe */ html, body { width: 100%; height: 100%; } html { display: table; } body { display: table-cell; vertical-align: middle; } </style> </head> <body> @inject('request', 'Illuminate\Http\Request') <div class="container" id="app" style="margin-top: -5%"> <div class="row"> <div class="col-12" style="text-align:center"> <h1 style="font-size: 4rem">Welcome to the Shop!</h1> </div> </div> <attendance-kiosk></attendance-kiosk> </div> </body> <script src="{{ mix('/js/app.js') }}"></script> @if (Session::has('sweet_alert.alert')) <script> Swal.fire({!! Session::pull('sweet_alert.alert') !!}); </script> @endif </html>
Add Topic Updates to upgrader script
<?php // 2.0.0 pr-7 to 2.0.0 pr-8 updater try { $db_engine = Config::get('mysql/engine'); } catch (Exception $e) { // unable to retrieve from config echo $e->getMessage() . '<br />'; } if (!$db_engine || ($db_engine != 'MyISAM' && $db_engine != 'InnoDB')) $db_engine = 'InnoDB'; try { $db_charset = Config::get('mysql/charset'); } catch (Exception $e) { // unable to retrieve from config echo $e->getMessage() . '<br />'; } if (!$db_charset || ($db_charset != 'utf8mb4' && $db_charset != 'latin1')) $db_charset = 'latin1'; // Edit Topics forum permission try { $queries->alterTable('forum_permissions', '`edit_topic`', "tinyint(1) NOT NULL DEFAULT '0'"); } catch (Exception $e) { echo $e->getMessage() . '<br />'; } // Custom pages basic setting try { $queries->alterTable('custom_pages', '`basic`', "tinyint(1) NOT NULL DEFAULT '0'"); } catch (Exception $e) { echo $e->getMessage() . '<br />'; } // Topic Updates try { $queries->alterTable('users', '`topic_updates`', "tinyint(1) NOT NULL DEFAULT '1'"); } catch (Exception $e) { echo $e->getMessage() . '<br />'; }
<?php // 2.0.0 pr-7 to 2.0.0 pr-8 updater try { $db_engine = Config::get('mysql/engine'); } catch (Exception $e) { // unable to retrieve from config echo $e->getMessage() . '<br />'; } if (!$db_engine || ($db_engine != 'MyISAM' && $db_engine != 'InnoDB')) $db_engine = 'InnoDB'; try { $db_charset = Config::get('mysql/charset'); } catch (Exception $e) { // unable to retrieve from config echo $e->getMessage() . '<br />'; } if (!$db_charset || ($db_charset != 'utf8mb4' && $db_charset != 'latin1')) $db_charset = 'latin1'; // Edit Topics forum permission try { $queries->alterTable('forum_permissions', '`edit_topic`', "tinyint(1) NOT NULL DEFAULT '0'"); } catch (Exception $e) { echo $e->getMessage() . '<br />'; } // Custom pages basic setting try { $queries->alterTable('custom_pages', '`basic`', "tinyint(1) NOT NULL DEFAULT '0'"); } catch (Exception $e) { echo $e->getMessage() . '<br />'; }
Make signup not require token in API
from rest_framework import viewsets, status from rest_framework.authtoken.models import Token from rest_framework.decorators import detail_route from rest_framework.response import Response from api.models import User from api.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes_by_action = {'create': []} @detail_route(methods=['put']) def follow(self, request, pk=None): # follows a given user pass @detail_route(methods=['put']) def unfollow(self, request, pk=None): # unfollows a given user pass # Override create to return token def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() headers = self.get_success_headers(serializer.data) response = serializer.data response['access_token'] = Token.objects.get(user=user).key return Response(response, status=status.HTTP_201_CREATED, headers=headers) # Token isn't required when creating user (signup) def get_permissions(self): try: return [permission() for permission in self.permission_classes_by_action[self.action]] except KeyError: return [permission() for permission in self.permission_classes]
from rest_framework import viewsets, status from rest_framework.authtoken.models import Token from rest_framework.decorators import detail_route from rest_framework.response import Response from api.models import User from api.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @detail_route(methods=['put']) def follow(self, request, pk=None): # follows a given user pass @detail_route(methods=['put']) def unfollow(self, request, pk=None): # unfollows a given user pass # Override create to return token def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() headers = self.get_success_headers(serializer.data) response = serializer.data response['access_token'] = Token.objects.get(user=user).key return Response(response, status=status.HTTP_201_CREATED, headers=headers)
Add styling clases to fix buttons appearing white on iOS
$(function() { var markdownTable = $('.markdown-table-wrap'); if (markdownTable.length) { $('<button class="btn btn--secondary btn--mobile-table-show">View table</button>').insertAfter(markdownTable); $('<button class="btn btn--secondary btn--mobile-table-hide">Close table</button>').insertAfter(markdownTable.find('table')); $('.btn--mobile-table-show').click(function () { $(this).closest('.markdown-table-container').find('.markdown-table-wrap').show(); }); $('.btn--mobile-table-hide').click(function () { $(this).closest('.markdown-table-wrap').css('display', ''); }); } });
$(function() { var markdownTable = $('.markdown-table-wrap'); if (markdownTable.length) { $('<button class="btn btn--mobile-table-show">View table</button>').insertAfter(markdownTable); $('<button class="btn btn--mobile-table-hide">Close table</button>').insertAfter(markdownTable.find('table')); $('.btn--mobile-table-show').click(function () { $(this).closest('.markdown-table-container').find('.markdown-table-wrap').show(); }); $('.btn--mobile-table-hide').click(function () { $(this).closest('.markdown-table-wrap').css('display', ''); }); } });
Move rabbit vars to globals
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Figure out how to do batching. TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
Update dsub version to 0.4.5 PiperOrigin-RevId: 393155372
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.5'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.5.dev0'
Increase timeout for stack test
/*global describe, it*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var assert = require('assert'); var run = require('./fixture/run'); describe('stack', function () { this.timeout(5000); it('does not screw up xunit', function (done) { run('passes', ['-R', 'xunit'], function (code, stdout) { var lines = stdout.split('\n'); var expect = '<testcase classname="test" name="passes" time="0'; assert.equal(lines[1].substring(0, expect.length), expect); assert.equal(lines[2], '</testsuite>'); assert.equal(code, 0); done(); }); }); });
/*global describe, it*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var assert = require('assert'); var run = require('./fixture/run'); describe('stack', function () { this.timeout(3000); it('does not screw up xunit', function (done) { run('passes', ['-R', 'xunit'], function (code, stdout) { var lines = stdout.split('\n'); var expect = '<testcase classname="test" name="passes" time="0'; assert.equal(lines[1].substring(0, expect.length), expect); assert.equal(lines[2], '</testsuite>'); assert.equal(code, 0); done(); }); }); });
Revert "Remove static when using @RegisterExtension" This reverts commit b7f7cf7efe5f941f2702181a603147b00c5a7337.
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia; import java.io.IOException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class ExceptionTest { @RegisterExtension static IgnoreIOExceptionExtension ignoreIOExceptionExtension = new IgnoreIOExceptionExtension(); @Test public void firstTest() throws IOException { throw new IOException("IO Exception"); } @Test public void secondTest() throws IOException { throw new IOException("My IO Exception"); } }
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia; import java.io.IOException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class ExceptionTest { @RegisterExtension IgnoreIOExceptionExtension ignoreIOExceptionExtension = new IgnoreIOExceptionExtension(); @Test public void firstTest() throws IOException { throw new IOException("IO Exception"); } @Test public void secondTest() throws IOException { throw new IOException("My IO Exception"); } }
Fix race conditions in migration 061 Migration 061 is supposed to add new `data_timestamp` field and populate it with value of `created_at` column. This was done by selecting all the backups and doing updates one-by-one. As it wasn't done in transaction solution was prone to race condition when a new backup is added while running the migration. This means that this migration could cause problems when running in live environment. With blueprint online-schema-upgrades we want to make Cinder able to perform migrations live. A solution is to change this statement to a single DB query which updates all the rows. This commit also removes unnecessary update to snapshot_id added there. As this column is nullable it will by default be NULL, so there's no need to set it manually to that value. As before and after this commit the migration does logically the same, this should be safe even if someone is doing inter-release deployments. An alternative would be to simply add transaction to the update step in the migration, but that would effectively lock the table for longer period of time than atomic one-query update. Closes-Bug: 1530358 Change-Id: Ib8733c096a3dbe2bad00beaf5734936ffcddda33
# Copyright (c) 2015 EMC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, DateTime, MetaData, String, Table def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine backups = Table('backups', meta, autoload=True) snapshot_id = Column('snapshot_id', String(length=36)) data_timestamp = Column('data_timestamp', DateTime) backups.create_column(snapshot_id) backups.create_column(data_timestamp) backups.update().values(data_timestamp=backups.c.created_at).execute()
# Copyright (c) 2015 EMC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, DateTime, MetaData, String, Table def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine backups = Table('backups', meta, autoload=True) snapshot_id = Column('snapshot_id', String(length=36)) data_timestamp = Column('data_timestamp', DateTime) backups.create_column(snapshot_id) backups.update().values(snapshot_id=None).execute() backups.create_column(data_timestamp) backups.update().values(data_timestamp=None).execute() # Copy existing created_at timestamp to data_timestamp # in the backups table. backups_list = list(backups.select().execute()) for backup in backups_list: backup_id = backup.id backups.update().\ where(backups.c.id == backup_id).\ values(data_timestamp=backup.created_at).execute()
Make JSON error code comparison type-strict
<?php namespace Spark\Handler; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Spark\Exception\HttpBadRequestException; use Zend\Diactoros\Stream; class JsonContentHandler extends ContentHandler { /** * @inheritDoc */ protected function isApplicableMimeType($mime) { return 'application/json' === $mime || 'application/vnd.api+json' === $mime; } /** * @inheritDoc */ protected function getParsedBody($body) { $body = json_decode($body); if (json_last_error() !== \JSON_ERROR_NONE) { $message = 'Error parsing JSON: ' . json_last_error_msg(); throw new HttpBadRequestException($message); } return $body; } }
<?php namespace Spark\Handler; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Spark\Exception\HttpBadRequestException; use Zend\Diactoros\Stream; class JsonContentHandler extends ContentHandler { /** * @inheritDoc */ protected function isApplicableMimeType($mime) { return 'application/json' === $mime || 'application/vnd.api+json' === $mime; } /** * @inheritDoc */ protected function getParsedBody($body) { $body = json_decode($body); if (json_last_error() != \JSON_ERROR_NONE) { $message = 'Error parsing JSON: ' . json_last_error_msg(); throw new HttpBadRequestException($message); } return $body; } }
Add line separator -- it is used in many places, so it is sensible to make it a constant.
/* * This file is part of Mapyrus. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package au.id.chenery.mapyrus; /** * Globally useful constants including fixed distance measurements. */ public class Constants { /* * Number of points and millimetres per inch. */ public static final int POINTS_PER_INCH = 72; public static final double MM_PER_INCH = 25.4; /* * Line separator in text files. */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); }
/* * This file is part of Mapyrus. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package au.id.chenery.mapyrus; /** * Globally useful constants including fixed distance measurements. */ public class Constants { /* * Number of points and millimetres per inch. */ public static final int POINTS_PER_INCH = 72; public static final double MM_PER_INCH = 25.4; }
Add parenthesized compound statements as a primary expression.
module.exports = grammar({ name: 'ruby', extras: $ => [ $.comment, $._line_break, /[ \t\r]/ ], rules: { program: $ => $._compound_statement, _compound_statement: $ => repeat(seq($._statement, optional($._terminator))), _statement: $ => choice($._expression), _expression: $ => choice($._argument), _argument: $ => choice($._primary), _primary: $ => choice( seq("(", $._compound_statement, ")"), $._variable ), _variable: $ => choice($.identifier , 'nil', 'self'), identifier: $ => seq(repeat(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/), comment: $ => token(seq('#', /.*/)), _line_break: $ => '\n', _terminator: $ => choice($._line_break, ';'), } });
module.exports = grammar({ name: 'ruby', extras: $ => [ $.comment, $._line_break, /[ \t\r]/ ], rules: { program: $ => $._compound_statement, _compound_statement: $ => repeat(seq($._statement, optional($._terminator))), _statement: $ => choice($._expression), _expression: $ => choice($._argument), _argument: $ => choice($._primary), _primary: $ => choice($._variable), _variable: $ => choice($.identifier , 'nil', 'self'), identifier: $ => seq(repeat(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/), comment: $ => token(seq('#', /.*/)), _line_break: $ => '\n', _terminator: $ => choice($._line_break, ';'), } });
Fix failing test on ProfilerHelper
<?php namespace LastCall\Crawler\Test\Helper; use LastCall\Crawler\Helper\ProfilerHelper; use Prophecy\Argument; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\Console\Style\OutputStyle; class ProfilerHelperTest extends \PHPUnit_Framework_TestCase { public function testGetTraceableDispatcher() { $helper = new ProfilerHelper(); $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher()); $this->assertInstanceOf(TraceableEventDispatcher::class, $dispatcher); } public function testRenderProfile() { $helper = new ProfilerHelper(); $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher()); $dispatcher->dispatch('foo'); $io = $this->prophesize(OutputStyle::class); $io->table(['Listener', 'Time'], Argument::that(function($rows) { return count($rows) === 1 && $rows[0][0] === 'foo' && is_numeric($rows[0][1]); }))->shouldBeCalled(); $helper->renderProfile($io->reveal()); } }
<?php namespace LastCall\Crawler\Test\Helper; use LastCall\Crawler\Helper\ProfilerHelper; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\Console\Style\OutputStyle; class ProfilerHelperTest extends \PHPUnit_Framework_TestCase { public function testGetTraceableDispatcher() { $helper = new ProfilerHelper(); $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher()); $this->assertInstanceOf(TraceableEventDispatcher::class, $dispatcher); } public function testRenderProfile() { $helper = new ProfilerHelper(); $dispatcher = $helper->getTraceableDispatcher(new EventDispatcher()); $dispatcher->dispatch('foo'); $io = $this->prophesize(OutputStyle::class); $io->table(['Listener', 'Time'], [['foo', 0]])->shouldBeCalled(); $helper->renderProfile($io->reveal()); } }
Add columns title for the export
<?php include "database_operations.php"; $db = new Database_operations(); // create the "request object" // output headers so that the file is downloaded rather than displayed header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=lectures.csv'); // create a file pointer connected to the output stream $output = fopen('php://output', 'w'); // output the column headings fputcsv($output, array('Année du baguage', 'Date du baguage', 'Bague métal', 'Numéro', 'Couleur', 'Sexe', 'Âge au baguage', 'Date de lecture', 'Nom du lecteur', 'Ville de lecture', 'Département de lecture', 'Lieu-dit de lecture', 'Coordonnée X', 'Coordonnée Y', 'Commentaires')); $data_observations = $db->csv_save(); foreach ($data_observations as $row) { fputcsv($output, $row); } ?>
<?php include "database_operations.php"; $db = new Database_operations(); // create the "request object" // output headers so that the file is downloaded rather than displayed header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=lectures.csv'); // create a file pointer connected to the output stream $output = fopen('php://output', 'w'); // output the column headings fputcsv($output, array('Année du baguage', 'Date du baguage', 'Bague métal', 'Numéro', 'Couleur', 'Sexe', 'Âge au baguage', 'Date de lecture', 'Nom du lecteur', 'Ville de lecture', 'Département de lecture', 'Lieu-dit de lecture')); $data_observations = $db->csv_save(); foreach ($data_observations as $row) { fputcsv($output, $row); } ?>
Stop using django's internal `_create_object_from_params`
# coding: utf-8 from __future__ import absolute_import, unicode_literals from django.db.models import QuerySet, Q from django.utils import timezone import logging logger = logging.getLogger(__name__) class SessionTokenQuerySet(QuerySet): def active(self): return self.filter(Q(revoked_at__isnull=True) | Q(revoked_at__gt=timezone.now())) def first_or_create(self, request_meta=None, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ if request_meta and "HTTP_USER_AGENT" in request_meta: kwargs["user_agent__startswith"] = request_meta.get("HTTP_USER_AGENT")[:100] obj = self.filter(**kwargs).first() created = False if not obj: obj = self.create(**kwargs) created = True return obj, created
# coding: utf-8 from __future__ import absolute_import, unicode_literals from django.db.models import QuerySet, Q from django.utils import timezone import logging logger = logging.getLogger(__name__) class SessionTokenQuerySet(QuerySet): def active(self): return self.filter(Q(revoked_at__isnull=True) | Q(revoked_at__gt=timezone.now())) def first_or_create(self, defaults=None, request_meta=None, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ if request_meta and "HTTP_USER_AGENT" in request_meta: kwargs["user_agent__startswith"] = request_meta.get("HTTP_USER_AGENT")[:100] params = self._extract_model_params(defaults, **kwargs) # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True obj = self.filter(**kwargs).first() if obj: return obj, False else: return self._create_object_from_params(kwargs, params)
Validate email the correct way
from django.contrib.auth.backends import ModelBackend from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.contrib.auth import models, load_backend, login from django.conf import settings class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None): try: validate_email(username) except ValidationError: return None try: user = models.User.objects.get(email=username) if user.check_password(password): return user except models.User.DoesNotExist: return None return None def login_user(request, user): if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): return login(request, user)
from django.contrib.auth.backends import ModelBackend from django.core.validators import email_re from django.contrib.auth import models, load_backend, login from django.conf import settings class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None): if email_re.search(username): try: user = models.User.objects.get(email=username) if user.check_password(password): return user except models.User.DoesNotExist: return None return None def login_user(request, user): if not hasattr(user, 'backend'): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break if hasattr(user, 'backend'): return login(request, user)
Add base element at start of head (in freeze-dry)
export default async function fixLinks({rootElement, docUrl}) { const head = rootElement.querySelector('head') if (head) { const base = head.ownerDocument.createElement('base') base.href = docUrl head.insertAdjacentElement('afterbegin', base) } else { const links = Array.from(rootElement.querySelectorAll('*[href]')) links.forEach(link => { const href = link.getAttribute('href') const absoluteUrl = new URL(href, docUrl) if (href !== absoluteUrl) { link.setAttribute('href', absoluteUrl) } }) // TODO rewrite other attributes than href (see http://stackoverflow.com/a/2725168) } }
export default async function fixLinks({rootElement, docUrl}) { const head = rootElement.querySelector('head') if (head) { const base = head.ownerDocument.createElement('base') base.href = docUrl head.appendChild(base) } else { const links = Array.from(rootElement.querySelectorAll('*[href]')) links.forEach(link => { const href = link.getAttribute('href') const absoluteUrl = new URL(href, docUrl) if (href !== absoluteUrl) { link.setAttribute('href', absoluteUrl) } }) // TODO rewrite other attributes than href (see http://stackoverflow.com/a/2725168) } }
Use notebook list's base_url [ci skip]
define(function(require) { var $ = require('jquery'); var Jupyter = require('base/js/namespace'); function load() { if (!Jupyter.notebook_list) return; var base_url = Jupyter.notebook_list.base_url; $("#tabs").append( $('<li>') .append( $('<a>') .attr('href', base_url + 'formgrader') .attr('target', '_blank') .text('Formgrader') ) ); } return { load_ipython_extension: load }; });
define(function(require) { var $ = require('jquery'); var Jupyter = require('base/js/namespace'); function load() { if (!Jupyter.notebook_list) return; var base_url = Jupyter.notebook_list.base_url; $("#tabs").append( $('<li>') .append( $('<a>') .attr('href', '/formgrader') .attr('target', '_blank') .text('Formgrader') ) ); } return { load_ipython_extension: load }; });