text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Make namespaces more clear in input_helpers.py
import importlib import warnings import distutils.version as dv def check_versions(minimum_versions): """Raises an ImportError if a dependent package is not installed and at the required version number, or provides a warning if the version of the dependent package cannot be found.""" for module_name in minimum_versions.keys(): minimum_version = dv.LooseVersion(minimum_versions[module_name]) try: module = importlib.import_module(module_name) module_version = dv.LooseVersion(module.__version__) except ImportError: raise ImportError(f"Unable to import {module_name} while " "importing PlasmaPy.") from None except AttributeError: # coveralls: ignore warnings.warn(f"{module_name} version {minimum_version.vstring} " "is required for PlasmaPy. However, the version of " f"{module_name} could not be determined to check if " "this requirement is met.") else: if minimum_version > module_version: raise ImportError( f"{module_name} {minimum_version} or newer is required " "for PlasmaPy. The currently installed version is " f"{module_version}.") from None
import importlib import warnings from distutils.version import LooseVersion def check_versions(minimum_versions): """Raises an ImportError if a dependent package is not installed and at the required version number, or provides a warning if the version of the dependent package cannot be found.""" for module_name in minimum_versions.keys(): minimum_version = LooseVersion(minimum_versions[module_name]) try: module = importlib.import_module(module_name) module_version = LooseVersion(module.__version__) except ImportError: raise ImportError(f"Unable to import {module_name} while " "importing PlasmaPy.") from None except AttributeError: # coveralls: ignore warnings.warn(f"{module_name} version {minimum_version.vstring} " "is required for PlasmaPy. However, the version of " f"{module_name} could not be determined to check if " "this requirement is met.") else: if minimum_version > module_version: raise ImportError( f"{module_name} {minimum_version} or newer is required " "for PlasmaPy. The currently installed version is " f"{module_version}.") from None
Convert ValueError -> ValidationError in ValuesListField
import six from swimlane.exceptions import ValidationError from .base import MultiSelectField class ValuesListField(MultiSelectField): field_type = 'Core.Models.Fields.ValuesListField, Core' supported_types = six.string_types def __init__(self, *args, **kwargs): """Map names to IDs for use in field rehydration""" super(ValuesListField, self).__init__(*args, **kwargs) self.selection_to_id_map = {f['name']: f['id'] for f in self.field_definition['values']} def validate_value(self, value): """Validate provided value is one of the valid options""" super(ValuesListField, self).validate_value(value) if value is not None: if value not in self.selection_to_id_map: raise ValidationError( self.record, 'Field "{}" invalid value "{}". Valid options: {}'.format( self.name, value, ', '.join(self.selection_to_id_map.keys()) ) ) def cast_to_python(self, value): """Store actual value as internal representation""" if value is not None: value = value['value'] return value def cast_to_swimlane(self, value): """Rehydrate value back as full JSON representation""" if value is None: return value return { '$type': 'Core.Models.Record.ValueSelection, Core', 'id': self.selection_to_id_map[value], 'value': value }
import six from .base import MultiSelectField class ValuesListField(MultiSelectField): field_type = 'Core.Models.Fields.ValuesListField, Core' supported_types = six.string_types def __init__(self, *args, **kwargs): """Map names to IDs for use in field rehydration""" super(ValuesListField, self).__init__(*args, **kwargs) self.selection_to_id_map = {f['name']: f['id'] for f in self.field_definition['values']} def validate_value(self, value): """Validate provided value is one of the valid options""" super(ValuesListField, self).validate_value(value) if value is not None: if value not in self.selection_to_id_map: raise ValueError('Field "{}" invalid value "{}". Valid options: {}'.format( self.name, value, ', '.join(self.selection_to_id_map.keys()) )) def cast_to_python(self, value): """Store actual value as internal representation""" if value is not None: value = value['value'] return value def cast_to_swimlane(self, value): """Rehydrate value back as full JSON representation""" if value is None: return value return { '$type': 'Core.Models.Record.ValueSelection, Core', 'id': self.selection_to_id_map[value], 'value': value }
Add 2nd parameter to create that's generated for requires that allows you to overwrite context.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ refines: 'foam.core.Requires', flags: ['swift'], requires: [ 'foam.swift.Argument', 'foam.swift.Method', ], properties: [ { name: 'swiftReturns', expression: function(path) { return this.lookup(path).model_.swiftName; }, }, ], methods: [ function writeToSwiftClass(cls, parentCls) { if ( ! parentCls.hasOwnAxiom(this.name) ) return; if (foam.core.InterfaceModel.isInstance(this.lookup(this.path).model_)) { return; } // TODO skip refines. cls.methods.push(this.Method.create({ name: this.name + '_create', returnType: this.swiftReturns, visibility: 'public', body: this.swiftInitializer(), args: [ this.Argument.create({ localName: 'args', defaultValue: '[:]', type: '[String:Any?]', }), this.Argument.create({ localName: 'x', defaultValue: 'nil', type: 'Context?', }), ], })); }, ], templates: [ { name: 'swiftInitializer', args: [], template: function() {/* return (x ?? __subContext__).create(<%=this.swiftReturns%>.self, args: args)! */}, }, ], });
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ refines: 'foam.core.Requires', flags: ['swift'], requires: [ 'foam.swift.Argument', 'foam.swift.Method', ], properties: [ { name: 'swiftReturns', expression: function(path) { return this.lookup(path).model_.swiftName; }, }, ], methods: [ function writeToSwiftClass(cls, parentCls) { if ( ! parentCls.hasOwnAxiom(this.name) ) return; if (foam.core.InterfaceModel.isInstance(this.lookup(this.path).model_)) { return; } // TODO skip refines. cls.methods.push(this.Method.create({ name: this.name + '_create', returnType: this.swiftReturns, visibility: 'public', body: this.swiftInitializer(), args: [ this.Argument.create({ localName: 'args', defaultValue: '[:]', type: '[String:Any?]', }), ], })); }, ], templates: [ { name: 'swiftInitializer', args: [], template: function() {/* return __subContext__.create(<%=this.swiftReturns%>.self, args: args)! */}, }, ], });
Fix unicode error on py2
# -*- coding: utf-8 -*- from __future__ import print_function import os import codecs import kombu from kombulogger import default_broker_url, default_queue_name class KombuLogServer(object): log_format = u'{host}\t{level}\t{message}' def __init__(self, url=None, queue=None): url = url or default_broker_url queue = queue or default_queue_name self.connection = kombu.Connection(url) self.queue = self.connection.SimpleQueue(queue, no_ack=True) path = os.path.join(os.getcwd(), queue) if not path.endswith('.log'): path += '.log' self.output_file = codecs.open(path, mode='ab', encoding='UTF-8') def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.queue.close() self.connection.close() self.output_file.close() return False def _format_dict(self, log_dict): return self.log_format.format(**log_dict) def run(self): while True: try: message = self.queue.get(block=True, timeout=1) payload = message.payload print(self._format_dict(payload), file=self.output_file) message.ack() except self.queue.Empty: pass
# -*- coding: utf-8 -*- from __future__ import print_function import os import codecs import kombu from kombulogger import default_broker_url, default_queue_name class KombuLogServer(object): log_format = '{host}\t{level}\t{message}' def __init__(self, url=None, queue=None): url = url or default_broker_url queue = queue or default_queue_name self.connection = kombu.Connection(url) self.queue = self.connection.SimpleQueue(queue, no_ack=True) path = os.path.join(os.getcwd(), queue) if not path.endswith('.log'): path += '.log' self.output_file = codecs.open(path, mode='ab', encoding='UTF-8') def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.queue.close() self.connection.close() self.output_file.close() return False def _format_dict(self, log_dict): return self.log_format.format(**log_dict) def run(self): while True: try: message = self.queue.get(block=True, timeout=1) payload = message.payload print(self._format_dict(payload), file=self.output_file) message.ack() except self.queue.Empty: pass
Remove deprecated parameter size in UploadedFile constructor call.
<?php namespace Vanio\DomainBundle\Model; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File as SymfonyFile; use Symfony\Component\HttpFoundation\File\UploadedFile; class FileToUpload extends UploadedFile { /** @var bool */ private $temporary = false; public function __construct(string $path, string $originalName = null, string $mimeType = null) { parent::__construct($path, $originalName ?? self::resolveOriginalName($path), $mimeType, null, true); } public static function temporary( string $path, string $originalName = null, string $mimeType = null ): self { $filesystem = new Filesystem; $target = tempnam(sys_get_temp_dir(), ''); $filesystem->copy($path, $target, true); $self = new self($target, $originalName, $mimeType); $self->temporary = true; return $self; } public function move($directory, $name = null): SymfonyFile { if ($this->temporary) { return parent::move($directory, $name); } $target = $this->getTargetFile($directory, $name); $filesystem = new Filesystem; $filesystem->copy($this->getPathname(), $target); return $target; } private static function resolveOriginalName(string $path): string { return basename(preg_replace('~\?.*$~', '', $path)); } }
<?php namespace Vanio\DomainBundle\Model; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File as SymfonyFile; use Symfony\Component\HttpFoundation\File\UploadedFile; class FileToUpload extends UploadedFile { /** @var bool */ private $temporary = false; public function __construct(string $path, string $originalName = null, string $mimeType = null, int $size = null) { parent::__construct($path, $originalName ?? self::resolveOriginalName($path), $mimeType, $size, null, true); } public static function temporary( string $path, string $originalName = null, string $mimeType = null, int $size = null ): self { $filesystem = new Filesystem; $target = tempnam(sys_get_temp_dir(), ''); $filesystem->copy($path, $target, true); $self = new self($target, $originalName, $mimeType, $size); $self->temporary = true; return $self; } public function move($directory, $name = null): SymfonyFile { if ($this->temporary) { return parent::move($directory, $name); } $target = $this->getTargetFile($directory, $name); $filesystem = new Filesystem; $filesystem->copy($this->getPathname(), $target); return $target; } private static function resolveOriginalName(string $path): string { return basename(preg_replace('~\?.*$~', '', $path)); } }
Hide progress bar when socket connection is lost
'use strict'; angular.module('sgApp') .controller('AppCtrl', function($scope, ngProgress) { // ngProgress do not respect styles assigned via CSS if we do not pass empty parameters // See: https://github.com/VictorBjelkholm/ngProgress/issues/33 ngProgress.height(''); ngProgress.color(''); // Scroll top when page is changed $scope.$on('$viewContentLoaded', function() { window.scrollTo(0, 0); }); $scope.$on('progress start', function() { ngProgress.start(); }); $scope.$on('progress end', function() { ngProgress.complete(); }); // Reload styles when server notifies about the changes // Add cache buster to every stylesheet on the page forcing them to reload $scope.$on('styles changed', function() { var links = Array.prototype.slice.call(document.getElementsByTagName('link')); links.forEach(function(link) { if (typeof link === 'object' && link.getAttribute('type') === 'text/css') { link.href = link.href.split('?')[0] + '?id=' + new Date().getTime(); } }); }); $scope.$on('socket connected', function() { console.log('Socket connection established'); //TODO: enable Designer Tool 'save changes' button? }); $scope.$on('socket disconnected', function() { console.error('Socket connection dropped'); //TODO: disable Designer Tool 'save changes' button? ngProgress.reset(); }); $scope.$on('socket error', function(err) { console.error('Socket error:', err); }); });
'use strict'; angular.module('sgApp') .controller('AppCtrl', function($scope, ngProgress) { // ngProgress do not respect styles assigned via CSS if we do not pass empty parameters // See: https://github.com/VictorBjelkholm/ngProgress/issues/33 ngProgress.height(''); ngProgress.color(''); // Scroll top when page is changed $scope.$on('$viewContentLoaded', function() { window.scrollTo(0, 0); }); $scope.$on('progress start', function() { ngProgress.start(); }); $scope.$on('progress end', function() { ngProgress.complete(); }); // Reload styles when server notifies about the changes // Add cache buster to every stylesheet on the page forcing them to reload $scope.$on('styles changed', function() { var links = Array.prototype.slice.call(document.getElementsByTagName('link')); links.forEach(function(link) { if (typeof link === 'object' && link.getAttribute('type') === 'text/css') { link.href = link.href.split('?')[0] + '?id=' + new Date().getTime(); } }); }); $scope.$on('socket connected', function() { console.log('Socket connection established'); //TODO: enable Designer Tool 'save changes' button? }); $scope.$on('socket disconnected', function() { console.error('Socket connection dropped'); //TODO: disable Designer Tool 'save changes' button? }); $scope.$on('socket error', function(err) { console.error('Socket error:', err); }); });
Refactor imports to be less verbose
import pytest try: from unittest import mock except ImportError: import mock from slackelot import SlackNotificationError, send_message def test_send_message_success(): """Returns True if response.status_code == 200""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response: webhook = 'https://hooks.slack.com/services/' assert send_message('foo', webhook) == True def test_send_message_raises_error_bad_request(): """Raises SlackNotificationError if response.status_code not 200""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response: with pytest.raises(SlackNotificationError) as error: webhook = 'https://hooks.slack.com/services/' send_message('foo', webhook) assert 'Slack notification failed' in str(error.value) def test_send_message_raises_error_bad_webhook(): """Raises SlackNotificationError if webhook_url malformed""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response: with pytest.raises(SlackNotificationError) as error: webhook = 'https://notthehookwerelookingfor.com' send_message('foo', webhook) assert 'webhook_url is not in the correct format' in str(error.value)
import pytest import mock from slackelot.slackelot import SlackNotificationError, send_message def test_send_message_success(): """Returns True if response.status_code == 200""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response: webhook = 'https://hooks.slack.com/services/' assert send_message('foo', webhook) == True def test_send_message_raises_error_bad_request(): """Raises SlackNotificationError if response.status_code not 200""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response: with pytest.raises(SlackNotificationError) as error: webhook = 'https://hooks.slack.com/services/' send_message('foo', webhook) assert 'Slack notification failed' in str(error.value) def test_send_message_raises_error_bad_webhook(): """Raises SlackNotificationError if webhook_url malformed""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response: with pytest.raises(SlackNotificationError) as error: webhook = 'https://notthehookwerelookingfor.com' send_message('foo', webhook) assert 'webhook_url is not in the correct format' in str(error.value)
CWAP-212: Fix documentation for the feature release toggle definitions document.
{ channels: { view: [ 'view-feature-release-toggle-definitions', 'view-config' ], add: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], replace: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], remove: [ 'remove-feature-release-toggle-definitions', 'remove-config' ] }, typeFilter: function(doc, oldDoc) { return doc._id === 'featureReleaseToggleDefinitions'; }, propertyValidators: { toggles: { // A list of the feature toggles defined for the application. type: 'array', arrayElementsValidator: { type: 'object', required: true, propertyValidators: { // The name of the feature toggle, as used within applications. name: { type: 'string', required: true, mustNotBeEmpty: true, regexPattern: featureToggleNameRegex }, // A description of the feature toggle for documentation within the feature toggle manager. description: { type: 'string', required: true, mustNotBeEmpty: true }, // The ticket id related to the feature toggle, for example KBW-1234 ticketId: { type: 'string' }, // The state of the feature toggle. state: { type: 'enum', predefinedValues: [ 'development', 'ready', 'remove' ], required: true }, // Any extra notes about the feature toggle note: { type: 'string' } } } } } }
{ channels: { view: [ 'view-feature-release-toggle-definitions', 'view-config' ], add: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], replace: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], remove: [ 'remove-feature-release-toggle-definitions', 'remove-config' ] }, typeFilter: function(doc, oldDoc) { return doc._id === 'featureReleaseToggleDefinitions'; }, propertyValidators: { toggles: { // A list of actions that are available to the recipient of the notification type: 'array', arrayElementsValidator: { type: 'object', required: true, propertyValidators: { name: { type: 'string', required: true, mustNotBeEmpty: true, regexPattern: featureToggleNameRegex }, description: { type: 'string', required: true, mustNotBeEmpty: true }, ticketId: { // the ticket id related to the feature toggle, for example KBW-1234 type: 'string' }, state: { type: 'enum', predefinedValues: [ 'development', 'ready', 'remove' ], required: true }, note: { // Any extra notes about the feature toggle type: 'string' } } } } } }
Remove testing dir from interface doc generation. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1390 ead46cd0-7350-4e37-8683-fc4c6f79bf00
#!/usr/bin/env python """Script to auto-generate interface docs. """ # stdlib imports import os import sys #***************************************************************************** if __name__ == '__main__': nipypepath = os.path.abspath('..') sys.path.insert(1,nipypepath) # local imports from interfacedocgen import InterfaceHelpWriter package = 'nipype' outdir = os.path.join('interfaces','generated') docwriter = InterfaceHelpWriter(package) # Packages that should not be included in generated API docs. docwriter.package_skip_patterns += ['\.externals$', '\.utils$', '\.pipeline', '\.testing', ] # Modules that should not be included in generated API docs. docwriter.module_skip_patterns += ['\.version$', '\.interfaces\.afni$', '\.interfaces\.base$', '\.interfaces\.matlab$', '\.interfaces\.rest$', '\.interfaces\.pymvpa$', '\.interfaces\.traits', '\.pipeline\.alloy$', '\.pipeline\.s3_node_wrapper$', '.\testing', ] docwriter.class_skip_patterns += ['FSL', 'FS', 'Spm', 'Tester', 'Spec$', 'afni', 'Numpy' # NipypeTester raises an # exception when instantiated in # InterfaceHelpWriter.generate_api_doc 'NipypeTester', ] docwriter.write_api_docs(outdir) docwriter.write_index(outdir, 'gen', relative_to='interfaces') print '%d files written' % len(docwriter.written_modules)
#!/usr/bin/env python """Script to auto-generate interface docs. """ # stdlib imports import os import sys #***************************************************************************** if __name__ == '__main__': nipypepath = os.path.abspath('..') sys.path.insert(1,nipypepath) # local imports from interfacedocgen import InterfaceHelpWriter package = 'nipype' outdir = os.path.join('interfaces','generated') docwriter = InterfaceHelpWriter(package) # Packages that should not be included in generated API docs. docwriter.package_skip_patterns += ['\.externals$', '\.utils$', '\.pipeline', '.\testing', ] # Modules that should not be included in generated API docs. docwriter.module_skip_patterns += ['\.version$', '\.interfaces\.afni$', '\.interfaces\.base$', '\.interfaces\.matlab$', '\.interfaces\.rest$', '\.interfaces\.pymvpa$', '\.interfaces\.traits', '\.pipeline\.alloy$', '\.pipeline\.s3_node_wrapper$', '.\testing', ] docwriter.class_skip_patterns += ['FSL', 'FS', 'Spm', 'Tester', 'Spec$', 'afni', 'Numpy' # NipypeTester raises an # exception when instantiated in # InterfaceHelpWriter.generate_api_doc 'NipypeTester', ] docwriter.write_api_docs(outdir) docwriter.write_index(outdir, 'gen', relative_to='interfaces') print '%d files written' % len(docwriter.written_modules)
Add an example with a country lookup
'use strict'; var React = require('react'); var Table = require('./table.jsx'); var App = React.createClass({ render() { var countries = { 'de': 'Germany', 'fi': 'Finland', 'se': 'Sweden' }; var config = { columns: [ { property: 'name', editable: true, header: 'Name', }, { property: 'position', header: 'Position', }, { property: 'country', header: 'Country', formatter: (country) => countries[country] }, { property: 'salary', header: 'Salary', formatter: (salary) => salary.toFixed(2) }, ] }; var data = [ { name: 'Jack Jackson', position: 'Boss', salary: 10000, country: 'se', }, { name: 'Bo Bobson', position: 'Contractor', salary: 4650.9234, country: 'de', }, { name: 'Cecilia Robertson', position: 'Client', salary: 6499.1038, country: 'fi', } ]; return ( <Table config={config} data={data}></Table> ); } }); module.exports = App;
'use strict'; var React = require('react'); var Table = require('./table.jsx'); var App = React.createClass({ render() { var config = { columns: [ { property: 'name', editable: true, header: 'Name', }, { property: 'position', header: 'Position', }, { property: 'salary', header: 'Salary', formatter: (salary) => salary.toFixed(2) } ] }; var data = [ { name: 'Jack Jackson', position: 'Boss', salary: 10000, }, { name: 'Bo Bobson', position: 'Contractor', salary: 4650.9234, }, { name: 'Cecilia Robertson', position: 'Client', salary: 6499.1038 } ]; return ( <Table config={config} data={data}></Table> ); } }); module.exports = App;
Remove some Python 2 syntax.
from django.template import loader from django.template.backends.django import Template as DjangoTemplate try: from django.template.backends.jinja2 import Template as Jinja2Template except ImportError: # Most likely Jinja2 isn't installed, in that case just create a class since # we always want it to be false anyway. class Jinja2Template: pass from render_block.django import django_render_block from render_block.exceptions import UnsupportedEngine def render_block_to_string(template_name, block_name, context=None, request=None): """ Loads the given template_name and renders the given block with the given dictionary as context. Returns a string. template_name The name of the template to load and render. If it's a list of template names, Django uses select_template() instead of get_template() to find the template. """ # Like render_to_string, template_name can be a string or a list/tuple. if isinstance(template_name, (tuple, list)): t = loader.select_template(template_name) else: t = loader.get_template(template_name) # Create the context instance. context = context or {} # The Django backend. if isinstance(t, DjangoTemplate): return django_render_block(t, block_name, context, request) elif isinstance(t, Jinja2Template): from render_block.jinja2 import jinja2_render_block return jinja2_render_block(t, block_name, context) else: raise UnsupportedEngine( 'Can only render blocks from the Django template backend.')
from django.template import loader from django.template.backends.django import Template as DjangoTemplate try: from django.template.backends.jinja2 import Template as Jinja2Template except ImportError: # Most likely Jinja2 isn't installed, in that case just create a class since # we always want it to be false anyway. class Jinja2Template(object): pass from render_block.django import django_render_block from render_block.exceptions import UnsupportedEngine def render_block_to_string(template_name, block_name, context=None, request=None): """ Loads the given template_name and renders the given block with the given dictionary as context. Returns a string. template_name The name of the template to load and render. If it's a list of template names, Django uses select_template() instead of get_template() to find the template. """ # Like render_to_string, template_name can be a string or a list/tuple. if isinstance(template_name, (tuple, list)): t = loader.select_template(template_name) else: t = loader.get_template(template_name) # Create the context instance. context = context or {} # The Django backend. if isinstance(t, DjangoTemplate): return django_render_block(t, block_name, context, request) elif isinstance(t, Jinja2Template): from render_block.jinja2 import jinja2_render_block return jinja2_render_block(t, block_name, context) else: raise UnsupportedEngine( 'Can only render blocks from the Django template backend.')
Add changelings to the character creation section
// Category View // ============= // Includes file dependencies define([ "jquery", "backbone", "text!../templates/character-create-view.html", "text!../templates/werewolf-create-view.html" ], function( $, Backbone, character_create_view_html , werewolf_create_view_html ) { // Extends Backbone.View var View = Backbone.View.extend( { // The View Constructor initialize: function() { _.bindAll(this, "scroll_back_after_page_change"); }, scroll_back_after_page_change: function() { var self = this; $(document).one("pagechange", function() { var top = _.parseInt(self.backToTop); $.mobile.silentScroll(top); }); }, // Renders all of the Category models on the UI render: function() { if ("Werewolf" == this.model.get("type")) { this.template = _.template(werewolf_create_view_html)({ "character": this.model } ); } else if ("ChangelingBetaSlice" == this.model.get("type")) { this.template = _.template(changelinge_beta_slice_create_view_html)({ "character": this.model } ); } else { this.template = _.template(character_create_view_html)({ "character": this.model } ); } // Renders the view's template inside of the current listview element this.$el.find("div[role='main']").html(this.template); this.$el.enhanceWithin(); // Maintains chainability return this; } } ); // Returns the View class return View; } );
// Category View // ============= // Includes file dependencies define([ "jquery", "backbone", "text!../templates/character-create-view.html", "text!../templates/werewolf-create-view.html" ], function( $, Backbone, character_create_view_html , werewolf_create_view_html ) { // Extends Backbone.View var View = Backbone.View.extend( { // The View Constructor initialize: function() { _.bindAll(this, "scroll_back_after_page_change"); }, scroll_back_after_page_change: function() { var self = this; $(document).one("pagechange", function() { var top = _.parseInt(self.backToTop); $.mobile.silentScroll(top); }); }, // Renders all of the Category models on the UI render: function() { if ("Werewolf" == this.model.get("type")) { this.template = _.template(werewolf_create_view_html)({ "character": this.model } ); } else { this.template = _.template(character_create_view_html)({ "character": this.model } ); } // Renders the view's template inside of the current listview element this.$el.find("div[role='main']").html(this.template); this.$el.enhanceWithin(); // Maintains chainability return this; } } ); // Returns the View class return View; } );
Drop existing products table before creation
# Create a database import sqlite3 import csv from datetime import datetime import sys reload(sys) sys.setdefaultencoding('utf8') class createDB(): def readCSV(self, filename): try: conn = sqlite3.connect('databaseForTest.db') print 'DB Creation Successful!' cur = conn.cursor() cur.execute('''DROP TABLE IF EXISTS PRODUCTS;''') cur.execute('''CREATE TABLE PRODUCTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, TITLE TEXT NOT NULL, DESCRIPTION TEXT NOT NULL, PRICE INTEGER NOT NULL, CREATED_AT TIMESTAMP, UPDATED_AT TIMESTAMP);''') print 'Table Creation Successful!' with open(filename) as f: reader = csv.reader(f) for row in reader: cur.execute("INSERT INTO PRODUCTS VALUES (null, ?, ?, ?, ?, ?);", (unicode(row[0]), unicode(row[1]), unicode(row[2]), datetime.now(), datetime.now())) print 'Successfully read data from CSV file!' conn.commit() conn.close() except Exception as err: print "Error: ", err c = createDB().readCSV('products.csv')
# Create a database import sqlite3 import csv from datetime import datetime import sys reload(sys) sys.setdefaultencoding('utf8') class createDB(): def readCSV(self, filename): try: conn = sqlite3.connect('databaseForTest.db') print 'DB Creation Successful!' cur = conn.cursor() # cur.execute('''DROP TABLE PRODUCTS;''') cur.execute('''CREATE TABLE PRODUCTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, TITLE TEXT NOT NULL, DESCRIPTION TEXT NOT NULL, PRICE INTEGER NOT NULL, CREATED_AT TIMESTAMP, UPDATED_AT TIMESTAMP);''') print 'Table Creation Successful!' with open(filename) as f: reader = csv.reader(f) for row in reader: cur.execute("INSERT INTO PRODUCTS VALUES (null, ?, ?, ?, ?, ?);", (unicode(row[0]), unicode(row[1]), unicode(row[2]), datetime.now(), datetime.now())) print 'Successfully read data from CSV file!' conn.commit() conn.close() except Exception as err: print "Error: ", err c = createDB().readCSV('products.csv')
Make dict updates more dense
# Import python libs import logging # Import salt libs import salt.utils log = logging.getLogger(__name__) def held(name): ''' Set package in 'hold' state, meaning it will not be upgraded. name The name of the package, e.g., 'tmux' ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} state = __salt__['pkg.get_selections']( pattern=name, ) if not state: ret.update(comment='Package {0} does not have a state'.format(name)) return ret if not salt.utils.is_true(state.get('hold', False)): if not __opts__['test']: result = __salt__['pkg.set_selections']( selection={'hold': [name]} ) ret.update(changes=result[name], result=True, comment='Package {0} is now being held'.format(name)) else: ret.update(result=None, comment='Package {0} is set to be held'.format(name)) else: ret.update(result= True, comment='Package {0} is already held'.format(name)) return ret
# Import python libs import logging # Import salt libs import salt.utils log = logging.getLogger(__name__) def held(name): ''' Set package in 'hold' state, meaning it will not be upgraded. name The name of the package, e.g., 'tmux' ''' ret = {'name': name} state = __salt__['pkg.get_selections']( pattern=name, ) if not state: ret.update({'changes': {}, 'result': False, 'comment': 'Package {0} does not have a state'.format( name )}) return ret if not salt.utils.is_true(state.get('hold', False)): if not __opts__['test']: result = __salt__['pkg.set_selections']( selection={'hold': [name]} ) ret.update({'changes': result[name], 'result': True, 'comment': 'Package {0} is now being held'.format( name )}) else: ret.update({'changes': {}, 'result': None, 'comment': 'Package {0} is set to be held'.format( name )}) else: ret.update({'changes': {}, 'result': True, 'comment': 'Package {0} is already held'.format(name)}) return ret
Include the baseApp when running onAppend function
(function () { module.exports = function (onCreate, onAppend) { var baseApp; return { /** * Array of properties to be copied from main app to sub app */ merged: ['view engine', 'views'], /** * Array of properties to be copied from main app to sub app locals */ locals: [], /** * Register the main express application, the source of merged/locals properties * * @param app */ create: function (app) { baseApp = app; onCreate && onCreate(app); onAppend && onAppend(app); return app; }, /** * Register a sub application, when the root is supplied the app is also bound to the main app. * * @param {string} [root] * @param app */ route: function(root, app) { if (arguments.length === 1) { app = root; root = null; } module.exports.merged.forEach(function (merged) { var baseAppValue = baseApp.get(merged); if (baseAppValue !== undefined) { app.set(merged, baseAppValue); } }); module.exports.locals.forEach(function (local) { app.locals[local] = baseApp.locals[local]; }); onAppend && onAppend(app, baseApp); if (root > 1) { baseApp.use(root, app); } return app; } }; }; }());
(function () { module.exports = function (onCreate, onAppend) { var baseApp; return { /** * Array of properties to be copied from main app to sub app */ merged: ['view engine', 'views'], /** * Array of properties to be copied from main app to sub app locals */ locals: [], /** * Register the main express application, the source of merged/locals properties * * @param app */ create: function (app) { baseApp = app; onCreate && onCreate(app); onAppend && onAppend(app); return app; }, /** * Register a sub application, when the root is supplied the app is also bound to the main app. * * @param {string} [root] * @param app */ route: function(root, app) { if (arguments.length === 1) { app = root; root = null; } module.exports.merged.forEach(function (merged) { var baseAppValue = baseApp.get(merged); if (baseAppValue !== undefined) { app.set(merged, baseAppValue); } }); module.exports.locals.forEach(function (local) { app.locals[local] = baseApp.locals[local]; }); onAppend && onAppend(app); if (root > 1) { baseApp.use(root, app); } return app; } }; }; }());
Fix loading the typeahead js in the search widget
<?php namespace Frontend\Modules\Search\Widgets; /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Core\Engine\Form as FrontendForm; use Frontend\Core\Engine\Navigation as FrontendNavigation; /** * This is a widget with the search form */ class Form extends FrontendBaseWidget { /** * @var FrontendForm */ private $frm; /** * Execute the extra */ public function execute() { parent::execute(); $this->loadTemplate(); $this->loadForm(); $this->parse(); } /** * Load the form */ private function loadForm() { $this->frm = new FrontendForm('search', FrontendNavigation::getURLForBlock('Search'), 'get', null, false); $widgetField = $this->frm->addText('q_widget'); $widgetField->setAttributes( array( 'itemprop' => 'query-input', 'data-role' => 'fork-widget-search-field', ) ); } /** * Parse the data into the template */ private function parse() { $this->addJS('/js/vendors/typeahead.bundle.min.js', true, false); $this->addCSS('Search.css'); $this->frm->parse($this->tpl); } }
<?php namespace Frontend\Modules\Search\Widgets; /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Core\Engine\Form as FrontendForm; use Frontend\Core\Engine\Navigation as FrontendNavigation; /** * This is a widget with the search form */ class Form extends FrontendBaseWidget { /** * @var FrontendForm */ private $frm; /** * Execute the extra */ public function execute() { parent::execute(); $this->loadTemplate(); $this->loadForm(); $this->parse(); } /** * Load the form */ private function loadForm() { $this->frm = new FrontendForm('search', FrontendNavigation::getURLForBlock('Search'), 'get', null, false); $widgetField = $this->frm->addText('q_widget'); $widgetField->setAttributes( array( 'itemprop' => 'query-input', 'data-role' => 'fork-widget-search-field', ) ); } /** * Parse the data into the template */ private function parse() { $this->addJS('/js/vendors/typeahead.bundle.min.js', 'Core', false, true); $this->addCSS('Search.css'); $this->frm->parse($this->tpl); } }
Allow passing Celery configuration under the project's config
import os import logbook from .base import SubsystemBase _logger = logbook.Logger(__name__) class TasksSubsystem(SubsystemBase): NAME = 'tasks' def activate(self, flask_app): from ..celery.app import celery_app self._config = self.project.config.get('celery', {}) # ensure critical celery config exists self._config.setdefault('broker_url', 'amqp://guest:guest@localhost/') override_broker_url = os.environ.get('COB_CELERY_BROKER_URL') if override_broker_url is not None: self._config['broker_url'] = override_broker_url celery_app.conf.update(self._config) self.queues = set() def get_queue_names(self): names = {queue_name for grain in self.grains for queue_name in grain.config.get('queue_names', [])} names.add('celery') return sorted(names) def configure_grain(self, grain, flask_app): _ = grain.load() def configure_app(self, flask_app): super().configure_app(flask_app) from ..celery.app import celery_app for task in celery_app.tasks.values(): queue_name = getattr(task, 'queue', None) if queue_name is not None: self.queues.add(queue_name) def iter_locations(self): return None
import os import logbook from .base import SubsystemBase _logger = logbook.Logger(__name__) class TasksSubsystem(SubsystemBase): NAME = 'tasks' def activate(self, flask_app): from ..celery.app import celery_app self._config = self.project.config.get('celery', {}) # ensure critical celery config exists self._config.setdefault('broker_url', 'amqp://guest:guest@localhost/') override_broker_url = os.environ.get('COB_CELERY_BROKER_URL') if override_broker_url is not None: self._config['broker_url'] = override_broker_url celery_app.conf.broker_url = self._config['broker_url'] self.queues = set() def get_queue_names(self): names = {queue_name for grain in self.grains for queue_name in grain.config.get('queue_names', [])} names.add('celery') return sorted(names) def configure_grain(self, grain, flask_app): _ = grain.load() def configure_app(self, flask_app): super().configure_app(flask_app) from ..celery.app import celery_app for task in celery_app.tasks.values(): queue_name = getattr(task, 'queue', None) if queue_name is not None: self.queues.add(queue_name) def iter_locations(self): return None
Allow keyless entry command to have no event.
package com.openxc.measurements; import java.util.Locale; import com.openxc.units.KeylessEntryCode; import com.openxc.units.State; public class KeylessEntryProgrammingCommand extends BaseMeasurement< State<KeylessEntryProgrammingCommand.Command>> { public final static String ID = "keyless_entry_command"; public enum Command { ADD, ERASE, AUTHENTICATE } public KeylessEntryProgrammingCommand(State<Command> command, KeylessEntryCode code) { super(command, code); } public KeylessEntryProgrammingCommand(Command command, String code) { super(new State<Command>(command), new KeylessEntryCode(code)); } public KeylessEntryProgrammingCommand(Command command) { super(new State<Command>(command)); } public KeylessEntryProgrammingCommand(String command, String code) { this(Command.valueOf(command.toUpperCase(Locale.US)), code); } @Override public String getSerializedValue() { return getValue().enumValue().toString().toLowerCase(); } @Override public KeylessEntryCode getEvent() { return (KeylessEntryCode) super.getEvent(); } @Override public String getSerializedEvent() { return getEvent() != null ? getEvent().getSerializedValue() : null; } @Override public String getGenericName() { return ID; } }
package com.openxc.measurements; import java.util.Locale; import com.openxc.units.KeylessEntryCode; import com.openxc.units.State; public class KeylessEntryProgrammingCommand extends BaseMeasurement< State<KeylessEntryProgrammingCommand.Command>> { public final static String ID = "keyless_entry_command"; public enum Command { ADD, ERASE, AUTHENTICATE } public KeylessEntryProgrammingCommand(State<Command> command, KeylessEntryCode code) { super(command, code); } public KeylessEntryProgrammingCommand(Command command, String code) { super(new State<Command>(command), new KeylessEntryCode(code)); } public KeylessEntryProgrammingCommand(Command command) { super(new State<Command>(command)); } public KeylessEntryProgrammingCommand(String command, String code) { this(Command.valueOf(command.toUpperCase(Locale.US)), code); } @Override public String getSerializedValue() { return getValue().enumValue().toString().toLowerCase(); } @Override public KeylessEntryCode getEvent() { return (KeylessEntryCode) super.getEvent(); } @Override public String getSerializedEvent() { return getEvent().getSerializedValue(); } @Override public String getGenericName() { return ID; } }
Remove references to unused library
'use strict'; /*! around | https://github.com/tofumatt/around HTML5 Foursquare Client */ // Require.js shortcuts to our libraries. require.config({ paths: { async_storage: 'lib/async_storage', backbone: 'lib/backbone', brick: 'lib/brick', 'coffee-script': 'lib/coffee-script', cs: 'lib/cs', localstorage: 'lib/backbone.localstorage', jed: 'lib/jed', tpl: 'lib/tpl', underscore: 'lib/lodash', zepto: 'lib/zepto' }, // The shim config allows us to configure dependencies for scripts that do // not call define() to register a module. shim: { backbone: { deps: [ 'underscore', 'zepto' ], exports: 'Backbone' }, brick: { exports: 'Brick' }, underscore: { exports: '_' }, zepto: { exports: 'Zepto' } } }); require(['cs!app']);
'use strict'; /*! around | https://github.com/tofumatt/around HTML5 Foursquare Client */ // Require.js shortcuts to our libraries. require.config({ paths: { async_storage: 'lib/async_storage', backbone: 'lib/backbone', brick: 'lib/brick', 'coffee-script': 'lib/coffee-script', cs: 'lib/cs', localstorage: 'lib/backbone.localstorage', jed: 'lib/jed', // oauth: 'lib/javascript-oauth2', tpl: 'lib/tpl', underscore: 'lib/lodash', zepto: 'lib/zepto' }, // The shim config allows us to configure dependencies for scripts that do // not call define() to register a module. shim: { backbone: { deps: [ 'underscore', 'zepto' ], exports: 'Backbone' }, brick: { exports: 'Brick' }, // oauth: { // exports: 'oauth' // }, underscore: { exports: '_' }, zepto: { exports: 'Zepto' } } }); require(['cs!app']);
Fix cache dir in Kernel
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new AppBundle\AppBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } public function getCacheDir() { return '/tmp/symfony/ukmrundown/cache/'; } public function getLogDir() { return '/tmp/symfony/ukmrundown/log/'; } }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new AppBundle\AppBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } public function getCacheDir() { return '/tmp/symfony/ukmdelta/cache/'; } public function getLogDir() { return '/tmp/symfony/ukmdelta/log/'; } }
Fix the line length in the updated tx rejection code.
<?php namespace DigiTickets\VerifoneWebService\Message\NonSessionBased; use DigiTickets\VerifoneWebService\Message\AbstractRemoteResponse; class PurchaseResponse extends AbstractRemoteResponse { const REJECTED_RESULTS = ['REFERRAL', 'DECLINED', 'COMMSDOWN']; private $tokenId; /** * Return the error message * * @return string */ public function getError() { $txnResult = $this->data->getMsgDataAttribute('txnresult'); return in_array($txnResult, self::REJECTED_RESULTS) ? 'Your transaction was unsuccessful. Please try again' : null; } public function getTransactionId() { return $this->data->getMsgDataAttribute('transactionid'); } public function setTokenId($value) { $this->tokenId = $value; } public function getMessage() { $error = $this->getError(); return is_null($error) ? $this->getAuthMessage() : $error; } public function getTransactionReference() { return json_encode([ 'transactionId' => $this->getTransactionId(), 'tokenId' => $this->request->getTokenId() ]); } public function getAuthCode() { return $this->data->getMsgDataAttribute('authcode'); } public function getAuthMessage() { return $this->data->getMsgDataAttribute('authmessage'); } }
<?php namespace DigiTickets\VerifoneWebService\Message\NonSessionBased; use DigiTickets\VerifoneWebService\Message\AbstractRemoteResponse; class PurchaseResponse extends AbstractRemoteResponse { const REJECTED_RESULTS = ['REFERRAL', 'DECLINED', 'COMMSDOWN']; private $tokenId; /** * Return the error message * * @return string */ public function getError() { $txnResult = $this->data->getMsgDataAttribute('txnresult'); return in_array($txnResult, self::REJECTED_RESULTS) ? 'Your transaction was unsuccessful. Please try again' : null; } public function getTransactionId() { return $this->data->getMsgDataAttribute('transactionid'); } public function setTokenId($value) { $this->tokenId = $value; } public function getMessage() { $error = $this->getError(); return is_null($error) ? $this->getAuthMessage() : $error; } public function getTransactionReference() { return json_encode([ 'transactionId' => $this->getTransactionId(), 'tokenId' => $this->request->getTokenId() ]); } public function getAuthCode() { return $this->data->getMsgDataAttribute('authcode'); } public function getAuthMessage() { return $this->data->getMsgDataAttribute('authmessage'); } }
Correct model reference in comments.
# encoding: utf-8 from django.views.generic import ListView from .viewmixins import OrderByMixin, PaginateMixin, SearchFormMixin class BaseListView(PaginateMixin, OrderByMixin, SearchFormMixin, ListView): """ Defines a base list view that supports pagination, ordering and basic search. Supports a filter description that can be used in templates: class ActiveCustomerList(BaseListView): filter_description = u"Active" queryset = Customer.active.all() {% block content %} <h2> {% if filter_description %} {{ filter_description|title }} customers {% else %} Customers {% endif %} </h2> <! -- more template --> {% end block %} """ def get_filter_description(self): if hasattr(self, 'filter_description'): return self.filter_description def get_context_data(self, **kwargs): data = super(BaseListView, self).get_context_data(**kwargs) filter_description = self.get_filter_description() if filter_description: data.update({'filter_description': filter_description}) return data
# encoding: utf-8 from django.views.generic import ListView from .viewmixins import OrderByMixin, PaginateMixin, SearchFormMixin class BaseListView(PaginateMixin, OrderByMixin, SearchFormMixin, ListView): """ Defines a base list view that supports pagination, ordering and basic search. Supports a filter description that can be used in templates: class ActiveCustomerList(BaseListView): filter_description = u"Active" queryset = Artist.active.all() {% block content %} <h2> {% if filter_description %} {{ filter_description|title }} customers {% else %} Customers {% endif %} </h2> <! -- more template --> {% end block %} """ def get_filter_description(self): if hasattr(self, 'filter_description'): return self.filter_description def get_context_data(self, **kwargs): data = super(BaseListView, self).get_context_data(**kwargs) filter_description = self.get_filter_description() if filter_description: data.update({'filter_description': filter_description}) return data
Create onLoginPressed function and add to render function
import React, { Component } from 'react'; import { StyleSheet, Text, View, TextInput, TouchableHighlight, } from 'react-native'; class Login extends Component{ constructor(){ super(); this.state = { name: "", username: "", password_digest: "", location: "", bio: "", preferred_contact: "", skills: "", seeking: "", errors: [], } } async onLoginPressed(){ } render() { return ( <View style={styles.container}> <Text> Login </Text> <TextInput onChangeText={ (val)=> this.setState({username: val}) } style={styles.input} placeholder='Username' /> <TextInput onChangeText={ (val)=> this.setState({password_digest: val}) } style={styles.input} placeholder="Password" /> <TouchableHighlight onPress={this.onRegisterPressed.bind(this)} style={styles.button}> <Text style={styles.buttonText}> Register </Text> </TouchableHighlight> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { fontSize: 20, alignSelf: 'center', margin: 40 }, input: { height: 50, marginTop: 10, padding: 4, fontSize: 15, borderWidth: 1, borderColor: '#48bbec' }, }); module.exports = Login;
import React, { Component } from 'react'; import { StyleSheet, Text, View, TextInput, TouchableHighlight, } from 'react-native'; class Login extends Component{ constructor(){ super(); this.state = { name: "", username: "", password_digest: "", location: "", bio: "", preferred_contact: "", skills: "", seeking: "", errors: [], } } render() { return ( <View style={styles.container}> <Text> Login </Text> <TextInput onChangeText={ (val)=> this.setState({username: val}) } style={styles.input} placeholder='Username' /> <TextInput onChangeText={ (val)=> this.setState({password_digest: val}) } style={styles.input} placeholder="Password" /> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { fontSize: 20, alignSelf: 'center', margin: 40 }, input: { height: 50, marginTop: 10, padding: 4, fontSize: 15, borderWidth: 1, borderColor: '#48bbec' }, }); module.exports = Login;
Stop sub totals being appended
(function () { 'use strict'; moj.Modules.SubTotal = { el: '.js-SubTotal', init: function () { _.bindAll(this, 'render', 'showSummary', 'calculate'); this.cacheEls(); this.bindEvents(); moj.log('init'); }, bindEvents: function () { this.$sets.on('keyup', 'input[type=number]', this.showSummary); moj.Events.on('render', this.render); }, cacheEls: function () { this.$sets = $(this.el); }, render: function () { this.$sets.each(this.showSummary); }, calculate: function (set) { var total = 0; set.find('input[type=number]').each(function (i, el) { var val = parseFloat($(el).val()); if (!isNaN(val)) { total += val; } }); return total; }, showSummary: function (e, el) { var $set = el !== undefined ? $(el) : $(e.target).closest(this.el), value = this.calculate($set); moj.log(CLA.templates); if ($set.find('.SubTotal').length > 0) { $set.find('.SubTotal').replaceWith(CLA.templates.SubTotal({value: value})); } else { $set.append(CLA.templates.SubTotal({value: value})); } } }; }());
(function () { 'use strict'; moj.Modules.SubTotal = { el: '.js-SubTotal', init: function () { _.bindAll(this, 'render', 'showSummary', 'calculate'); this.cacheEls(); this.bindEvents(); moj.log('init'); }, bindEvents: function () { this.$sets.on('keyup', 'input[type=number]', this.showSummary); moj.Events.on('render', this.render); }, cacheEls: function () { this.$sets = $(this.el); }, render: function () { this.$sets.each(this.showSummary); }, calculate: function (set) { var total = 0; set.find('input[type=number]').each(function (i, el) { var val = parseFloat($(el).val()); if (!isNaN(val)) { total += val; } }); return total; }, showSummary: function (e, el) { var $set = el !== undefined ? $(el) : $(e.target).closest(this.el), value = this.calculate($set); moj.log(CLA.templates); if ($set.find('.ValueSummary').length > 0) { $set.find('.ValueSummary').replaceWith(CLA.templates.SubTotal({value: value})); } else { $set.append(CLA.templates.SubTotal({value: value})); } } }; }());
[IMP] Add warehouse_id to existing onchange.
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ('inbound', 'Inbound')], string='Direction', states={'draft': [('readonly', False)]}, readonly=True) @api.onchange('warehouse_id', 'direction') def _onchange_location_id(self): if self.direction == 'outbound': # Stock Location set to Partner Locations/Customers self.location_id = \ self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = \ self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get('no_change_childs', False): for line in self.stock_request_ids: line.direction = self.direction
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ('inbound', 'Inbound')], string='Direction', states={'draft': [('readonly', False)]}, readonly=True) @api.onchange('direction') def _onchange_location_id(self): if self.direction == 'outbound': # Stock Location set to Partner Locations/Customers self.location_id = \ self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = \ self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get('no_change_childs', False): for line in self.stock_request_ids: line.direction = self.direction
Make the array functions indicate if anything happened
<?php /* * This file is part of StyleCI. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace StyleCI\Config; /** * This is the array helper class. * * @author Graham Campbell <[email protected]> * @author Joseph Cohen <[email protected]> */ class Arr { /** * Get an item from an array. * * @param array $array * @param string $key * @param mixed $default * * @return mixed */ public static function get(&$array, $key, $default = null) { return isset($array[$key]) ? $array[$key] : $default; } /** * Add an item to an array. * * @param array $array * @param mixed $item * * @return bool */ public static function add(&$array, $item) { if (!in_array($item, $array, true)) { $array[] = $item; return true; } return false; } /** * Remove an item from an array. * * @param array $array * @param mixed $item * * @return bool */ public static function remove(&$array, $item) { $index = array_search($item, $array, true); if ($index !== false) { unset($array[$index]); return true; } return false; } }
<?php /* * This file is part of StyleCI. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace StyleCI\Config; /** * This is the array helper class. * * @author Graham Campbell <[email protected]> * @author Joseph Cohen <[email protected]> */ class Arr { /** * Get an item from an array. * * @param array $array * @param string $key * @param mixed $default * * @return mixed */ public static function get(&$array, $key, $default = null) { return isset($array[$key]) ? $array[$key] : $default; } /** * Add an item to an array. * * @param array $array * @param mixed $item * * @return void */ public static function add(&$array, $item) { if (!in_array($item, $array, true)) { $array[] = $item; } } /** * Remove an item from an array. * * @param array $array * @param mixed $item * * @return void */ public static function remove(&$array, $item) { $index = array_search($item, $array, true); if ($index !== false) { unset($array[$index]); } } }
Test for any RTI element on the POI model Previously RTI would be added, now it defaults to []
define(['moxie.conf', 'underscore', 'today/views/CardView', 'hbs!today/templates/rti'], function(conf, _, CardView, rtiTemplate) { var RTI_REFRESH = 60000; // 1 minute var RTICard = CardView.extend({ initialize: function() { this.model.on('change', this.render, this); }, weight: 75, manage: true, attributes: { 'class': 'today', 'style': 'display:none;', }, serialize: function() { return this.model.toJSON(); }, template: rtiTemplate, beforeRender: function() { this.el.style.display = 'none'; }, afterRender: function() { this.clearRefresh(); if (this.model.get('RTI').length > 0) { this.refreshID = this.model.renderRTI(this.$('#poi-rti')[0], RTI_REFRESH); this.model.rti.on('sync', this.showEl, this); } }, showEl: function() { this.el.style.display = null; }, clearRefresh: function() { if (this.refreshID) { clearInterval(this.refreshID); } }, cleanup: function() { this.clearRefresh(); this.model.off(); if ('unfollowUser' in this.model) { this.model.unfollowUser(); } }, }); return RTICard; });
define(['moxie.conf', 'underscore', 'today/views/CardView', 'hbs!today/templates/rti'], function(conf, _, CardView, rtiTemplate) { var RTI_REFRESH = 60000; // 1 minute var RTICard = CardView.extend({ initialize: function() { this.model.on('change', this.render, this); }, weight: 75, manage: true, attributes: { 'class': 'today', 'style': 'display:none;', }, serialize: function() { return this.model.toJSON(); }, template: rtiTemplate, beforeRender: function() { this.el.style.display = 'none'; }, afterRender: function() { this.clearRefresh(); if (this.model.get('RTI')) { this.refreshID = this.model.renderRTI(this.$('#poi-rti')[0], RTI_REFRESH); this.model.rti.on('sync', this.showEl, this); } }, showEl: function() { this.el.style.display = null; }, clearRefresh: function() { if (this.refreshID) { clearInterval(this.refreshID); } }, cleanup: function() { this.clearRefresh(); this.model.off(); if ('unfollowUser' in this.model) { this.model.unfollowUser(); } }, }); return RTICard; });
Add console email read function
<?php namespace RoyallTheFourth\QuickList\Common; use Respect\Validation\Validator; use Symfony\Component\Yaml\Yaml; function iterableToArray(iterable $iter): array { $out = []; foreach ($iter as $el) { $out[] = $el; } return $out; } function config(): array { return Yaml::parse(file_get_contents(__DIR__ . '/../config/config.yml')); } function mailer(array $config): \PHPMailer { $mailer = new \PHPMailer(true); $mailer->isSMTP(); $mailer->Host = implode(';', $config['smtp']['hosts']); $mailer->Username = $config['smtp']['user']; $mailer->Password = $config['smtp']['pass']; $mailer->SMTPSecure = $config['smtp']['security']; $mailer->SMTPAuth = true; $mailer->SMTPKeepAlive = true; $mailer->Port = $config['smtp']['port']; $mailer->setFrom($config['from']); return $mailer; } /** * Converts database times to human-readable times * * @param string $dateTime The dateTime in UTC * @param \DateTimeZone $timezone * @return string */ function localDate(?string $dateTime, \DateTimeZone $timezone): string { if ($dateTime === null) { return ''; } return (new \DateTimeImmutable($dateTime, new \DateTimeZone('UTC'))) ->setTimezone($timezone) ->format('Y-m-d H:i:s'); } function readEmailsFromConsole(): iterable { while ($email = readline()) { if (Validator::email()->validate($email)) { yield $email; } } }
<?php namespace RoyallTheFourth\QuickList\Common; use Symfony\Component\Yaml\Yaml; function iterableToArray(iterable $iter): array { $out = []; foreach ($iter as $el) { $out[] = $el; } return $out; } function config(): array { return Yaml::parse(file_get_contents(__DIR__ . '/../config/config.yml')); } function mailer(array $config): \PHPMailer { $mailer = new \PHPMailer(true); $mailer->isSMTP(); $mailer->Host = implode(';', $config['smtp']['hosts']); $mailer->Username = $config['smtp']['user']; $mailer->Password = $config['smtp']['pass']; $mailer->SMTPSecure = $config['smtp']['security']; $mailer->SMTPAuth = true; $mailer->SMTPKeepAlive = true; $mailer->Port = $config['smtp']['port']; $mailer->setFrom($config['from']); return $mailer; } /** * Converts database times to human-readable times * * @param string $dateTime The dateTime in UTC * @param \DateTimeZone $timezone * @return string */ function localDate(?string $dateTime, \DateTimeZone $timezone): string { if ($dateTime === null) { return ''; } return (new \DateTimeImmutable($dateTime, new \DateTimeZone('UTC'))) ->setTimezone($timezone) ->format('Y-m-d H:i:s'); }
Load the analytics and mongoose only in the production mode.
"use strict"; const isProduction = process.env.NODE_ENV === "production"; module.exports = { metadata: { siteTitle: "Bloggify" , description: "We make publishing easy." , domain: isProduction ? "https://bloggify.org" : "http://localhost:8080" , twitter: "Bloggify" } , theme: { previewLink: "https://preview.bloggify.org" } , themeDir: "/theme" , pluginConfigs: { "bloggify-ajs-renderer": { disableCache: false } , "bloggify-mongoose": { db: "mongodb://localhost/bloggify-live" , models: { Stat: { ip: String , user_agent: String , device: Object , url: String , path: String , headers: Object , session: Object , date: { type: Date, default: () => new Date() } } } } , "bloggify-plugin-manager": { plugins: [ "bloggify-router", "bloggify-ajs-renderer", "bloggify-viewer" ].concat( isProduction ? ["bloggify-analytics", "bloggify-mongoose"] : [] ) } } };
"use strict"; const isProduction = process.env.NODE_ENV === "production"; module.exports = { metadata: { siteTitle: "Bloggify" , description: "We make publishing easy." , domain: isProduction ? "https://bloggify.org" : "http://localhost:8080" , twitter: "Bloggify" } , theme: { previewLink: "https://preview.bloggify.org" } , themeDir: "/theme" , pluginConfigs: { "bloggify-ajs-renderer": { disableCache: false } , "bloggify-mongoose": { db: "mongodb://localhost/bloggify-live" , models: { Stat: { ip: String , user_agent: String , device: Object , url: String , path: String , headers: Object , session: Object , date: { type: Date, default: () => new Date() } } } } , "bloggify-plugin-manager": { plugins: [ "bloggify-router", "bloggify-ajs-renderer", "bloggify-viewer" ].concat( isProduction ? [] : ["bloggify-analytics", "bloggify-mongoose"] ) } } };
Set default value for "versioned" to false.
<?php return [ /* |---------------------------------------------------------------- | Asset containers. |---------------------------------------------------------------- | | Asset containers to be loaded. | */ "containers" => array( "images" => [ "print_pattern" => '<img src="{{URL}}">', "file_regex" => "/\\.(jpg|jpeg|tiff|gif|png|bmp|ico)$/i", "path" => "/public/assets/images", "url" => "/assets/images", "versioned" => false ], "scripts" => [ "print_pattern" => '<script src="{{URL}}" type="application/javascript"></script>', "file_regex" => "/\\.js$/i", "path" => "/public/assets/scripts", "url" => "/assets/scripts", "versioned" => false ], "styles" => [ "print_pattern" => '<link rel="stylesheet" type="text/css" href="{{URL}}" title="{{NAME}}">', "file_regex" => "/\\.css$/i", "path" => "/public/assets/styles", "url" => "/assets/styles", "versioned" => false ], // // Add your own custom containers here. // ) ];
<?php return [ /* |---------------------------------------------------------------- | Asset containers. |---------------------------------------------------------------- | | Asset containers to be loaded. | */ "containers" => array( "images" => [ "print_pattern" => '<img src="{{URL}}">', "file_regex" => "/\\.(jpg|jpeg|tiff|gif|png|bmp|ico)$/i", "path" => "/public/assets/images", "url" => "/assets/images", "versioned" => false ], "scripts" => [ "print_pattern" => '<script src="{{URL}}" type="application/javascript"></script>', "file_regex" => "/\\.js$/i", "path" => "/public/assets/scripts", "url" => "/assets/scripts", "versioned" => true ], "styles" => [ "print_pattern" => '<link rel="stylesheet" type="text/css" href="{{URL}}" title="{{NAME}}">', "file_regex" => "/\\.css$/i", "path" => "/public/assets/styles", "url" => "/assets/styles", "versioned" => true ], // // Add your own custom containers here. // ) ];
Add stub for creating job definitions. Add back snapshot uploading prior to job submission
// dependencies ------------------------------------------------------------ import aws from '../libs/aws'; import scitran from '../libs/scitran'; // handlers ---------------------------------------------------------------- /** * Jobs * * Handlers for job actions. */ let handlers = { /** * Create Job Definition */ createJobDefinition(req, res, next) { }, /** * Describe Job Definitions */ describeJobDefinitions(req, res, next) { aws.batch.sdk.describeJobDefinitions({}, (err, data) => { if (err) { return next(err); } else { let definitions = {}; for (let definition of data.jobDefinitions) { if (!definitions.hasOwnProperty(definition.jobDefinitionName)) { definitions[definition.jobDefinitionName] = {}; } definitions[definition.jobDefinitionName][definition.revision] = definition; } res.send(definitions); } }); }, /** * Submit Job */ submitJob(req, res) { let job = req.body; const batchJobParams = { jobDefinition: job.jobDefinition, jobName: job.jobName, parameters: job.parameters }; batchJobParams.jobQueue = 'bids-queue'; scitran.downloadSymlinkDataset(job.snapshotId, (err, hash) => { aws.s3.uploadSnapshot(hash, () => { aws.batch.sdk.submitJob(batchJobParams, (err, data) => { res.send(data); }); }); }); } }; export default handlers;
// dependencies ------------------------------------------------------------ import aws from '../libs/aws'; // handlers ---------------------------------------------------------------- /** * Jobs * * Handlers for job actions. */ let handlers = { /** * Describe Job Definitions */ describeJobDefinitions(req, res, next) { aws.batch.sdk.describeJobDefinitions({}, (err, data) => { if (err) { return next(err); } else { let definitions = {}; for (let definition of data.jobDefinitions) { if (!definitions.hasOwnProperty(definition.jobDefinitionName)) { definitions[definition.jobDefinitionName] = {}; } definitions[definition.jobDefinitionName][definition.revision] = definition; } res.send(definitions); } }); }, /** * Submit Job */ submitJob(req, res) { let job = req.body; const batchJobParams = { jobDefinition: job.jobDefinition, jobName: job.jobName, parameters: job.parameters }; batchJobParams.jobQueue = 'bids-queue'; aws.batch.sdk.submitJob(batchJobParams, (err, data) => { res.send(data); }); } }; export default handlers;
[SimpleJobSchedule] Add base key to redis backed time keeper
<?php declare(strict_types=1); namespace Issei\SimpleJobSchedule\TimeKeeper; use Issei\SimpleJobSchedule\TimeKeeperInterface; use Predis\Client as Redis; /** * @author Issei Murasawa <[email protected]> */ class RedisTimeKeeper implements TimeKeeperInterface { /** * @var Redis */ private $redis; /** * @var string */ private $baseKey; public function __construct(Redis $redis, string $baseKey) { $this->redis = $redis; $this->baseKey = $baseKey; } /** * {@inheritdoc} */ public function getLastRanTime(string $key): ?\DateTimeInterface { $lastRanAtAsEpoch = $this->redis->get($this->getKeyFor($key)); return $lastRanAtAsEpoch ? (new \DateTimeImmutable())->setTimestamp((int) $lastRanAtAsEpoch) : null ; } /** * {@inheritdoc} */ public function attemptToKeepRunTime(string $key, \DateTimeInterface $runTime): bool { $script = <<< 'LUA' local last_run_at = redis.call('GET', KEYS[1]) if last_run_at ~= ARGV[1] then redis.call('SET', KEYS[1], ARGV[1]) return 1 else return 0 end LUA; return (bool) $this->redis->eval($script, 1, $this->getKeyFor($key), $runTime->getTimestamp()); } private function getKeyFor(string $key): string { return $this->baseKey . ':' . $key; } }
<?php declare(strict_types=1); namespace Issei\SimpleJobSchedule\TimeKeeper; use Issei\SimpleJobSchedule\TimeKeeperInterface; use Predis\Client as Redis; /** * @author Issei Murasawa <[email protected]> */ class RedisTimeKeeper implements TimeKeeperInterface { /** * @var Redis */ private $redis; public function __construct(Redis $redis) { $this->redis = $redis; } /** * {@inheritdoc} */ public function getLastRanTime(string $key): ?\DateTimeInterface { $lastRanAtAsEpoch = $this->redis->get($key); return $lastRanAtAsEpoch ? (new \DateTimeImmutable())->setTimestamp((int) $lastRanAtAsEpoch) : null ; } /** * {@inheritdoc} */ public function attemptToKeepRunTime(string $key, \DateTimeInterface $runTime): bool { $script = <<< 'LUA' local last_run_at = redis.call('GET', KEYS[1]) if last_run_at ~= ARGV[1] then redis.call('SET', KEYS[1], ARGV[1]) return 1 else return 0 end LUA; return (bool) $this->redis->eval($script, 1, $key, $runTime->getTimestamp()); } }
Remove navigator user agent as it causes the app to break
'use strict'; import * as types from '../actions/actionTypes'; import config from '../config'; const initialState = { isFetching: true, question: '', latest: '' }; export default function main(state = initialState, action = {}) { switch (action.type) { case types.GET_LATEST: return case types.RECEIVE_FETCH: console.log(action); return { ...state, isFetching: false, latest: action.question }; case types.SET_TEXT: return { ...state, question: action.question }; case types.SUBMIT_QUESTION: fetch('http://' + config.host + '/api/submit', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ question: state.question }) }); return state; default: return state; } }
'use strict'; import * as types from '../actions/actionTypes'; import config from '../config'; window.navigator.userAgent = "react-native"; const initialState = { isFetching: true, question: '', latest: '' }; export default function main(state = initialState, action = {}) { switch (action.type) { case types.GET_LATEST: return case types.RECEIVE_FETCH: console.log(action); return { ...state, isFetching: false, latest: action.question }; case types.SET_TEXT: return { ...state, question: action.question }; case types.SUBMIT_QUESTION: fetch('http://' + config.host + '/api/submit', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ question: state.question }) }); return state; default: return state; } }
Speed up showing favorite icons
function getFavoriteTeams() { var cookieName = "tba-favorite-teams"; var storedFavoriteTeams = $.cookie(cookieName); console.log(storedFavoriteTeams); if (storedFavoriteTeams == null) { // Set cookie expiration var date = new Date(); date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 minutes $.ajax({ type: 'GET', dataType: 'json', url: '/_/account/favorites/1', success: function(favorites, textStatus, xhr) { var favoriteTeams = {}; for (var key in favorites) { favoriteTeams[favorites[key]['model_key']] = true; } $.cookie(cookieName, JSON.stringify(favoriteTeams), { expires: date }); updateMatchFavorites(favoriteTeams); }, error: function(xhr, textStatus, errorThrown) { $.cookie(cookieName, JSON.stringify({}), { expires: date }); } }); } else { updateMatchFavorites(JSON.parse(storedFavoriteTeams)); } } function updateMatchFavorites(favoriteTeams) { $(".favorite-team-dot").each(function() { if ($(this).attr("data-team") in favoriteTeams) { $(this).show(); // Dot $(this).closest('tr').find('.favorite-match-icon').show(); // Star } }); } $(document).ready(function(){ getFavoriteTeams(); });
function getFavoriteTeams() { var cookieName = "tba-favorite-teams"; var storedFavoriteTeams = $.cookie(cookieName); console.log(storedFavoriteTeams); if (storedFavoriteTeams == null) { // Set cookie expiration var date = new Date(); date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 minutes $.ajax({ type: 'GET', dataType: 'json', url: '/_/account/favorites/1', success: function(favorites, textStatus, xhr) { var favoriteTeams = {}; for (var key in favorites) { favoriteTeams[favorites[key]['model_key']] = true; } $.cookie(cookieName, JSON.stringify(favoriteTeams), { expires: date }); updateMatchFavorites(favoriteTeams); }, error: function(xhr, textStatus, errorThrown) { $.cookie(cookieName, JSON.stringify({}), { expires: date }); } }); } else { updateMatchFavorites(JSON.parse(storedFavoriteTeams)); } } function updateMatchFavorites(favoriteTeams) { $(".favorite-match-icon").each(function () { var match_teams = JSON.parse($(this).attr("data-teams")); for (var i in match_teams) { if (match_teams[i] in favoriteTeams) { $(this).show(); } } }); $(".favorite-team-dot").each(function() { if ($(this).attr("data-team") in favoriteTeams) { $(this).show(); } }); } $(document).ready(function(){ getFavoriteTeams(); });
Update namespaces for beta 8 Refs flarum/core#1235.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Auth\Facebook\Listener; use Flarum\Frontend\Event\Rendering; use Illuminate\Contracts\Events\Dispatcher; class AddClientAssets { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(Rendering::class, [$this, 'addAssets']); } /** * @param Rendering $event */ public function addAssets(Rendering $event) { if ($event->isForum()) { $event->addAssets([ __DIR__.'/../../js/forum/dist/extension.js', __DIR__.'/../../less/forum/extension.less' ]); $event->addBootstrapper('flarum/auth/facebook/main'); } if ($event->isAdmin()) { $event->addAssets([ __DIR__.'/../../js/admin/dist/extension.js' ]); $event->addBootstrapper('flarum/auth/facebook/main'); } } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Auth\Facebook\Listener; use Flarum\Event\ConfigureWebApp; use Illuminate\Contracts\Events\Dispatcher; class AddClientAssets { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(ConfigureWebApp::class, [$this, 'addAssets']); } /** * @param ConfigureClientView $event */ public function addAssets(ConfigureWebApp $event) { if ($event->isForum()) { $event->addAssets([ __DIR__.'/../../js/forum/dist/extension.js', __DIR__.'/../../less/forum/extension.less' ]); $event->addBootstrapper('flarum/auth/facebook/main'); } if ($event->isAdmin()) { $event->addAssets([ __DIR__.'/../../js/admin/dist/extension.js' ]); $event->addBootstrapper('flarum/auth/facebook/main'); } } }
Add tags and filters into the context
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.parser = parse.Parser(raw) self.nodelist = self.parser() code = ast.Expression( body=ast.GeneratorExp( elt=ast.Call( func=ast.Name(id='str', ctx=ast.Load()), args=[ ast.Call( func=ast.Attribute( value=ast.Name(id='x', ctx=ast.Load()), attr='render', ctx=ast.Load() ), args=[ast.Name(id='context', ctx=ast.Load())], keywords=[], starargs=None, kwargs=None ), ], keywords=[], starargs=None, kwargs=None ), generators=[ ast.comprehension( target=ast.Name(id='x', ctx=ast.Store()), iter=ast.Name(id='nodelist', ctx=ast.Load()), ifs=[] ), ] ) ) ast.fix_missing_locations(code) self.code = compile(code, filename='<template>', mode='eval') def render(self, context): ctx = dict(context, _filter=self.parser.filters, _tag=self.parser.tags) global_ctx = { 'nodelist': self.nodelist, 'context': ctx, } return ''.join(eval(self.code, global_ctx, {}))
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.parser = parse.Parser(raw) self.nodelist = self.parser() code = ast.Expression( body=ast.GeneratorExp( elt=ast.Call( func=ast.Name(id='str', ctx=ast.Load()), args=[ ast.Call( func=ast.Attribute( value=ast.Name(id='x', ctx=ast.Load()), attr='render', ctx=ast.Load() ), args=[ast.Name(id='context', ctx=ast.Load())], keywords=[], starargs=None, kwargs=None ), ], keywords=[], starargs=None, kwargs=None ), generators=[ ast.comprehension( target=ast.Name(id='x', ctx=ast.Store()), iter=ast.Name(id='nodelist', ctx=ast.Load()), ifs=[] ), ] ) ) ast.fix_missing_locations(code) self.code = compile(code, filename='<template>', mode='eval') def render(self, context): global_ctx = { 'nodelist': self.nodelist, 'context': dict(context), 'filters': self.parser.filters, 'tags': self.parser.tags, } return ''.join(eval(self.code, global_ctx, {}))
Exclude files in .travis folder from testExecutableFiles test
<?php namespace Concrete\Tests\File; use PHPUnit_Framework_TestCase; class ExecutableFilesTest extends PHPUnit_Framework_TestCase { public function testExecutableFiles() { if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Testing executable files requires a Posix environment'); } $rc = -1; $output = []; @exec('find ' . escapeshellarg(DIR_BASE) . ' -type f -executable', $output, $rc); if ($rc !== 0) { $this->markTestSkipped('Failed to retrieve the list of executable files (' . implode("\n", $output) . ')'); } $output = array_map(function ($file) { return substr($file, strlen(DIR_BASE) + 1); }, $output); $actual = array_filter($output, function ($file) { return strpos($file, '.git/') !== 0 && strpos($file, 'concrete/vendor/') !== 0 && strpos($file, 'packages/') !== 0 && strpos($file, 'updates/') !== 0 && strpos($file, '.travis/') !== 0 ; }); sort($actual); $expected = [ 'concrete/bin/concrete5', ]; $this->assertSame( $expected, $actual, 'Checking that only selected files are executable' ); } }
<?php namespace Concrete\Tests\File; use PHPUnit_Framework_TestCase; class ExecutableFilesTest extends PHPUnit_Framework_TestCase { public function testExecutableFiles() { if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Testing executable files requires a Posix environment'); } $rc = -1; $output = []; @exec('find ' . escapeshellarg(DIR_BASE) . ' -type f -executable', $output, $rc); if ($rc !== 0) { $this->markTestSkipped('Failed to retrieve the list of executable files (' . implode("\n", $output) . ')'); } $output = array_map(function ($file) { return substr($file, strlen(DIR_BASE) + 1); }, $output); $actual = array_filter($output, function ($file) { return strpos($file, '.git/') !== 0 && strpos($file, 'concrete/vendor/') !== 0 && strpos($file, 'packages/') !== 0 && strpos($file, 'updates/') !== 0 ; }); sort($actual); $expected = [ 'concrete/bin/concrete5', ]; $this->assertSame( $expected, $actual, 'Checking that only selected files are executable' ); } }
Remove "function()" from database-files. Why was it inserted in the first place?
var esformatter = require('esformatter'); var stringify = require("json-literal").stringify; var fs = require("fs"); var path = require("path"); /** * Class that writes an object to a file (using the `json-literal` module) * @param {*} `data` the javascript object, * @constructor */ function Writer(data) { var prettyPrint = false; /** * Enable pretty printed output */ this.pretty = function () { prettyPrint = true; return this; }; /** * Write the data to a file (synchronously). * @param {string} `targetDir` the directory of the file * @param {string} `filename` the name of the file */ this.writeTo = function (targetDir, filename) { // Remove wrapping parens which are always created by json-literal var node = stringify(data).replace(/^\((.*)\)$/, "$1"); // Create a valid javascript module var string = "module.exports = " + node + ";"; // If prettyprint is enabled, use esformatter to format // the resulting javascript. if (prettyPrint) { string = esformatter.format(string, { // indent is hard coded to 4 spaces at the moment indent: { value: ' ' } }); } // Write the data... var targetFile = path.join(targetDir, filename); console.log("Writing ", targetFile); fs.writeFileSync(targetFile, string, "utf-8"); console.log("done"); } } module.exports = Writer;
var esformatter = require('esformatter'); var stringify = require("json-literal").stringify; var fs = require("fs"); var path = require("path"); /** * Class that writes an object to a file (using the `json-literal` module) * @param {*} `data` the javascript object, * @constructor */ function Writer(data) { var prettyPrint = false; /** * Enable pretty printed output */ this.pretty = function () { prettyPrint = true; return this; }; /** * Write the data to a file (synchronously). * @param {string} `targetDir` the directory of the file * @param {string} `filename` the name of the file */ this.writeTo = function (targetDir, filename) { // Remove wrapping parens which are always created by json-literal var node = stringify(data).replace(/^\((.*)\)$/, "$1"); // Create a valid javascript module var string = "module.exports = function() { return " + node + "};"; // If prettyprint is enabled, use esformatter to format // the resulting javascript. if (prettyPrint) { string = esformatter.format(string, { // indent is hard coded to 4 spaces at the moment indent: { value: ' ' } }); } // Write the data... var targetFile = path.join(targetDir, filename); console.log("Writing ", targetFile); fs.writeFileSync(targetFile, string, "utf-8"); console.log("done"); } } module.exports = Writer;
Enable dark mode in Telescope
<?php namespace App\Providers; use Laravel\Telescope\Telescope; use Illuminate\Support\Facades\Gate; use Laravel\Telescope\IncomingEntry; use Laravel\Telescope\TelescopeApplicationServiceProvider; class TelescopeServiceProvider extends TelescopeApplicationServiceProvider { /** * Register any application services. * * @return void */ public function register() { Telescope::night(); $this->hideSensitiveRequestDetails(); Telescope::filter(function (IncomingEntry $entry) { if ($this->app->isLocal()) { return true; } return $entry->isReportableException() || $entry->isFailedJob() || $entry->isScheduledTask() || $entry->hasMonitoredTag(); }); } /** * Prevent sensitive request details from being logged by Telescope. * * @return void */ protected function hideSensitiveRequestDetails() { if ($this->app->isLocal()) { return; } Telescope::hideRequestParameters(['_token']); Telescope::hideRequestHeaders([ 'cookie', 'x-csrf-token', 'x-xsrf-token', ]); } /** * Register the Telescope gate. * * This gate determines who can access Telescope in non-local environments. * * @return void */ protected function gate() { Gate::define('viewTelescope', function ($user) { return in_array($user->name, [ 'jonny', ]); }); } }
<?php namespace App\Providers; use Laravel\Telescope\Telescope; use Illuminate\Support\Facades\Gate; use Laravel\Telescope\IncomingEntry; use Laravel\Telescope\TelescopeApplicationServiceProvider; class TelescopeServiceProvider extends TelescopeApplicationServiceProvider { /** * Register any application services. * * @return void */ public function register() { // Telescope::night(); $this->hideSensitiveRequestDetails(); Telescope::filter(function (IncomingEntry $entry) { if ($this->app->isLocal()) { return true; } return $entry->isReportableException() || $entry->isFailedJob() || $entry->isScheduledTask() || $entry->hasMonitoredTag(); }); } /** * Prevent sensitive request details from being logged by Telescope. * * @return void */ protected function hideSensitiveRequestDetails() { if ($this->app->isLocal()) { return; } Telescope::hideRequestParameters(['_token']); Telescope::hideRequestHeaders([ 'cookie', 'x-csrf-token', 'x-xsrf-token', ]); } /** * Register the Telescope gate. * * This gate determines who can access Telescope in non-local environments. * * @return void */ protected function gate() { Gate::define('viewTelescope', function ($user) { return in_array($user->name, [ 'jonny', ]); }); } }
Add the futures lib backport as a dependency.
from setuptools import setup, find_packages from lighthouse import __version__ classifiers = [] with open("classifiers.txt") as fd: classifiers = fd.readlines() setup( name="lighthouse", version=__version__, description="Service discovery tool focused on ease-of-use and resiliency", author="William Glass", author_email="[email protected]", url="http://github.com/wglass/lighthouse", license="MIT", classifiers=classifiers, packages=find_packages(exclude=["tests", "tests.*"]), include_package_data=True, package_data={ "lighthouse": ["haproxy/*.json"], }, install_requires=[ "watchdog", "pyyaml", "kazoo", "six", "futures", ], extras_require={ "redis": [], }, entry_points={ "console_scripts": [ "lighthouse-reporter = lighthouse.scripts.reporter:run", "lighthouse-writer = lighthouse.scripts.writer:run" ], "lighthouse.balancers": [ "haproxy = lighthouse.haproxy.balancer:HAProxy", ], "lighthouse.discovery": [ "zookeeper = lighthouse.zookeeper:ZookeeperDiscovery", ], "lighthouse.checks": [ "http = lighthouse.checks.http:HTTPCheck", "tcp = lighthouse.checks.tcp:TCPCheck", "redis = lighthouse.redis.check:RedisCheck [redis]", ] }, tests_require=[ "nose", "mock", "coverage", "flake8", ], )
from setuptools import setup, find_packages from lighthouse import __version__ classifiers = [] with open("classifiers.txt") as fd: classifiers = fd.readlines() setup( name="lighthouse", version=__version__, description="Service discovery tool focused on ease-of-use and resiliency", author="William Glass", author_email="[email protected]", url="http://github.com/wglass/lighthouse", license="MIT", classifiers=classifiers, packages=find_packages(exclude=["tests", "tests.*"]), include_package_data=True, package_data={ "lighthouse": ["haproxy/*.json"], }, install_requires=[ "watchdog", "pyyaml", "kazoo", "six", ], extras_require={ "redis": [], }, entry_points={ "console_scripts": [ "lighthouse-reporter = lighthouse.scripts.reporter:run", "lighthouse-writer = lighthouse.scripts.writer:run" ], "lighthouse.balancers": [ "haproxy = lighthouse.haproxy.balancer:HAProxy", ], "lighthouse.discovery": [ "zookeeper = lighthouse.zookeeper:ZookeeperDiscovery", ], "lighthouse.checks": [ "http = lighthouse.checks.http:HTTPCheck", "tcp = lighthouse.checks.tcp:TCPCheck", "redis = lighthouse.redis.check:RedisCheck [redis]", ] }, tests_require=[ "nose", "mock", "coverage", "flake8", ], )
Fix wrong path in readme
from setuptools import setup version = "0.10.2" setup( name="setuptools-rust", version=version, author="Nikolay Kim", author_email="[email protected]", url="https://github.com/PyO3/setuptools-rust", keywords="distutils setuptools rust", description="Setuptools rust extension plugin", long_description=open("README.rst").read(), license="MIT", packages=["setuptools_rust"], install_requires=["semantic_version>=2.6.0", "toml>=0.9.0"], zip_safe=True, classifiers=[ "Topic :: Software Development :: Version Control", "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Development Status :: 5 - Production/Stable", "Operating System :: POSIX", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", ], entry_points=""" [distutils.commands] check_rust=setuptools_rust.check:check_rust clean_rust=setuptools_rust:clean_rust build_ext=setuptools_rust:build_ext build_rust=setuptools_rust:build_rust test_rust=setuptools_rust:test_rust tomlgen_rust=setuptools_rust:tomlgen_rust """, )
from setuptools import setup version = "0.10.2" setup( name="setuptools-rust", version=version, author="Nikolay Kim", author_email="[email protected]", url="https://github.com/PyO3/setuptools-rust", keywords="distutils setuptools rust", description="Setuptools rust extension plugin", long_description="\n\n".join( (open("README.rst").read(), open("CHANGES.rst").read()) ), license="MIT", packages=["setuptools_rust"], install_requires=["semantic_version>=2.6.0", "toml>=0.9.0"], zip_safe=True, classifiers=[ "Topic :: Software Development :: Version Control", "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Development Status :: 5 - Production/Stable", "Operating System :: POSIX", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", ], entry_points=""" [distutils.commands] check_rust=setuptools_rust.check:check_rust clean_rust=setuptools_rust:clean_rust build_ext=setuptools_rust:build_ext build_rust=setuptools_rust:build_rust test_rust=setuptools_rust:test_rust tomlgen_rust=setuptools_rust:tomlgen_rust """, )
Enable context provider for TraceErrorsMiddleware
import logging from paste.deploy.converters import asbool log = logging.getLogger(__name__) def _turbogears_backlash_context(environ): tgl = environ.get('tg.locals') return {'request':getattr(tgl, 'request', None)} def ErrorHandler(app, global_conf, **errorware): """ErrorHandler Toggle If debug is enabled, this function will return the app wrapped in the WebError ``EvalException`` middleware which displays interactive debugging sessions when a traceback occurs. Otherwise, the app will be wrapped in the WebError ``ErrorMiddleware``, and the ``errorware`` dict will be passed into it. The ``ErrorMiddleware`` handles sending an email to the address listed in the .ini file, under ``email_to``. """ try: import backlash except ImportError: #pragma: no cover log.warn('backlash not installed, debug mode won\'t be available') return app if asbool(global_conf.get('debug')): app = backlash.DebuggedApplication(app, context_injectors=[_turbogears_backlash_context]) return app def ErrorReporter(app, global_conf, **errorware): try: import backlash except ImportError: #pragma: no cover log.warn('backlash not installed, email tracebacks won\'t be available') return app from backlash.trace_errors import EmailReporter if not asbool(global_conf.get('debug')): app = backlash.TraceErrorsMiddleware(app, [EmailReporter(**errorware)], context_injectors=[_turbogears_backlash_context]) return app
import logging from paste.deploy.converters import asbool log = logging.getLogger(__name__) def _turbogears_backlash_context(environ): tgl = environ.get('tg.locals') return {'request':getattr(tgl, 'request', None)} def ErrorHandler(app, global_conf, **errorware): """ErrorHandler Toggle If debug is enabled, this function will return the app wrapped in the WebError ``EvalException`` middleware which displays interactive debugging sessions when a traceback occurs. Otherwise, the app will be wrapped in the WebError ``ErrorMiddleware``, and the ``errorware`` dict will be passed into it. The ``ErrorMiddleware`` handles sending an email to the address listed in the .ini file, under ``email_to``. """ try: import backlash except ImportError: #pragma: no cover log.warn('backlash not installed, debug mode won\'t be available') return app if asbool(global_conf.get('debug')): app = backlash.DebuggedApplication(app, context_injectors=[_turbogears_backlash_context]) return app def ErrorReporter(app, global_conf, **errorware): try: import backlash except ImportError: #pragma: no cover log.warn('backlash not installed, email tracebacks won\'t be available') return app from backlash.trace_errors import EmailReporter if not asbool(global_conf.get('debug')): app = backlash.TraceErrorsMiddleware(app, [EmailReporter(**errorware)]) return app
Add state saving to Tally
package com.stevescodingblog.androidapps.tally; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.prefs.Preferences; public class MainActivity extends Activity { int _tally = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final View layoutRoot = this.findViewById(R.id.layoutRoot); layoutRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { _tally += 1; updateUi(); } }); final Button resetButton = (Button) this.findViewById(R.id.tallyButton); resetButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { _tally = 0; updateUi(); } }); this.updateUi(); } protected void updateUi() { final TextView tallyDisplay = (TextView)this.findViewById(R.id.tallyDisplay); tallyDisplay.setText(Integer.toString(this._tally)); } @Override protected void onStart() { super.onStart(); this.loadState(); this.updateUi(); } @Override protected void onStop() { super.onStop(); saveState(); } private void loadState() { // See if we have previously saved the count, and load it SharedPreferences prefs = getPreferences(MODE_PRIVATE); this._tally = prefs.getInt("count", 0); } private void saveState() { // Get the preferences and the editor for the preferences SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); // Store our count.. editor.putInt("count", this._tally); // Save changes editor.commit(); } }
package com.stevescodingblog.androidapps.tally; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { int _tally = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final View layoutRoot = this.findViewById(R.id.layoutRoot); layoutRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { _tally += 1; updateUi(); } }); final Button resetButton = (Button) this.findViewById(R.id.tallyButton); resetButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { _tally = 1; updateUi(); } }); } protected void updateUi() { final TextView tallyDisplay = (TextView)this.findViewById(R.id.tallyDisplay); tallyDisplay.setText(Integer.toString(this._tally)); } }
Revert "set only forEach globally for Array.prototyp if not exists (ie8 fallback)" This reverts commit 6c9d18931103e20f5be97250352fc14fd678d990. Reason is that admin is broken with this commit (no menu is shown).
var _ = require('underscore'); _.extend(Array.prototype, { //deprecated! -> forEach (ist auch ein JS-Standard!) each: function(fn, scope) { _.each(this, fn, scope); }, //to use array.forEach directly forEach: function(fn, scope) { _.forEach(this, fn, scope); } }); if (typeof Array.prototype.add != 'function') { //add is alias for push Array.prototype.add = function () { this.push.apply(this, arguments); }; } if (typeof Array.prototype.shuffle != 'function') { //+ Jonas Raoni Soares Silva //@ http://jsfromhell.com/array/shuffle [rev. #1] Array.prototype.shuffle = function () { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; }; } //source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }
var _ = require('underscore'); if (typeof Array.prototype.forEach != 'function') { Array.prototype.forEach = function (fn, scope) { _.forEach(this, fn, scope); }; } //source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }
Add log function for compatibility with Console API
'use strict'; var catchErrors = require('./lib/catchErrors'); var log = require('./lib/log'); var transportConsole = require('./lib/transports/console'); var transportFile = require('./lib/transports/file'); var transportRemote = require('./lib/transports/remote'); var transportMainConsole = require('./lib/transports/mainConsole'); var transportRendererConsole = require('./lib/transports/rendererConsole'); var utils = require('./lib/utils'); module.exports = { catchErrors: function callCatchErrors(options) { var opts = Object.assign({}, { log: module.exports.error, showDialog: process.type === 'browser' }, options || {}); catchErrors(opts); }, hooks: [], isDev: utils.isDev(), levels: ['error', 'warn', 'info', 'verbose', 'debug', 'silly'], variables: { processType: process.type } }; module.exports.transports = { console: transportConsole(module.exports), file: transportFile(module.exports), remote: transportRemote(module.exports), mainConsole: transportMainConsole(module.exports), rendererConsole: transportRendererConsole(module.exports) }; module.exports.levels.forEach(function (level) { module.exports[level] = log.bind(null, module.exports, level); }); module.exports.log = log.bind(null, module.exports, 'info'); module.exports.default = module.exports;
'use strict'; var catchErrors = require('./lib/catchErrors'); var log = require('./lib/log'); var transportConsole = require('./lib/transports/console'); var transportFile = require('./lib/transports/file'); var transportRemote = require('./lib/transports/remote'); var transportMainConsole = require('./lib/transports/mainConsole'); var transportRendererConsole = require('./lib/transports/rendererConsole'); var utils = require('./lib/utils'); module.exports = { catchErrors: function callCatchErrors(options) { var opts = Object.assign({}, { log: module.exports.error, showDialog: process.type === 'browser' }, options || {}); catchErrors(opts); }, hooks: [], isDev: utils.isDev(), levels: ['error', 'warn', 'info', 'verbose', 'debug', 'silly'], variables: { processType: process.type } }; module.exports.transports = { console: transportConsole(module.exports), file: transportFile(module.exports), remote: transportRemote(module.exports), mainConsole: transportMainConsole(module.exports), rendererConsole: transportRendererConsole(module.exports) }; module.exports.levels.forEach(function (level) { module.exports[level] = log.bind(null, module.exports, level); }); module.exports.default = module.exports;
Print http start to beginning
#!/usr/bin/env node 'use strict'; var config = require('./config'); var http = require('http'); var ip = require('ip'); var exec = require('child_process').exec; var createHandler = require('github-webhook-handler'); var handler = createHandler({ secret: config.SECRET, path: config.HOOK_PATH }); http.createServer(function (req, res) { handler(req, res, function(err) { res.statusCode = 404; res.end('error') }); }).listen(config.PORT, function () { console.log('GitHub webhook running at: http://' + ip.address() + ':' + config.PORT + config.HOOK_PATH); console.log('Listening for commits to branch ' + config.BRANCH); }); handler.on('push', function (event) { if (event.payload.ref === config.BRANCH) { console.log(new Date(), ' : Running deployment now...'); exec('sh deploy.sh', function(error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } console.log('Deployment finished!'); }); } }); handler.on('error', function (error) { console.error('Webhook error: ' + error); });
#!/usr/bin/env node 'use strict'; var config = require('./config'); var http = require('http'); var ip = require('ip'); var exec = require('child_process').exec; var createHandler = require('github-webhook-handler'); var handler = createHandler({ secret: config.SECRET, path: config.HOOK_PATH }); http.createServer(function (req, res) { handler(req, res, function(err) { res.statusCode = 404; res.end('error') }); }).listen(config.PORT, function () { console.log('GitHub webhook running at: ' + ip.address() + ':' + config.PORT + config.HOOK_PATH); console.log('Listening for commits to branch ' + config.BRANCH); }); handler.on('push', function (event) { if (event.payload.ref === config.BRANCH) { console.log(new Date(), ' : Running deployment now...'); exec('sh deploy.sh', function(error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } console.log('Deployment finished!'); }); } }); handler.on('error', function (error) { console.error('Webhook error: ' + error); });
Remove commented out logged decorator
import urlparse import celery import requests from celery.utils.log import get_task_logger from django.conf import settings from framework.tasks import app as celery_app logger = get_task_logger(__name__) class VarnishTask(celery.Task): abstract = True max_retries = 5 def get_varnish_servers(): # TODO: this should get the varnish servers from HAProxy or a setting return settings.VARNISH_SERVERS @celery_app.task(base=VarnishTask, name='caching_tasks.ban_url') def ban_url(url): if settings.ENABLE_VARNISH: parsed_url = urlparse.urlparse(url) for host in get_varnish_servers(): varnish_parsed_url = urlparse.urlparse(host) ban_url = '{scheme}://{netloc}{path}.*'.format( scheme=varnish_parsed_url.scheme, netloc=varnish_parsed_url.netloc, path=parsed_url.path ) response = requests.request('BAN', ban_url, headers=dict( Host=parsed_url.hostname )) if not response.ok: logger.error('Banning {} failed with message {}'.format( url, response.text ))
import urlparse import celery import requests from celery.utils.log import get_task_logger from django.conf import settings from framework.tasks import app as celery_app logger = get_task_logger(__name__) class VarnishTask(celery.Task): abstract = True max_retries = 5 def get_varnish_servers(): # TODO: this should get the varnish servers from HAProxy or a setting return settings.VARNISH_SERVERS @celery_app.task(base=VarnishTask, name='caching_tasks.ban_url') # @logged('ban_url') def ban_url(url): if settings.ENABLE_VARNISH: parsed_url = urlparse.urlparse(url) for host in get_varnish_servers(): varnish_parsed_url = urlparse.urlparse(host) ban_url = '{scheme}://{netloc}{path}.*'.format( scheme=varnish_parsed_url.scheme, netloc=varnish_parsed_url.netloc, path=parsed_url.path ) response = requests.request('BAN', ban_url, headers=dict( Host=parsed_url.hostname )) if not response.ok: logger.error('Banning {} failed with message {}'.format( url, response.text ))
Use finally so connection is also closed on exception.
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.config['password'] self.enable = self.config['enable'] self.method = self.method.encode('utf-8', 'ignore') self.username = self.username.encode('utf-8', 'ignore') self.password = self.password.encode('utf-8', 'ignore') self.enable = self.enable.encode('utf-8', 'ignore') utf8_host = host.encode('utf-8', 'ignore') utf8_commands = [] for cmd in command: utf8_commands.append(cmd.encode('utf-8', 'ignore')) transport = None try: transport = generic(host=utf8_host, username=self.username, enable=self.enable, method=self.method, password=self.password) return_value = transport.configure(utf8_commands) _return_value = str(return_value).encode('utf-8', 'ignore') if save is True: transport.configure(["write mem"]) return _return_value except Exception as err: self.logger.exception('Config command threw an exception') self.logger.error(err) sys.exit(2) finally: if transport: transport.close()
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.config['password'] self.enable = self.config['enable'] self.method = self.method.encode('utf-8', 'ignore') self.username = self.username.encode('utf-8', 'ignore') self.password = self.password.encode('utf-8', 'ignore') self.enable = self.enable.encode('utf-8', 'ignore') utf8_host = host.encode('utf-8', 'ignore') utf8_commands = [] for cmd in command: utf8_commands.append(cmd.encode('utf-8', 'ignore')) try: transport = generic(host=utf8_host, username=self.username, enable=self.enable, method=self.method, password=self.password) return_value = transport.configure(utf8_commands) _return_value = str(return_value).encode('utf-8', 'ignore') if save is True: transport.configure(["write mem"]) transport.close() return _return_value except Exception, err: self.logger.info('FUBARd') self.logger.info(err) sys.exit(2)
Add min task to release.
var exec = require('child_process').exec; module.exports = function(grunt) { grunt.initConfig({ qunit: ['./test/index.html'], lint: ['supermodel.js', './test/*.js'], min: { 'supermodel.min.js': 'supermodel.js' }, watch: { default: { files: ['supermodel.js', 'test/index.html', 'test/**/*.js'], tasks: 'default' } }, jshint: { options: { eqnull: true, undef: true }, globals: { // QUnit ok: true, test: true, module: true, raises: true, deepEqual: true, strictEqual: true, // Dependencies _: true, jQuery: true, Backbone: true, Supermodel: true } } }); grunt.registerTask('default', 'lint qunit'); grunt.registerTask('release', 'default docco min'); grunt.registerTask('docco', function() { // Inform grunt when we're finished. var done = this.async(); // Kick off docco and log results. exec('docco supermodel.js', function(err, stdout, stderr) { if (err) { grunt.log.error(err); return done(err.code); } grunt.log.write(stdout); done(); }); }); };
var exec = require('child_process').exec; module.exports = function(grunt) { grunt.initConfig({ qunit: ['./test/index.html'], lint: ['supermodel.js', './test/*.js'], watch: { default: { files: ['supermodel.js', 'test/index.html', 'test/**/*.js'], tasks: 'default' } }, jshint: { options: { eqnull: true, undef: true }, globals: { // QUnit ok: true, test: true, module: true, raises: true, deepEqual: true, strictEqual: true, // Dependencies _: true, jQuery: true, Backbone: true, Supermodel: true } } }); grunt.registerTask('default', 'lint qunit'); grunt.registerTask('release', 'default docco'); grunt.registerTask('docco', function() { // Inform grunt when we're finished. var done = this.async(); // Kick off docco and log results. exec('docco supermodel.js', function(err, stdout, stderr) { if (err) { grunt.log.error(err); return done(err.code); } grunt.log.write(stdout); done(); }); }); };
CRM-2906: Refresh attachment grid after click on attachment link on email
/*jslint nomen: true*/ /*global define*/ define([ 'jquery', 'underscore', 'orotranslation/js/translator', 'backbone', 'oroui/js/messenger', 'oroui/js/app/views/base/view', 'oroui/js/mediator' ], function ($, _, __, Backbone, messenger, BaseView, mediator) { 'use strict'; var EmailAttachmentLink; /** * @export oroemail/js/app/views/email-attachment-link-view */ EmailAttachmentLink = BaseView.extend({ options: {}, events: { 'click .icon-link': 'linkAttachment' }, /** * Constructor * * @param options {Object} */ initialize: function (options) { this.options = _.defaults(options || {}, this.options); EmailAttachmentLink.__super__.initialize.apply(this, arguments); }, /** * onClick event listener */ linkAttachment: function (e) { var self = this; e.preventDefault(); $.getJSON( this.options.url, {}, function (response) { if (_.isUndefined(response.error)) { messenger.notificationFlashMessage('success', __('oro.email.attachment.added')); self.reloadAttachmentGrid(); } else { messenger.notificationFlashMessage('error', __(response.error)); } } ); return false; }, reloadAttachmentGrid: function() { mediator.trigger('datagrid:doRefresh:attachment-grid'); } }); return EmailAttachmentLink; });
/*jslint nomen: true*/ /*global define*/ define([ 'jquery', 'underscore', 'orotranslation/js/translator', 'backbone', 'oroui/js/messenger', 'oroui/js/app/views/base/view' ], function ($, _, __, Backbone, messenger, BaseView) { 'use strict'; var EmailAttachmentLink; /** * @export oroemail/js/app/views/email-attachment-link-view */ EmailAttachmentLink = BaseView.extend({ options: {}, events: { 'click .icon-link': 'linkAttachment' }, /** * Constructor * * @param options {Object} */ initialize: function (options) { this.options = _.defaults(options || {}, this.options); EmailAttachmentLink.__super__.initialize.apply(this, arguments); }, /** * onClick event listener */ linkAttachment: function (e) { e.preventDefault(); $.getJSON( this.options.url, {}, function (response) { if (_.isUndefined(response.error)) { messenger.notificationFlashMessage('success', __('oro.email.attachment.added')); } else { messenger.notificationFlashMessage('error', __(response.error)); } } ); return false; } }); return EmailAttachmentLink; });
Convert currency name to currency iso code
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } static getCurrencyCode(name) { const dict = { 'US Dollar​': 'USD', 'Euro​': 'EUR', 'Pound Sterling​': 'GBP', 'Swiss Franc​': 'CHF', 'Japanese Yen 100​': 'JPY', 'Saudi Riyal​': 'SAR', 'Kuwaiti Dinar​': 'KWD', 'UAE Dirham​': 'AED', 'Chinese yuan​': 'CNY', }; return (dict[name]); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); const rates = []; tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); rates.push({ code: CBE.getCurrencyCode(currencyName), buy: currencyBuy, sell: currencySell, }); }); return rates; } }
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); }); const rates = []; return rates; } }
Update view after updating template
<?php EngineBlock_ApplicationSingleton::getInstance()->flushLog('Showing feedback page with message: ' . $layout->title); ?> <div class="l-overflow"> <table class="comp-table"> <thead></thead> <tbody> <?php if (!empty($_SESSION['feedbackInfo']) && is_array($_SESSION['feedbackInfo'])) { foreach($_SESSION['feedbackInfo'] as $name => $value) { if (empty($value)) { continue; } ?> <tr> <td class="strong"><?= EngineBlock_View::htmlSpecialCharsText($this->t($name))?>:</td> <td style="font-size: 0.8em;"><?= EngineBlock_View::htmlSpecialCharsText($value);?></td> </tr> <?php } } ?> </tbody> </table> </div> <p><?= $this->t('error_help_desc'); ?></p> <?php // @todo make the number of steps in history that the back button makes dynamic, it is not always 2 ?> <a href="#" id="GoBack" class="c-button" onclick="history.back(-2); return false;"> <?= $this->t('go_back'); ?> </a>
<?php $log = EngineBlock_ApplicationSingleton::getInstance()->getLog(); $log->log('Showing feedback page with message: ' . $layout->title, EngineBlock_Log::INFO); $log->getQueueWriter()->flush('feedback page shown'); ?> <div class="l-overflow"> <table class="comp-table"> <thead></thead> <tbody> <?php if (!empty($_SESSION['feedbackInfo']) && is_array($_SESSION['feedbackInfo'])) { foreach($_SESSION['feedbackInfo'] as $name => $value) { if (empty($value)) { continue; } ?> <tr> <td class="strong"><?= EngineBlock_View::htmlSpecialCharsText($this->t($name))?>:</td> <td style="font-size: 0.8em;"><?= EngineBlock_View::htmlSpecialCharsText($value);?></td> </tr> <?php } } ?> </tbody> </table> </div> <p><?= $this->t('error_help_desc'); ?></p> <?php // @todo make the number of steps in history that the back button makes dynamic, it is not always 2 ?> <a href="#" id="GoBack" class="c-button" onclick="history.back(-2); return false;"> <?= $this->t('go_back'); ?> </a>
Update filter. Review by @nicolaasdiebaas
from setuptools import setup, find_packages setup( name="seed-stage-based-messaging", version="0.1", url='http://github.com/praekelt/seed-stage-based-messaging', license='BSD', author='Praekelt Foundation', author_email='[email protected]', packages=find_packages(), include_package_data=True, install_requires=[ 'Django==1.9.1', 'djangorestframework==3.3.2', 'dj-database-url==0.3.0', 'psycopg2==2.6.2', 'raven==5.10.0', 'gunicorn==19.4.5', 'django-filter==0.12.0', 'dj-static==0.0.6', 'celery==3.1.19', 'django-celery==3.1.17', 'redis==2.10.5', 'pytz==2015.7', 'requests==2.9.1', 'go-http==0.3.0' ], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import setup, find_packages setup( name="seed-stage-based-messaging", version="0.1", url='http://github.com/praekelt/seed-stage-based-messaging', license='BSD', author='Praekelt Foundation', author_email='[email protected]', packages=find_packages(), include_package_data=True, install_requires=[ 'Django==1.9.1', 'djangorestframework==3.3.2', 'dj-database-url==0.3.0', 'psycopg2==2.6.1', 'raven==5.10.0', 'gunicorn==19.4.5', 'django-filter==0.12.0', 'dj-static==0.0.6', 'celery==3.1.19', 'django-celery==3.1.17', 'redis==2.10.5', 'pytz==2015.7', 'requests==2.9.1', 'go-http==0.3.0' ], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Update redis commands toTree tests
'use strict'; var RedisCommands = require('../js/service/redis-commands'), should = require('should'); describe('RedisCommands', function () { // TODO: fix RedisCommands to fit these tests describe('To tree', function () { var redisCommands = new RedisCommands(); it('Should convert basic keys to a tree', function () { var keys = [ 'abc:xyz', 'abc:ijk', 'lmn:opq' ]; var tree = redisCommands.toTree(keys); tree.should.have.ownProperty('abc'); tree.should.have.ownProperty('lmn'); tree.abc.should.have.ownProperty('isLeaf'); tree.abc.should.have.ownProperty('children'); tree.abc.isLeaf.should.not.be.ok; }); it('Should mark some nodes as leaves', function () { var keys = [ 'abc', 'abc:xyz', 'abc:ijk', 'abc:ijk:lmn', 'lmn:opq' ]; var tree = redisCommands.toTree(keys); tree.abc.isLeaf.should.be.ok; tree.abc.children.xyz.isLeaf.should.be.ok; tree.abc.children.ijk.isLeaf.should.be.ok; tree.abc.children.ijk.children.lmn.isLeaf.should.be.ok; tree.lmn.isLeaf.should.not.be.ok; tree.lmn.children.opq.isLeaf.should.be.ok; }); }); });
'use strict'; var RedisCommands = require('../js/service/redis-commands'), should = require('should'); describe('RedisCommands', function () { // TODO: fix RedisCommands to fit these tests describe('To tree', function () { var redisCommands = new RedisCommands(); it('Should convert basic keys to a tree', function () { var keys = [ 'abc:xyz', 'abc:ijk', 'lmn:opq' ]; var tree = redisCommands.toTree(keys); tree.should.have.ownProperty('isLeaf'); tree.should.have.ownProperty('children'); tree.children.should.have.ownProperty('abc'); tree.children.should.have.ownProperty('lmn'); tree.isLeaf.should.not.be.ok; }); it('Should mark some nodes as leaves', function () { var keys = [ 'abc', 'abc:xyz', 'abc:ijk', 'abc:ijk:lmn', 'lmn:opq' ]; var tree = redisCommands.toTree(keys); tree.isLeaf.should.not.be.ok; tree.children.abc.isLeaf.should.be.ok; tree.children.abc.children.xyz.isLeaf.should.be.ok; tree.children.abc.children.ijk.isLeaf.should.be.ok; tree.children.abc.children.ijk.children.lmn.isLeaf.should.be.ok; tree.children.lmn.isLeaf.should.not.be.ok; tree.children.lmn.children.opq.isLeaf.should.be.ok; }); }); });
Fix test failure in MPI
import hoomd import io import numpy def test_table_pressure(simulation_factory, two_particle_snapshot_factory): """Test that write.table can log MD pressure values.""" thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All()) snap = two_particle_snapshot_factory() if snap.communicator.rank == 0: snap.particles.velocity[:] = [[-2, 0, 0], [2, 0, 0]] sim = simulation_factory(snap) sim.operations.add(thermo) integrator = hoomd.md.Integrator(dt=0.0) integrator.methods.append( hoomd.md.methods.NVT(hoomd.filter.All(), tau=1, kT=1)) sim.operations.integrator = integrator logger = hoomd.logging.Logger(categories=['scalar']) logger.add(thermo, quantities=['pressure']) output = io.StringIO("") table_writer = hoomd.write.Table(1, logger, output) sim.operations.writers.append(table_writer) sim.run(1) ideal_gas_pressure = (2 * thermo.translational_kinetic_energy / 3 / sim.state.box.volume) if sim.device.communicator.rank == 0: output_lines = output.getvalue().split('\n') numpy.testing.assert_allclose(float(output_lines[1]), ideal_gas_pressure, rtol=0.2)
import hoomd import io import numpy def test_table_pressure(simulation_factory, two_particle_snapshot_factory): """Test that write.table can log MD pressure values.""" thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All()) snap = two_particle_snapshot_factory() if snap.communicator.rank == 0: snap.particles.velocity[:] = [[-2, 0, 0], [2, 0, 0]] sim = simulation_factory(snap) sim.operations.add(thermo) integrator = hoomd.md.Integrator(dt=0.0) integrator.methods.append( hoomd.md.methods.NVT(hoomd.filter.All(), tau=1, kT=1)) sim.operations.integrator = integrator logger = hoomd.logging.Logger(categories=['scalar']) logger.add(thermo, quantities=['pressure']) output = io.StringIO("") table_writer = hoomd.write.Table(1, logger, output) sim.operations.writers.append(table_writer) sim.run(1) output_lines = output.getvalue().split('\n') ideal_gas_pressure = (2 * thermo.translational_kinetic_energy / 3 / sim.state.box.volume) numpy.testing.assert_allclose(float(output_lines[1]), ideal_gas_pressure, rtol=0.2)
Fix 1010 upgrade step (setBatchID -> setBatch)
import logging from Acquisition import aq_base from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def addBatches(tool): """ """ portal = aq_parent(aq_inner(tool)) portal_catalog = getToolByName(portal, 'portal_catalog') setup = portal.portal_setup # reimport Types Tool to add BatchFolder and Batch setup.runImportStepFromProfile('profile-bika.lims:default', 'typeinfo') # reimport Workflows to add bika_batch_workflow setup.runImportStepFromProfile('profile-bika.lims:default', 'workflow') typestool = getToolByName(portal, 'portal_types') workflowtool = getToolByName(portal, 'portal_workflow') # Add the BatchFolder at /batches typestool.constructContent(type_name="BatchFolder", container=portal, id='batches', title='Batches') obj = portal['batches'] obj.unmarkCreationFlag() obj.reindexObject() # and place it after ClientFolder portal.moveObjectToPosition('batches', portal.objectIds().index('clients')) # add Batch to all AnalysisRequest objects. # When the objects are reindexed, BatchUID will also be populated proxies = portal_catalog(portal_type="AnalysiRequest") ars = (proxy.getObject() for proxy in proxies) for ar in ars: ar.setBatch(None) return True
import logging from Acquisition import aq_base from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def addBatches(tool): """ """ portal = aq_parent(aq_inner(tool)) portal_catalog = getToolByName(portal, 'portal_catalog') setup = portal.portal_setup # reimport Types Tool to add BatchFolder and Batch setup.runImportStepFromProfile('profile-bika.lims:default', 'typeinfo') # reimport Workflows to add bika_batch_workflow setup.runImportStepFromProfile('profile-bika.lims:default', 'workflow') typestool = getToolByName(portal, 'portal_types') workflowtool = getToolByName(portal, 'portal_workflow') # Add the BatchFolder at /batches typestool.constructContent(type_name="BatchFolder", container=portal, id='batches', title='Batches') obj = portal['batches'] obj.unmarkCreationFlag() obj.reindexObject() # and place it after ClientFolder portal.moveObjectToPosition('batches', portal.objectIds().index('clients')) # add BatchID to all AnalysisRequest objects. # When the objects are reindexed, BatchUID will also be populated proxies = portal_catalog(portal_type="AnalysiRequest") ars = (proxy.getObject() for proxy in proxies) for ar in ars: ar.setBatchID(None) return True
tools/scyllatop: Use 'erase' to clear the screen The 'clear' function explicitly clears the screen and repaints it which causes really annoying flicker. Use 'erase' to make scyllatop more pleasant on the eyes. Message-Id: <[email protected]>
import time import curses import curses.panel import logging class Base(object): def __init__(self, window): lines, columns = window.getmaxyx() self._window = curses.newwin(lines, columns) self._panel = curses.panel.new_panel(self._window) def writeStatusLine(self, measurements): line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines()) columns = self.dimensions()['columns'] self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE) def availableLines(self): STATUS_LINE = 1 return self.dimensions()['lines'] - STATUS_LINE def refresh(self): curses.panel.update_panels() curses.doupdate() def onTop(self): logging.info('put {0} view on top'.format(self.__class__.__name__)) self._panel.top() curses.panel.update_panels() curses.doupdate() def clearScreen(self): self._window.erase() self._window.move(0, 0) def writeLine(self, thing, line): self._window.addstr(line, 0, str(thing)) def dimensions(self): lines, columns = self._window.getmaxyx() return {'lines': lines, 'columns': columns}
import time import curses import curses.panel import logging class Base(object): def __init__(self, window): lines, columns = window.getmaxyx() self._window = curses.newwin(lines, columns) self._panel = curses.panel.new_panel(self._window) def writeStatusLine(self, measurements): line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines()) columns = self.dimensions()['columns'] self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE) def availableLines(self): STATUS_LINE = 1 return self.dimensions()['lines'] - STATUS_LINE def refresh(self): curses.panel.update_panels() curses.doupdate() def onTop(self): logging.info('put {0} view on top'.format(self.__class__.__name__)) self._panel.top() curses.panel.update_panels() curses.doupdate() def clearScreen(self): self._window.clear() self._window.move(0, 0) def writeLine(self, thing, line): self._window.addstr(line, 0, str(thing)) def dimensions(self): lines, columns = self._window.getmaxyx() return {'lines': lines, 'columns': columns}
Update management command for various changes
from django.core.management.base import BaseCommand from django.db.models import Prefetch from mla_game.apps.transcript.tasks import update_transcript_stats from ...models import ( Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection, ) class Command(BaseCommand): help = '''Find all Transcripts with votes or corrections and update stats for that transcript''' def handle(self, *args, **options): eligible_transcripts = set() transcript_qs = Transcript.objects.only('pk') votes = TranscriptPhraseVote.objects.filter( upvote__in=[True, False] ).prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) corrections = TranscriptPhraseCorrection.objects.all().prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) eligible_transcripts.update( [vote.transcript_phrase.transcript.pk for vote in votes] ) eligible_transcripts.update( [correction.transcript_phrase.transcript.pk for correction in corrections] ) transcripts_to_process = Transcript.objects.filter( pk__in=eligible_transcripts).only('pk') for transcript in transcripts_to_process: update_transcript_stats(transcript)
from django.core.management.base import BaseCommand from django.db.models import Prefetch from mla_game.apps.transcript.tasks import update_transcript_stats from ...models import ( Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection, ) class Command(BaseCommand): help = '''Find all Transcripts with votes or corrections and update stats for that transcript''' def handle(self, *args, **options): eligible_transcripts = set() transcript_qs = Transcript.objects.only('pk') downvotes = TranscriptPhraseVote.objects.filter( upvote=False ).prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) upvotes = TranscriptPhraseCorrection.objects.all().prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) eligible_transcripts.update( [vote.transcript_phrase.transcript.pk for vote in downvotes] ) eligible_transcripts.update( [vote.transcript_phrase.transcript.pk for vote in upvotes] ) transcripts_to_process = Transcript.objects.filter( pk__in=eligible_transcripts).only('pk') for transcript in transcripts_to_process: update_transcript_stats(transcript)
Fix className var in initDefinition
var checkValidator = function( validator, fieldName, className ) { if (!Match.test( validator, Match.OneOf(Astro.FieldValidator, [Astro.FieldValidator]) )) { throw new TypeError( 'The validator for the "' + fieldName + '" field in the "' + className + '" class schema has to be a ' + 'function, an array of validators or a single validator' ); } }; Astro.eventManager.on( 'initDefinition', function onInitDefinitionValidators(schemaDefinition) { var className = schemaDefinition.name; var validators = {}; if (_.has(schemaDefinition, 'fields')) { _.each(schemaDefinition.fields, function(fieldDefinition, fieldName) { if (_.has(fieldDefinition, 'validator')) { var validator = fieldDefinition.validator; if (_.isArray(validator)) { validator = Validators.and(validator); } if (validator) { // Check validity of the validator definition. checkValidator(validator, fieldName, className); validators[fieldName] = validator; } } }); } if (_.has(schemaDefinition, 'validators')) { _.each(schemaDefinition.validators, function(validator, fieldName) { var validator; if (_.isArray(validator)) { validator = Validators.and(validator); } if (validator) { // Check validity of the validator definition. checkValidator(validator, fieldName, className); validators[fieldName] = validator; } }); } schemaDefinition.validators = validators; } );
var checkValidator = function( validator, fieldName, className ) { if (!Match.test( validator, Match.OneOf(Astro.FieldValidator, [Astro.FieldValidator]) )) { throw new TypeError( 'The validator for the "' + fieldName + '" field in the "' + className + '" class schema has to be a ' + 'function, an array of validators or a single validator' ); } }; Astro.eventManager.on( 'initDefinition', function onInitDefinitionValidators(schemaDefinition) { var className = schemaDefinition.className; var validators = {}; if (_.has(schemaDefinition, 'fields')) { _.each(schemaDefinition.fields, function(fieldDefinition, fieldName) { if (_.has(fieldDefinition, 'validator')) { var validator = fieldDefinition.validator; if (_.isArray(validator)) { validator = Validators.and(validator); } if (validator) { // Check validity of the validator definition. checkValidator(validator, fieldName, className); validators[fieldName] = validator; } } }); } if (_.has(schemaDefinition, 'validators')) { _.each(schemaDefinition.validators, function(validator, fieldName) { var validator; if (_.isArray(validator)) { validator = Validators.and(validator); } if (validator) { // Check validity of the validator definition. checkValidator(validator, fieldName, className); validators[fieldName] = validator; } }); } schemaDefinition.validators = validators; } );
Allow new user AJAX call to accept HTTP status code instead of manual code
angular.module('dataGoMain') .controller('WelcomeController', ['$scope', '$http', 'dataGoAPI', '$rootScope',function($scope, $http, dataGoAPI, $rootScope){ console.log('in HomeCtrl'); $scope.registerUser = registerUser; $scope.loginEmail = ''; $scope.loginPassword = ''; $scope.registrationError = {"username" : false}; function registerUser() { console.log('inside registerUser within welcomeController.js') var data = {email: $scope.email, password: $scope.password} dataGoAPI.registerNewUser(data) .success(function (response) { if(response.token) { $rootScope.login($scope.email,$scope.password); } else if(response.code === 0) { $scope.registrationError.username = response.message; } }) .error (function(response) { console.log(response) }) } }]);
angular.module('dataGoMain') .controller('WelcomeController', ['$scope', '$http', 'dataGoAPI', '$rootScope',function($scope, $http, dataGoAPI, $rootScope){ console.log('in HomeCtrl'); $scope.registerUser = registerUser; $scope.loginEmail = ''; $scope.loginPassword = ''; $scope.registrationError = {"username" : false}; function registerUser() { console.log('inside registerUser within welcomeController.js') var data = {email: $scope.email, password: $scope.password} dataGoAPI.registerNewUser(data) .success(function (response) { if(response.code === 1) { $rootScope.login($scope.email,$scope.password); } else if(response.code === 0) { $scope.registrationError.username = response.message; } }) .error (function(response) { console.log(response) }) } }]);
Add a proper License PyPI classifier
import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a youtube mashup video in a list of tagged audio files', long_description=readme, author=u'Balthazar Rouberol', author_email=u'[email protected]', license='License :: OSI Approved :: MIT License', packages=['mashdown'], install_requires=['pydub', 'pafy', 'mutagen'], entry_points={ 'console_scripts': ['mashdown=main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Sound/Audio :: Conversion', 'Topic :: Multimedia :: Video :: Conversion' ], zip_safe=False, )
import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a youtube mashup video in a list of tagged audio files', long_description=readme, author=u'Balthazar Rouberol', author_email=u'[email protected]', license='License :: OSI Approved :: MIT License', packages=['mashdown'], install_requires=['pydub', 'pafy', 'mutagen'], entry_points={ 'console_scripts': ['mashdown=main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: TODO', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Sound/Audio :: Conversion', 'Topic :: Multimedia :: Video :: Conversion' ], zip_safe=False, )
Add utility method to check between the two different publish message forms
package de.innoaccel.wamp.server.message; import java.util.List; public class PublishMessage implements Message { private String topicURI; private Object event; private boolean excludeMe; private List<String> exclude; private List<String> eligable; public PublishMessage(String topicURI, Object event) { this(topicURI, event, false); } public PublishMessage(String topicURI, Object event, boolean excludeMe) { this(topicURI, event, excludeMe, null, null); } public PublishMessage(String topicURI, Object event, List<String> exclude, List<String> eligable) { this(topicURI, event, false, exclude, eligable); } private PublishMessage(String topicURI, Object event, boolean excludeMe, List<String> exclude, List<String> eligable) { this.topicURI = topicURI; this.event = event; this.excludeMe = excludeMe; this.exclude = exclude; this.eligable = eligable; } @Override public int getMessageCode() { return Message.PUBLISH; } public String getTopicURI() { return this.topicURI; } public Object getEvent() { return event; } public boolean excludeMe() { return excludeMe; } public List<String> getExclude() { return exclude; } public List<String> getEligable() { return eligable; } public boolean isTargeted() { return (null != this.exclude || null != this.eligable); } }
package de.innoaccel.wamp.server.message; import java.util.List; public class PublishMessage implements Message { private String topicURI; private Object event; private boolean excludeMe; private List<String> exclude; private List<String> eligable; public PublishMessage(String topicURI, Object event) { this(topicURI, event, false); } public PublishMessage(String topicURI, Object event, boolean excludeMe) { this(topicURI, event, excludeMe, null, null); } public PublishMessage(String topicURI, Object event, List<String> exclude, List<String> eligable) { this(topicURI, event, false, exclude, eligable); } private PublishMessage(String topicURI, Object event, boolean excludeMe, List<String> exclude, List<String> eligable) { this.topicURI = topicURI; this.event = event; this.excludeMe = excludeMe; this.exclude = exclude; this.eligable = eligable; } @Override public int getMessageCode() { return Message.PUBLISH; } public String getTopicURI() { return this.topicURI; } public Object getEvent() { return event; } public boolean excludeMe() { return excludeMe; } public List<String> getExclude() { return exclude; } public List<String> getEligable() { return eligable; } }
Replace getPage() with getPageOrRoot() to make tests work again
<?php class Kwf_Component_View_Helper_ComponentWithMaster extends Kwf_Component_View_Helper_Component { public function componentWithMaster(array $componentWithMaster) { $last = array_pop($componentWithMaster); $component = $last['data']; if ($last['type'] == 'master') { $innerComponent = $componentWithMaster[0]['data']; $vars = array(); $vars['component'] = $innerComponent; $vars['data'] = $innerComponent; $vars['componentWithMaster'] = $componentWithMaster; $vars['cssClass'] = Kwc_Abstract::getCssClass($component->componentClass); $vars['boxes'] = array(); foreach ($innerComponent->getPageOrRoot()->getChildBoxes() as $box) { $vars['boxes'][$box->box] = $box; } $view = new Kwf_Component_View($this->_getRenderer()); $view->assign($vars); return $view->render($this->_getRenderer()->getTemplate($component, 'Master')); } else if ($last['type'] == 'component') { $plugins = self::_getGroupedViewPlugins($component->componentClass); return '<div class="kwfMainContent" style="width: ' . $component->getComponent()->getContentWidth() . 'px">' . "\n " . $this->_getRenderPlaceholder($component->componentId, array(), null, 'component', $plugins) . "\n" . '</div>' . "\n"; } else { throw new Kwf_Exception("invalid type"); } } }
<?php class Kwf_Component_View_Helper_ComponentWithMaster extends Kwf_Component_View_Helper_Component { public function componentWithMaster(array $componentWithMaster) { $last = array_pop($componentWithMaster); $component = $last['data']; if ($last['type'] == 'master') { $innerComponent = $componentWithMaster[0]['data']; $vars = array(); $vars['component'] = $innerComponent; $vars['data'] = $innerComponent; $vars['componentWithMaster'] = $componentWithMaster; $vars['cssClass'] = Kwc_Abstract::getCssClass($component->componentClass); $vars['boxes'] = array(); foreach ($innerComponent->getPage()->getChildBoxes() as $box) { $vars['boxes'][$box->box] = $box; } $view = new Kwf_Component_View($this->_getRenderer()); $view->assign($vars); return $view->render($this->_getRenderer()->getTemplate($component, 'Master')); } else if ($last['type'] == 'component') { $plugins = self::_getGroupedViewPlugins($component->componentClass); return '<div class="kwfMainContent" style="width: ' . $component->getComponent()->getContentWidth() . 'px">' . "\n " . $this->_getRenderPlaceholder($component->componentId, array(), null, 'component', $plugins) . "\n" . '</div>' . "\n"; } else { throw new Kwf_Exception("invalid type"); } } }
Sort on imdb rating if filmtipset ratings are the same.
from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) movie_data = sorted(movie_data, key=lambda data: (data.get("filmtipset_my_grade", 0), data.get("imdb_rating", 0)), reverse=True) return movie_data def output(self, movie_data): movie_data = self.process_data(movie_data) print() for data in movie_data[:10]: print("%s (Filmtipset: %s, IMDB: %s)" % ( data["title"], data.get("filmtipset_my_grade", "-"), data.get("imdb_rating", "-"), )) print(" [Genre: %s, Country: %s, Year: %s]" % ( ", ".join(data.get("genre", "-")), data.get("country", "-"), data.get("year", "-"), )) plot = data.get("plot", None) if plot: text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent=" ", subsequent_indent=" ") print("\n".join(text)) print()
from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) movie_data = sorted(movie_data, key=lambda data: data.get("filmtipset_my_grade", 0), reverse=True) return movie_data def output(self, movie_data): movie_data = self.process_data(movie_data) print() for data in movie_data[:10]: print("%s (Filmtipset: %s, IMDB: %s)" % ( data["title"], data.get("filmtipset_my_grade", "-"), data.get("imdb_rating", "-"), )) print(" [Genre: %s, Country: %s, Year: %s]" % ( ", ".join(data.get("genre", "-")), data.get("country", "-"), data.get("year", "-"), )) plot = data.get("plot", None) if plot: text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent=" ", subsequent_indent=" ") print("\n".join(text)) print()
Update namespaces for beta 8 Refs flarum/core#1235.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Auth\Twitter\Listener; use Flarum\Frontend\Event\Rendering; use Illuminate\Contracts\Events\Dispatcher; class AddClientAssets { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(Rendering::class, [$this, 'addAssets']); } /** * @param Rendering $event */ public function addAssets(Rendering $event) { if ($event->isForum()) { $event->addAssets([ __DIR__.'/../../js/forum/dist/extension.js', __DIR__.'/../../less/forum/extension.less' ]); $event->addBootstrapper('flarum/auth/twitter/main'); } if ($event->isAdmin()) { $event->addAssets([ __DIR__.'/../../js/admin/dist/extension.js' ]); $event->addBootstrapper('flarum/auth/twitter/main'); } } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Auth\Twitter\Listener; use Flarum\Event\ConfigureWebApp; use Illuminate\Contracts\Events\Dispatcher; class AddClientAssets { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(ConfigureWebApp::class, [$this, 'addAssets']); } /** * @param ConfigureClientView $event */ public function addAssets(ConfigureWebApp $event) { if ($event->isForum()) { $event->addAssets([ __DIR__.'/../../js/forum/dist/extension.js', __DIR__.'/../../less/forum/extension.less' ]); $event->addBootstrapper('flarum/auth/twitter/main'); } if ($event->isAdmin()) { $event->addAssets([ __DIR__.'/../../js/admin/dist/extension.js' ]); $event->addBootstrapper('flarum/auth/twitter/main'); } } }
Allow Connection.send to take unicode message
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" self.send('USER meshybot 0 * :MeshyBot7') self.send('NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" # Cast to bytes try: message = message.encode() except AttributeError: pass # Add line ending. message = message + b'\r\n' print('write', message) self.writer.write(message)
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" self.send(b'USER meshybot 0 * :MeshyBot7') self.send(b'NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" message = message + b'\r\n' print('write', message) self.writer.write(message)
Fix in CPU requirement naming
/** * Author: Milica Kadic * Date: 2/3/15 * Time: 3:03 PM */ 'use strict'; angular.module('registryApp.cliche') .constant('rawJob', { inputs: {}, allocatedResources: { cpu: 0, mem: 0 } }) .constant('rawTool', { 'id': '', 'class': 'CommandLineTool', '@context': 'https://github.com/common-workflow-language/common-workflow-language/blob/draft-1/specification/tool-description.md', label: '', description: '', owner: [], contributor: [], requirements: [ { 'class': 'DockerRequirement', imgRepo: '', imgTag: '', imgId: '' }, { 'class': 'CPURequirement', value: 1 }, { 'class': 'MemRequirement', value: 1000 } ], inputs: [], outputs: [], //moved CLI adapter to root baseCommand: [''], stdin: '', stdout: '', argAdapters: [] }) .constant('rawTransform', { 'class': 'Expression', engine: '#cwl-js-engine', script: '' });
/** * Author: Milica Kadic * Date: 2/3/15 * Time: 3:03 PM */ 'use strict'; angular.module('registryApp.cliche') .constant('rawJob', { inputs: {}, allocatedResources: { cpu: 0, mem: 0 } }) .constant('rawTool', { 'id': '', 'class': 'CommandLineTool', '@context': 'https://github.com/common-workflow-language/common-workflow-language/blob/draft-1/specification/tool-description.md', label: '', description: '', owner: [], contributor: [], requirements: [ { 'class': 'DockerRequirement', imgRepo: '', imgTag: '', imgId: '' }, { 'class': 'CpuRequirement', value: 500 }, { 'class': 'MemRequirement', value: 1000 } ], inputs: [], outputs: [], //moved CLI adapter to root baseCommand: [''], stdin: '', stdout: '', argAdapters: [] }) .constant('rawTransform', { 'class': 'Expression', engine: '#cwl-js-engine', script: '' });
Use interface TestListener instead of deprecated abstract class BaseTestListener
<?php namespace { use PHPUnit\Framework\TestListener; use PHPUnit\Framework\TestListenerDefaultImplementation; use PHPUnit\Framework\TestSuite; use Symfony\Component\Process\Process; final class PhpUnitStartServerListener implements TestListener { use TestListenerDefaultImplementation; /** * @var string */ private $suiteName; /** * @var string */ private $socket; /** * @var string */ private $documentRoot; /** * PhpUnitStartServerListener constructor. * * @param string $suiteName * @param string $socket * @param string $documentRoot */ public function __construct(string $suiteName, string $socket, string $documentRoot) { $this->suiteName = $suiteName; $this->socket = $socket; $this->documentRoot = $documentRoot; } /** * @inheritdoc */ public function startTestSuite(TestSuite $suite): void { if ($suite->getName() === $this->suiteName) { $process = new Process( sprintf( 'php -S %s %s', $this->socket, $this->documentRoot ) ); $process->start(); // Wait for the server. sleep(1); } } } }
<?php namespace { use PHPUnit\Framework\BaseTestListener; use PHPUnit\Framework\TestSuite; use Symfony\Component\Process\Process; final class PhpUnitStartServerListener extends BaseTestListener { /** * @var string */ private $suiteName; /** * @var string */ private $socket; /** * @var string */ private $documentRoot; /** * PhpUnitStartServerListener constructor. * * @param string $suiteName * @param string $socket * @param string $documentRoot */ public function __construct(string $suiteName, string $socket, string $documentRoot) { $this->suiteName = $suiteName; $this->socket = $socket; $this->documentRoot = $documentRoot; } /** * @inheritdoc */ public function startTestSuite(TestSuite $suite): void { parent::startTestSuite($suite); if ($suite->getName() === $this->suiteName) { $process = new Process( sprintf( 'php -S %s %s', $this->socket, $this->documentRoot ) ); $process->start(); // Wait for the server. sleep(1); } } } }
Fix bad reference to host node Also store the host as a instance property to avoid calling into Attribute every scroll
/*jshint browser:true, yui:true */ YUI.add("plugin-lazy-images", function(Y) { "use strict"; var plugins = Y.namespace("Plugins"), LazyImages; LazyImages = Y.Base.create("lazyImages", Y.Plugin.Base, [], { // Y.Base lifecycle fns initializer : function() { var host = this.get("host"); host.plug(Y.Plugin.ScrollInfo, { scrollMargin : this.get("distance") }); this._handles = [ host.scrollInfo.after([ "scrollDown", "scrollUp" ], this.loadVisible, this) ]; this._host = host; }, destructor : function() { this.get("host").unplug(Y.Plugin.ScrollInfo); new Y.EventTarget(this._handles).detach(); this._handles = this._host = null; }, // Public API loadVisible : function() { this._host.scrollInfo.getOnscreenNodes("[data-src]").each(function(img) { img.set("src", img.getData("src")); img.removeAttribute("data-src"); }); } }, { NS : "lazyimg", ATTRS : { distance : { value : 100 } } }); plugins.LazyImages = LazyImages; }, "@VERSION@", { requires : [ // YUI "base-build", "plugin", "node-scroll-info" ] });
/*jshint browser:true, yui:true */ YUI.add("plugin-lazy-images", function(Y) { "use strict"; var plugins = Y.namespace("Plugins"), LazyImages; LazyImages = Y.Base.create("lazyImages", Y.Plugin.Base, [], { // Y.Base lifecycle fns initializer : function() { var host = this.get("host"); host.plug(Y.Plugin.ScrollInfo, { scrollMargin : this.get("distance") }); this._handles = [ host.scrollInfo.after([ "scrollDown", "scrollUp" ], this.loadVisible, this) ]; }, destructor : function() { this.get("host").unplug(Y.Plugin.ScrollInfo); new Y.EventTarget(this._handles).detach(); this._handles = null; }, // Public API loadVisible : function() { host.scrollInfo.getOnscreenNodes("[data-src]").each(function(img) { img.set("src", img.getData("src")); img.removeAttribute("data-src"); }); } }, { NS : "lazyimg", ATTRS : { distance : { value : 100 } } }); plugins.LazyImages = LazyImages; }, "@VERSION@", { requires : [ // YUI "base-build", "plugin", "node-scroll-info" ] });
FIx bug when the dep names regexp doesn't have a match
(function (ng) { 'use strict'; /** * Angular.js utility for cleaner dependency injection. */ var $inject = function (cls, self, args) { var i; var key; var str; var func; var depNames = []; var deps = []; var l = cls.$inject.length; // Inject all dependencies into the self reference. for (i = 0; i < l; i++) { key = '_' + cls.$inject[i]; self[key] = args[i]; } for (key in cls.prototype) { if (typeof cls.prototype[key] === 'function') { func = cls.prototype[key]; str = func.toString(); // List of dependencies. depNames = str.match(/\/\*\s*\$inject:([^*]+)/); // Skip methods without the $inject comment. if (!depNames || depNames.length < 2) continue; depNames = depNames[1].split(','); // Map the dependency names to the actual dependencies. args = depNames.map(function (name) { return self['_' + name.trim()]; }); // Add the "this" value to the arguments list. args.unshift(func); self[key] = func.bind.apply(func, args); } } }; var $injectService = function () { return $inject; }; ng.module('cg.inject', []) .factory('$inject', $injectService); })(angular);
(function (ng) { 'use strict'; /** * Angular.js utility for cleaner dependency injection. */ var $inject = function (cls, self, args) { var i; var key; var str; var func; var depNames = []; var deps = []; var l = cls.$inject.length; // Inject all dependencies into the self reference. for (i = 0; i < l; i++) { key = '_' + cls.$inject[i]; self[key] = args[i]; } for (key in cls.prototype) { if (typeof cls.prototype[key] === 'function') { func = cls.prototype[key]; str = func.toString(); // List of dependencies. depNames = str.match(/\/\*\s*\$inject:([^*]+)/); // Skip methods without the $inject comment. if (depNames && depNames.length < 2) continue; depNames = depNames[1].split(','); // Map the dependency names to the actual dependencies. args = depNames.map(function (name) { return self['_' + name.trim()]; }); // Add the "this" value to the arguments list. args.unshift(func); self[key] = func.bind.apply(func, args); } } }; var $injectService = function () { return $inject; }; ng.module('cg.inject', []) .factory('$inject', $injectService); })(angular);
Use the git status command for building the files-list
<?php namespace GrumPHP\Locator; use GitElephant\Repository; use GitElephant\Status\Status; use GitElephant\Status\StatusFile; /** * Class Git * * @package GrumPHP\Locator */ class ChangedFiles implements LocatorInterface { const PATTERN_ALL = '/(.*)/'; const PATTERN_PHP = '/(.*)\.php$/i'; /** * @var string */ protected $gitDir; /** * @var Status */ protected $status; /** * @param $gitDir */ public function __construct($gitDir) { $this->gitDir = $gitDir; } /** * @return Status */ public function getStatus() { if (!$this->status) { $repository = Repository::open($this->gitDir); $this->status = $repository->getStatus(); } return $this->status; } /** * @param $pattern * * @return array|void */ public function locate($pattern = self::PATTERN_ALL) { $status = $this->getStatus(); $status->all(); /** @var StatusFile $file */ foreach ($status->all() as $file) { // Skip untracked and deleted files: if (in_array($file->getType(), [StatusFile::UNTRACKED, StatusFile::DELETED])) { continue; } // Validate path with a pattern. $path = $file->getName(); if (!preg_match($pattern, $path)) { continue; } $files[] = $path; } return $files; } }
<?php namespace GrumPHP\Locator; use GitElephant\Objects\Diff\Diff; use GitElephant\Objects\Diff\DiffObject; use GitElephant\Repository; /** * Class Git * * @package GrumPHP\Locator */ class ChangedFiles implements LocatorInterface { const PATTERN_ALL = '/(.*)/'; const PATTERN_PHP = '/(.*)\.php$/i'; /** * @var string */ protected $gitDir; /** * @var Diff */ protected $diff; /** * @param $gitDir */ public function __construct($gitDir) { $this->gitDir = $gitDir; } /** * @return Diff */ public function getDiff() { if (!$this->diff) { $repository = Repository::open($this->gitDir); $this->diff = $repository->getDiff(); } return $this->diff; } /** * @param $pattern * * @return array|void */ public function locate($pattern = self::PATTERN_ALL) { $diff = $this->getDiff(); $files = array(); /** @var DiffObject $change */ foreach ($diff as $change) { $path = $change->hasPathChanged() ? $change->getDestinationPath() : $change->getOriginalPath(); if (!preg_match($pattern, $path)) { continue; } $files[] = $path; } return $files; } }
Return the function again from the hook decorator The decorator variant of hook registration did not return anything, meaning that the decorated function would end up being `None`. This was not noticed, as the functions are rarely called manually, as opposed to being invoked via the hook.
from django.conf import settings try: from importlib import import_module except ImportError: # for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7) from django.utils.importlib import import_module _hooks = {} def register(hook_name, fn=None): """ Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_name', my_hook) """ # Pretend to be a decorator if fn is not supplied if fn is None: def decorator(fn): register(hook_name, fn) return fn return decorator if hook_name not in _hooks: _hooks[hook_name] = [] _hooks[hook_name].append(fn) _searched_for_hooks = False def search_for_hooks(): global _searched_for_hooks if not _searched_for_hooks: for app_module in settings.INSTALLED_APPS: try: import_module('%s.wagtail_hooks' % app_module) except ImportError: continue _searched_for_hooks = True def get_hooks(hook_name): search_for_hooks() return _hooks.get(hook_name, [])
from django.conf import settings try: from importlib import import_module except ImportError: # for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7) from django.utils.importlib import import_module _hooks = {} def register(hook_name, fn=None): """ Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_name', my_hook) """ # Pretend to be a decorator if fn is not supplied if fn is None: return lambda fn: register(hook_name, fn) if hook_name not in _hooks: _hooks[hook_name] = [] _hooks[hook_name].append(fn) _searched_for_hooks = False def search_for_hooks(): global _searched_for_hooks if not _searched_for_hooks: for app_module in settings.INSTALLED_APPS: try: import_module('%s.wagtail_hooks' % app_module) except ImportError: continue _searched_for_hooks = True def get_hooks(hook_name): search_for_hooks() return _hooks.get(hook_name, [])
Update LinkedIn PYMK script to work with new page Addresses https://greasyfork.org/en/forum/discussion/27748/missing-url
// ==UserScript== // @name LinkedIn hide email contacts from "People You May Know" // @namespace http://mathemaniac.org // @version 1.2.0 // @description Hides those annoying email contacts from PYMK // @match https://www.linkedin.com/mynetwork* // @copyright 2015-2017, Sebastian Paaske Tørholm // @require https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js // ==/UserScript== $(function () { $('.mn-pymk-list__card:has(.mn-person-info__guest-handle)').remove(); // Remove when autoloading new ones var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; var config = { childList: true, characterData: false, attributes: false, subtree: true }; var observer = new MutationObserver( function (mutations) { mutations.forEach( function (mutation) { if (mutation.addedNodes) { $(mutation.addedNodes).each( function () { if ($(this).hasClass('mn-person-info__guest-handle')) { console.log("removing card for ", $(this).text()); $(this).parents('.mn-pymk-list__card').remove(); } } ); } }); }); $('.mn-pymk-list__cards').each( function () { observer.observe(this, config); } ); });
// ==UserScript== // @name LinkedIn hide email contacts from "People You May Know" // @namespace http://mathemaniac.org // @version 1.1.0 // @description Hides those annoying email contacts from PYMK // @match http://www.linkedin.com/people/pymk* // @match https://www.linkedin.com/people/pymk* // @copyright 2015, Sebastian Paaske Tørholm // @require https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js // ==/UserScript== $(function () { $('ul.people-cards-list li[id*="@"]').remove(); // Remove when autoloading new ones var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; var config = { childList: true, characterData: false, attributes: false, subtree: true }; var observer = new MutationObserver( function (mutations) { mutations.forEach( function (mutation) { if (mutation.addedNodes) { $(mutation.addedNodes).each( function () { if ($(this).attr('id').match(/card-.*@.*/)) { console.log("removing ", $(this).attr('id')); $(this).remove(); } } ); } }); }); $('ul.people-cards-list').each( function () { observer.observe(this, config); } ); });
Add classifier for Python 3.7.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="django-pgallery", version=__import__("pgallery").__version__, description="Photo gallery app for PostgreSQL and Django.", long_description=read("README.rst"), author="Zbigniew Siciarz", author_email="[email protected]", url="https://github.com/zsiciarz/django-pgallery", download_url="https://pypi.python.org/pypi/django-pgallery", license="MIT", install_requires=[ "Django>=2.0,<3.0", "Pillow", "psycopg2>=2.5", "django-markitup>=3.5", "django-model-utils>=4.0", ], packages=find_packages(exclude=["tests"]), include_package_data=True, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Utilities", ], )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="django-pgallery", version=__import__("pgallery").__version__, description="Photo gallery app for PostgreSQL and Django.", long_description=read("README.rst"), author="Zbigniew Siciarz", author_email="[email protected]", url="https://github.com/zsiciarz/django-pgallery", download_url="https://pypi.python.org/pypi/django-pgallery", license="MIT", install_requires=[ "Django>=2.0,<3.0", "Pillow", "psycopg2>=2.5", "django-markitup>=3.5", "django-model-utils>=4.0", ], packages=find_packages(exclude=["tests"]), include_package_data=True, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Topic :: Utilities", ], )
Add whitespace to trigger travis
from setuptools import setup, find_packages, Command version = __import__('eemeter').get_version() long_description = "Standard methods for calculating energy efficiency savings." class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess import sys errno = subprocess.call([sys.executable, 'runtests.py', '--runslow', '--cov=eemeter']) raise SystemExit(errno) setup(name='eemeter', version=version, description='Open Energy Efficiency Meter', long_description=long_description, url='https://github.com/impactlab/eemeter/', author='Matt Gee, Phil Ngo, Eric Potash', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], cmdclass = {'test': PyTest}, keywords='open energy efficiency meter method methods calculation savings', packages=find_packages(), install_requires=['pint', 'pyyaml', 'scipy', 'numpy', 'pandas', 'requests', 'pytz'], package_data={'': ['*.json','*.gz']}, )
from setuptools import setup, find_packages, Command version = __import__('eemeter').get_version() long_description = "Standard methods for calculating energy efficiency savings." class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess import sys errno = subprocess.call([sys.executable, 'runtests.py', '--runslow', '--cov=eemeter']) raise SystemExit(errno) setup(name='eemeter', version=version, description='Open Energy Efficiency Meter', long_description=long_description, url='https://github.com/impactlab/eemeter/', author='Matt Gee, Phil Ngo, Eric Potash', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], cmdclass = {'test': PyTest}, keywords='open energy efficiency meter method methods calculation savings', packages=find_packages(), install_requires=['pint', 'pyyaml', 'scipy', 'numpy', 'pandas', 'requests', 'pytz'], package_data={'': ['*.json','*.gz']}, )
Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@326640 91177308-0d34-0410-b5e6-96231b3b80d8
"""Test that the clang modules cache directory can be controlled.""" from __future__ import print_function import unittest2 import os import time import platform import shutil import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ObjCModulesTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) @skipUnlessDarwin def test_expr(self): self.build() self.main_source_file = lldb.SBFileSpec("main.m") self.runCmd("settings set target.auto-import-clang-modules true") mod_cache = self.getBuildArtifact("my-clang-modules-cache") if os.path.isdir(mod_cache): shutil.rmtree(mod_cache) self.assertFalse(os.path.isdir(mod_cache), "module cache should not exist") self.runCmd('settings set clang.modules-cache-path "%s"' % mod_cache) self.runCmd('settings set target.clang-module-search-paths "%s"' % self.getSourceDir()) (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( self, "Set breakpoint here", self.main_source_file) self.runCmd("expr @import Foo") self.assertTrue(os.path.isdir(mod_cache), "module cache exists")
"""Test that the clang modules cache directory can be controlled.""" from __future__ import print_function import unittest2 import os import time import platform import shutil import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ObjCModulesTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) def test_expr(self): self.build() self.main_source_file = lldb.SBFileSpec("main.m") self.runCmd("settings set target.auto-import-clang-modules true") mod_cache = self.getBuildArtifact("my-clang-modules-cache") if os.path.isdir(mod_cache): shutil.rmtree(mod_cache) self.assertFalse(os.path.isdir(mod_cache), "module cache should not exist") self.runCmd('settings set clang.modules-cache-path "%s"' % mod_cache) self.runCmd('settings set target.clang-module-search-paths "%s"' % self.getSourceDir()) (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( self, "Set breakpoint here", self.main_source_file) self.runCmd("expr @import Darwin") self.assertTrue(os.path.isdir(mod_cache), "module cache exists")
Fix issue with dropping a file into a log entry
/* * jQuery File Upload Plugin JS Example 5.0.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://creativecommons.org/licenses/MIT/ */ /*jslint nomen: false */ /*global $ */ $(function () { // Initialize the jQuery File Upload widget: $('div[id^="fileupload_"]').each(function(index,element){ $(this).fileupload({dropZone: $(this).parent()}); }); // Load existing files: $('div[id^="fileupload_"]').each(function(index,element){ $.getJSON($('div',element).prop('title'), function (files) { var fu = $(element).data('fileupload'); if(files != null){ fu._adjustMaxNumberOfFiles(-files.length); fu._renderDownload(files) .appendTo($('.files',element)) .fadeIn(function () { // Fix for IE7 and lower: $(this).show(); }); } }); }); // Open download dialogs via iframes, // to prevent aborting current uploads: $('div[id^="fileupload_"]').each(function(index,element){ $('.files a:not([target^=_blank])',element).live('click', function (e) { e.preventDefault(); $('<iframe style="display:none;"></iframe>') .prop('src', this.href) .appendTo('body'); }); }); });
/* * jQuery File Upload Plugin JS Example 5.0.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://creativecommons.org/licenses/MIT/ */ /*jslint nomen: false */ /*global $ */ $(function () { // Initialize the jQuery File Upload widget: $('div[id^="fileupload_"]').fileupload(); // Load existing files: $('div[id^="fileupload_"]').each(function(index,element){ $.getJSON($('div',element).prop('title'), function (files) { var fu = $(element).data('fileupload'); if(files != null){ fu._adjustMaxNumberOfFiles(-files.length); fu._renderDownload(files) .appendTo($('.files',element)) .fadeIn(function () { // Fix for IE7 and lower: $(this).show(); }); } }); }); // Open download dialogs via iframes, // to prevent aborting current uploads: $('div[id^="fileupload_"]').each(function(index,element){ $('.files a:not([target^=_blank])',element).live('click', function (e) { e.preventDefault(); $('<iframe style="display:none;"></iframe>') .prop('src', this.href) .appendTo('body'); }); }); });
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
# -*- coding: utf-8 -*- from django.test import Client from django.http import SimpleCookie from webtest import TestResponse from django_webtest.compat import urlparse class DjangoWebtestResponse(TestResponse): """ WebOb's Response quacking more like django's HttpResponse. This is here to make more django's TestCase asserts work, not to provide a generally useful proxy. """ streaming = False @property def status_code(self): return self.status_int @property def _charset(self): return self.charset @property def content(self): return self.body @property def url(self): return self['location'] @property def client(self): client = Client() client.cookies = SimpleCookie() for k,v in self.test_app.cookies.items(): client.cookies[k] = v return client def __getitem__(self, item): item = item.lower() if item == 'location': # django's test response returns location as http://testserver/, # WebTest returns it as http://localhost:80/ e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(self.location) if e_netloc == 'localhost:80': e_netloc = 'testserver' return urlparse.urlunsplit([e_scheme, e_netloc, e_path, e_query, e_fragment]) for header, value in self.headerlist: if header.lower() == item: return value raise KeyError(item)
# -*- coding: utf-8 -*- from django.test import Client from django.http import SimpleCookie from webtest import TestResponse from django_webtest.compat import urlparse class DjangoWebtestResponse(TestResponse): """ WebOb's Response quacking more like django's HttpResponse. This is here to make more django's TestCase asserts work, not to provide a generally useful proxy. """ streaming = False @property def status_code(self): return self.status_int @property def _charset(self): return self.charset @property def content(self): return self.body @property def client(self): client = Client() client.cookies = SimpleCookie() for k,v in self.test_app.cookies.items(): client.cookies[k] = v return client def __getitem__(self, item): item = item.lower() if item == 'location': # django's test response returns location as http://testserver/, # WebTest returns it as http://localhost:80/ e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(self.location) if e_netloc == 'localhost:80': e_netloc = 'testserver' return urlparse.urlunsplit([e_scheme, e_netloc, e_path, e_query, e_fragment]) for header, value in self.headerlist: if header.lower() == item: return value raise KeyError(item)
Remove more obsolete code in v2
import sys from threading import local def debug():# pragma no cover def pm(etype, value, tb): import pdb, traceback try: from IPython.ipapi import make_session; make_session() from IPython.Debugger import Pdb sys.stderr.write('Entering post-mortem IPDB shell\n') p = Pdb(color_scheme='Linux') p.reset() p.setup(None, tb) p.print_stack_trace() sys.stderr.write('%s: %s\n' % ( etype, value)) p.cmdloop() p.forget() # p.interaction(None, tb) except ImportError: sys.stderr.write('Entering post-mortem PDB shell\n') traceback.print_exception(etype, value, tb) pdb.post_mortem(tb) sys.excepthook = pm def expose(func): func.exposed = True return func class Undefined(object): pass UNDEFINED=Undefined() class flattener(object): def __init__(self, iterator): self.iterator = iterator @classmethod def decorate(cls, func): def inner(*args, **kwargs): return cls(func(*args, **kwargs)) return inner def __iter__(self): for x in self.iterator: if isinstance(x, flattener): for xx in x: yield xx else: yield x
import sys from threading import local def debug(): def pm(etype, value, tb): # pragma no cover import pdb, traceback try: from IPython.ipapi import make_session; make_session() from IPython.Debugger import Pdb sys.stderr.write('Entering post-mortem IPDB shell\n') p = Pdb(color_scheme='Linux') p.reset() p.setup(None, tb) p.print_stack_trace() sys.stderr.write('%s: %s\n' % ( etype, value)) p.cmdloop() p.forget() # p.interaction(None, tb) except ImportError: sys.stderr.write('Entering post-mortem PDB shell\n') traceback.print_exception(etype, value, tb) pdb.post_mortem(tb) sys.excepthook = pm def expose(func): func.exposed = True return func class Undefined(object): pass UNDEFINED=Undefined() class flattener(object): def __init__(self, iterator): self.iterator = iterator @classmethod def decorate(cls, func): def inner(*args, **kwargs): return cls(func(*args, **kwargs)) return inner def __iter__(self): for x in self.iterator: if isinstance(x, flattener): for xx in x: yield xx else: yield x class TLProxy(object): def __init__(self, factory): self._factory = factory self._local = local() def _get(self): try: result = self._local.value except AttributeError: result = self._local.value = self.factory() return result def __getattr__(self, name): return getattr(self._get(), name)
Use stable ids for the RecyclerView adapter
package com.appyvet.rangebarsample; import android.app.Activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; public class RecyclerViewActivity extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Removes title bar and sets content view this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_recyclerview); RecyclerView recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); Adapter adapter = new Adapter(); adapter.setHasStableIds(true); recyclerView.setAdapter(adapter); } public static class Adapter extends RecyclerView.Adapter<VH> { @NonNull @Override public VH onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { return new VH(LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.recyclerview_item, viewGroup, false)); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return position; } @Override public void onBindViewHolder(@NonNull VH vh, int i) { } @Override public int getItemCount() { return 50; } } public static class VH extends RecyclerView.ViewHolder { public VH(@NonNull View itemView) { super(itemView); } } }
package com.appyvet.rangebarsample; import android.app.Activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; public class RecyclerViewActivity extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Removes title bar and sets content view this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_recyclerview); RecyclerView recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(new Adapter()); } public static class Adapter extends RecyclerView.Adapter<VH> { @NonNull @Override public VH onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { return new VH(LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.recyclerview_item, viewGroup, false)); } @Override public void onBindViewHolder(@NonNull VH vh, int i) { } @Override public int getItemCount() { return 100; } } public static class VH extends RecyclerView.ViewHolder { public VH(@NonNull View itemView) { super(itemView); } } }
Revert Promise to Ember.Promise change
import Ember from 'ember'; // global Promise export default Ember.Controller.extend({ possibleTypes: Ember.computed.map('model.type', m => m), assignedLots: Ember.computed.map('model.lots', m => m), candidateLots: Ember.computed('[email protected]', { set(key, value) { return value; }, get() { var self = this; var req = this.get('model'); console.log('Recomputing available parts'); if (Ember.isEmpty(req)) { return []; } Promise.all(this.get('possibleTypes')).then(function (types) { var lots = []; types.forEach(function (type) { lots.pushObject(type.get('lots')); }); Promise.all(lots).then(function (lots) { var usable = []; lots.forEach(function (lotArray) { lotArray.forEach(function (lot) { usable.pushObject(lot); }); }); self.set('candidateLots', usable); }); }); return []; } }), assignableLots: Ember.computed.map('resolvedLots', m => m), resolvedLots: Ember.computed.filterBy('candidateLots', 'canBeAssigned', true) });
import Ember from 'ember'; export default Ember.Controller.extend({ possibleTypes: Ember.computed.map('model.type', m => m), assignedLots: Ember.computed.map('model.lots', m => m), candidateLots: Ember.computed('[email protected]', { set(key, value) { return value; }, get() { var self = this; var req = this.get('model'); console.log('Recomputing available parts'); if (Ember.isEmpty(req)) { return []; } Ember.Promise.all(this.get('possibleTypes')).then(function (types) { var lots = []; types.forEach(function (type) { lots.pushObject(type.get('lots')); }); Ember.Promise.all(lots).then(function (lots) { var usable = []; lots.forEach(function (lotArray) { lotArray.forEach(function (lot) { usable.pushObject(lot); }); }); self.set('candidateLots', usable); }); }); return []; } }), assignableLots: Ember.computed.map('resolvedLots', m => m), resolvedLots: Ember.computed.filterBy('candidateLots', 'canBeAssigned', true) });
Make inbetween tag releases 'dev', not 'post'.
#!/usr/bin/env python # Source: https://github.com/Changaco/version.py from os.path import dirname, isdir, join import re from subprocess import CalledProcessError, check_output PREFIX = '' tag_re = re.compile(r'\btag: %s([0-9][^,]*)\b' % PREFIX) version_re = re.compile('^Version: (.+)$', re.M) def get_version(): # Return the version if it has been injected into the file by git-archive version = tag_re.search('$Format:%D$') if version: return version.group(1) d = dirname(__file__) if isdir(join(d, '../.git')): # Get the version using "git describe". cmd = 'git describe --tags --match %s[0-9]* --dirty' % PREFIX try: version = check_output(cmd.split()).decode().strip()[len(PREFIX):] except CalledProcessError: raise RuntimeError('Unable to get version number from git tags') # PEP 440 compatibility if '-' in version: version = '.dev'.join(version.split('-')[:2]) else: # Extract the version from the PKG-INFO file. with open(join(d, '../PKG-INFO')) as f: version = version_re.search(f.read()).group(1) return version if __name__ == '__main__': print(get_version())
#!/usr/bin/env python # Source: https://github.com/Changaco/version.py from os.path import dirname, isdir, join import re from subprocess import CalledProcessError, check_output PREFIX = '' tag_re = re.compile(r'\btag: %s([0-9][^,]*)\b' % PREFIX) version_re = re.compile('^Version: (.+)$', re.M) def get_version(): # Return the version if it has been injected into the file by git-archive version = tag_re.search('$Format:%D$') if version: return version.group(1) d = dirname(__file__) if isdir(join(d, '../.git')): # Get the version using "git describe". cmd = 'git describe --tags --match %s[0-9]* --dirty' % PREFIX try: version = check_output(cmd.split()).decode().strip()[len(PREFIX):] except CalledProcessError: raise RuntimeError('Unable to get version number from git tags') # PEP 440 compatibility if '-' in version: version = '.post'.join(version.split('-')[:2]) else: # Extract the version from the PKG-INFO file. with open(join(d, '../PKG-INFO')) as f: version = version_re.search(f.read()).group(1) return version if __name__ == '__main__': print(get_version())
Fix a bug where query strings would 404
/* Sets up a connect server to work from the /build folder. May also set up a livereload server at some point. */ var fs = require("fs"); var path = require("path"); var url = require("url"); module.exports = function(grunt) { grunt.loadNpmTasks("grunt-contrib-connect"); grunt.config.merge({ connect: { dev: { options: { livereload: true, base: "./build", //middleware to protect against case-insensitive file systems middleware: function(connect, options, ware) { var base = options.base.pop(); ware.unshift(function(req, response, next) { var href = url.parse(req.url).pathname; var location = path.join(base, href); var filename = path.basename(href); if (!filename) return next(); var dir = path.dirname(location); fs.readdir(dir, function(err, list) { if (list.indexOf(filename) == -1) { response.statusCode = 404; response.end(); } else { next(); } }) }); return ware; } } } } }) };
/* Sets up a connect server to work from the /build folder. May also set up a livereload server at some point. */ var fs = require("fs"); var path = require("path"); module.exports = function(grunt) { grunt.loadNpmTasks("grunt-contrib-connect"); grunt.config.merge({ connect: { dev: { options: { livereload: true, base: "./build", //middleware to protect against case-insensitive file systems middleware: function(connect, options, ware) { var base = options.base.pop(); ware.unshift(function(req, response, next) { var location = path.join(base, req.url); var filename = path.basename(req.url); if (!filename) return next(); var dir = path.dirname(location); fs.readdir(dir, function(err, list) { if (list.indexOf(filename) == -1) { response.statusCode = 404; response.end(); } else { next(); } }) }); return ware; } } } } }) };
Allow for missing directories in $PATH
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
Add theme prop to SimpleSelect instance
const PropTypes = require('prop-types'); const React = require('react'); const Button = require('./Button'); const SimpleSelect = require('./SimpleSelect'); class HeaderMenu extends React.Component { static propTypes = { buttonIcon: PropTypes.string, buttonText: PropTypes.string.isRequired, items: PropTypes.array.isRequired, theme: themeShape } state = { showSimpleSelectMenu: false } toggle = () => { this.setState({ showSimpleSelectMenu: !this.state.showSimpleSelectMenu }); } render () { const theme = StyleUtils.mergeTheme(this.props.theme); const items = this.props.items.map(item => Object.assign({}, item, { onClick: (event, itemClicked) => { this.toggle(); item.onClick(event, itemClicked); } }) ); return ( <div style={{ width: 150 }}> <Button icon={this.props.buttonIcon} onClick={this.toggle} theme={theme} type='neutral' > {this.props.buttonText} </Button> {this.state.showSimpleSelectMenu ? ( <SimpleSelect items={items} onScrimClick={this.toggle} styles={{ menu: { left: 65 } }} theme={theme} /> ) : null} </div> ); } } module.exports = HeaderMenu;
const PropTypes = require('prop-types'); const React = require('react'); const Button = require('./Button'); const SimpleSelect = require('./SimpleSelect'); class HeaderMenu extends React.Component { static propTypes = { buttonIcon: PropTypes.string, buttonText: PropTypes.string.isRequired, items: PropTypes.array.isRequired, theme: themeShape } state = { showSimpleSelectMenu: false } toggle = () => { this.setState({ showSimpleSelectMenu: !this.state.showSimpleSelectMenu }); } render () { const theme = StyleUtils.mergeTheme(this.props.theme); const items = this.props.items.map(item => Object.assign({}, item, { onClick: (event, itemClicked) => { this.toggle(); item.onClick(event, itemClicked); } }) ); return ( <div style={{ width: 150 }}> <Button icon={this.props.buttonIcon} onClick={this.toggle} theme={theme} type='neutral' > {this.props.buttonText} </Button> {this.state.showSimpleSelectMenu ? ( <SimpleSelect items={items} onScrimClick={this.toggle} styles={{ menu: { left: 65 } }} /> ) : null} </div> ); } } module.exports = HeaderMenu;
Move the ParentTaxonPrefixPreview logic to the bottom The functions are hoisted anyway.
(function (Modules) { "use strict"; Modules.ParentTaxonPrefixPreview = function () { this.start = function(el) { var $parentSelectEl = $(el).find('select.js-parent-taxon'); var $pathPrefixEl = $(el).find('.js-path-prefix-hint'); function getParentPathPrefix(callback) { var parentTaxonContentId = $parentSelectEl.val(); if (parentTaxonContentId.length === 0) { callback(); return; } $.getJSON( window.location.origin + '/taxons/' + parentTaxonContentId + '.json' ).done(function(taxon) { callback(taxon.path_prefix); }); } function updateBasePathPreview() { getParentPathPrefix(function (path_prefix) { if (path_prefix) { $pathPrefixEl.html('Base path must start with <b>/' + path_prefix + '</b>'); $pathPrefixEl.removeClass('hidden'); } else { $pathPrefixEl.addClass('hidden'); $pathPrefixEl.text(''); } }); } updateBasePathPreview(); $parentSelectEl.change(updateBasePathPreview); }; }; })(window.GOVUKAdmin.Modules);
(function (Modules) { "use strict"; Modules.ParentTaxonPrefixPreview = function () { this.start = function(el) { var $parentSelectEl = $(el).find('select.js-parent-taxon'); var $pathPrefixEl = $(el).find('.js-path-prefix-hint'); updateBasePathPreview(); $parentSelectEl.change(updateBasePathPreview); function getParentPathPrefix(callback) { var parentTaxonContentId = $parentSelectEl.val(); if (parentTaxonContentId.length === 0) { callback(); return; } $.getJSON( window.location.origin + '/taxons/' + parentTaxonContentId + '.json' ).done(function(taxon) { callback(taxon.path_prefix); }); } function updateBasePathPreview() { getParentPathPrefix(function (path_prefix) { if (path_prefix) { $pathPrefixEl.html('Base path must start with <b>/' + path_prefix + '</b>'); $pathPrefixEl.removeClass('hidden'); } else { $pathPrefixEl.addClass('hidden'); $pathPrefixEl.text(''); } }); } }; }; })(window.GOVUKAdmin.Modules);
Add better exception handling on invalid json
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): return self.get(attr) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): return self.get(attr) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except: raise ImportError( 'Couldn\'t load json from"{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
Insert date when email was received Sometimes we receive email reports like "this is happening right now" and there is no date/time included. So if we process emails once per hour - we don't have info about event time. Additional field `extra.email_received` in the mail body collector would help.
# -*- coding: utf-8 -*- """ Uses the common mail iteration method from the lib file. """ from .lib import MailCollectorBot class MailBodyCollectorBot(MailCollectorBot): def init(self): super().init() self.content_types = getattr(self.parameters, 'content_types', ('plain', 'html')) if isinstance(self.content_types, str): self.content_types = [x.strip() for x in self.content_types.split(',')] elif not self.content_types or self.content_types is True: # empty string, null, false, true self.content_types = ('plain', 'html') def process_message(self, uid, message): seen = False for content_type in self.content_types: for body in message.body[content_type]: if not body: continue report = self.new_report() report["raw"] = body report["extra.email_subject"] = message.subject report["extra.email_from"] = ','.join(x['email'] for x in message.sent_from) report["extra.email_message_id"] = message.message_id report["extra.email_received"] = message.date self.send_message(report) # at least one body has successfully been processed seen = True return seen BOT = MailBodyCollectorBot
# -*- coding: utf-8 -*- """ Uses the common mail iteration method from the lib file. """ from .lib import MailCollectorBot class MailBodyCollectorBot(MailCollectorBot): def init(self): super().init() self.content_types = getattr(self.parameters, 'content_types', ('plain', 'html')) if isinstance(self.content_types, str): self.content_types = [x.strip() for x in self.content_types.split(',')] elif not self.content_types or self.content_types is True: # empty string, null, false, true self.content_types = ('plain', 'html') def process_message(self, uid, message): seen = False for content_type in self.content_types: for body in message.body[content_type]: if not body: continue report = self.new_report() report["raw"] = body report["extra.email_subject"] = message.subject report["extra.email_from"] = ','.join(x['email'] for x in message.sent_from) report["extra.email_message_id"] = message.message_id self.send_message(report) # at least one body has successfully been processed seen = True return seen BOT = MailBodyCollectorBot
Load template from `cherrypy.request.template` in handler.
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filename=None, directories=None, module_directory=None, collection_size=-1): if filename is None or directories is None: return # Find the appropriate template lookup. key = (tuple(directories), module_directory) try: lookup = self._lookups[key] except KeyError: lookup = TemplateLookup(directories=directories, module_directory=module_directory, collection_size=collection_size, input_encoding='utf8') self._lookups[key] = lookup cherrypy.request.lookup = lookup cherrypy.request.template = lookup.get_template(filename) # Replace the current handler. inner_handler = cherrypy.serving.request.handler def wrapper(*args, **kwargs): context = inner_handler(*args, **kwargs) response = cherrypy.request.template.render(**context) return response cherrypy.serving.request.handler = wrapper
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filename=None, directories=None, module_directory=None, collection_size=-1): if filename is None or directories is None: return # Find the appropriate template lookup. key = (tuple(directories), module_directory) try: lookup = self._lookups[key] except KeyError: lookup = TemplateLookup(directories=directories, module_directory=module_directory, collection_size=collection_size, input_encoding='utf8') self._lookups[key] = lookup cherrypy.request.lookup = lookup # Replace the current handler. cherrypy.request.template = template = lookup.get_template(filename) inner_handler = cherrypy.serving.request.handler def wrapper(*args, **kwargs): context = inner_handler(*args, **kwargs) response = template.render(**context) return response cherrypy.serving.request.handler = wrapper
Set mode = edit in project activity
package mozilla.org.webmaker.activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import org.json.JSONException; import mozilla.org.webmaker.R; import mozilla.org.webmaker.WebmakerActivity; import mozilla.org.webmaker.router.Router; public class Project extends WebmakerActivity { public Project() { super("project", R.id.project_layout, R.layout.project_layout, R.menu.menu_project); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { routeParams.put("mode", "edit"); } catch (JSONException e) { // do nothing } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(menuResId, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Fetch project ID String id; try { id = routeParams.get("project").toString(); } catch (JSONException e) { return super.onOptionsItemSelected(item); } // Handle button press switch (item.getItemId()) { case R.id.action_play: Router.sharedRouter().open("/projects/" + id + "/play"); return true; case R.id.action_settings: Router.sharedRouter().open("/projects/" + id + "/settings"); return true; case R.id.action_share: // @todo return true; default: return super.onOptionsItemSelected(item); } } }
package mozilla.org.webmaker.activity; import android.view.Menu; import android.view.MenuItem; import org.json.JSONException; import mozilla.org.webmaker.R; import mozilla.org.webmaker.WebmakerActivity; import mozilla.org.webmaker.router.Router; public class Project extends WebmakerActivity { public Project() { super("project", R.id.project_layout, R.layout.project_layout, R.menu.menu_project); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(menuResId, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Fetch project ID String id; try { id = routeParams.get("project").toString(); } catch (JSONException e) { return super.onOptionsItemSelected(item); } // Handle button press switch (item.getItemId()) { case R.id.action_play: Router.sharedRouter().open("/projects/" + id + "/play"); return true; case R.id.action_settings: Router.sharedRouter().open("/projects/" + id + "/settings"); return true; case R.id.action_share: // @todo return true; default: return super.onOptionsItemSelected(item); } } }
Fix submodules for the "no-prebuilt install from npm" case
var path = require("path"); var rootDir = path.join(__dirname, "../.."); var exec = require(path.join(rootDir, "./utils/execPromise")); module.exports = function getStatus() { return exec("git submodule status", { cwd: rootDir}) .then(function(stdout) { if (!stdout) { // In the case where we pull from npm they pre-init the submoduels for // us and `git submodule status` returns empty-string. In that case // we'll just assume that we're good. return Promise.resolve([]); } function getStatusPromiseFromLine(line) { var lineSections = line.trim().split(" "); var onNewCommit = !!~lineSections[0].indexOf("+"); var needsInitialization = !!~lineSections[0].indexOf("-"); var commitOid = lineSections[0].replace("+", "").replace("-", ""); var name = lineSections[1]; return exec("git status", { cwd: path.join(rootDir, name)}) .then(function(workDirStatus) { return { commitOid: commitOid, onNewCommit: onNewCommit, name: name, needsInitialization: needsInitialization, workDirDirty: !~workDirStatus .trim() .split("\n") .pop() .indexOf("nothing to commit") }; }); } return Promise.all(stdout .trim() .split("\n") .map(getStatusPromiseFromLine) ); }); };
var path = require("path"); var rootDir = path.join(__dirname, "../.."); var exec = require(path.join(rootDir, "./utils/execPromise")); module.exports = function getStatus() { return exec("git submodule status", { cwd: rootDir}) .then(function(stdout) { function getStatusPromiseFromLine(line) { var lineSections = line.trim().split(" "); var onNewCommit = !!~lineSections[0].indexOf("+"); var needsInitialization = !!~lineSections[0].indexOf("-"); var commitOid = lineSections[0].replace("+", "").replace("-", ""); var name = lineSections[1]; return exec("git status", { cwd: path.join(rootDir, name)}) .then(function(workDirStatus) { return { commitOid: commitOid, onNewCommit: onNewCommit, name: name, needsInitialization: needsInitialization, workDirDirty: !~workDirStatus .trim() .split("\n") .pop() .indexOf("nothing to commit") }; }); } return Promise.all(stdout .trim() .split("\n") .map(getStatusPromiseFromLine) ); }); };
Use clear() instead of manually deleting all elements in the body
#!/usr/bin/env python from __future__ import print_function import sys import argparse from lxml import etree NS = {'x': 'http://www.w3.org/1999/xhtml', 'mml':'http://www.w3.org/1998/Math/MathML'} body_xpath = etree.XPath('//x:body', namespaces=NS) math_xpath = etree.XPath("//mml:math", namespaces=NS) def main(html_in, html_out=sys.stdout): """Extract math nodes from book html file""" html = etree.parse(html_in) body = body_xpath(html)[0] math = math_xpath(body) body.clear() for m in math: body.append(m) print(etree.tostring(html), file=html_out) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Extract only math nodes from book html file") parser.add_argument("html_in", type=argparse.FileType('r'), help="assembled fullbook HTML file") parser.add_argument("html_out", nargs="?", type=argparse.FileType('w'), help="math-only HTML file output (default stdout)", default=sys.stdout) args = parser.parse_args() main(args.html_in, args.html_out)
#!/usr/bin/env python from __future__ import print_function import sys import argparse from lxml import etree NS = {'x': 'http://www.w3.org/1999/xhtml', 'mml':'http://www.w3.org/1998/Math/MathML'} body_xpath = etree.XPath('//x:body', namespaces=NS) math_xpath = etree.XPath("//mml:math", namespaces=NS) def main(html_in, html_out=sys.stdout): """Extract math nodes from book html file""" html = etree.parse(html_in) body = body_xpath(html)[0] math = math_xpath(body) for c in body.iterchildren(): body.remove(c) for m in math: body.append(m) print(etree.tostring(html), file=html_out) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Extract only math nodes from book html file") parser.add_argument("html_in", type=argparse.FileType('r'), help="assembled fullbook HTML file") parser.add_argument("html_out", nargs="?", type=argparse.FileType('w'), help="math-only HTML file output (default stdout)", default=sys.stdout) args = parser.parse_args() main(args.html_in, args.html_out)
Use raw command method to run all commands in wrapper
# -*- coding: utf-8 -*- import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): out, err = command("kill-session -t {}".format(session)) if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): out, err = command("ls") if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): out, err = command("new -s {}".format(session)) if "duplicate session" in err: raise SessionExists(session) def attach(session): out, err = command("attach-session -t {}".format(session)) if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): try: create(session) except SessionExists: attach(session)
# -*- coding: utf-8 -*- import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): p = subprocess.Popen("tmux kill-session -t {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): p = subprocess.Popen("tmux ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): p = subprocess.Popen("tmux new -s {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "duplicate session" in err: raise SessionExists(session) def attach(session): p = subprocess.Popen("tmux attach-session -t {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): create(session) except SessionExists: attach(session)
Throw exception if curl call fails
<?php class Twocheckout_Api_Requester { public $apiBaseUrl; private $user; private $pass; function __construct() { $this->user = Twocheckout::$user; $this->pass = Twocheckout::$pass; $this->apiBaseUrl = Twocheckout::$apiBaseUrl; } function do_call($urlSuffix, $data=array()) { $url = $this->apiBaseUrl . $urlSuffix; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json")); curl_setopt($ch, CURLOPT_USERAGENT, "2Checkout PHP/0.1.0%s"); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, "{$this->user}:{$this->pass}"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $resp = curl_exec($ch); curl_close($ch); if ($resp === FALSE) { throw new Twocheckout_Error("cURL call failed", "403"); } else { return $resp; } } }
<?php class Twocheckout_Api_Requester { public $apiBaseUrl; private $user; private $pass; function __construct() { $this->user = Twocheckout::$user; $this->pass = Twocheckout::$pass; $this->apiBaseUrl = Twocheckout::$apiBaseUrl; } function do_call($urlSuffix, $data=array()) { $url = $this->apiBaseUrl . $urlSuffix; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json")); curl_setopt($ch, CURLOPT_USERAGENT, "2Checkout PHP/0.1.0%s"); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, "{$this->user}:{$this->pass}"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $resp = curl_exec($ch); curl_close($ch); return $resp; } }
Fix to Travis build script.
# -*- coding: utf-8 -*- import os from travispy import travispy from travispy import TravisPy def main(): restarted = [] building = [] for domain in [travispy.PUBLIC, travispy.PRIVATE]: print "Enumerate repos on ", domain conn = TravisPy.github_auth(os.environ['GITHUB_KEY'], domain) user = conn.user() repos = conn.repos(member=user.login) for repo in repos: if not repo.active: continue print u"Checking repo: {}\n{!r}".format(repo.slug, repo.description) try: build = conn.build(repo.last_build_id) if "kitrun.py" in build.config.get("script", [""])[0]: print "Found drift project: ", repo.slug if not build.running: print "Restarting..." build.restart() restarted.append(repo.slug) else: print "Build is already running!" building.append(repo.slug) else: print "Not a drift based project." except Exception as e: print "Can't build repo: ", e print "" if restarted: print "Repos restarted:" for reponame in restarted: print "\t", reponame else: print "No builds restarted." if building: print "Repos already building:" for reponame in building: print "\t", reponame if __name__ == "__main__": main()
# -*- coding: utf-8 -*- import os from travispy import travispy from travispy import TravisPy def main(): restarted = [] building = [] for domain in [travispy.PUBLIC, travispy.PRIVATE]: print "Enumerate repos on ", domain conn = TravisPy.github_auth(os.environ['GITHUB_KEY'], domain) user = conn.user() repos = conn.repos(member=user.login) for repo in repos: if not repo.active: continue print u"Checking repo: {}\n{}".format(repo.slug, repo.description) try: build = conn.build(repo.last_build_id) if "kitrun.py" in build.config.get("script", [""])[0]: print "Found drift project: ", repo.slug if not build.running: print "Restarting..." build.restart() restarted.append(repo.slug) else: print "Build is already running!" building.append(repo.slug) else: print "Not a drift based project." except Exception as e: print "Can't build repo: ", e print "" if restarted: print "Repos restarted:" for reponame in restarted: print "\t", reponame else: print "No builds restarted." if building: print "Repos already building:" for reponame in building: print "\t", reponame if __name__ == "__main__": main()
Remove IF EXISTS from DROP TABLE when resetting the db.
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE categories ''') db.execute(''' DROP TABLE articles ''') db.execute(''' DROP TABLE snippets ''') db.execute(''' DROP TABLE articles_categories ''') db.execute(''' CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT) ''') db.execute(''' INSERT INTO categories VALUES ("unassigned", "unassigned") ''') db.execute(''' CREATE TABLE articles_categories (article_id TEXT, category_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE, FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE) ''') db.execute(''' CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT, title TEXT) ''') db.execute(''' CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT, section TEXT, article_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE) ''') return db def create_indices(): db = init_db() db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles ON snippets(article_id);''')
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE IF EXISTS categories ''') db.execute(''' DROP TABLE IF EXISTS articles ''') db.execute(''' DROP TABLE IF EXISTS snippets ''') db.execute(''' DROP TABLE IF EXISTS articles_categories ''') db.execute(''' CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT) ''') db.execute(''' INSERT INTO categories VALUES ("unassigned", "unassigned") ''') db.execute(''' CREATE TABLE articles_categories (article_id TEXT, category_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE, FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE) ''') db.execute(''' CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT, title TEXT) ''') db.execute(''' CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT, section TEXT, article_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE) ''') return db def create_indices(): db = init_db() db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles ON snippets(article_id);''')
Fix regexp to detect markdown file (URL with GET parameters)
window.addEventListener('load', function load(event) { window.removeEventListener('load', load, false); MarkdownViewer.init(); }, false); if (!MarkdownViewer) { var MarkdownViewer = { init: function() { var appcontent = document.getElementById('appcontent'); if (appcontent) appcontent.addEventListener('DOMContentLoaded', this.onPageLoad, true); }, onPageLoad: function(aEvent) { var document = aEvent.originalTarget; var markdownFileExtension = /\.m(arkdown|kdn?|d(o?wn)?)(#.*)?(.*)$/i; if (document.location.protocol !== "view-source:" && markdownFileExtension.test(document.location.href)) { var content = document.firstChild; content.innerHTML = '<!DOCTYPE html>' + '<head>' + ' <title></title>' + ' <meta charset="utf-8" />' + ' <link rel="stylesheet" type="text/css" href="resource://mdvskin/markdown-viewer.css" />' + '</head>' + '<body class="container">' + marked(content.textContent) + '</body>'; document.title = document.body.firstChild.textContent.substr(0, 50).replace('<', '&lt;').replace('>', '&gt;'); } } }; }
window.addEventListener('load', function load(event) { window.removeEventListener('load', load, false); MarkdownViewer.init(); }, false); if (!MarkdownViewer) { var MarkdownViewer = { init: function() { var appcontent = document.getElementById('appcontent'); if (appcontent) appcontent.addEventListener('DOMContentLoaded', this.onPageLoad, true); }, onPageLoad: function(aEvent) { var document = aEvent.originalTarget; var markdownFileExtension = /\.m(arkdown|kdn?|d(o?wn)?)(#.*)?$/i; if (document.location.protocol !== "view-source:" && markdownFileExtension.test(document.location.href)) { var content = document.firstChild; content.innerHTML = '<!DOCTYPE html>' + '<head>' + ' <title></title>' + ' <meta charset="utf-8" />' + ' <link rel="stylesheet" type="text/css" href="resource://mdvskin/markdown-viewer.css" />' + '</head>' + '<body class="container">' + marked(content.textContent) + '</body>'; document.title = document.body.firstChild.textContent.substr(0, 50).replace('<', '&lt;').replace('>', '&gt;'); } } }; }
Fix Queued states to be pending instead of paused
package com.novoda.downloadmanager.lib; public class PublicFacingStatusTranslator { public int translate(int status) { switch (status) { case DownloadStatus.SUBMITTED: case DownloadStatus.PENDING: case DownloadStatus.QUEUED_DUE_CLIENT_RESTRICTIONS: case DownloadStatus.WAITING_TO_RETRY: case DownloadStatus.WAITING_FOR_NETWORK: case DownloadStatus.QUEUED_FOR_WIFI: return DownloadManager.STATUS_PENDING; case DownloadStatus.RUNNING: return DownloadManager.STATUS_RUNNING; case DownloadStatus.PAUSED_BY_APP: return DownloadManager.STATUS_PAUSED; case DownloadStatus.PAUSING: return DownloadManager.STATUS_PAUSING; case DownloadStatus.SUCCESS: return DownloadManager.STATUS_SUCCESSFUL; case DownloadStatus.DELETING: return DownloadManager.STATUS_DELETING; default: return DownloadManager.STATUS_FAILED; } } }
package com.novoda.downloadmanager.lib; public class PublicFacingStatusTranslator { public int translate(int status) { switch (status) { case DownloadStatus.SUBMITTED: case DownloadStatus.PENDING: return DownloadManager.STATUS_PENDING; case DownloadStatus.RUNNING: return DownloadManager.STATUS_RUNNING; case DownloadStatus.QUEUED_DUE_CLIENT_RESTRICTIONS: case DownloadStatus.PAUSED_BY_APP: case DownloadStatus.WAITING_TO_RETRY: case DownloadStatus.WAITING_FOR_NETWORK: case DownloadStatus.QUEUED_FOR_WIFI: return DownloadManager.STATUS_PAUSED; case DownloadStatus.PAUSING: return DownloadManager.STATUS_PAUSING; case DownloadStatus.SUCCESS: return DownloadManager.STATUS_SUCCESSFUL; case DownloadStatus.DELETING: return DownloadManager.STATUS_DELETING; default: return DownloadManager.STATUS_FAILED; } } }
Use previews in ranger fzf
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m --preview 'cat {}'" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="fd -t d --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" else: # match files and directories command="fd --hidden | fzf +m" # command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ # -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file)
Update JS regex to strip trigger words
(function(env){ "use strict"; env.ddg_spice_gifs = function (api_result) { if (!api_result || !api_result.data || !api_result.data.length){ return Spice.failed("gifs"); } var searchTerm = DDG.get_query().replace(/gifs?|giphy/ig,'').trim(); Spice.add({ id: 'gifs', name: 'Gifs', data: api_result.data, view: 'Images', meta: { sourceName: 'Giphy', sourceUrl: 'http://giphy.com/search/' + encodeURIComponent(searchTerm), count: api_result.pagination.count, total: api_result.pagination.total_count, itemType: 'Gifs' }, normalize: function(item) { if (item.rating !== "g") { return null; } return { thumbnail: item.images.fixed_height_still.url, image: item.images.fixed_height.url, url: item.url, height: item.images.fixed_height.height, width: item.images.fixed_height.width, title: item.caption || null }; }, templates: { item: 'images_item', detail: 'images_detail' } }); }; })(this);
(function(env){ "use strict"; env.ddg_spice_gifs = function (api_result) { if (!api_result || !api_result.data || !api_result.data.length){ return Spice.failed("gifs"); } var searchTerm = DDG.get_query().replace(/gifs?/i,'').trim(); Spice.add({ id: 'gifs', name: 'Gifs', data: api_result.data, view: 'Images', meta: { sourceName: 'Giphy', sourceUrl: 'http://giphy.com/search/' + encodeURIComponent(searchTerm), count: api_result.pagination.count, total: api_result.pagination.total_count, itemType: 'Gifs' }, normalize: function(item) { if (item.rating !== "g") { return null; } return { thumbnail: item.images.fixed_height_still.url, image: item.images.fixed_height.url, url: item.url, height: item.images.fixed_height.height, width: item.images.fixed_height.width, title: item.caption || null }; }, templates: { item: 'images_item', detail: 'images_detail' } }); }; })(this);