text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Include `roundrobin` in the dependencies
# -*- coding: utf-8 -*- import ast import os import re import sys from setuptools import find_packages, setup ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) # parse version from locust/__init__.py _version_re = re.compile(r"__version__\s+=\s+(.*)") _init_file = os.path.join(ROOT_PATH, "locust", "__init__.py") with open(_init_file, "rb") as f: version = str(ast.literal_eval(_version_re.search(f.read().decode("utf-8")).group(1))) setup( name="locust", version=version, install_requires=[ "gevent>=20.9.0", "flask>=2.0.0", "Werkzeug>=2.0.0", "requests>=2.9.1", "msgpack>=0.6.2", "pyzmq>=16.0.2", "geventhttpclient>=1.4.4", "ConfigArgParse>=1.0", "psutil>=5.6.7", "Flask-BasicAuth>=0.2.0", "Flask-Cors>=3.0.10", "roundrobin>=0.0.2", ], test_suite="locust.test", tests_require=[ "cryptography", "mock", "pyquery", ], extras_require={ ":sys_platform == 'win32'": ["pywin32"], }, )
# -*- coding: utf-8 -*- import ast import os import re import sys from setuptools import find_packages, setup ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) # parse version from locust/__init__.py _version_re = re.compile(r"__version__\s+=\s+(.*)") _init_file = os.path.join(ROOT_PATH, "locust", "__init__.py") with open(_init_file, "rb") as f: version = str(ast.literal_eval(_version_re.search(f.read().decode("utf-8")).group(1))) setup( name="locust", version=version, install_requires=[ "gevent>=20.9.0", "flask>=2.0.0", "Werkzeug>=2.0.0", "requests>=2.9.1", "msgpack>=0.6.2", "pyzmq>=16.0.2", "geventhttpclient>=1.4.4", "ConfigArgParse>=1.0", "psutil>=5.6.7", "Flask-BasicAuth>=0.2.0", "Flask-Cors>=3.0.10", ], test_suite="locust.test", tests_require=[ "cryptography", "mock", "pyquery", ], extras_require={ ":sys_platform == 'win32'": ["pywin32"], }, )
Use a data provider so we can show multiple failures
<?php /* * This file is part of Alt Three TestBench. * * (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 AltThree\TestBench; use CallbackFilterIterator; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use ReflectionClass; /** * This is the existence trait. * * @author Graham Campbell <[email protected]> */ trait ExistenceTrait { /** * @dataProvider provideFilesToCheck */ public function testExistence($class, $test) { $this->assertTrue(class_exists($class), "Expected the class {$class} to exist."); $this->assertTrue(class_exists($test), "Expected there to be tests for {$class}."); } public function provideFilesToCheck() { $source = $this->getSourceNamespace(); $tests = $this->getTestNamespace(); $path = $this->getSourcePath(); $len = strlen($path); $files = new CallbackFilterIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)), function ($file) { return $file->getFilename()[0] !== '.' && !$file->isDir(); }); return array_map(function ($file) use ($len, $source, $tests) { $name = str_replace('/', '\\', strtok(substr($file->getPathname(), $len), '.')); return ["{$source}{$name}", "{$tests}{$name}Test"]; }, iterator_to_array($files)); } protected function getTestNamespace() { return (new ReflectionClass($this))->getNamespaceName(); } protected function getSourceNamespace() { return str_replace('\\Tests\\', '\\', $this->getTestNamespace()); } }
<?php /* * This file is part of Alt Three TestBench. * * (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 AltThree\TestBench; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use ReflectionClass; /** * This is the existence trait. * * @author Graham Campbell <[email protected]> */ trait ExistenceTrait { public function testExistence() { $source = $this->getSourceNamespace(); $tests = $this->getTestNamespace(); $path = $this->getSourcePath(); $len = strlen($path); $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); foreach ($files as $file) { if ($file->getFilename()[0] === '.' || $file->isDir()) { continue; } $name = str_replace('/', '\\', strtok(substr($file->getPathname(), $len), '.')); $this->assertTrue(class_exists("{$source}{$name}")); $this->assertTrue(class_exists("{$tests}{$name}Test")); } } protected function getTestNamespace() { return (new ReflectionClass($this))->getNamespaceName(); } protected function getSourceNamespace() { return str_replace('\\Tests\\', '\\', $this->getTestNamespace()); } }
Handle error message case on product create front end
app.controller('indexController', ['$scope', '$http', function($scope, $http){ $scope.currency = 'USD'; $scope.codes = currencyCodes; $scope.handleCodeChange = function ($index) { $scope.currency = $scope.codes[$index]; console.log($scope.currency); }; $scope.toggleAdd = function () { $scope.shouldShowAdd = !$scope.shouldShowAdd; $('#addItem').slideToggle(300); console.log('Show pressed'); }; document.scope = $scope; $scope.formSubmit = function () { $scope.posting = true; $scope.formData = {_token: csrfToken, title: $scope.title, currency: $scope.currency, price: $scope.price}; console.log($scope.formData); $http.post('/items', JSON.stringify($scope.formData)) .success(function (data, status, headers, config) { console.log('the data to be sent is ' + JSON.stringify(data)); $scope.responseData = data; console.log($scope.responseData); if (data.message) { $scope.posting = false; humane.log(data.message); } if (data.redirect_url) { window.location = $scope.responseData.redirect_url; } $scope.posting = false; }) .error(function (data, status, headers, config) { console.log(data); $scope.posting = false; }); }; }]);
app.controller('indexController', ['$scope', '$http', function($scope, $http){ $scope.currency = 'USD'; $scope.codes = currencyCodes; $scope.handleCodeChange = function ($index) { $scope.currency = $scope.codes[$index]; console.log($scope.currency); }; $scope.toggleAdd = function () { $scope.shouldShowAdd = !$scope.shouldShowAdd; $('#addItem').slideToggle(300); console.log('Show pressed'); }; document.scope = $scope; $scope.formSubmit = function () { $scope.posting = true; $scope.formData = {_token: csrfToken, title: $scope.title, currency: $scope.currency, price: $scope.price}; console.log($scope.formData); $http.post('/items', JSON.stringify($scope.formData)) .success(function (data, status, headers, config) { console.log('the data to be sent is ' + JSON.stringify(data)); $scope.responseData = data; console.log($scope.responseData); window.location = $scope.responseData.redirect_url; $scope.posting = false; }) .error(function (data, status, headers, config) { console.log(data); $scope.posting = false; }); }; }]);
Hide contact form when sending succeeded.
angular.module('codebrag.common.directives').directive('contactFormPopup', function() { function ContactFormPopup($scope, $http) { $scope.isVisible = false; $scope.submit = function() { clearStatus(); sendFeedbackViaUservoice().then(success, failure); function success() { $scope.success = true; clearFormFields(); } function failure() { $scope.failure = true; } }; $scope.$on('openContactFormPopup', function() { $scope.isVisible = true; }); $scope.close = function() { $scope.isVisible = false; clearStatus(); clearFormFields(); }; function clearStatus() { delete $scope.success; delete $scope.failure; } function clearFormFields() { $scope.msg = {}; $scope.contactForm.$setPristine(); } function sendFeedbackViaUservoice() { var apiKey = 'vvT4cCa8uOpfhokERahg'; var data = { format: 'json', client: apiKey, ticket: { message: $scope.msg.body, subject: $scope.msg.subject }, email: $scope.msg.email }; var url = 'https://codebrag.uservoice.com/api/v1/tickets/create_via_jsonp.json?' + $.param(data) + '&callback=JSON_CALLBACK'; return $http.jsonp(url); } } return { restrict: 'E', replace: true, scope: {}, templateUrl: 'views/popups/contactForm.html', controller: ContactFormPopup }; });
angular.module('codebrag.common.directives').directive('contactFormPopup', function() { function ContactFormPopup($scope, $http) { $scope.isVisible = false; $scope.submit = function() { sendFeedbackViaUservoice().then(success, failure); function success() { $scope.success = true; clearFormFields(); } function failure() { $scope.failure = true; } }; $scope.$on('openContactFormPopup', function() { $scope.isVisible = true; }); $scope.close = function() { $scope.isVisible = false; delete $scope.success; delete $scope.failure; clearFormFields(); }; function clearFormFields() { $scope.msg = {}; $scope.contactForm.$setPristine(); } function sendFeedbackViaUservoice() { var apiKey = 'vvT4cCa8uOpfhokERahg'; var data = { format: 'json', client: apiKey, ticket: { message: $scope.msg.body, subject: $scope.msg.subject }, email: $scope.msg.email }; var url = 'https://codebrag.uservoice.com/api/v1/tickets/create_via_jsonp.json?' + $.param(data) + '&callback=JSON_CALLBACK'; return $http.jsonp(url); } } return { restrict: 'E', replace: true, scope: {}, templateUrl: 'views/popups/contactForm.html', controller: ContactFormPopup }; });
Use requests' reponse.text per documentation
import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ def assertRequest(self, method="GET", url="", status_code=200, contains=None, **kwargs): """ Asserts requests on a given endpoint """ if contains is None: cotains = [] if method is "GET": request = requests.get elif method is "POST": request = requests.post elif method is "PUT": request = requests.put elif method is "DELETE": request = requests.delete response = request(url, **kwargs) self.assertEqual(response.status_code, status_code) if contains: for item in contains: self.assertIn(item, response.text) def assertGet(self, *args, **kwargs): """ Asserts GET requests on a URL """ self.assertRequest("GET", *args, **kwargs) def assertPost(self, *args, **kwargs): """ Asserts POST requests on a URL """ self.assertRequest("POST", *args, **kwargs) def assertPut(self, *args, **kwargs): """ Asserts PUT requests on a URL """ self.assertRequest("PUT", *args, **kwargs) def assertDelete(self, *args, **kwargs): """ Asserts DELETE requests on a URL """ self.assertRequest("DELETE", *args, **kwargs)
import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ def assertRequest(self, method="GET", url="", status_code=200, contains=None, **kwargs): """ Asserts requests on a given endpoint """ if contains is None: cotains = [] if method is "GET": request = requests.get elif method is "POST": request = requests.post elif method is "PUT": request = requests.put elif method is "DELETE": request = requests.delete response = request(url, **kwargs) self.assertEqual(response.status_code, status_code) if contains: for item in contains: self.assertIn(item, response.content) def assertGet(self, *args, **kwargs): """ Asserts GET requests on a URL """ self.assertRequest("GET", *args, **kwargs) def assertPost(self, *args, **kwargs): """ Asserts POST requests on a URL """ self.assertRequest("POST", *args, **kwargs) def assertPut(self, *args, **kwargs): """ Asserts PUT requests on a URL """ self.assertRequest("PUT", *args, **kwargs) def assertDelete(self, *args, **kwargs): """ Asserts DELETE requests on a URL """ self.assertRequest("DELETE", *args, **kwargs)
Set textarea value using 'value' prop
import ClearButton from '../buttons/ClearButton' import React, {PropTypes} from 'react' import FormBuilderPropTypes from '../FormBuilderPropTypes' import equals from 'shallow-equals' import styles from './styles/Text.css' export default class Str extends React.Component { static displayName = 'Text'; static propTypes = { field: FormBuilderPropTypes.field.isRequired, value: PropTypes.string, onChange: PropTypes.func }; static defaultProps = { value: '', onChange() {} }; constructor(props, context) { super(props, context) this.handleChange = this.handleChange.bind(this) } shouldComponentUpdate(nextProps) { return !equals(this.props, nextProps) } handleChange(e) { const val = e.target.value || undefined this.props.onChange({patch: {$set: val}}) } render() { const {value, field} = this.props return ( <div className={styles.root}> <div className={styles.inner}> <ClearButton className={styles.clearButton} /> <textarea className={styles.textarea} placeholder={field.placeholder} onChange={this.handleChange} rows={field.rows || 10} value={value} > </textarea> </div> </div> ) } }
import ClearButton from '../buttons/ClearButton' import React, {PropTypes} from 'react' import FormBuilderPropTypes from '../FormBuilderPropTypes' import equals from 'shallow-equals' import styles from './styles/Text.css' export default class Str extends React.Component { static displayName = 'Text'; static propTypes = { field: FormBuilderPropTypes.field.isRequired, value: PropTypes.string, onChange: PropTypes.func }; static defaultProps = { value: '', onChange() {} }; constructor(props, context) { super(props, context) this.handleChange = this.handleChange.bind(this) } shouldComponentUpdate(nextProps) { return !equals(this.props, nextProps) } handleChange(e) { const val = e.target.value || undefined this.props.onChange({patch: {$set: val}}) } render() { const {value, field} = this.props return ( <div className={styles.root}> <div className={styles.inner}> <ClearButton className={styles.clearButton} /> <textarea className={styles.textarea} placeholder={field.placeholder} onChange={this.handleChange} rows={field.rows || 10} > {value} </textarea> </div> </div> ) } }
Update selectors in Capsule CRM integration Update the class selectors used in the Capsule integration to reflect changes in Capsule.
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; // List items togglbutton.render('.list li:not(.toggl)', {observe: true}, function (elem) { var link, taskElement = $('.task-title', elem), description = $('a', taskElement).textContent.trim(), projectName = function () { var label = $('span.highlight', taskElement); if (!!label) { return label.textContent; } return ""; }; link = togglbutton.createTimerLink({ className: 'capsule', description: description, projectName: projectName, buttonType: 'minimal' }); taskElement.appendChild(link); }); // List items in new UI togglbutton.render('.general-task-item:not(.toggl)', {observe: true}, function (elem) { var link, taskElement = $('.general-task-item-title', elem), description = function () { var desc = $('.general-task-item-title-text', elem); if (!!desc) { return desc.textContent.trim(); } return ""; }, projectName = function () { var label = $('.general-task-item-category', elem); if (!!label) { return label.textContent; } return ""; }; link = togglbutton.createTimerLink({ className: 'capsule', description: description, projectName: projectName, buttonType: 'minimal' }); taskElement.appendChild(link); });
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; // List items togglbutton.render('.list li:not(.toggl)', {observe: true}, function (elem) { var link, taskElement = $('.task-title', elem), description = $('a', taskElement).textContent.trim(), projectName = function () { var label = $('span.highlight', taskElement); if (!!label) { return label.textContent; } return ""; }; link = togglbutton.createTimerLink({ className: 'capsule', description: description, projectName: projectName, buttonType: 'minimal' }); taskElement.appendChild(link); }); // List items in new UI togglbutton.render('.task-item:not(.toggl)', {observe: true}, function (elem) { var link, taskElement = $('.task-item-title', elem), description = function () { var desc = $('.task-item-title-text', elem); if (!!desc) { return desc.textContent.trim(); } return ""; }, projectName = function () { var label = $('span.task-item-category', elem); if (!!label) { return label.textContent; } return ""; }; link = togglbutton.createTimerLink({ className: 'capsule', description: description, projectName: projectName, buttonType: 'minimal' }); taskElement.appendChild(link); });
Fix load config from local db config file
import click from .history import clone from . import config def validate_remote(ctx, param, value): if value: try: remote, branch = value.split('/') return (remote, branch) except ValueError: raise click.BadParameter('remote need to be in format <remote>/<branch>') def validate_cols(ctx, param, value): if value: try: validated = {c: index for index, c in enumerate(value.split(',')) if c} for col in ('name', 'login', 'password'): assert col in validated return validated except (AttributeError, ValueError): raise click.BadParameter('cols need to be in format col1,col2,col3') except AssertionError as e: raise click.BadParameter('missing mandatory column: {}'.format(e)) def validate_config(ctx, param, value): overrides = {k: v for k, v in ctx.params.items() if v} configuration = {} configuration.update(config.DEFAULT) # Default configuration configuration.update(config.read(config.HOMEDIR, '.passpierc')) # Global configuration if value: configuration.update(config.read(value)) # Options configuration configuration.update(overrides) # Command line options if config.is_repo_url(configuration['path']) is True: temporary_path = clone(configuration['path'], depth="1") configuration['path'] = temporary_path configuration.update(config.read(configuration['path'])) configuration = config.setup_crypt(configuration) return configuration
import click from .history import clone from . import config def validate_remote(ctx, param, value): if value: try: remote, branch = value.split('/') return (remote, branch) except ValueError: raise click.BadParameter('remote need to be in format <remote>/<branch>') def validate_cols(ctx, param, value): if value: try: validated = {c: index for index, c in enumerate(value.split(',')) if c} for col in ('name', 'login', 'password'): assert col in validated return validated except (AttributeError, ValueError): raise click.BadParameter('cols need to be in format col1,col2,col3') except AssertionError as e: raise click.BadParameter('missing mandatory column: {}'.format(e)) def validate_config(ctx, param, value): overrides = {k: v for k, v in ctx.params.items() if v} configuration = {} configuration.update(config.DEFAULT) # Default configuration configuration.update(config.read(config.HOMEDIR, '.passpierc')) # Global configuration if value: configuration.update(config.read(value)) # Options configuration configuration.update(overrides) # Command line options if config.is_repo_url(configuration['path']) is True: temporary_path = clone(configuration['path'], depth="1") configuration.update(config.read(temporary_path)) # Read cloned config configuration['path'] = temporary_path configuration = config.setup_crypt(configuration) return configuration
Add information about date confirmed
var Promise = require('bluebird'); var moment = require('moment'); module.exports = { createOrSave: function(app, tournament) { if (!app.googleCalendar) { return Promise.reject(new Error('Calendar service not exist')); } var insert = Promise.promisify(app.googleCalendar.events.insert, {context: app.googleCalendar}); var update = Promise.promisify(app.googleCalendar.events.update, {context: app.googleCalendar}); var date = moment(tournament.date).format('YYYY-MM-DD'); let summary = tournament.isDateConfirmed ? '' : '/!\\ '; summary += `${tournament.town} - ${tournament.format || ?} - ${tournament.organizer}`; var options = { resource: { summary, description: tournament.information, location: tournament.adress, end: {date: date}, start: {date: date} } }; if (!tournament.regionId) { return Promise.reject(new Error('Region not defined')); } return app.models.Region.findById(tournament.regionId) .then(function (region) { if (!region) return Promise.reject(new Error('Region not defined')); options.calendarId = region.googleId; if (!options.calendarId) return Promise.reject(new Error('Region do not have calendar')); if (tournament.googleId) { options.eventId = tournament.googleId; return update(options); } else { return insert(options); } }); } };
var Promise = require('bluebird'); var moment = require('moment'); module.exports = { createOrSave: function(app, tournament) { if (!app.googleCalendar) { return Promise.reject(new Error('Calendar service not exist')); } var insert = Promise.promisify(app.googleCalendar.events.insert, {context: app.googleCalendar}); var update = Promise.promisify(app.googleCalendar.events.update, {context: app.googleCalendar}); var date = moment(tournament.date).format('YYYY-MM-DD'); var options = { resource: { summary: tournament.town + ' - ' + tournament.format + ' - ' + tournament.organizer, description: tournament.information, location: tournament.adress, end: {date: date}, start: {date: date} } }; if (!tournament.regionId) { return Promise.reject(new Error('Region not defined')); } return app.models.Region.findById(tournament.regionId) .then(function (region) { if (!region) return Promise.reject(new Error('Region not defined')); options.calendarId = region.googleId; if (!options.calendarId) return Promise.reject(new Error('Region do not have calendar')); if (tournament.googleId) { options.eventId = tournament.googleId; return update(options); } else { return insert(options); } }); } };
Fix a bunch of PEP8 warnings.
#! /usr/bin/env python import argparse import csv import itertools import logging import math import os import miseq_logging BAD_ERROR_RATE = 7.5 def parseArgs(): parser = argparse.ArgumentParser( description='Post-processing of short-read alignments.') parser.add_argument('quality_csv', type=argparse.FileType('rU'), help='QC error rate data, grouped by tile') parser.add_argument('bad_cycles_csv', type=argparse.FileType('w'), help='List of tiles and cycles rejected for poor quality') return parser.parse_args() logger = miseq_logging.init_logging_console_only(logging.DEBUG) def grouper(cycle): return (cycle['tile'], math.copysign(1, int(cycle['cycle']))) def main(): args = parseArgs() with args.quality_csv, args.bad_cycles_csv: reader = csv.DictReader(args.quality_csv) writer = csv.DictWriter(args.bad_cycles_csv, ['tile', 'cycle', 'errorrate'], lineterminator=os.linesep) writer.writeheader() for _tile_direction, cycles in itertools.groupby(reader, grouper): is_bad = False for cycle in cycles: errorrate = cycle['errorrate'] is_bad = (is_bad or errorrate == '' or float(errorrate) >= BAD_ERROR_RATE) if is_bad: writer.writerow(cycle) if __name__ == '__main__': main()
#! /usr/bin/env python import argparse import csv import itertools import logging import math import os import miseq_logging BAD_ERROR_RATE = 7.5 def parseArgs(): parser = argparse.ArgumentParser( description='Post-processing of short-read alignments.') parser.add_argument('quality_csv', type=argparse.FileType('rU'), help='QC error rate data, grouped by tile') parser.add_argument('bad_cycles_csv', type=argparse.FileType('w'), help='List of tiles and cycles rejected for poor quality') return parser.parse_args() logger = miseq_logging.init_logging_console_only(logging.DEBUG) def grouper(cycle): return (cycle['tile'], math.copysign(1, int(cycle['cycle']))) def main(): args = parseArgs() with args.quality_csv, args.bad_cycles_csv: reader = csv.DictReader(args.quality_csv) writer = csv.DictWriter(args.bad_cycles_csv, ['tile', 'cycle', 'errorrate'], lineterminator=os.linesep) writer.writeheader() for _tile_direction, cycles in itertools.groupby(reader, grouper): is_bad = False for cycle in cycles: errorrate = cycle['errorrate'] is_bad = (is_bad or errorrate == '' or float(errorrate) >= BAD_ERROR_RATE) if is_bad: writer.writerow(cycle) if __name__ == '__main__': main()
Use "having" instead of "where". We don't want to break the query and want to filter by all possible fields.
<? class QuickSearch extends Filter { /* * Quicksearch represents one-field filter which goes perfectly with a grid */ var $region=null; var $region_url=null; function defaultTemplate(){ return array('compact_form','form'); } function init(){ parent::init(); $this->useDQ($this->owner->dq); $this->addField('Search','q','Find'); $this->addButton('Go')->submitForm($this); $this->onSubmit()->submitForm($this); } function useFields($fields){ $this->fields=$fields; return $this; } function applyDQ($dq){ if(!($v=$this->get('q')))return; $v=addslashes($v); // quote it $q=array(); foreach($this->fields as $field){ $q[]="$field like '%".$v."%'"; } if($q){ $dq->having(join(' or ',$q)); } } function submitted(){ if(parent::submitted()){ $a=$this->add('Ajax'); if(!$this->region){ $a->redirect(); }else{ if($this->region_url){ $a->loadRegionURL($this->region,$this->region_url); }else{ $a->reloadRegion($this->region); } } $a->execute(); } } }
<? class QuickSearch extends Filter { /* * Quicksearch represents one-field filter which goes perfectly with a grid */ var $region=null; var $region_url=null; function defaultTemplate(){ return array('compact_form','form'); } function init(){ parent::init(); $this->useDQ($this->owner->dq); $this->addField('Search','q','Find'); $this->addButton('Go')->submitForm($this); $this->onSubmit()->submitForm($this); } function useFields($fields){ $this->fields=$fields; return $this; } function applyDQ($dq){ if(!($v=$this->get('q')))return; $v=addslashes($v); // quote it $q=array(); foreach($this->fields as $field){ $q[]="$field like '%".$v."%'"; } if($q){ $dq->where(join(' or ',$q)); } } function submitted(){ if(parent::submitted()){ $a=$this->add('Ajax'); if(!$this->region){ $a->redirect(); }else{ if($this->region_url){ $a->loadRegionURL($this->region,$this->region_url); }else{ $a->reloadRegion($this->region); } } $a->execute(); } } }
Include templates in package distribution
import sys from setuptools import setup # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) setup( name='django-verified-email', version='0.1.1', description='Verified email changes for django', long_description=long_description, license='BSD', packages=['verified_email_change'], install_requires=[ 'Django>=1.7', 'django-ogmios', 'django-decoratormixins', 'django-absoluteuri', ], cmdclass={'test': PyTest}, tests_require=[ 'pytest', 'pytest-cov', 'pytest-django', ], package_data={ '': ['templates/**/*.html'], }, )
import sys from setuptools import setup # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) setup( name='django-verified-email', version='0.1.1.dev0', description='Verified email changes for django', long_description=long_description, license='BSD', packages=['verified_email_change'], install_requires=[ 'Django>=1.7', 'django-ogmios', 'django-decoratormixins', 'django-absoluteuri', ], cmdclass={'test': PyTest}, tests_require=[ 'pytest', 'pytest-cov', 'pytest-django', ], )
Apply label in TextField Object.
/** * Main application class of "QxMaterialDemo". */ qx.Class.define("qxmaterialdemo.Application", { extend: qxm.Application, // extend: qxm.application.Standalone, members: { /** * This method contains the initial application code and gets called * during startup of the application * * @lint ignoreDeprecated(alert) */ main: function() { // Call super class this.base(arguments); // Enable logging in debug variant if (qx.core.Environment.get("qx.debug")) { // support native logging capabilities, e.g. Firebug for Firefox qx.log.appender.Native; } /* Enable context menu */ qx.core.Init.getApplication().getRoot().setNativeContextMenu(true); var root = this.getRoot(); // Document is the application root var doc = new qxm.ui.container.Composite(new qxm.ui.layout.VBox()); root.add(doc, {top: 0, left: 0, bottom: 0, right: 0}); // Create a button var textfield = new qxm.ui.form.MTextField().set({label: 'First Text'}); doc.add(textfield); // Create a button var button = new qxm.ui.form.Button("First Button"); button.addListener("execute", function(e) { componentHandler.upgradeDom(); alert("Hello World!"); }); doc.add(button); componentHandler.upgradeDom(); } } });
/** * Main application class of "QxMaterialDemo". */ qx.Class.define("qxmaterialdemo.Application", { extend: qxm.Application, // extend: qxm.application.Standalone, members: { /** * This method contains the initial application code and gets called * during startup of the application * * @lint ignoreDeprecated(alert) */ main: function() { // Call super class this.base(arguments); // Enable logging in debug variant if (qx.core.Environment.get("qx.debug")) { // support native logging capabilities, e.g. Firebug for Firefox qx.log.appender.Native; } /* Enable context menu */ qx.core.Init.getApplication().getRoot().setNativeContextMenu(true); var root = this.getRoot(); // Document is the application root var doc = new qxm.ui.container.Composite(new qxm.ui.layout.VBox()); root.add(doc, {top: 0, left: 0, bottom: 0, right: 0}); // Create a button var textfield = new qxm.ui.form.MTextField(); doc.add(textfield); // Create a button var button = new qxm.ui.form.Button("First Button"); button.addListener("execute", function(e) { componentHandler.upgradeDom(); alert("Hello World!"); }); doc.add(button); componentHandler.upgradeDom(); } } });
Add __repr__ and __str__ methods to dummy object.
#!/usr/bin/env python """Simple library for parsing deeply nested structure (dict, json) into regular object. You can specify fields to extract, and argument names in created object. Example content = { 'name': 'Bob', 'details': { 'email': '[email protected]', } } fields = ( ('name', ), ('details__email', 'details_email') ) item = deep_parse_dict(content, fields) assert item.name == 'Bob' assert item.details_email == '[email protected]' """ class DeepParseObject(object): """Simple dummy object to hold content.""" def __str__(self): return 'DeepParseObject: %s' % self.__dict__ def __repr__(self): return 'DeepParseObject: %r' % self.__dict__ def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse
#!/usr/bin/env python """Simple library for parsing deeply nested structure (dict, json) into regular object. You can specify fields to extract, and argument names in created object. Example content = { 'name': 'Bob', 'details': { 'email': '[email protected]', } } fields = ( ('name', ), ('details__email', 'details_email') ) item = deep_parse_dict(content, fields) assert item.name == 'Bob' assert item.details_email == '[email protected]' """ class DeepParseObject(object): """Simple dummy object to hold content.""" pass def deep_parse_dict(content, fields, exc_class=Exception, separator='__'): """Extracting fields specified in ``fields`` from ``content``.""" deep_parse = DeepParseObject() for field in fields: try: lookup_name, store_name = field[0], field[0] if len(field) > 1: lookup_name, store_name = field parts = lookup_name.split(separator) value = content for part in parts: value = value[part] setattr(deep_parse, store_name, value) except Exception as original_exc: exc = exc_class('Error parsing field %r' % field) exc.error_field = field exc.original_exc = original_exc raise exc return deep_parse
Add time complexity for zigzagArray problem
/* Input array: 8 7 9 2 1 10 < > < > < 7 9 2 8 1 10 */ import java.util.*; import java.lang.*; class Solution{ public static Scanner sc = new Scanner(System.in); public static void main(String[] args){ int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } zigZagSort(arr,n); print(arr,n); } public static void zigZagSort(int[] arr, int n){ boolean toggle = true; int temp = 0; for(int i=0;i<n-1;i++){ if(toggle){ // should be a < b if(arr[i]>arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } else{ // should be a < b if(arr[i]<arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } toggle=!toggle; } } public static void print(int[] arr,int n){ for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } } // Complexity of the algorithm is O(n), where n is number of elements in the array
/* Input array: 8 7 9 2 1 10 < > < > < 7 9 2 8 1 10 */ import java.util.*; import java.lang.*; class Solution{ public static Scanner sc = new Scanner(System.in); public static void main(String[] args){ int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } zigZagSort(arr,n); print(arr,n); } public static void zigZagSort(int[] arr, int n){ boolean toggle = true; int temp = 0; for(int i=0;i<n-1;i++){ if(toggle){ // should be a < b if(arr[i]>arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } else{ // should be a < b if(arr[i]<arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } toggle=!toggle; } } public static void print(int[] arr,int n){ for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } }
Fix a regression in accessing the username for the session. My previous optimization to fetching the user resource along with the session broke the `get_username()` function, which attempted to follow a now non-existent link. It's been updated to get the expanded user resource instead and access the username from that. Testing Done: Ran `rbt status`. Before, it would crash with an attribute error. After, it showed me a list of my open review requests. Reviewed at https://reviews.reviewboard.org/r/6900/
from __future__ import unicode_literals import getpass import logging import sys from six.moves import input from rbtools.api.errors import AuthorizationError from rbtools.commands import CommandError def get_authenticated_session(api_client, api_root, auth_required=False): """Return an authenticated session. None will be returned if the user is not authenticated, unless the 'auth_required' parameter is True, in which case the user will be prompted to login. """ session = api_root.get_session(expand='user') if not session.authenticated: if not auth_required: return None logging.warning('You are not authenticated with the Review Board ' 'server at %s, please login.' % api_client.url) sys.stderr.write('Username: ') username = input() password = getpass.getpass(b'Password: ') api_client.login(username, password) try: session = session.get_self() except AuthorizationError: raise CommandError('You are not authenticated.') return session def get_user(api_client, api_root, auth_required=False): """Return the user resource for the current session.""" session = get_authenticated_session(api_client, api_root, auth_required) if session: return session.user return None def get_username(api_client, api_root, auth_required=False): """Return the username for the current session.""" user = get_user(api_client, api_root, auth_required) if user: return user.username return None
from __future__ import unicode_literals import getpass import logging import sys from six.moves import input from rbtools.api.errors import AuthorizationError from rbtools.commands import CommandError def get_authenticated_session(api_client, api_root, auth_required=False): """Return an authenticated session. None will be returned if the user is not authenticated, unless the 'auth_required' parameter is True, in which case the user will be prompted to login. """ session = api_root.get_session(expand='user') if not session.authenticated: if not auth_required: return None logging.warning('You are not authenticated with the Review Board ' 'server at %s, please login.' % api_client.url) sys.stderr.write('Username: ') username = input() password = getpass.getpass(b'Password: ') api_client.login(username, password) try: session = session.get_self() except AuthorizationError: raise CommandError('You are not authenticated.') return session def get_user(api_client, api_root, auth_required=False): """Return the user resource for the current session.""" session = get_authenticated_session(api_client, api_root, auth_required) if session: return session.user def get_username(api_client, api_root, auth_required=False): """Return the username for the current session.""" session = get_authenticated_session(api_client, api_root, auth_required) if session: return session.links.user.title
[Notifier][Slack] Remove :void from test methods
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Notifier\Bridge\Slack\Tests; use PHPUnit\Framework\TestCase; use Symfony\Component\Notifier\Bridge\Slack\SlackTransportFactory; use Symfony\Component\Notifier\Exception\UnsupportedSchemeException; use Symfony\Component\Notifier\Transport\Dsn; final class SlackTransportFactoryTest extends TestCase { public function testCreateWithDsn() { $factory = new SlackTransportFactory(); $host = 'testHost'; $path = 'testPath'; $transport = $factory->create(Dsn::fromString(sprintf('slack://%s/%s', $host, $path))); $this->assertSame(sprintf('slack://%s/%s', $host, $path), (string) $transport); } public function testSupportsSlackScheme() { $factory = new SlackTransportFactory(); $this->assertTrue($factory->supports(Dsn::fromString('slack://host/path'))); $this->assertFalse($factory->supports(Dsn::fromString('somethingElse://host/path'))); } public function testNonSlackSchemeThrows() { $factory = new SlackTransportFactory(); $this->expectException(UnsupportedSchemeException::class); $factory->create(Dsn::fromString('somethingElse://host/path')); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Notifier\Bridge\Slack\Tests; use PHPUnit\Framework\TestCase; use Symfony\Component\Notifier\Bridge\Slack\SlackTransportFactory; use Symfony\Component\Notifier\Exception\UnsupportedSchemeException; use Symfony\Component\Notifier\Transport\Dsn; final class SlackTransportFactoryTest extends TestCase { public function testCreateWithDsn(): void { $factory = new SlackTransportFactory(); $host = 'testHost'; $path = 'testPath'; $transport = $factory->create(Dsn::fromString(sprintf('slack://%s/%s', $host, $path))); $this->assertSame(sprintf('slack://%s/%s', $host, $path), (string) $transport); } public function testSupportsSlackScheme(): void { $factory = new SlackTransportFactory(); $this->assertTrue($factory->supports(Dsn::fromString('slack://host/path'))); $this->assertFalse($factory->supports(Dsn::fromString('somethingElse://host/path'))); } public function testNonSlackSchemeThrows(): void { $factory = new SlackTransportFactory(); $this->expectException(UnsupportedSchemeException::class); $factory->create(Dsn::fromString('somethingElse://host/path')); } }
Improve user edit modal, now it saves the last name and bio
/*****************************************************************************/ /* UserProfileEdit: Event Handlers */ /*****************************************************************************/ Template.UserProfileEdit.events({ 'click #confirm': function(event) { event.preventDefault(); var newUsername = $('#new-username').val(); var newFirstName = $('#new-firstname').val(); var newLastname = $('#new-lastname').val(); var newEmail = $('#new-email').val(); var newBio = $('#new-bio').val(); var newPassword = $('#new-password').val(); // Validate username, e-mail and password // Save new data if (newFirstName) { Meteor.users.update({ _id: Meteor.userId() }, { $set: { "profile.firstName": newFirstName } }); } if (newLastName) { Meteor.users.update({ _id: Meteor.userId() }, { $set: { "profile.lastName": newLastName } }); } if (newBio) { Meteor.users.update({ _id: Meteor.userId() }, { $set: { "profile.bio": newBio } }); } } }); /*****************************************************************************/ /* UserProfileEdit: Helpers */ /*****************************************************************************/ Template.UserProfileEdit.helpers({ data: function() { return this; } }); /*****************************************************************************/ /* UserProfileEdit: Lifecycle Hooks */ /*****************************************************************************/ Template.UserProfileEdit.onCreated(function() {}); Template.UserProfileEdit.onRendered(function() {}); Template.UserProfileEdit.onDestroyed(function() {});
/*****************************************************************************/ /* UserProfileEdit: Event Handlers */ /*****************************************************************************/ Template.UserProfileEdit.events({ 'click #confirm': function(event) { event.preventDefault(); var newUsername = $('#new-username').val(); var newFirstName = $('#new-firstname').val(); var newLastname = $('#new-lastname').val(); var newEmail = $('#new-email').val(); var newBio = $('#new-bio').val(); var newPassword = $('#new-password').val(); // Validate username, e-mail and password // Save new data if (newFirstName) { Meteor.users.update({ _id: Meteor.userId() }, { $set: { "profile.firstName": newFirstName } }); } } }); /*****************************************************************************/ /* UserProfileEdit: Helpers */ /*****************************************************************************/ Template.UserProfileEdit.helpers({ data: function() { return this; } }); /*****************************************************************************/ /* UserProfileEdit: Lifecycle Hooks */ /*****************************************************************************/ Template.UserProfileEdit.onCreated(function() {}); Template.UserProfileEdit.onRendered(function() {}); Template.UserProfileEdit.onDestroyed(function() {});
Change base path for dummy
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/ember-cli-toggle', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, 'ember-cli-toggle': { //includedThemes: ['light', 'ios', 'flip'], //excludedThemes: ['flip'], //defaultTheme: 'light', //defaultSize: 'small' } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'auto'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, 'ember-cli-toggle': { //includedThemes: ['light', 'ios', 'flip'], //excludedThemes: ['flip'], //defaultTheme: 'light', //defaultSize: 'small' } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'auto'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Allow minimatch match slashes too
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = o[p[0]]? o[p[0]].toLowerCase(): ''; var b = p[1]? p[1].toLowerCase(): ''; return minimatch(a, b, { matchBase: true }); }).filter(fp.id).length === zq.length; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = o[p[0]]? o[p[0]].toLowerCase(): ''; var b = p[1]? p[1].toLowerCase(): ''; return minimatch(a, b); }).filter(fp.id).length === zq.length; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
Add collection and db id injection
'use strict'; module.exports = { mongodb: { class: 'vendor.mongodb' }, db: { collections: ['db'], class: 'db', declinations: '$connections$', properties: { id: '@_@', connectionUrl: '@url@', connectionOptions: '@options@', mongodb: '#mongodb#' }, induced: { collection: { service: 'collection', factory: 'db', context: '@.@', property: 'collections', collection: true } } }, collection: { collections: ['collection'], class: 'collection', properties: { mongodb: '#mongodb#' }, factories: { db: { declinations: '!collections!', properties: { id: '@_@', name: '@name@', document: '@document@', options: '@options@', indexes: '@indexes@' } } } } };
'use strict'; module.exports = { mongodb: { class: 'vendor.mongodb' }, db: { collections: ['db'], class: 'db', declinations: '$connections$', properties: { name: '@_@', connectionUrl: '@url@', connectionOptions: '@options@', mongodb: '#mongodb#' }, induced: { collection: { service: 'collection', factory: 'db', context: '@.@', property: 'collections', collection: true } } }, collection: { collections: ['collection'], class: 'collection', properties: { mongodb: '#mongodb#' }, factories: { db: { declinations: '!collections!', properties: { name: '@name@', document: '@document@', options: '@options@', indexes: '@indexes@' } } } } };
Add width heigt column to face migration file
<?php use yii\db\Migration; /** * Handles the creation of table `faces`. * Has foreign keys to the tables: * * - `image` */ class m170124_153250_create_faces_table extends Migration { /** * @inheritdoc */ public function up() { $this->createTable('faces', [ 'id' => $this->primaryKey(), 'image_id' => $this->integer()->notNull(), 'width' => $this->integer()->notNull(), 'height' => $this->integer()->notNull(), 'confident_level' => $this->string(), 'gender' => $this->string(), ]); // creates index for column `image_id` $this->createIndex( 'idx-faces-image_id', 'faces', 'image_id' ); // add foreign key for table `image` $this->addForeignKey( 'fk-faces-image_id', 'faces', 'image_id', 'image', 'id', 'CASCADE' ); } /** * @inheritdoc */ public function down() { // drops foreign key for table `image` $this->dropForeignKey( 'fk-faces-image_id', 'faces' ); // drops index for column `image_id` $this->dropIndex( 'idx-faces-image_id', 'faces' ); $this->dropTable('faces'); } }
<?php use yii\db\Migration; /** * Handles the creation of table `faces`. * Has foreign keys to the tables: * * - `image` */ class m170124_153250_create_faces_table extends Migration { /** * @inheritdoc */ public function up() { $this->createTable('faces', [ 'id' => $this->primaryKey(), 'image_id' => $this->integer()->notNull(), 'confident_level' => $this->string(), 'gender' => $this->string(), ]); // creates index for column `image_id` $this->createIndex( 'idx-faces-image_id', 'faces', 'image_id' ); // add foreign key for table `image` $this->addForeignKey( 'fk-faces-image_id', 'faces', 'image_id', 'image', 'id', 'CASCADE' ); } /** * @inheritdoc */ public function down() { // drops foreign key for table `image` $this->dropForeignKey( 'fk-faces-image_id', 'faces' ); // drops index for column `image_id` $this->dropIndex( 'idx-faces-image_id', 'faces' ); $this->dropTable('faces'); } }
Fix bash completion for HelpCommand and fully typed subcommands
package ee.shy.cli.command; import ee.shy.cli.Command; import ee.shy.cli.SuperCommand; import java.io.IOException; import java.util.Map; public class CompletionCommand implements Command { private final Command rootCommand; public CompletionCommand(Command rootCommand) { this.rootCommand = rootCommand; } @Override public void execute(String[] args) throws IOException { Command command = rootCommand; for (int i = 0; i <= args.length; i++) { // loop for one extra time for supercommands without arguments if (command instanceof SuperCommand) { Map<String, Command> subCommands = ((SuperCommand) command).getSubCommands(); Command subCommand; if ((i < args.length - 1) // complete subcommand even if fully typed (don't nest yet) && ((subCommand = subCommands.get(args[i])) != null)) { command = subCommand; } else { System.out.println(String.join(" ", subCommands.keySet())); break; } } else if (command instanceof HelpCommand) { command = ((HelpCommand) command).getRootCommand(); // changed command point without parsing extra argument i--; // step back for that extra argument } } } @Override public String getHelp() { return null; } }
package ee.shy.cli.command; import ee.shy.cli.Command; import ee.shy.cli.SuperCommand; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class CompletionCommand implements Command { private final Command rootCommand; public CompletionCommand(Command rootCommand) { this.rootCommand = rootCommand; } @Override public void execute(String[] args) throws IOException { List<String> argsList = new ArrayList<>(Arrays.asList(args)); argsList.add(null); Command command = rootCommand; for (String arg : argsList) { if (command instanceof SuperCommand) { Map<String, Command> subCommands = ((SuperCommand) command).getSubCommands(); Command subCommand = subCommands.get(arg); if (subCommand != null) { command = subCommand; } else { System.out.println(String.join(" ", subCommands.keySet())); break; } } else if (command instanceof HelpCommand) { command = ((HelpCommand) command).getRootCommand(); } } } @Override public String getHelp() { return null; } }
Use self.stdout.write() instead of print(). This is the recommended way in the Django documentation: https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/
import requests from django.core.management import call_command from django.core.management.base import NoArgsCommand from django.conf import settings from django.utils.six.moves import input class Command(NoArgsCommand): """ Download and load dev fixtures from www.python.org """ help = "Download and load dev fixtures from python.org" def handle_noargs(self, **options): # Confirm the user wants to do this confirm = input("""You have requested to load the python.org development fixtures. This will IRREVERSIBLY DESTROY all data currently in your local database. Are you sure you want to do this? Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """) if confirm in ('y', 'yes'): self.stdout.write("\nBeginning download, note this can take a couple of minutes...") r = requests.get(settings.DEV_FIXTURE_URL, stream=True) if r.status_code != 200: self.stdout.write("Unable to download file: Received status code {}".format(r.status_code)) with open('/tmp/dev-fixtures.json.gz', 'wb') as f: for chunk in r.iter_content(chunk_size=1024): f.write(chunk) f.flush() self.stdout.write("Download complete, loading fixtures") call_command('loaddata', '/tmp/dev-fixtures.json') self.stdout.write("END: Fixtures loaded")
import requests from django.core.management import call_command from django.core.management.base import NoArgsCommand from django.conf import settings from django.utils.six.moves import input class Command(NoArgsCommand): """ Download and load dev fixtures from www.python.org """ help = "Download and load dev fixtures from python.org" def handle_noargs(self, **options): # Confirm the user wants to do this confirm = input("""You have requested to load the python.org development fixtures. This will IRREVERSIBLY DESTROY all data currently in your local database. Are you sure you want to do this? Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """) if confirm in ('y', 'yes'): if confirm: print() print("Beginning download, note this can take a couple of minutes...") r = requests.get(settings.DEV_FIXTURE_URL, stream=True) if r.status_code != 200: print("Unable to download file: Received status code {}".format(r.status_code)) with open('/tmp/dev-fixtures.json.gz', 'wb') as f: for chunk in r.iter_content(chunk_size=1024): f.write(chunk) f.flush() print("Download complete, loading fixtures") call_command('loaddata', '/tmp/dev-fixtures.json') print("END: Fixtures loaded")
Use more natural constructor call
// volontary written in ES5, so that it works with Node 4.x var path = require('path'); var webpack = require('webpack'); var ProgressBarPlugin = require('progress-bar-webpack-plugin'); var HasteMapWebPackResolver = require('haste-map-webpack-resolver'); var currentDir = path.resolve(__dirname, '.'); module.exports = { context: currentDir, entry: './entry-point.js', output: { path: './dist', filename: 'entry-point.bundle.js', library: 'entry-point', libraryTarget: 'umd', umdNamedDefine: true }, devtool: 'sourcemap', target: 'node', module: { rules: [ { test: /\.js/, exclude: /(node_modules)/, use: [ { loader: 'babel-loader', query: { presets: ['babel-preset-es2015'] }, } ] } ], }, resolve: { plugins: [new HasteMapWebPackResolver({ rootPath: path.resolve(__dirname, '.'), })], }, plugins: [ new webpack.BannerPlugin( { banner: 'require("source-map-support").install();', raw: true, entryOnly: false, } ), new ProgressBarPlugin(), ], };
// volontary written in ES5, so that it works with Node 4.x var path = require('path'); var webpack = require('webpack'); var ProgressBarPlugin = require('progress-bar-webpack-plugin'); var buildResolver = require('haste-map-webpack-resolver'); var currentDir = path.resolve(__dirname, '.'); module.exports = { context: currentDir, entry: './entry-point.js', output: { path: './dist', filename: 'entry-point.bundle.js', library: 'entry-point', libraryTarget: 'umd', umdNamedDefine: true }, devtool: 'sourcemap', target: 'node', module: { rules: [ { test: /\.js/, exclude: /(node_modules)/, use: [ { loader: 'babel-loader', query: { presets: ['babel-preset-es2015'] }, } ] } ], }, resolve: { plugins: [buildResolver({ rootPath: path.resolve(__dirname, '.'), })], }, plugins: [ new webpack.BannerPlugin( { banner: 'require("source-map-support").install();', raw: true, entryOnly: false, } ), new ProgressBarPlugin(), ], };
Adjust macro tests to new template location
#!/usr/bin/env python import unittest import os.path from macropolo import MacroTestCase, JSONTestCaseLoader from macropolo.environments import SheerEnvironment class CFGovTestCase(SheerEnvironment, MacroTestCase): """ A MacroTestCase subclass for cfgov-refresh. """ def search_root(self): """ Return the root of the search path for templates. """ # Get the cfgov-refresh root dir, ../../../ # PLEASE NOTE: This presumes that the file containing the test always # lives three levels above the cfgov-refresh root. templates = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, 'cfgov/jinja2/v1')) return templates def search_exceptions(self): """ Return a list of subdirectory names that should not be searched for templates. """ templates = 'cfgov/jinja2/v1' return [ templates + '/_defaults', templates + '/_lib', templates + '/_queries', templates + '/_settings', 'test', 'config' ] # Create CFGovTestCase subclasses for all JSON tests. tests_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'tests')) JSONTestCaseLoader(tests_path, CFGovTestCase, globals()) # Run the tests if we're executed if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest import os.path from macropolo import MacroTestCase, JSONTestCaseLoader from macropolo.environments import SheerEnvironment class CFGovTestCase(SheerEnvironment, MacroTestCase): """ A MacroTestCase subclass for cfgov-refresh. """ def search_root(self): """ Return the root of the search path for templates. """ # Get the cfgov-refresh root dir, ../../../ # PLEASE NOTE: This presumes that the file containing the test always # lives three levels above the cfgov-refresh root. templates = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, 'cfgov/v1/jinja2/v1')) return templates def search_exceptions(self): """ Return a list of subdirectory names that should not be searched for templates. """ templates = 'cfgov/v1/jinja2/v1' return [ templates + '/_defaults', templates + '/_lib', templates + '/_queries', templates + '/_settings', 'test', 'config' ] # Create CFGovTestCase subclasses for all JSON tests. tests_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'tests')) JSONTestCaseLoader(tests_path, CFGovTestCase, globals()) # Run the tests if we're executed if __name__ == '__main__': unittest.main()
Enhance compatibility with Symfony 5.
<?php declare(strict_types=1); /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015-2019, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\UserBundle\DataFixtures\ORM; use Darvin\UserBundle\Entity\BaseUser; use Darvin\UserBundle\User\UserFactoryInterface; use Darvin\Utils\DataFixtures\ORM\AbstractFixture; use Doctrine\Persistence\ObjectManager; /** * User data fixture */ class LoadUserData extends AbstractFixture { /** * {@inheritDoc} */ public function load(ObjectManager $manager): void { $manager->persist($this->createUser()); $manager->flush(); } /** * @return \Darvin\UserBundle\Entity\BaseUser */ private function createUser(): BaseUser { return $this->getUserFactory()->createUser() ->setEmail('[email protected]') ->setPlainPassword('admin') ->setRoles([ 'ROLE_SUPER_ADMIN', ]); } /** * @return \Darvin\UserBundle\User\UserFactoryInterface */ private function getUserFactory(): UserFactoryInterface { return $this->container->get('darvin_user.user.factory'); } }
<?php declare(strict_types=1); /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015-2019, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\UserBundle\DataFixtures\ORM; use Darvin\UserBundle\Entity\BaseUser; use Darvin\UserBundle\User\UserFactoryInterface; use Darvin\Utils\DataFixtures\ORM\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; /** * User data fixture */ class LoadUserData extends AbstractFixture { /** * {@inheritDoc} */ public function load(ObjectManager $manager): void { $manager->persist($this->createUser()); $manager->flush(); } /** * @return \Darvin\UserBundle\Entity\BaseUser */ private function createUser(): BaseUser { return $this->getUserFactory()->createUser() ->setEmail('[email protected]') ->setPlainPassword('admin') ->setRoles([ 'ROLE_SUPER_ADMIN', ]); } /** * @return \Darvin\UserBundle\User\UserFactoryInterface */ private function getUserFactory(): UserFactoryInterface { return $this->container->get('darvin_user.user.factory'); } }
Fix logging the JSON result
from sublime_plugin import WindowCommand from ...common import util from ...core.git_command import GitCommand from .. import github, git_mixins from GitSavvy.core.runtime import enqueue_on_worker START_CREATE_MESSAGE = "Forking {repo} ..." END_CREATE_MESSAGE = "Fork created successfully." __all__ = ['gs_github_create_fork'] class gs_github_create_fork( WindowCommand, git_mixins.GithubRemotesMixin, GitCommand, ): def run(self): enqueue_on_worker(self.run_async) def run_async(self): remotes = self.get_remotes() base_remote_name = self.get_integrated_remote_name(remotes) base_remote_url = remotes[base_remote_name] base_remote = github.parse_remote(base_remote_url) self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url)) result = github.create_fork(base_remote) self.window.status_message(END_CREATE_MESSAGE) util.debug.add_to_log({"github: fork result": result}) url = ( result["ssh_url"] if base_remote_url.startswith("git@") else result["clone_url"] ) self.window.run_command("gs_remote_add", { "url": url, "set_as_push_default": True })
from sublime_plugin import WindowCommand from ...common import util from ...core.git_command import GitCommand from .. import github, git_mixins from GitSavvy.core.runtime import enqueue_on_worker START_CREATE_MESSAGE = "Forking {repo} ..." END_CREATE_MESSAGE = "Fork created successfully." __all__ = ['gs_github_create_fork'] class gs_github_create_fork( WindowCommand, git_mixins.GithubRemotesMixin, GitCommand, ): def run(self): enqueue_on_worker(self.run_async) def run_async(self): remotes = self.get_remotes() base_remote_name = self.get_integrated_remote_name(remotes) base_remote_url = remotes[base_remote_name] base_remote = github.parse_remote(base_remote_url) self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url)) result = github.create_fork(base_remote) self.window.status_message(END_CREATE_MESSAGE) util.debug.add_to_log(("github: fork result:\n{}".format(result))) url = ( result["ssh_url"] if base_remote_url.startswith("git@") else result["clone_url"] ) self.window.run_command("gs_remote_add", { "url": url, "set_as_push_default": True })
Work around Chrome's over-eager validation of integration config form. Chrome loves to test the validation of forms, even going so far as to run validation on inputs which are not visible to the user. It then errors out on the console that it can't focus the input. This change goes through and adds the `disabled` prop to any tool option inputs which are hidden (because they don't apply to the currently-selected tool), working around the validation on the client. Testing Done: Was able to create an integration config for Review Bot without Chrome going nuts. Reviewed at https://reviews.reviewboard.org/r/11184/
$(function() { const $tool = $('#id_tool'); const $toolOptions = $('#row-tool_options'); if ($tool.length === 1 && $toolOptions.length === 1) { const $itemAboveOptions = $toolOptions.prev(); function changeToolVisibility() { const selectedTool = parseInt($tool.val(), 10); let $lastVisibleChild = null; $toolOptions.find('.form-row').each((i, el) => { const $el = $(el); const $input = $toolOptions.find('input, select, textarea'); if ($el.data('tool-id') === selectedTool) { $el.show(); $lastVisibleChild = $el; /* * Chrome validation will go nuts even on form fields that * aren't visible unless they're also disabled. */ $input.prop('disabled', true); } else { $el.hide(); $input.prop('disabled', false); } }); /* * Normally, the :last-child rule would hide this border. Instead, * we have to override it because the parent has a bunch of other * children after the last one that happen to be hidden. */ if ($lastVisibleChild !== null) { $lastVisibleChild.css('border-bottom', 0); $itemAboveOptions.css('border-bottom', ''); } else { $itemAboveOptions.css('border-bottom', 0); } } $tool.change(() => changeToolVisibility()); changeToolVisibility(); } });
$(function() { const $tool = $('#id_tool'); const $toolOptions = $('#row-tool_options'); if ($tool.length === 1 && $toolOptions.length === 1) { const $itemAboveOptions = $toolOptions.prev(); function changeToolVisibility() { const selectedTool = parseInt($tool.val(), 10); let $lastVisibleChild = null; $toolOptions.find('.form-row').each((i, el) => { const $el = $(el); if ($el.data('tool-id') === selectedTool) { $el.show(); $lastVisibleChild = $el; } else { $el.hide(); } }); /* * Normally, the :last-child rule would hide this border. Instead, * we have to override it because the parent has a bunch of other * children after the last one that happen to be hidden. */ if ($lastVisibleChild !== null) { $lastVisibleChild.css('border-bottom', 0); $itemAboveOptions.css('border-bottom', ''); } else { $itemAboveOptions.css('border-bottom', 0); } } $tool.change(() => changeToolVisibility()); changeToolVisibility(); } });
Make Graph an attribute rather than an inheritance
from rdflib import Graph from ktbs_bench.bnsparqlstore import SPARQLStore class BenchableStore: """Allows to use a store/graph for benchmarks. Contains a rdflib.Graph with setup and teardown. """ def __init__(self, store, graph_id, store_config, store_create=False): self.graph = Graph(store=store, identifier=graph_id) self._store_config = store_config self._store_create = store_create def connect(self, store_create=None): if store_create: do_create = store_create else: do_create = self._store_create self.graph.open(self._store_config, create=do_create) def close(self, commit_pending_transaction=False): self.graph.close(commit_pending_transaction=commit_pending_transaction) def destroy(self): if isinstance(self.graph.store, SPARQLStore): self.sparql_destroy() else: self.graph.destroy(self._store_config) def sparql_destroy(self): """Try to destroy the graph as if the current store is a SPARQLStore.""" # TODO improve destroy by using SPARQL CLEAR GRAPH if RDFLib supports it # or execute something on the command line for s, p, o in self.graph: self.graph.remove((s, p, o))
from rdflib import Graph from ktbs_bench.bnsparqlstore import SPARQLStore class BenchableStore(Graph): def __init__(self, connect_args, create_func=None, create_args=[], *args, **kwargs): super(BenchableStore, self).__init__(*args, **kwargs) self.connect_args = connect_args self.create_func = create_func self.create_args = create_args def connect(self): if isinstance(self.connect_args, dict): self.open(**self.connect_args) else: raise TypeError("connect_args must be a dict.") def create(self): if self.create_func: self.create_func(*self.create_args) # TODO gerer exception si db existe deja def destroy(self): """For SQL: destroy tables of the DB, not the DB itself.""" if isinstance(self.store, SPARQLStore): self.sparql_destroy() else: super(BenchableStore, self).destroy(self.connect_args['configuration']) def sparql_destroy(self): """Try to destroy the graph as if the current store is a SPARQLStore.""" # TODO improve destroy by using SPARQL CLEAR GRAPH if RDFLib supports it # or execute something on the command line for s, p, o in self: self.remove((s, p, o))
Use max number of attempts to scan user queues
'use strict'; var QUEUE = require('../job_queue').QUEUE; var MAX_SCAN_ATTEMPTS = 50; function QueueSeeker(pool) { this.pool = pool; } module.exports = QueueSeeker; QueueSeeker.prototype.seek = function (callback) { var initialCursor = ['0']; var attemps = 0; var users = {}; var self = this; this.pool.acquire(QUEUE.DB, function(err, client) { if (err) { return callback(err); } self._seek(client, initialCursor, users, attemps, function(err, users) { self.pool.release(QUEUE.DB, client); return callback(err, Object.keys(users)); }); }); }; QueueSeeker.prototype._seek = function (client, cursor, users, attemps, callback) { var self = this; var redisParams = [cursor[0], 'MATCH', QUEUE.PREFIX + '*']; client.scan(redisParams, function(err, currentCursor) { if (err) { return callback(null, users); } var queues = currentCursor[1]; if (queues) { queues.forEach(function (queue) { var user = queue.substr(QUEUE.PREFIX.length); users[user] = true; }); } var hasMore = currentCursor[0] !== '0' && attemps < MAX_SCAN_ATTEMPTS; if (!hasMore) { return callback(null, users); } attemps += 1; self._seek(client, currentCursor, users, attemps, callback); }); };
'use strict'; var QUEUE = require('../job_queue').QUEUE; function QueueSeeker(pool) { this.pool = pool; } module.exports = QueueSeeker; QueueSeeker.prototype.seek = function (callback) { var initialCursor = ['0']; var users = {}; var self = this; this.pool.acquire(QUEUE.DB, function(err, client) { if (err) { return callback(err); } self._seek(client, initialCursor, users, function(err, users) { self.pool.release(QUEUE.DB, client); return callback(err, Object.keys(users)); }); }); }; QueueSeeker.prototype._seek = function (client, cursor, users, callback) { var self = this; var redisParams = [cursor[0], 'MATCH', QUEUE.PREFIX + '*']; client.scan(redisParams, function(err, currentCursor) { if (err) { return callback(null, users); } var queues = currentCursor[1]; if (queues) { queues.forEach(function (queue) { var user = queue.substr(QUEUE.PREFIX.length); users[user] = true; }); } var hasMore = currentCursor[0] !== '0'; if (!hasMore) { return callback(null, users); } self._seek(client, currentCursor, users, callback); }); };
Add link to details for now
import React from 'react' import { Link } from 'gatsby' import './footer.css' const Footer = () => ( <div style={{ // position: 'absolute', // bottom: '0', // left: '0', // right: '0', background: '#0C192E', marginBottom: '0rem', height: '80px', }} > <div className="footer" style={{ margin: '0 auto', maxWidth: 960, padding: '1.45rem 1.0875rem', }} > <p style={{ margin: 0 }}> <Link to="/" style={{ color: 'white', textDecoration: 'none', }} > <i className="material-icons">map</i> </Link> </p> <p style={{ margin: 0 }}> <Link to="/list" style={{ color: 'white', textDecoration: 'none', }} > <i className="material-icons">list</i> </Link> </p> <p style={{ margin: 0 }}> <Link to="/details" style={{ color: 'white', textDecoration: 'none', }} > {/* {siteTitle} */} <i className="material-icons">info</i> </Link> </p> </div> </div> ) export default Footer
import React from 'react' import { Link } from 'gatsby' import './footer.css' const Footer = () => ( <div style={{ // position: 'absolute', // bottom: '0', // left: '0', // right: '0', background: '#0C192E', marginBottom: '0rem', height: '80px', }} > <div className="footer" style={{ margin: '0 auto', maxWidth: 960, padding: '1.45rem 1.0875rem', }} > <p style={{ margin: 0 }}> <Link to="/" style={{ color: 'white', textDecoration: 'none', }} > <i className="material-icons">map</i> </Link> </p> <p style={{ margin: 0 }}> <Link to="/list" style={{ color: 'white', textDecoration: 'none', }} > <i className="material-icons">list</i> </Link> </p> <p style={{ margin: 0 }}> <Link to="/" style={{ color: 'white', textDecoration: 'none', }} > {/* {siteTitle} */} <i className="material-icons">info</i> </Link> </p> </div> </div> ) export default Footer
Handle 404s due to index not existing when doing versioning
import json import logging from elasticsearch import Elasticsearch from scrapi import settings from scrapi.processing.base import BaseProcessor es = Elasticsearch( settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT ) logging.getLogger('elasticsearch').setLevel(logging.WARN) logging.getLogger('elasticsearch.trace').setLevel(logging.WARN) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) es.cluster.health(wait_for_status='yellow') logger = logging.getLogger(__name__) class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized): data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } normalized['dateUpdated'] = self.version_dateUpdated(normalized) es.index( body=data, refresh=True, index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) def version_dateUpdated(self, normalized): try: old_doc = es.get_source( index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) except elasticsearch.IndexMissingException: return normalized['dateUpdated'] return old_doc['dateUpdated'] if old_doc else normalized['dateUpdated']
import json import logging from elasticsearch import Elasticsearch from scrapi import settings from scrapi.processing.base import BaseProcessor es = Elasticsearch( settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT ) logging.getLogger('elasticsearch').setLevel(logging.WARN) logging.getLogger('elasticsearch.trace').setLevel(logging.WARN) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) es.cluster.health(wait_for_status='yellow') logger = logging.getLogger(__name__) class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized): data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } normalized['dateUpdated'] = self.version_dateUpdated(normalized) es.index( body=data, refresh=True, index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) def version_dateUpdated(self, normalized): old_doc = es.get_source( index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ignore=[404] ) logger.info(json.dumps(old_doc, indent=4)) return old_doc['dateUpdated'] if old_doc else normalized['dateUpdated']
Add conditional import of the enum34 library This lib is used to bing enumerations to Python <= 3.3.
""" This module gives the "listener" classes for the PyEcore notification layer. The main class to create a new listener is "EObserver" which is triggered each time a modification is perfomed on an observed element. """ try: from enum34 import unique, Enum except ImportError: from enum import unique, Enum class ENotifer(object): def notify(self, notification): notification.notifier = notification.notifier or self for listener in self._eternal_listener + self.listeners: listener.notifyChanged(notification) @unique class Kind(Enum): ADD = 0 ADD_MANY = 1 MOVE = 2 REMOVE = 3 REMOVE_MANY = 4 SET = 5 UNSET = 6 class Notification(object): def __init__(self, notifier=None, kind=None, old=None, new=None, feature=None): self.notifier = notifier self.kind = kind self.old = old self.new = new self.feature = feature def __repr__(self): return ('[{0}] old={1} new={2} obj={3} #{4}' .format(self.kind.name, self.old, self.new, self.notifier, self.feature)) class EObserver(object): def __init__(self, notifier=None, notifyChanged=None): if notifier: notifier.listeners.append(self) if notifyChanged: self.notifyChanged = notifyChanged def observe(self, notifier): notifier.listeners.append(self) def notifyChanged(self, notification): pass
""" This module gives the "listener" classes for the PyEcore notification layer. The main class to create a new listener is "EObserver" which is triggered each time a modification is perfomed on an observed element. """ class ENotifer(object): def notify(self, notification): notification.notifier = notification.notifier or self for listener in self._eternal_listener + self.listeners: listener.notifyChanged(notification) @unique class Kind(Enum): ADD = 0 ADD_MANY = 1 MOVE = 2 REMOVE = 3 REMOVE_MANY = 4 SET = 5 UNSET = 6 class Notification(object): def __init__(self, notifier=None, kind=None, old=None, new=None, feature=None): self.notifier = notifier self.kind = kind self.old = old self.new = new self.feature = feature def __repr__(self): return ('[{0}] old={1} new={2} obj={3} #{4}' .format(self.kind.name, self.old, self.new, self.notifier, self.feature)) class EObserver(object): def __init__(self, notifier=None, notifyChanged=None): if notifier: notifier.listeners.append(self) if notifyChanged: self.notifyChanged = notifyChanged def observe(self, notifier): notifier.listeners.append(self) def notifyChanged(self, notification): pass
Make generic (can now be applied to pages and dataobjects)
<?php class FaqSegment extends DataObject { private static $db = [ 'Title' => 'Varchar(255)', 'Answer' => 'HTMLText', 'SortOrder' => 'Int' ]; private static $has_one = [ 'OwnerObject' => 'DataObject' ]; private static $default_sort = 'SortOrder'; private static $field_labels = [ 'Title' => 'Question', 'Answer' => 'Answer' ]; public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->addFieldsToTab('Root.Main', [ TextField::create('Title', 'Question'), HtmlEditorField::create('Answer', 'Answer')->setRows(20) ]); $fields->removeByName('SortOrder'); $fields->removeByName('PageID'); }); $fields = parent::getCMSFields(); return $fields; } public function canView($member = null) { return true; } public function canEdit($member = null) { return true; } public function canDelete($member = null) { return true; } public function canCreate($member = null) { return true; } }
<?php class FaqSegment extends DataObject { private static $db = [ 'Title' => 'Varchar(255)', 'Answer' => 'HTMLText', 'SortOrder' => 'Int' ]; private static $has_one = [ 'Page' => 'Page' ]; private static $default_sort = 'SortOrder'; private static $field_labels = [ 'Title' => 'Question', 'Answer' => 'Answer' ]; public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->addFieldsToTab('Root.Main', [ TextField::create('Title', 'Question'), HtmlEditorField::create('Answer', 'Answer')->setRows(20) ]); $fields->removeByName('SortOrder'); $fields->removeByName('PageID'); }); $fields = parent::getCMSFields(); return $fields; } public function canView($member = null) { return true; } public function canEdit($member = null) { return true; } public function canDelete($member = null) { return true; } public function canCreate($member = null) { return true; } }
Remove unnecesary logs from order function
/* global console, Calendar, vis */ (function() { "use strict"; var calendar = new Calendar(); calendar.init(document.getElementById('visualization'), { height: "100vh", orientation: "top", zoomKey: 'shiftKey', zoomMax: 315360000000, zoomMin: 600000, editable: { add: false, updateTime: true, updateGroup: false, remove: true }, groupOrder: function (a, b) { if (a.id === "Demos") { return -1; } if (b.id === "Demos") { return 1; } var groups = [a.id, b.id]; groups.sort(); if (a.id === groups[0]) { return -1; } else { return 1; } } }); $(document).ready(function(){ $('.vis-center>.vis-content').on('scroll', function () { $('.vis-left>.vis-content').scrollTop($(this).scrollTop()); }); $('.vis-left>.vis-content').on('scroll', function () { $('.vis-center>.vis-content').scrollTop($(this).scrollTop()); }); }); })();
/* global console, Calendar, vis */ (function() { "use strict"; var calendar = new Calendar(); calendar.init(document.getElementById('visualization'), { height: "100vh", orientation: "top", zoomKey: 'shiftKey', zoomMax: 315360000000, zoomMin: 600000, editable: { add: false, updateTime: true, updateGroup: false, remove: true }, groupOrder: function (a, b) { console.log("Ordenar!!"); console.log(a.id); console.log(b.id); if (a.id === "demos") { return -1; } if (b.id === "demos") { return 1; } var groups = [a.id, b.id]; groups.sort(); if (a.id === groups[0]) { return -1; } else { return 1; } } }); $(document).ready(function(){ $('.vis-center>.vis-content').on('scroll', function () { $('.vis-left>.vis-content').scrollTop($(this).scrollTop()); }); $('.vis-left>.vis-content').on('scroll', function () { $('.vis-center>.vis-content').scrollTop($(this).scrollTop()); }); }); })();
Update the javadoc to show that the basic ontology information can come from go terms OR eco terms
package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model; import uk.ac.ebi.quickgo.rest.comm.ResponseType; import java.util.List; /** * Represents part of the model corresponding to the response available from the resource: * * <ul> * <li>/go/terms/{term}</li> * </ul> * * or * * <ul> * <li>/eco/terms/{term}</li> * </ul> * * This model captures the parts reached by the JSON path expression, "$.results.name". * * Created 07/04/17 * @author Edd */ public class BasicOntology implements ResponseType { private List<Result> results; public BasicOntology() {} public List<Result> getResults() { return results; } public void setResults(List<Result> results) { this.results = results; } @Override public String toString() { return "ResponseType{" + "results=" + results + '}'; } public static class Result { private String id; private String name; public Result() {} public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Result{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } } }
package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model; import uk.ac.ebi.quickgo.rest.comm.ResponseType; import java.util.List; /** * Represents part of the model corresponding to the response available from the resource: * * <ul> * <li>/go/terms/{term}</li> * </ul> * * This model captures the parts reached by the JSON path expression, "$.results.name". * * Created 07/04/17 * @author Edd */ public class BasicOntology implements ResponseType { private List<Result> results; public BasicOntology() {} public List<Result> getResults() { return results; } public void setResults(List<Result> results) { this.results = results; } @Override public String toString() { return "ResponseType{" + "results=" + results + '}'; } public static class Result { private String id; private String name; public Result() {} public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Result{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } } }
Fix counts for search timeline updates
YUI.add("model-timeline-base", function(Y) { "use strict"; var models = Y.namespace("Falco.Models"), TimelineBase; TimelineBase = Y.Base.create("timeline", Y.Model, [], { initializer : function(config) { var tweets; config || (config = {}); tweets = new models.Tweets({ items : config.tweets || [] }); this.set("tweets", tweets); this._handles = [ tweets.after([ "more", "add" ], this._tweetAdd, this) ]; this.publish("tweets", { preventable : false }); }, destructor : function() { new Y.EventTarget(this._handles).detach(); this._handles = null; this.get("tweets").destroy(); }, // Override .toJSON() to make sure tweets are included toJSON : function() { var json = TimelineBase.superclass.toJSON.apply(this); json.tweets = json.tweets.toJSON(); return json; }, _tweetAdd : function(e) { var count = 1; // Don't notify for tweets from cache if(e.cached) { return; } if(e.parsed || e.models) { count = (e.parsed || e.models).length; } this.fire("tweets", { count : count }); } }); models.TimelineBase = TimelineBase; }, "@VERSION@", { requires : [ // YUI "base-build", "model", // Models "model-list-tweets" ] });
YUI.add("model-timeline-base", function(Y) { "use strict"; var models = Y.namespace("Falco.Models"), TimelineBase; TimelineBase = Y.Base.create("timeline", Y.Model, [], { initializer : function(config) { var tweets; config || (config = {}); tweets = new models.Tweets({ items : config.tweets || [] }); this.set("tweets", tweets); this._handles = [ tweets.after([ "more", "add" ], this._tweetAdd, this) ]; this.publish("tweets", { preventable : false }); }, destructor : function() { new Y.EventTarget(this._handles).detach(); this._handles = null; this.get("tweets").destroy(); }, // Override .toJSON() to make sure tweets are included toJSON : function() { var json = TimelineBase.superclass.toJSON.apply(this); json.tweets = json.tweets.toJSON(); return json; }, _tweetAdd : function(e) { var count = 1; // Don't notify for tweets from cache if(e.cached) { return; } if(e.response || e.models) { count = (e.response || e.models).length; } this.fire("tweets", { count : count }); } }); models.TimelineBase = TimelineBase; }, "@VERSION@", { requires : [ // YUI "base-build", "model", // Models "model-list-tweets" ] });
Change once to on for m:job.created listener
minerva.views.JobsPanel = minerva.View.extend({ initialize: function () { var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum; var columns = columnEnum.COLUMN_STATUS_ICON | columnEnum.COLUMN_TITLE; this.jobListWidget = new girder.views.jobs_JobListWidget({ columns: columns, showHeader: false, pageLimit: 10, showPaging: false, triggerJobClick: true, parentView: this }).on('g:jobClicked', function (job) { // TODO right way to update specific job? // otherwise can get a detail that is out of sync with actual job status // seems weird to update the entire collection from here // another option is to refresh the job specifically this.jobListWidget.collection.on('g:changed', function () { job = this.jobListWidget.collection.get(job.get('id')); this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({ job: job, el: $('#g-dialog-container'), parentView: this }); this.jobDetailsWidgetModalWrapper.render(); }, this); this.jobListWidget.collection.fetch({}, true); }, this); girder.events.on('m:job.created', function () { this.jobListWidget.collection.fetch({}, true); }, this); }, render: function () { this.$el.html(minerva.templates.jobsPanel({})); this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render(); return this; } });
minerva.views.JobsPanel = minerva.View.extend({ initialize: function () { var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum; var columns = columnEnum.COLUMN_STATUS_ICON | columnEnum.COLUMN_TITLE; this.jobListWidget = new girder.views.jobs_JobListWidget({ columns: columns, showHeader: false, pageLimit: 10, showPaging: false, triggerJobClick: true, parentView: this }).on('g:jobClicked', function (job) { // TODO right way to update specific job? // otherwise can get a detail that is out of sync with actual job status // seems weird to update the entire collection from here // another option is to refresh the job specifically this.jobListWidget.collection.on('g:changed', function () { job = this.jobListWidget.collection.get(job.get('id')); this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({ job: job, el: $('#g-dialog-container'), parentView: this }); this.jobDetailsWidgetModalWrapper.render(); }, this); this.jobListWidget.collection.fetch({}, true); }, this); girder.events.once('m:job.created', function () { this.jobListWidget.collection.fetch({}, true); }, this); }, render: function () { this.$el.html(minerva.templates.jobsPanel({})); this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render(); return this; } });
Remove not necessary code in Setting class
""" This class is used in kaggle competitions """ import json class Settings(): train_path = None test_path = None model_path = None submission_path = None string_train_path = "TRAIN_DATA_PATH" string_test_path = "TEST_DATA_PATH" string_model_path = "MODEL_PATH" string_submission_path = "SUBMISSION_PATH" def __init__(self): self._load_settings() def __str__(self): to_print = "\n".join([self.string_train_path, self.train_path, self.string_test_path, self.test_path, self.string_model_path, self.model_path, self.string_submission_path, self.submission_path]) return to_print def _load_settings(self): with open('SETTINGS.json') as json_data: settings = json.load(json_data) self.train_path=settings[self.string_train_path] self.test_path=settings[self.string_test_path] self.model_path=settings[self.string_model_path] self.submission_path=settings[self.string_submission_path]
""" This class is used in kaggle competitions """ import json class Settings(): train_path = None test_path = None model_path = None submission_path = None string_train_path = "TRAIN_DATA_PATH" string_test_path = "TEST_DATA_PATH" string_model_path = "MODEL_PATH" string_submission_path = "SUBMISSION_PATH" def __init__(self): self._load_settings() def __str__(self): to_print = "\n".join([self.string_train_path, self.train_path, self.string_test_path, self.test_path, self.string_model_path, self.model_path, self.string_submission_path, self.submission_path]) return to_print def _load_settings(self): with open('SETTINGS.json') as json_data: settings = json.load(json_data) self.train_path=settings[self.string_train_path] self.test_path=settings[self.string_test_path] self.model_path=settings[self.string_model_path] self.submission_path=settings[self.string_submission_path] s = Settings()
Use Image component as image source instead of raw object
import React, { Component, StyleSheet, PropTypes, Image, View } from 'react-native'; export default class Media extends Component { static propTypes = { image: PropTypes.shape({type: PropTypes.oneOf([Image])}).isRequired, height: PropTypes.number, overlay: PropTypes.bool, children: PropTypes.node }; static defaultProps = { height: 150, overlay: false }; render() { const { image, height, overlay, children } = this.props; return ( <View style={{ height }}> {React.cloneElement(image, { style: [styles.media, { height }] })} { children && <View style={[styles.content, overlay && { backgroundColor: 'rgba(0,0,0,.35)' }]}> {children} </View> } </View> ); } } const styles = StyleSheet.create({ media: { position: 'absolute', left: -16, right: -16, }, content: { position: 'absolute', left: -16, right: -16, bottom: 0, paddingTop: 24, paddingBottom: 16, paddingLeft: 16, paddingRight: 16 } });
import React, { Component, StyleSheet, PropTypes, Image, View } from 'react-native'; export default class Media extends Component { static propTypes = { src: PropTypes.object.isRequired, height: PropTypes.number, overlay: PropTypes.bool, children: PropTypes.node }; static defaultProps = { height: 150, overlay: false }; render() { const { src, height, overlay, children } = this.props; return ( <View style={{ height }}> <Image source={src} style={[styles.media, { height }]} /> { children && <View style={[styles.content, overlay && { backgroundColor: 'rgba(0,0,0,.35)' }]}> {children} </View> } </View> ); } } const styles = StyleSheet.create({ media: { position: 'absolute', top: -16, left: -16, right: -16, bottom: -16 }, content: { position: 'absolute', left: -16, right: -16, bottom: 16, paddingTop: 24, paddingBottom: 16, paddingLeft: 16, paddingRight: 16 } });
Make all search form fields optional.
from django import forms import settings OUTCOME_CHOICES = settings.EVENT_OUTCOME_CHOICES EVENT_TYPE_CHOICES = settings.EVENT_TYPE_CHOICES class EventSearchForm(forms.Form): outcome = forms.ChoiceField( widget=forms.Select( attrs={ 'id': 'prependedInput', 'class': 'input-small', } ), choices=OUTCOME_CHOICES, required=False) event_type = forms.ChoiceField( widget=forms.Select( attrs={ 'id': 'prependedInput', 'class': 'input-medium', } ), choices=EVENT_TYPE_CHOICES, required=False) start_date = forms.DateField( widget=forms.DateInput( attrs={ 'id': 'startdatepicker', 'placeholder': 'Start Date', 'class': 'input-small', } ), required=False) end_date = forms.DateField( widget=forms.DateInput( attrs={ 'id': 'enddatepicker', 'placeholder': 'End Date', 'class': 'input-small', } ), required=False) linked_object_id = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Linked Object ID', 'class': 'input-medium', } ), max_length=20, required=False, )
from django import forms import settings OUTCOME_CHOICES = settings.EVENT_OUTCOME_CHOICES EVENT_TYPE_CHOICES = settings.EVENT_TYPE_CHOICES class EventSearchForm(forms.Form): outcome = forms.ChoiceField( widget=forms.Select( attrs={ 'id': 'prependedInput', 'class': 'input-small', } ), choices=OUTCOME_CHOICES, ) event_type = forms.ChoiceField( widget=forms.Select( attrs={ 'id': 'prependedInput', 'class': 'input-medium', } ), choices=EVENT_TYPE_CHOICES, ) start_date = forms.DateField( widget=forms.DateInput( attrs={ 'id': 'startdatepicker', 'placeholder': 'Start Date', 'class': 'input-small', } ) ) end_date = forms.DateField( widget=forms.DateInput( attrs={ 'id': 'enddatepicker', 'placeholder': 'End Date', 'class': 'input-small', } ) ) linked_object_id = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Linked Object ID', 'class': 'input-medium', } ), max_length=20, )
Add Ionicons to icon font list
<?php namespace Kibo\Phast\Filters\CSS\FontSwap; use Kibo\Phast\Services\ServiceFilter; use Kibo\Phast\ValueObjects\Resource; class Filter implements ServiceFilter { const FONT_FACE_REGEXP = '/(@font-face\s*\{)([^}]*)/i'; const ICON_FONT_FAMILIES = [ 'Font Awesome', 'GeneratePress', 'Dashicons', 'Ionicons', ]; private $fontDisplayBlockPattern; public function __construct() { $this->fontDisplayBlockPattern = $this->getFontDisplayBlockPattern(); } public function apply(Resource $resource, array $request) { $css = $resource->getContent(); $filtered = preg_replace_callback(self::FONT_FACE_REGEXP, function ($match) { list($block, $start, $contents) = $match; $mode = preg_match($this->fontDisplayBlockPattern, $contents) ? 'block' : 'swap'; return $start . 'font-display:' . $mode . ';' . $contents; }, $css); return $resource->withContent($filtered); } private function getFontDisplayBlockPattern() { $patterns = []; foreach (self::ICON_FONT_FAMILIES as $family) { $chars = str_split($family); $chars = array_map(function ($char) { return preg_quote($char, '~'); }, $chars); $patterns[] = implode('\s*', $chars); } return '~' . implode('|', $patterns) . '~i'; } }
<?php namespace Kibo\Phast\Filters\CSS\FontSwap; use Kibo\Phast\Services\ServiceFilter; use Kibo\Phast\ValueObjects\Resource; class Filter implements ServiceFilter { const FONT_FACE_REGEXP = '/(@font-face\s*\{)([^}]*)/i'; const ICON_FONT_FAMILIES = [ 'Font Awesome', 'GeneratePress', 'Dashicons', ]; private $fontDisplayBlockPattern; public function __construct() { $this->fontDisplayBlockPattern = $this->getFontDisplayBlockPattern(); } public function apply(Resource $resource, array $request) { $css = $resource->getContent(); $filtered = preg_replace_callback(self::FONT_FACE_REGEXP, function ($match) { list($block, $start, $contents) = $match; $mode = preg_match($this->fontDisplayBlockPattern, $contents) ? 'block' : 'swap'; return $start . 'font-display:' . $mode . ';' . $contents; }, $css); return $resource->withContent($filtered); } private function getFontDisplayBlockPattern() { $patterns = []; foreach (self::ICON_FONT_FAMILIES as $family) { $chars = str_split($family); $chars = array_map(function ($char) { return preg_quote($char, '~'); }, $chars); $patterns[] = implode('\s*', $chars); } return '~' . implode('|', $patterns) . '~i'; } }
Update the alert template a bit. Allow closing by ESC
angular.module('com.likalo.ui') .factory('uiDialog', ['ngDialog', function (ngDialog) { return { alert: function (title, message) { var infoClass; title = title || 'Alert'; message = message || ''; return ngDialog.open({ plain: true, closeByNavigation: true, className: 'UI-modal UI-modal--alert', template: '<aside class="UI-info-block--alert"><svg class="UI-info-block--decorator"><rect class="UI-decorator--base" height="100%"></rect><use xmlns:xlink="http://www.w3.org/1999/xlink" class="UI-decorator--icon" xlink:href="#icon--block-alert"></use></svg><p class="UI-info-block--content"><strong>' + title + '</strong><br/>' + message + '</p></aside>' }); }, modal: function (template, controller, more) { return ngDialog.openConfirm(angular.extend({ closeByDocument: false, closeByNavigation: true, className: 'UI-modal UI-modal--dialog', template: template, controller: controller }, more)); }, view: function (template, controller, more) { return ngDialog.open(angular.extend({ showClose: false, closeByEscape: false, closeByDocument: false, closeByNavigation: true, className: 'UI-modal UI-modal--view', template: template, controller: controller }, more)); } }; } ]);
angular.module('com.likalo.ui') .factory('uiDialog', ['ngDialog', function (ngDialog) { return { alert: function (title, message) { var infoClass; title = title || 'Alert'; message = message || ''; return ngDialog.open({ plain: true, closeByNavigation: true, className: 'UI-modal UI-modal--alert', template: '<aside class="UI-info-block--alert"><svg class="UI-info-block--decorator"><rect class="UI-decorator--base" height="100%"></rect><use xmlns:xlink="http://www.w3.org/1999/xlink" class="UI-decorator--icon" ui-icon-xlink-href="alert" xlink:href="#icon--alert"></use></svg><p class="UI-info-block--content"><strong>' + title + '</strong><br/>' + message + '</p></aside>' }); }, modal: function (template, controller, more) { return ngDialog.openConfirm(angular.extend({ showClose: false, closeByEscape: false, closeByDocument: false, className: 'UI-modal UI-modal--dialog', template: template, controller: controller }, more)); }, view: function (template, controller, more) { return ngDialog.open(angular.extend({ showClose: false, closeByEscape: true, closeByDocument: true, closeByNavigation: true, className: 'UI-modal UI-modal--view', template: template, controller: controller }, more)); } }; } ]);
Build before every test as a way to keep builds up to date (thanks @hodgestar)
module.exports = function (grunt) { var paths = require('./paths'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.initConfig({ paths: paths, watch: { src: { files: ['<%= paths.src.all %>'], tasks: ['build'] } }, concat: { prd: { src: ['<%= paths.src.prd %>'], dest: '<%= paths.dest.prd %>' }, demo: { src: ['<%= paths.src.demo %>'], dest: '<%= paths.dest.demo %>' }, }, mochaTest: { test: { src: [ '<%= paths.src.lib %>', '<%= paths.test.requires %>', '<%= paths.test.spec %>' ], options: { reporter: 'spec' } } } }); grunt.registerTask('test', [ 'build', 'mochaTest' ]); grunt.registerTask('build', [ 'concat', ]); grunt.registerTask('default', [ 'build', 'test' ]); };
module.exports = function (grunt) { var paths = require('./paths'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.initConfig({ paths: paths, watch: { src: { files: ['<%= paths.src.all %>'], tasks: ['build'] } }, concat: { prd: { src: ['<%= paths.src.prd %>'], dest: '<%= paths.dest.prd %>' }, demo: { src: ['<%= paths.src.demo %>'], dest: '<%= paths.dest.demo %>' }, }, mochaTest: { test: { src: [ '<%= paths.src.lib %>', '<%= paths.test.requires %>', '<%= paths.test.spec %>' ], options: { reporter: 'spec' } } } }); grunt.registerTask('test', [ 'mochaTest' ]); grunt.registerTask('build', [ 'concat', ]); grunt.registerTask('default', [ 'build', 'test' ]); };
Set short open tags to on by default
<?php class PhpTemplate { protected $_dir = Null; protected $_data = Array(); protected $_headers = Array(); public $app = Null; public $router = Null; public function __construct() { ini_set('output_buffering', 'On'); ini_set('short_open_tag', 'On'); $this->_dir = '../views/'; $this->app = App::instance(); $this->router = Router::instance(); } public function render($__view, $data = Array()) { $content = $this->renderPartial($__view, $data); echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content)); } public function renderPartial($__view, $__data = Array()) { $this->_data = array_merge($__data, $this->_data); ob_start(); include($this->_dir.$__view.'.php'); $content = ob_get_contents(); ob_end_clean(); return $content; } public function addHeader($header) { if (!in_array($header, $this->_headers)) $this->_headers[] = $header; } public function getHeaders() { return $this->_headers; } public function __set($key, $value) { $this->_data[$key] = $value; } public function __get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : Null; } public function __isset($key) { return isset($this->_data[$key]); } }
<?php class PhpTemplate { protected $_dir = Null; protected $_data = Array(); protected $_headers = Array(); public $app = Null; public $router = Null; public function __construct() { ini_set('output_buffering', 'On'); $this->_dir = '../views/'; $this->app = App::instance(); $this->router = Router::instance(); } public function render($__view, $data = Array()) { $content = $this->renderPartial($__view, $data); echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content)); } public function renderPartial($__view, $__data = Array()) { $this->_data = array_merge($__data, $this->_data); ob_start(); include($this->_dir.$__view.'.php'); $content = ob_get_contents(); ob_end_clean(); return $content; } public function addHeader($header) { if (!in_array($header, $this->_headers)) $this->_headers[] = $header; } public function getHeaders() { return $this->_headers; } public function __set($key, $value) { $this->_data[$key] = $value; } public function __get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : Null; } public function __isset($key) { return isset($this->_data[$key]); } }
Fix bug with port change
var express = require('express'); var bodyParser = require('body-parser'); var ipcMain = require('electron').ipcMain; var notificationListener = express(); const path = require('path'); // Load all endpoint modules. function loadAllModuleEndpoints() { notificationListener.use(bodyParser.json()); var pjson = require('./package.json'); for (dependency in pjson.dependencies) { loadEndpoint(dependency); } } // Load endpoint module which are local node modules found in the modules folder with the prefix 'esn-endpoints-'. function loadEndpoint(dependency) { if (dependency.indexOf('esn-endpoints-') === 0) { var endpoints = require(dependency); if (typeof endpoints.load == 'function') { console.log("Loaded module " + dependency); endpoints.load(notificationListener); } else { console.log("Failed to register module: " + dependency + " as it is missing required function load(api)"); } } } module.exports = { // Start REST API which contains an endpoint for retrieving notifications. listen: function(port) { var server = notificationListener.listen(port); console.log("Listening for notifications on http://localhost:%s", port); // If port is changed in settings.html page reload server ipcMain.on('port-changed', function(event) { server.close(); notificationListener.listen(global.settings.port); console.log("Listening for notifications on http://localhost:%s", global.settings.port); }); loadAllModuleEndpoints(); } }
var express = require('express'); var bodyParser = require('body-parser'); var ipcMain = require('electron').ipcMain; var notificationListener = express(); const path = require('path'); // Load all endpoint modules. function loadAllModuleEndpoints() { notificationListener.use(bodyParser.json()); var pjson = require('./package.json'); for (dependency in pjson.dependencies) { loadEndpoint(dependency); } } // Load endpoint module which are local node modules found in the modules folder with the prefix 'esn-endpoints-'. function loadEndpoint(dependency) { if (dependency.indexOf('esn-endpoints-') === 0) { var endpoints = require(dependency); if (typeof endpoints.load == 'function') { console.log("Loaded module " + dependency); endpoints.load(notificationListener); } else { console.log("Failed to register module: " + dependency + " as it is missing required function load(api)"); } } } module.exports = { // Start REST API which contains an endpoint for retrieving notifications. listen: function(port) { var server = notificationListener.listen(port); console.log("Listening for notifications on http://localhost:%s", port); // If port is changed in settings.html page reload server ipcMain.on('port-changed', function(event) { server.close(); notificationListener.listen(port); console.log("Listening for notifications on http://localhost:%s", port); }); loadAllModuleEndpoints(); } }
Fix unitialized variable compiler error
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.util.concurrent; import foam.core.Agency; import foam.core.ContextAgent; import foam.core.X; /** * An Aynchronous implementation of the AssemblyLine interface. * Uses the threadpool to avoid blocking the caller. **/ public class AsyncAssemblyLine extends SyncAssemblyLine { protected Agency pool_; protected X x_; public AsyncAssemblyLine(X x) { x_ = x; pool_ = (Agency) x.get("threadPool"); } public void enqueue(Assembly job) { final Assembly previous; synchronized ( startLock_ ) { previous = q_; q_ = job; try { job.executeUnderLock(); job.startJob(); } catch (Throwable t) { q_ = previous; throw t; } } pool_.submit(x_, new ContextAgent() { public void execute(X x) { try { job.executeJob(); if ( previous != null ) previous.waitToComplete(); synchronized ( endLock_ ) { job.endJob(); job.complete(); } } finally { // Isn't required, but helps GC last entry. synchronized ( startLock_ ) { // If I'm still the only job in the queue, then remove me if ( q_ == job ) q_ = null; } } }}, "SyncAssemblyLine"); } }
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.util.concurrent; import foam.core.Agency; import foam.core.ContextAgent; import foam.core.X; /** * An Aynchronous implementation of the AssemblyLine interface. * Uses the threadpool to avoid blocking the caller. **/ public class AsyncAssemblyLine extends SyncAssemblyLine { protected Agency pool_; protected X x_; public AsyncAssemblyLine(X x) { x_ = x; pool_ = (Agency) x.get("threadPool"); } public void enqueue(Assembly job) { final Assembly previous; synchronized ( startLock_ ) { try { previous = q_; q_ = job; job.executeUnderLock(); job.startJob(); } catch (Throwable t) { q_ = previous; throw t; } } pool_.submit(x_, new ContextAgent() { public void execute(X x) { try { job.executeJob(); if ( previous != null ) previous.waitToComplete(); synchronized ( endLock_ ) { job.endJob(); job.complete(); } } finally { // Isn't required, but helps GC last entry. synchronized ( startLock_ ) { // If I'm still the only job in the queue, then remove me if ( q_ == job ) q_ = null; } } }}, "SyncAssemblyLine"); } }
Remove option for non-thunk SQS initialization
from .base import BackendFactory, Backend from ..queue.sqs import SQSQueue class SQSBackendFactory(BackendFactory): def __init__(self, sqs_connection_thunk, visibility_timeout=30, wait_time=10, create_if_missing=False): """To allow backends to be initialized lazily, this factory requires a thunk (parameter-less closure) which returns an initialized SQS connection. This thunk is called as late as possible to initialize the connection and perform operations against the SQS API. We do this so that backends can be made available at import time without requiring a connection to be created at import time as well.""" self.sqs_connection_thunk = sqs_connection_thunk self.visibility_timeout = visibility_timeout self.wait_time = wait_time self.create_if_missing = create_if_missing def _create_backend_for_group(self, group): queue = SQSQueue(self.sqs_connection_thunk, self._queue_name(group), self.visibility_timeout, self.wait_time, create_if_missing=self.create_if_missing) error_queue = SQSQueue(self.sqs_connection_thunk, self._queue_name('{}_error'.format(group)), self.visibility_timeout, self.wait_time, create_if_missing=self.create_if_missing) return SQSBackend(group, queue, error_queue) class SQSBackend(Backend): pass
from .base import BackendFactory, Backend from ..queue.sqs import SQSQueue class SQSBackendFactory(BackendFactory): def __init__(self, sqs_connection_or_thunk, visibility_timeout=30, wait_time=10, create_if_missing=False): if callable(sqs_connection_or_thunk): self.sqs_connection_thunk = sqs_connection_or_thunk else: self.sqs_connection_thunk = lambda: sqs_connection_or_thunk self.visibility_timeout = visibility_timeout self.wait_time = wait_time self.create_if_missing = create_if_missing def _create_backend_for_group(self, group): queue = SQSQueue(self.sqs_connection_thunk, self._queue_name(group), self.visibility_timeout, self.wait_time, create_if_missing=self.create_if_missing) error_queue = SQSQueue(self.sqs_connection_thunk, self._queue_name('{}_error'.format(group)), self.visibility_timeout, self.wait_time, create_if_missing=self.create_if_missing) return SQSBackend(group, queue, error_queue) class SQSBackend(Backend): pass
Update to latest i18n API
import Vue from 'vue'; import vuexI18n from 'vuex-i18n'; import store from '../store'; import locales from './locales'; import fallback from '../assets/i18n/en.json'; Vue.use(vuexI18n.plugin, store); Vue.i18n.add('en', fallback); Vue.i18n.set('en'); Vue.i18n.fallback('en'); export default { init() { let userLang = window.localStorage.getItem('contao_manager_locale'); if (!userLang) { userLang = navigator.language || navigator.userLanguage; } return this.load(userLang); }, load(locale) { window.localStorage.setItem('contao_manager_locale', locale); if (Vue.i18n.localeExists(locale)) { Vue.i18n.set(locale); return new Promise(resolve => resolve()); } if (!locales[locale]) { if (locale.length === 5) { return this.load(locale.slice(0, 2)); } return new Promise(resolve => resolve()); } return Vue.http.get(`assets/i18n/${locale}.json`).then( response => response.json().then((json) => { Vue.i18n.add(locale, json); Vue.i18n.set(locale); }), () => {}, ); }, };
import Vue from 'vue'; import vuexI18n from 'vuex-i18n'; import store from '../store'; import locales from './locales'; import fallback from '../assets/i18n/en.json'; Vue.use(vuexI18n.plugin, store); Vue.i18n.add('en', fallback); Vue.i18n.set('en'); Vue.i18n.fallback('en'); export default { init() { let userLang = window.localStorage.getItem('contao_manager_locale'); if (!userLang) { userLang = navigator.language || navigator.userLanguage; } return this.load(userLang); }, load(locale) { window.localStorage.setItem('contao_manager_locale', locale); if (Vue.i18n.exists(locale)) { Vue.i18n.set(locale); return new Promise(resolve => resolve()); } if (!locales[locale]) { if (locale.length === 5) { return this.load(locale.slice(0, 2)); } return new Promise(resolve => resolve()); } return Vue.http.get(`assets/i18n/${locale}.json`).then( response => response.json().then((json) => { Vue.i18n.add(locale, json); Vue.i18n.set(locale); }), () => {}, ); }, };
Add string and json representations of all Job instances
<?php namespace josegonzalez\Queuesadilla\Job; use JsonSerializable; class Base implements JsonSerializable { const LOW = 4; const NORMAL = 3; const MEDIUM = 2; const HIGH = 1; const CRITICAL = 0; protected $engine; protected $item; public function __construct($item, $engine) { $this->engine = $engine; $this->item = $item; return $this; } public function attempts() { if (array_key_exists('attempts', $this->item)) { return $this->item['attempts']; } return $this->item['attempts'] = 0; } public function data($key = null, $default = null) { if ($key === null) { return $this->item['args'][0]; } if (array_key_exists($key, $this->item['args'][0])) { return $this->item['args'][0][$key]; } return $default; } public function delete() { return $this->engine->delete($this->item); } public function item() { return $this->item; } public function release($delay = 0) { if (!isset($this->item['attempts'])) { $this->item['attempts'] = 0; } $this->item['attempts'] += 1; $this->item['delay'] = $delay; return $this->engine->release($this->item); } public function __toString() { return $this->item; } public function jsonSerialize() { return $this->item; } }
<?php namespace josegonzalez\Queuesadilla\Job; class Base { const LOW = 4; const NORMAL = 3; const MEDIUM = 2; const HIGH = 1; const CRITICAL = 0; protected $engine; protected $item; public function __construct($item, $engine) { $this->engine = $engine; $this->item = $item; return $this; } public function attempts() { if (array_key_exists('attempts', $this->item)) { return $this->item['attempts']; } return $this->item['attempts'] = 0; } public function data($key = null, $default = null) { if ($key === null) { return $this->item['args'][0]; } if (array_key_exists($key, $this->item['args'][0])) { return $this->item['args'][0][$key]; } return $default; } public function delete() { return $this->engine->delete($this->item); } public function item() { return $this->item; } public function release($delay = 0) { if (!isset($this->item['attempts'])) { $this->item['attempts'] = 0; } $this->item['attempts'] += 1; $this->item['delay'] = $delay; return $this->engine->release($this->item); } }
Support Symfony Process 2.3 "process timed-out" exception message
<?php namespace Liip\RMT\Tests\Functional; use Exception; use Liip\RMT\Context; use Liip\RMT\Prerequisite\TestsCheck; class TestsCheckTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector'); $informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false); $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface'); $output->method('write'); $context = Context::getInstance(); $context->setService('information-collector', $informationCollector); $context->setService('output', $output); } /** @test */ public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s() { $check = new TestsCheck(array('command' => 'echo OK')); $check->execute(); } /** @test */ public function succeeds_when_command_finished_within_configured_timeout() { $check = new TestsCheck(array('command' => 'echo OK', 'timeout' => 0.100)); $check->execute(); } /** @test */ public function fails_when_the_command_exceeds_the_timeout() { $this->setExpectedExceptionRegExp('Exception', 'process.*time.*out'); $check = new TestsCheck(array('command' => 'sleep 1', 'timeout' => 0.100)); $check->execute(); } }
<?php namespace Liip\RMT\Tests\Functional; use Exception; use Liip\RMT\Context; use Liip\RMT\Prerequisite\TestsCheck; class TestsCheckTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector'); $informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false); $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface'); $output->method('write'); $context = Context::getInstance(); $context->setService('information-collector', $informationCollector); $context->setService('output', $output); } /** @test */ public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s() { $check = new TestsCheck(array('command' => 'echo OK')); $check->execute(); } /** @test */ public function succeeds_when_command_finished_within_configured_timeout() { $check = new TestsCheck(array('command' => 'echo OK', 'timeout' => 0.100)); $check->execute(); } /** @test */ public function fails_when_the_command_exceeds_the_timeout() { $this->setExpectedException('Exception', 'exceeded the timeout'); $check = new TestsCheck(array('command' => 'sleep 1', 'timeout' => 0.100)); $check->execute(); } }
Set user's name as anonymous if no name is specified
/** * 24.05.2017 * TCP Chat using NodeJS * https://github.com/PatrikValkovic/TCPChat * Created by patri */ 'use strict' const net = require('net') const log = require('./logger') const config = require('../config.json') const GroupManager = require('./groupManager') const Parser = require('./Parser') const Client = require('./Client') if (require.main === module) { GroupManager.createGroup(config.defaultGroups) const parser = new Parser() const server = net.createServer() server.on('connection', (socket) => { const client = new Client(socket) log.info('Client connected') socket.on('close', () => { log.info('Socket ended') client.disconnect() }) socket.once('data', (name) => { let obtainedName = name.toString().trim() client.name = obtainedName === '' ? 'anonymous' : obtainedName socket.write('Welcome to chat, type /help for more help\n') socket.on('data',(content) => { parser.parse(client, content.toString()) }) }) socket.on('error', () => { log.warning('Error with socket') client.disconnect() }) socket.write('Please enter your name: ') }) server.listen(config.port, config.host, () => { const address = server.address() log.info(`Server running on ${address.address}:${address.port}`) }) }
/** * 24.05.2017 * TCP Chat using NodeJS * https://github.com/PatrikValkovic/TCPChat * Created by patri */ 'use strict' const net = require('net') const log = require('./logger') const config = require('../config.json') const GroupManager = require('./groupManager') const Parser = require('./Parser') const Client = require('./Client') if (require.main === module) { GroupManager.createGroup(config.defaultGroups) const parser = new Parser() const server = net.createServer() server.on('connection', (socket) => { const client = new Client(socket) log.info('Client connected') socket.on('close', () => { log.info('Socket ended') client.disconnect() }) socket.once('data', (name) => { client.name = name.toString().trim() socket.write('Welcome to chat, type /help for more help\n') socket.on('data',(content) => { parser.parse(client, content.toString()) }) }) socket.on('error', () => { log.warning('Error with socket') client.disconnect() }) socket.write('Please enter your name: ') }) server.listen(config.port, config.host, () => { const address = server.address() log.info(`Server running on ${address.address}:${address.port}`) }) }
Fix issue where logout redirects to non-locale URI
<?php namespace Anomaly\UsersModule\Http\Controller; use Anomaly\Streams\Platform\Http\Controller\PublicController; use Anomaly\Streams\Platform\Routing\UrlGenerator; use Anomaly\UsersModule\User\UserAuthenticator; use Illuminate\Contracts\Auth\Guard; use Illuminate\Translation\Translator; /** * Class LoginController * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> */ class LoginController extends PublicController { /** * Return the login form. * * @param Translator $translator * @return \Illuminate\Http\RedirectResponse */ public function login(Translator $translator) { $this->template->set( 'meta_title', $translator->trans('anomaly.module.users::breadcrumb.login') ); return $this->view->make('anomaly.module.users::login'); } /** * Logout the active user. * * @param UserAuthenticator $authenticator * @param Guard $auth * @return \Illuminate\Http\RedirectResponse */ public function logout(UserAuthenticator $authenticator, Guard $auth, UrlGenerator $url) { if (!$auth->guest()) { $authenticator->logout(); } $this->messages->success($this->request->get('message', 'anomaly.module.users::message.logged_out')); return $this->response->redirectTo($this->url->to($this->request->get('redirect', '/'))); } }
<?php namespace Anomaly\UsersModule\Http\Controller; use Anomaly\Streams\Platform\Http\Controller\PublicController; use Anomaly\UsersModule\User\UserAuthenticator; use Illuminate\Contracts\Auth\Guard; use Illuminate\Translation\Translator; /** * Class LoginController * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> */ class LoginController extends PublicController { /** * Return the login form. * * @param Translator $translator * @return \Illuminate\Http\RedirectResponse */ public function login(Translator $translator) { $this->template->set( 'meta_title', $translator->trans('anomaly.module.users::breadcrumb.login') ); return $this->view->make('anomaly.module.users::login'); } /** * Logout the active user. * * @param UserAuthenticator $authenticator * @param Guard $auth * @return \Illuminate\Http\RedirectResponse */ public function logout(UserAuthenticator $authenticator, Guard $auth) { if (!$auth->guest()) { $authenticator->logout(); } $this->messages->success($this->request->get('message', 'anomaly.module.users::message.logged_out')); return $this->response->redirectTo($this->request->get('redirect', '/')); } }
Fix in getLimitQuery not valid result
<?php namespace Helper; use APIJet\Config; use \PDO; class Db { private static $instance = null; private static $options = [ PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; private function __construct() {} private function __clone() {} public static function getInstance() { if (self::$instance === null) { $config = Config::getByName('Db'); self::$instance = new PDO('mysql:host='.$config['hostname'].';dbname='.$config['database'], $config['username'], $config['password'], self::$options ); } return self::$instance; } public static function execQuery($query, array $parameters = []) { $statement = self::getInstance()->prepare($query); $statement->execute($parameters); return $statement; } public static function getLimitQuery($limit, $offset) { $limit = (int) $limit; $offset = (int) $offset; return " LIMIT ".($offset * $limit).", $limit "; } public static function getLastInsertId() { return self::getInstance()->lastInsertId(); } }
<?php namespace Helper; use APIJet\Config; use \PDO; class Db { private static $instance = null; private static $options = [ PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; private function __construct() {} private function __clone() {} public static function getInstance() { if (self::$instance === null) { $config = Config::getByName('Db'); self::$instance = new PDO('mysql:host='.$config['hostname'].';dbname='.$config['database'], $config['username'], $config['password'], self::$options ); } return self::$instance; } public static function execQuery($query, array $parameters = []) { $statement = self::getInstance()->prepare($query); $statement->execute($parameters); return $statement; } public static function getLimitQuery($limit, $offset) { $limit = (int) $limit; $offset = (int) $offset; return " LIMIT $offset, $limit "; } public static function getLastInsertId() { return self::getInstance()->lastInsertId(); } }
[REF] openacademy: Add sql constraint identation fixed
# -*- coding: utf-8 -*- from openerp import models, fields, api ''' This module create model of Course ''' class Course(models.Model): '''This class create model of Course''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # field reserved to identified rec_name description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") @api.multi def copy(self, default=None): default = dict(default or {}) copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default) _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ]
# -*- coding: utf-8 -*- from openerp import models, fields, api ''' This module create model of Course ''' class Course(models.Model): '''This class create model of Course''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # field reserved to identified rec_name description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") @api.multi def copy(self, default=None): default = dict(default or {}) copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default) _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ]
Update class name validator implementation.
<?php namespace PhpSpec\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class DescribeCommand extends Command { public function __construct() { parent::__construct('describe'); $this->setDefinition(array( new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'), )); } protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getApplication()->getContainer(); $container->configure(); $classname = $input->getArgument('class'); $pattern = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/'; if (!preg_match($pattern, $classname)) { throw new \InvalidArgumentException( sprintf('String "%s" is not a valid class name.', $classname) . PHP_EOL . 'Please see reference document:' . 'https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md' ); } $resource = $container->get('locator.resource_manager')->createResource($classname); $container->get('code_generator')->generate($resource, 'specification'); } }
<?php namespace PhpSpec\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class DescribeCommand extends Command { public function __construct() { parent::__construct('describe'); $this->setDefinition(array( new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'), )); } protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getApplication()->getContainer(); $container->configure(); $classname = $input->getArgument('class'); $pattern = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/'; if (!preg_match($pattern, $classname)) { throw new \InvalidArgumentException(sprintf( "String \"%s\" is not a valid class name.\nPlease see reference document: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md", $classname )); } $resource = $container->get('locator.resource_manager')->createResource($classname); $container->get('code_generator')->generate($resource, 'specification'); } }
Fix test runner importing wrong module.
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ROOT_URLCONF='publisher.urls', INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'publisher', ], SITE_ID=1, NOSE_ARGS=['-s'], ) try: import django setup = django.setup except AttributeError: pass else: setup() from django_nose import NoseTestSuiteRunner except ImportError: raise ImportError('To fix this error, run: pip install -r requirements-test.txt') def run_tests(*test_args): if not test_args: test_args = ['publisher.tests.tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ROOT_URLCONF='publisher.urls', INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'publisher', ], SITE_ID=1, NOSE_ARGS=['-s'], ) try: import django setup = django.setup except AttributeError: pass else: setup() from django_nose import NoseTestSuiteRunner except ImportError: raise ImportError('To fix this error, run: pip install -r requirements-test.txt') def run_tests(*test_args): if not test_args: test_args = ['tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
Use render function instead of template This is needed for runtime only environment in Vue
import noop from 'lodash/noop'; import omitBy from 'lodash/omitBy'; import isArray from 'lodash/isArray'; import normalizeProps from './normalizeProps'; export default function connect(mapStateAsProps = noop, mapActionsAsProps = noop) { return (children) => { const props = children.props || {}; const subscriptions = children.collect || {}; const allProps = { ...normalizeProps(props), ...normalizeProps(subscriptions) }; children.props = allProps; delete children.collect; return { name: 'VuaRedux', props: props, render(h) { const keys = Object.keys(allProps); let propsToPass = {}; for (let i = 0; i < keys.length; i++) { propsToPass[keys[i]] = this[keys[i]]; } return h(children, { props: propsToPass }) }, data() { const store = this.$store; const state = mapStateAsProps(store.getState()) || {}; const actions = mapActionsAsProps(store.dispatch, store.getState) || {}; return { ...state, ...actions }; }, created() { const store = this.$store; const state = mapStateAsProps(store.getState()) || {}; const stateNames = Object.keys(state); this.unsubscribe = store.subscribe(() => { const state = mapStateAsProps(store.getState()); for (let i = 0; i < stateNames.length; i++) { this[stateNames[i]] = state[stateNames[i]]; } }); }, beforeDestroy() { this.unsubscribe(); } }; }; }
import noop from 'lodash/noop'; import omitBy from 'lodash/omitBy'; import isArray from 'lodash/isArray'; import normalizeProps from './normalizeProps'; export default function connect(mapStateAsProps = noop, mapActionsAsProps = noop) { return (children) => { const props = children.props || {}; const subscriptions = children.collect || {}; const allProps = { ...normalizeProps(props), ...normalizeProps(subscriptions) }; const propsToPass = Object.keys(allProps).map(key => `:${key}='${key}'`).join(' '); const template = `<children ${propsToPass}></children>`; children.props = allProps; delete children.collect; return { template, props: props, data() { const store = this.$store; const state = mapStateAsProps(store.getState()) || {}; const actions = mapActionsAsProps(store.dispatch, store.getState) || {}; return { ...state, ...actions }; }, components: { children }, created() { const store = this.$store; const state = mapStateAsProps(store.getState()) || {}; const stateNames = Object.keys(state); this.unsubscribe = store.subscribe(() => { const state = mapStateAsProps(store.getState()); stateNames.forEach((key) => { // fixme: use a simple loop this[key] = state[key]; }); }); }, beforeDestroy() { this.unsubscribe(); } }; }; }
Set referer header to prevent CSRF
// Copyright (C) 2007-2014, GoodData(R) Corporation. var httpProxy = require('http-proxy'); module.exports = function(host) { var currentHost, currentPort; var proxy = new httpProxy.RoutingProxy({ target: { https: true } }); var requestProxy = function(req, res, next) { // Because backend does not answer without set content length if (req.method === 'DELETE') { // Only set content-length to zero if not already specified req.headers['content-length'] = req.headers['content-length'] || '0'; } // White labeled resources are based on host header req.headers['host'] = currentHost + (currentPort!==443 ? ':'+currentPort : ''); // Remove Origin header so it's not evaluated as cross-domain request req.headers['origin'] = null; // To prevent CSRF req.headers['referer'] = 'https://' + host; // Proxy received request to curret backend endpoint proxy.proxyRequest(req, res, { host: currentHost, port: currentPort, target: { // don't choke on self-signed certificates used by *.getgooddata.com rejectUnauthorized: false } }); }; requestProxy.proxy = proxy; requestProxy.setHost = function(value) { var splithost = value ? value.split(/:/) : ''; currentHost = splithost[0]; currentPort = parseInt(splithost[1] || '443', 10); }; // set the host/port combination requestProxy.setHost(host); return requestProxy; };
// Copyright (C) 2007-2014, GoodData(R) Corporation. var httpProxy = require('http-proxy'); module.exports = function(host) { var currentHost, currentPort; var proxy = new httpProxy.RoutingProxy({ target: { https: true } }); var requestProxy = function(req, res, next) { // Because backend does not answer without set content length if (req.method === 'DELETE') { // Only set content-length to zero if not already specified req.headers['content-length'] = req.headers['content-length'] || '0'; } // White labeled resources are based on host header req.headers['host'] = currentHost + (currentPort!==443 ? ':'+currentPort : ''); // Remove Origin header so it's not evaluated as cross-domain request req.headers['origin'] = null; // Proxy received request to curret backend endpoint proxy.proxyRequest(req, res, { host: currentHost, port: currentPort, target: { // don't choke on self-signed certificates used by *.getgooddata.com rejectUnauthorized: false } }); }; requestProxy.proxy = proxy; requestProxy.setHost = function(value) { var splithost = value ? value.split(/:/) : ''; currentHost = splithost[0]; currentPort = parseInt(splithost[1] || '443', 10); }; // set the host/port combination requestProxy.setHost(host); return requestProxy; };
Add katex as an angular constant
/*! * angular-katex v0.2.1 * https://github.com/tfoxy/angular-katex * * Copyright 2015 Tomás Fox * Released under the MIT license */ (function() { 'use strict'; angular.module('katex', []) .constant('katex', katex) .provider('katexConfig', ['katex', function(katex) { var self = this; self.errorTemplate = function(err) { return '<span class="katex-error">' + err + '</span>'; }; self.errorHandler = function(err, text, element) { element.html(self.errorTemplate(err, text)); }; self.render = function(element, text) { try { katex.render(text || '', element[0]); } catch (err) { self.errorHandler(err, text, element); } }; //noinspection JSUnusedGlobalSymbols this.$get = function() { return this; }; }]) .directive('katex', ['katexConfig', function(katexConfig) { return { restrict: 'AE', compile: function(element) { katexConfig.render(element, element.html()); } }; }]) .directive('katexBind', ['katexConfig', function(katexConfig) { return { restrict: 'A', link: function(scope, element, attrs) { var model = attrs.katexBind; scope.$watch(model, function(text) { katexConfig.render(element, text); }); } }; }]); })();
/*! * angular-katex v0.2.1 * https://github.com/tfoxy/angular-katex * * Copyright 2015 Tomás Fox * Released under the MIT license */ (function() { 'use strict'; angular.module('katex', []) .provider('katexConfig', function() { var self = this; self.errorTemplate = function(err) { return '<span class="katex-error">' + err + '</span>'; }; self.errorHandler = function(err, text, element) { element.html(self.errorTemplate(err, text)); }; self.render = function(element, text) { try { katex.render(text || '', element[0]); } catch (err) { self.errorHandler(err, text, element); } }; //noinspection JSUnusedGlobalSymbols this.$get = function() { return this; }; }) .directive('katex', ['katexConfig', function(katexConfig) { return { restrict: 'AE', compile: function(element) { katexConfig.render(element, element.html()); } }; }]) .directive('katexBind', ['katexConfig', function(katexConfig) { return { restrict: 'A', link: function(scope, element, attrs) { var model = attrs.katexBind; scope.$watch(model, function(text) { katexConfig.render(element, text); }); } }; }]); })();
Update DI extension to recognize new parameter Make sure we fetch avalange_imagine.not_found_images parameter collection into imagine.not_found_images parameter.
<?php namespace Avalanche\Bundle\ImagineBundle\DependencyInjection; use InvalidArgumentException; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class AvalancheImagineExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('imagine.xml'); $config = $this->mergeConfig($configs); $driver = isset($config['driver']) ? strtolower($config['driver']) : 'gd'; if (!in_array($driver, array('gd', 'imagick', 'gmagick'))) { throw new InvalidArgumentException('Invalid imagine driver specified'); } $container->setAlias('imagine', new Alias('imagine.' . $driver)); foreach (array('cache_prefix', 'web_root', 'source_root', 'filters', 'not_found_images') as $key) { isset($config[$key]) && $container->setParameter('imagine.' . $key, $config[$key]); } } private function mergeConfig(array $configs) { $config = array(); foreach ($configs as $cnf) { $config = array_merge_recursive($config, $cnf); } return $config; } function getAlias() { return 'avalanche_imagine'; } }
<?php namespace Avalanche\Bundle\ImagineBundle\DependencyInjection; use InvalidArgumentException; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class AvalancheImagineExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('imagine.xml'); $config = $this->mergeConfig($configs); $driver = isset($config['driver']) ? strtolower($config['driver']) : 'gd'; if (!in_array($driver, array('gd', 'imagick', 'gmagick'))) { throw new InvalidArgumentException('Invalid imagine driver specified'); } $container->setAlias('imagine', new Alias('imagine.' . $driver)); foreach (array('cache_prefix', 'web_root', 'source_root', 'filters') as $key) { isset($config[$key]) && $container->setParameter('imagine.' . $key, $config[$key]); } } private function mergeConfig(array $configs) { $config = array(); foreach ($configs as $cnf) { $config = array_merge_recursive($config, $cnf); } return $config; } function getAlias() { return 'avalanche_imagine'; } }
Fix @variable directive without arguments
<?php namespace Milax\Mconsole\Providers; use Illuminate\Support\ServiceProvider; use Milax\Mconsole\Models\MconsoleUploadPreset; use Milax\Mconsole\Models\Variable; use Blade; use View; class MconsoleBladeExtensions extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { Blade::directive('datetime', function ($expression) { return "<?php echo \Carbon\Carbon::now()->format({$expression}); ?>"; }); Blade::directive('variable', function ($expression) { $string = str_remove_parenthesis($expression); return '<?php $args = [' . $string . ']; $variable = \Milax\Mconsole\Models\Variable::getCached()->where("key", $args[0])->first(); if ($variable) { $arr = empty($args[1]) ? [] : $args[1]; $renderer = new \Milax\Mconsole\Blade\BladeRenderer($variable->value, $arr); echo $renderer->render(); } ?>'; }); } }
<?php namespace Milax\Mconsole\Providers; use Illuminate\Support\ServiceProvider; use Milax\Mconsole\Models\MconsoleUploadPreset; use Milax\Mconsole\Models\Variable; use Blade; use View; class MconsoleBladeExtensions extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { Blade::directive('datetime', function ($expression) { return "<?php echo \Carbon\Carbon::now()->format({$expression}); ?>"; }); Blade::directive('variable', function ($expression) { $string = str_remove_parenthesis($expression); return '<?php $args = [' . $string . ']; $variable = \Milax\Mconsole\Models\Variable::getCached()->where("key", $args[0])->first(); if ($variable) { $renderer = new \Milax\Mconsole\Blade\BladeRenderer($variable->value, $args[1]); echo $renderer->render(); } ?>'; }); } }
Normalize string before passing it to detectors
<?php namespace Linko\Spam; class SpamFilter { /** * Holds registed spam detectors * * @var SpamDetectorInterface[] */ private $_spamDetectors = array(); /** * Checks if a string is spam or not * * @param $string * * @return SpamResult */ public function check($string) { $failure = 0; $string = $this->_normalizeString($string); foreach ($this->getDetectors() as $spamDetector) { if($spamDetector->detect($string)) { $failure++; } } return new SpamResult($failure > 0 ? true : false); } /** * Registers a Spam Detector * * @param SpamDetectorInterface $spamDetector * * @return SpamFilter */ public function registerDetector(SpamDetectorInterface $spamDetector) { $detectorClass = get_class($spamDetector); $this->_spamDetectors[$detectorClass] = $spamDetector; return $this; } /** * Gets a list of all spam detectors * * @return SpamDetectorInterface[] */ public function getDetectors() { return $this->_spamDetectors; } /** * Used to normalize string before passing * it to detectors * * @param string $string * * @return string */ private function _normalizeString($string) { return trim(strtolower($string)); } }
<?php namespace Linko\Spam; class SpamFilter { /** * Holds registed spam detectors * * @var SpamDetectorInterface[] */ private $_spamDetectors = array(); /** * Checks if a string is spam or not * * @param $string * * @return SpamResult */ public function check($string) { $failure = 0; foreach ($this->getDetectors() as $spamDetector) { if($spamDetector->detect($string)) { $failure++; } } return new SpamResult($failure > 0 ? true : false); } /** * Registers a Spam Detector * * @param SpamDetectorInterface $spamDetector * * @return SpamFilter */ public function registerDetector(SpamDetectorInterface $spamDetector) { $detectorClass = get_class($spamDetector); $this->_spamDetectors[$detectorClass] = $spamDetector; return $this; } /** * Gets a list of all spam detectors * * @return SpamDetectorInterface[] */ public function getDetectors() { return $this->_spamDetectors; } }
Add incomplete category into showcommand
package seedu.tasklist.logic.commands; /** * Shows all tasks that fulfill the category keyword. * Keyword matching is case insensitive. */ public class ShowCommand extends Command { public static final String COMMAND_WORD = "show"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Shows all tasks under the requested category. " + "The specified keywords (case-insensitive) are shown as a list with index numbers.\n" + "Parameters: KEYWORD (all, incomplete, complete, p/[PRIORITY]\n" + "Example: " + COMMAND_WORD + " all"; public static final String MESSAGE_SHOW_FAILURE = "Invalid category. Available categories: all, incomplete, complete, p/[PRIORITY]"; public static final String MESSAGE_SUCCESS = "Shown requested tasks."; private final String keyword; public ShowCommand(String keyword) { this.keyword = keyword; } @Override public CommandResult execute() { if (keyword.equals("all")) { model.updateFilteredListToShowAll(); } else if (keyword.equals("incomplete")) { model.updateFilteredListToShowIncomplete(); } else if (keyword.equalsIgnoreCase("complete")) { model.updateFilteredListToShowComplete(); } else if (keyword.equalsIgnoreCase("p/high") || keyword.equalsIgnoreCase("p/normal") || keyword.equalsIgnoreCase("p/low")){ model.updateFilteredListToShowPriority(keyword); } else { return new CommandResult(String.format(MESSAGE_SHOW_FAILURE)); } return new CommandResult(String.format(getMessageForPersonListShownSummary(model.getFilteredPersonList().size()))); } }
package seedu.tasklist.logic.commands; /** * Shows all tasks that fulfill the category keyword. * Keyword matching is case insensitive. */ public class ShowCommand extends Command { public static final String COMMAND_WORD = "show"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Shows all tasks under the requested category. " + "The specified keywords (case-insensitive) are shown as a list with index numbers.\n" + "Parameters: KEYWORD (all, incomplete, complete, p/[PRIORITY]\n" + "Example: " + COMMAND_WORD + " all"; public static final String MESSAGE_SHOW_FAILURE = "Invalid category. Available categories: all, incomplete, complete, p/[PRIORITY]"; public static final String MESSAGE_SUCCESS = "Shown requested tasks."; private final String keyword; public ShowCommand(String keyword) { this.keyword = keyword; } @Override public CommandResult execute() { if (keyword.equals("all")) { model.updateFilteredListToShowAll(); } else if (keyword.equalsIgnoreCase("complete")) { model.updateFilteredListToShowComplete(); } else if (keyword.equalsIgnoreCase("p/high") || keyword.equalsIgnoreCase("p/normal") || keyword.equalsIgnoreCase("p/low")){ model.updateFilteredListToShowPriority(keyword); } else { return new CommandResult(String.format(MESSAGE_SHOW_FAILURE)); } return new CommandResult(String.format(getMessageForPersonListShownSummary(model.getFilteredPersonList().size()))); } }
Correct table names in migration
<?php namespace Surfnet\StepupMiddleware\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20160622160146 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('DROP TABLE institution_with_personal_ra_details'); } /** * @param Schema $schema */ public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('DROP TABLE institution_with_personal_ra_details'); } }
<?php namespace Surfnet\StepupMiddleware\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20160622160146 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('DROP TABLE institution_with_ra_locations'); } /** * @param Schema $schema */ public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB'); $this->addSql('DROP TABLE institution_with_ra_locations'); } }
Revise download_url string for consistency with main script
import os from setuptools import setup from pyspeedtest import __program__, __version__ # allow setup.py to be run from any path os.chdir(os.path.dirname(os.path.abspath(__file__))) setup( name=__program__, version=__version__, py_modules=['pyspeedtest'], scripts=['bin/pyspeedtest'], license='MIT', description='Speedtest.net python script', url='https://github.com/fopina/pyspeedtest', download_url='https://github.com/fopina/pyspeedtest/tarball/v%s' % __version__, author='Filipe Pina', author_email='[email protected]', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5' ], keywords=['speed', 'test', 'bandwidth'] )
import os from setuptools import setup from pyspeedtest import __program__, __version__ # allow setup.py to be run from any path os.chdir(os.path.dirname(os.path.abspath(__file__))) setup( name=__program__, version=__version__, py_modules=['pyspeedtest'], scripts=['bin/pyspeedtest'], license='MIT', description='Speedtest.net python script', url='https://github.com/fopina/pyspeedtest', download_url='https://github.com/fopina/pyspeedtest/tarball/v' + __version__, author='Filipe Pina', author_email='[email protected]', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5' ], keywords=['speed', 'test', 'bandwidth'] )
Make "register" return False when username is already taken
# -*- coding: utf-8 -*- # from twisted.words.xish import domish from twisted.words.protocols.jabber.xmpp_stringprep import nodeprep from base import * import random import time import bnw.core.bnw_objects as objs def _(s, user): return s from uuid import uuid4 import re @check_arg(name=USER_RE) @defer.inlineCallbacks def cmd_register(request, name=""): """ Регистрация """ if request.user: defer.returnValue( dict(ok=False, desc=u'You are already registered as %s' % ( request.user['name'],), ) ) else: name = name.lower()[:128] if name == 'anonymous': defer.returnValue( dict(ok=False, desc=u'You aren''t anonymous.') ) user = objs.User({'id': uuid4().hex, 'name': name, 'login_key': uuid4().hex, 'regdate': int(time.time()), 'jid': request.jid.userhost(), 'interface': 'redeye', 'settings': { 'servicejid': request.to.userhost() }, }) if not (yield objs.User.find_one({'name': name})): _ = yield user.save() defer.returnValue( dict(ok=True, desc='We registered you as %s.' % (name,)) ) else: defer.returnValue( dict(ok=False, desc='This username is already taken') )
# -*- coding: utf-8 -*- # from twisted.words.xish import domish from twisted.words.protocols.jabber.xmpp_stringprep import nodeprep from base import * import random import time import bnw.core.bnw_objects as objs def _(s, user): return s from uuid import uuid4 import re @check_arg(name=USER_RE) @defer.inlineCallbacks def cmd_register(request, name=""): """ Регистрация """ if request.user: defer.returnValue( dict(ok=False, desc=u'You are already registered as %s' % ( request.user['name'],), ) ) else: name = name.lower()[:128] if name == 'anonymous': defer.returnValue( dict(ok=False, desc=u'You aren''t anonymous.') ) user = objs.User({'id': uuid4().hex, 'name': name, 'login_key': uuid4().hex, 'regdate': int(time.time()), 'jid': request.jid.userhost(), 'interface': 'redeye', 'settings': { 'servicejid': request.to.userhost() }, }) if not (yield objs.User.find_one({'name': name})): _ = yield user.save() defer.returnValue( dict(ok=True, desc='We registered you as %s.' % (name,)) ) else: defer.returnValue( dict(ok=True, desc='This username is already taken') )
Fix my silly mistake combining the arrays of objects
var request = require('request'); var _und = require('underscore'); /* Get orders listing. */ exports.list = function(req, res){ var results = { orders: [], bitStampOrders: [], btceOrders: [] }; request('https://www.bitstamp.net/api/transactions/', function(error, response, body){ if(!error && response.statusCode == 200) { results.bitStampOrders = JSON.parse(body); } request('https://btc-e.com/api/2/btc_usd/trades', function(error, response, body) { if(!error && response.statusCode == 200) { results.btceOrders = JSON.parse(body); } var mappedBitStampOrders = _und.map(results.bitStampOrders, function(order){ return { time: order.date, quantity: order.amount, price: order.price, exchange: 'bitstamp.net' }; }); var mappedBtceOrders = _und.map(results.btceOrders, function(order){ return { time: order.date, quantity: order.amount, price: order.price, exchange: 'btc-e.com' }; }); var combinedOrders = _und.union(mappedBitStampOrders, mappedBtceOrders); var sortedCombinedOrders = _und.sortBy(combinedOrders, function(order){ return -1 * order.date; }); results.orders = _und.first(sortedCombinedOrders, 10); res.send(results); }); }); };
var request = require('request'); var _und = require('underscore'); /* Get orders listing. */ exports.list = function(req, res){ var results = { orders: [], bitStampOrders: [], btceOrders: [] }; request('https://www.bitstamp.net/api/transactions/', function(error, response, body){ if(!error && response.statusCode == 200) { results.bitStampOrders = JSON.parse(body); } request('https://btc-e.com/api/2/btc_usd/trades', function(error, response, body) { if(!error && response.statusCode == 200) { results.btceOrders = JSON.parse(body); } var combinedOrders = _und.map(results.bitStampOrders, function(order){ return { time: order.date, quantity: order.amount, price: order.price, exchange: 'bitstamp.net' }; }) + _und.map(results.btceOrders, function(order){ return { time: order.date, quantity: order.amount, price: order.price, exchange: 'btc-e.com' }; }); console.log(combinedOrders[0].time); var sortedCombinedOrders = _und.sortBy(combinedOrders, function(order){ return -1 * order.date; }); results.orders = _und.first(sortedCombinedOrders, 10); //console.log(results); res.send(results); }); }); };
Update to support FIT 1.4.3-SNAPSHOT
package org.pitest.cucumber; import cucumber.api.junit.Cucumber; import cucumber.runtime.Runtime; import cucumber.runtime.model.CucumberScenario; import gherkin.formatter.Formatter; import gherkin.formatter.Reporter; import gherkin.formatter.model.TagStatement; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.pitest.testapi.ResultCollector; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ScenarioTestUnitTest { @Mock CucumberScenario scenario; @Mock private ResultCollector resultCollector; @Before public void setUp() throws Exception { TagStatement gherkin = mock(TagStatement.class); when(scenario.getGherkinModel()).thenReturn(gherkin); } @Test public void should_run_scenario_and_call_collector_when_ran() { // given ScenarioTestUnit testUnit = new ScenarioTestUnit(HideFromJUnit.Concombre.class, scenario); // when testUnit.execute(resultCollector); // then verify(scenario, times(1)).run(any(Formatter.class), any(Reporter.class), any(Runtime.class)); } private static class HideFromJUnit { @RunWith(Cucumber.class) private static class Concombre { } } }
package org.pitest.cucumber; import cucumber.api.junit.Cucumber; import cucumber.runtime.Runtime; import cucumber.runtime.model.CucumberScenario; import gherkin.formatter.Formatter; import gherkin.formatter.Reporter; import gherkin.formatter.model.TagStatement; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.pitest.testapi.ResultCollector; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ScenarioTestUnitTest { @Mock CucumberScenario scenario; @Mock private ResultCollector resultCollector; @Before public void setUp() throws Exception { TagStatement gherkin = mock(TagStatement.class); when(scenario.getGherkinModel()).thenReturn(gherkin); } @Test public void should_run_scenario_and_call_collector_when_ran() { // given ScenarioTestUnit testUnit = new ScenarioTestUnit(HideFromJUnit.Concombre.class, scenario); // when testUnit.execute(getClass().getClassLoader(), resultCollector); // then verify(scenario, times(1)).run(any(Formatter.class), any(Reporter.class), any(Runtime.class)); } private static class HideFromJUnit { @RunWith(Cucumber.class) private static class Concombre { } } }
Make sure we can rebuild the menu
'use strict' void (function () { const remote = require('remote') const Tray = remote.require('tray') const Menu = remote.require('menu') const MenuItem = remote.require('menu-item') const dialog = remote.require('dialog') const ipc = require('ipc') const grunt = require('./lib/Grunt') // Set up tray menu. let tray = new Tray('IconTemplate.png') let trayMenu = new Menu() build() function build () { trayMenu.append(new MenuItem({ label: window.localStorage.getItem('current'), click: function () { dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) { if (dir !== undefined) { window.localStorage.setItem('current', dir) } }) } })) trayMenu.append(new MenuItem({type: 'separator'})) grunt.getTasks() .then(function (tasks) { for (let task of tasks) { let item = { label: task, click: function () { grunt.runTask(task, function () { // Rebuild menu trayMenu = new Menu() build() }) } } if (global.processes[task]) { item.icon = 'running.png' } trayMenu.append(new MenuItem(item)) } trayMenu.append(new MenuItem({type: 'separator'})) trayMenu.append(new MenuItem({ label: 'Quit', click: function () { ipc.send('app-quit') } })) trayMenu.items[0].label = ':D' tray.setContextMenu(trayMenu) }) } })()
'use strict' void (function () { const remote = require('remote') const Tray = remote.require('tray') const Menu = remote.require('menu') const MenuItem = remote.require('menu-item') const dialog = remote.require('dialog') const ipc = require('ipc') const grunt = require('./lib/Grunt') // Set up tray menu. let tray = new Tray('IconTemplate.png') let trayMenu = new Menu() trayMenu.append(new MenuItem({ label: window.localStorage.getItem('current'), click: function () { dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) { if (dir !== undefined) { window.localStorage.setItem('current', dir) } }) } })) trayMenu.append(new MenuItem({type: 'separator'})) grunt.getTasks() .then(function (tasks) { for (let task of tasks) { trayMenu.append(new MenuItem({ label: task, click: function () { grunt.runTask(task) } })) } trayMenu.append(new MenuItem({type: 'separator'})) trayMenu.append(new MenuItem({ label: 'Quit', click: function () { ipc.send('app-quit') } })) tray.setContextMenu(trayMenu) }) })()
Make sure the trigger view is locked down
from django.contrib import admin from django.http import HttpResponseRedirect, Http404 from django.conf.urls import url from django.utils.decorators import method_decorator from django.contrib.admin.views.decorators import staff_member_required from .models import TestResult from .prod_tests.entity_counting_test import test_entity_count_vs_length class TestResultAdmin(admin.ModelAdmin): list_display = ( 'name', 'django_version', 'djangae_version', 'last_modified', 'status', 'score' ) class TestAdminSite(admin.AdminSite): index_template = "testapp/admin_index.html" def __init__(self, *args, **kwargs): self.tests = { "Counting Performance": test_entity_count_vs_length } super(TestAdminSite, self).__init__(*args, **kwargs) def each_context(self, request): return { "admin_site": self } def get_urls(self): urls = super(TestAdminSite, self).get_urls() my_urls = [ url(r'^trigger/$', self.trigger_test), ] return my_urls + urls @method_decorator(staff_member_required) def trigger_test(self, request): try: test = self.tests[request.POST["name"]] except KeyError: raise Http404("Invalid test") test() return HttpResponseRedirect("/admin/") admin_site = TestAdminSite() admin_site.register(TestResult, TestResultAdmin)
from django.contrib import admin from django.http import HttpResponseRedirect, Http404 from django.conf.urls import patterns from django.conf.urls import url from django.shortcuts import redirect from .models import TestResult from .prod_tests.entity_counting_test import test_entity_count_vs_length class TestResultAdmin(admin.ModelAdmin): list_display = ( 'name', 'django_version', 'djangae_version', 'last_modified', 'status', 'score' ) class TestAdminSite(admin.AdminSite): index_template = "testapp/admin_index.html" def __init__(self, *args, **kwargs): self.tests = { "Counting Performance": test_entity_count_vs_length } super(TestAdminSite, self).__init__(*args, **kwargs) def each_context(self, request): return { "admin_site": self } def get_urls(self): urls = super(TestAdminSite, self).get_urls() my_urls = [ url(r'^trigger/$', self.trigger_test), ] return my_urls + urls def trigger_test(self, request): try: test = self.tests[request.POST["name"]] except KeyError: raise Http404("Invalid test") test() return HttpResponseRedirect("/admin/") admin_site = TestAdminSite() admin_site.register(TestResult, TestResultAdmin)
Add CR2 to allowed files
import os from addict import Dict from gallery.models import File def get_dir_file_contents(dir_id): print(File.query.filter(File.parent == dir_id).all()) return File.query.filter(File.parent == dir_id).all() def get_dir_tree_dict(): path = os.path.normpath("/gallery-data/root") file_tree = Dict() for root, _, files in os.walk(path, topdown=True): path = root.split('/') path.pop(0) file_tree_fd = file_tree for part in path: file_tree_fd = file_tree_fd[part] file_tree_fd['.'] = files return file_tree def convert_bytes_to_utf8(dic): for key in dic: if isinstance(key, bytes): k = key.decode('utf-8') v = dic[key] del dic[key] dic[k] = v if isinstance(dic[key], bytes): v = dic[key].decode('utf-8') dic[key] = v return dic def allowed_file(filename): return '.' in filename and filename.lower().rsplit('.', 1)[1] in \ [ 'txt', 'png', 'jpg', 'jpeg', 'mpg', 'mp4', 'avi', 'cr2' ]
import os from addict import Dict from gallery.models import File def get_dir_file_contents(dir_id): print(File.query.filter(File.parent == dir_id).all()) return File.query.filter(File.parent == dir_id).all() def get_dir_tree_dict(): path = os.path.normpath("/gallery-data/root") file_tree = Dict() for root, _, files in os.walk(path, topdown=True): path = root.split('/') path.pop(0) file_tree_fd = file_tree for part in path: file_tree_fd = file_tree_fd[part] file_tree_fd['.'] = files return file_tree def convert_bytes_to_utf8(dic): for key in dic: if isinstance(key, bytes): k = key.decode('utf-8') v = dic[key] del dic[key] dic[k] = v if isinstance(dic[key], bytes): v = dic[key].decode('utf-8') dic[key] = v return dic def allowed_file(filename): return '.' in filename and filename.lower().rsplit('.', 1)[1] in \ [ 'txt', 'png', 'jpg', 'jpeg', 'mpg', 'mp4', 'avi' ]
Correct linting error with order of requires
const merge = require("webpack-merge"); const PostCompile = require("post-compile-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const Version = require("node-version-assets"); const postCSSPlugins = [ require("postcss-easy-import")({ prefix: "_" }), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-color-function"), require("postcss-hexrgba"), require("autoprefixer"), require("cssnano") ]; const common = require("./webpack.common.js"); module.exports = env => { const opt = env || {}; return merge(common, { mode: "production", plugins: opt.deploy && [ new PostCompile(() => { new Version({ assets: [ "./src/_compiled/main.css", "./src/_compiled/main.js", "./src/_compiled/vendors~main.js", "./src/_compiled/runtime~main.js" ], grepFiles: ["./src/index.html"] }).run(); }) ], module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { url: false } }, { loader: "postcss-loader", options: { plugins: postCSSPlugins } } ] } ] } }); };
const merge = require("webpack-merge"); const PostCompile = require("post-compile-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const Version = require("node-version-assets"); const common = require("./webpack.common.js"); const postCSSPlugins = [ require("postcss-easy-import")({ prefix: "_" }), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-color-function"), require("postcss-hexrgba"), require("autoprefixer"), require("cssnano") ]; module.exports = env => { const opt = env || {}; return merge(common, { mode: "production", plugins: opt.deploy && [ new PostCompile(() => { new Version({ assets: [ "./src/_compiled/main.css", "./src/_compiled/main.js", "./src/_compiled/vendors~main.js", "./src/_compiled/runtime~main.js" ], grepFiles: ["./src/index.html"] }).run(); }) ], module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { url: false } }, { loader: "postcss-loader", options: { plugins: postCSSPlugins } } ] } ] } }); };
Return more than 10 domains
from .es_query import HQESQuery from . import filters class FormES(HQESQuery): index = 'forms' default_filters = { 'is_xform_instance': {"term": {"doc_type": "xforminstance"}}, 'has_xmlns': {"not": {"missing": {"field": "xmlns"}}}, 'has_user': {"not": {"missing": {"field": "form.meta.userID"}}}, } @property def builtin_filters(self): return [ xmlns, app, submitted, completed, user_id, ] + super(FormES, self).builtin_filters def user_facet(self): return self.terms_facet('form.meta.userID', 'user') def domain_facet(self): return self.terms_facet('domain', 'domain', 1000000) def xmlns(xmlns): return filters.term('xmlns.exact', xmlns) def app(app_id): return filters.term('app_id', app_id) def submitted(gt=None, gte=None, lt=None, lte=None): return filters.date_range('received_on', gt, gte, lt, lte) def completed(gt=None, gte=None, lt=None, lte=None): return filters.date_range('form.meta.timeEnd', gt, gte, lt, lte) def user_id(user_ids): return filters.term('form.meta.userID', list(user_ids))
from .es_query import HQESQuery from . import filters class FormES(HQESQuery): index = 'forms' default_filters = { 'is_xform_instance': {"term": {"doc_type": "xforminstance"}}, 'has_xmlns': {"not": {"missing": {"field": "xmlns"}}}, 'has_user': {"not": {"missing": {"field": "form.meta.userID"}}}, } @property def builtin_filters(self): return [ xmlns, app, submitted, completed, user_id, ] + super(FormES, self).builtin_filters def user_facet(self): return self.terms_facet('form.meta.userID', 'user') def domain_facet(self): return self.terms_facet('domain', 'domain') def xmlns(xmlns): return filters.term('xmlns.exact', xmlns) def app(app_id): return filters.term('app_id', app_id) def submitted(gt=None, gte=None, lt=None, lte=None): return filters.date_range('received_on', gt, gte, lt, lte) def completed(gt=None, gte=None, lt=None, lte=None): return filters.date_range('form.meta.timeEnd', gt, gte, lt, lte) def user_id(user_ids): return filters.term('form.meta.userID', list(user_ids))
Make hashmaploader use Map instead of hashmap
package org.twig.loader; import org.twig.exception.LoaderException; import java.util.HashMap; import java.util.Map; /** * Used for unit tests only */ public class HashMapLoader implements Loader { Map<String, String> hashMap; /** * Default constructor */ public HashMapLoader() { hashMap = new HashMap<>(); } /** * Construct the loader with an existing hash map * @param hashMap The hashMap with templates */ public HashMapLoader(Map<String, String> hashMap) { this.hashMap = hashMap; } @Override public String getSource(String name) throws LoaderException { if (hashMap.containsKey(name)) { return hashMap.get(name); } throw LoaderException.notDefined(name); } @Override public String getCacheKey(String name) throws LoaderException { if (!this.hashMap.containsKey(name)) { throw LoaderException.notDefined(name); } return this.hashMap.get(name); } /** * Get the hash map * @return The hashMap with templates */ public Map<String, String> getHashMap() { return hashMap; } /** * Set the hashmap * @param hashMap The hashMap with templates */ public void setHashMap(Map<String, String> hashMap) { this.hashMap = hashMap; } }
package org.twig.loader; import org.twig.exception.LoaderException; import java.util.HashMap; /** * Used for unit tests only */ public class HashMapLoader implements Loader { HashMap<String, String> hashMap; /** * Default constructor */ public HashMapLoader() { hashMap = new HashMap<>(); } /** * Construct the loader with an existing hash map * @param hashMap The hashMap with templates */ public HashMapLoader(HashMap<String, String> hashMap) { this.hashMap = hashMap; } @Override public String getSource(String name) throws LoaderException { if (hashMap.containsKey(name)) { return hashMap.get(name); } throw LoaderException.notDefined(name); } @Override public String getCacheKey(String name) throws LoaderException { if (!this.hashMap.containsKey(name)) { throw LoaderException.notDefined(name); } return this.hashMap.get(name); } /** * Get the hash map * @return The hashMap with templates */ public HashMap<String, String> getHashMap() { return hashMap; } /** * Set the hashmap * @param hashMap The hashMap with templates */ public void setHashMap(HashMap<String, String> hashMap) { this.hashMap = hashMap; } }
Make command invisible by default
import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel'], hidden=True) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel']) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
Add 'My Image Requests' to secondary image navigation
define(function (require) { var React = require('react/addons'), Router = require('react-router'), Glyphicon = require('components/common/Glyphicon.react'), context = require('context'); return React.createClass({ renderRoute: function (name, linksTo, icon, requiresLogin) { if (requiresLogin && !context.profile) return null; return ( <li key={name}> <Router.Link to={linksTo}> <Glyphicon name={icon}/> <span>{name}</span> </Router.Link> </li> ) }, render: function () { return ( <div> <div className="secondary-nav"> <div className="container"> <ul className="secondary-nav-links"> {this.renderRoute("Search", "search", "search", false)} {this.renderRoute("Favorites", "favorites", "bookmark", true)} {this.renderRoute("My Images", "authored", "user", true)} {this.renderRoute("My Image Requests", "my-image-requests", "export", true)} {this.renderRoute("Tags", "tags", "tags", false)} </ul> </div> </div> </div> ); } }); });
define(function (require) { var React = require('react/addons'), Router = require('react-router'), Glyphicon = require('components/common/Glyphicon.react'), context = require('context'); return React.createClass({ renderRoute: function (name, linksTo, icon, requiresLogin) { if (requiresLogin && !context.profile) return null; return ( <li key={name}> <Router.Link to={linksTo}> <Glyphicon name={icon}/> <span>{name}</span> </Router.Link> </li> ) }, render: function () { return ( <div> <div className="secondary-nav"> <div className="container"> <ul className="secondary-nav-links"> {this.renderRoute("Search", "search", "search", false)} {this.renderRoute("Favorites", "favorites", "bookmark", true)} {this.renderRoute("My Images", "authored", "user", true)} {this.renderRoute("Tags", "tags", "tags", false)} </ul> </div> </div> </div> ); } }); });
Allow turning off coverage reporting for performance tests
/*eslint-env node */ /*eslint no-var: 0 */ var coverage = String(process.env.COVERAGE)!=='false'; module.exports = function(config) { config.set({ frameworks: ['mocha', 'chai-sinon'], reporters: ['mocha'].concat(coverage ? 'coverage' : []), coverageReporter: { reporters: [ { type: 'text-summary' }, { type: 'html', dir: 'coverage' } ] }, browsers: ['PhantomJS'], files: [ 'test/browser/**.js', 'test/shared/**.js' ], preprocessors: { 'test/**/*.js': ['webpack'], 'src/**/*.js': ['webpack'], '**/*.js': ['sourcemap'] }, webpack: { module: { /* Transpile source and test files */ preLoaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { loose: 'all', blacklist: ['es6.tailCall'] } } ], /* Only Instrument our source files for coverage */ loaders: [].concat( coverage ? { test: /\.jsx?$/, loader: 'isparta', include: /src/ } : []) }, resolve: { modulesDirectories: [__dirname, 'node_modules'] } }, webpackMiddleware: { noInfo: true } }); };
/*eslint-env node */ /*eslint no-var: 0 */ module.exports = function(config) { config.set({ frameworks: ['mocha', 'chai-sinon'], reporters: ['mocha', 'coverage'], coverageReporter: { reporters: [ { type: 'text-summary' }, { type: 'html', dir: 'coverage' } ] }, browsers: ['PhantomJS'], files: [ 'test/browser/**.js', 'test/shared/**.js' ], preprocessors: { 'test/**/*.js': ['webpack'], 'src/**/*.js': ['webpack'], '**/*.js': ['sourcemap'] }, webpack: { module: { /* Transpile source and test files */ preLoaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { loose: 'all', blacklist: ['es6.tailCall'] } } ], /* Only Instrument our source files for coverage */ loaders: [ { test: /\.jsx?$/, loader: 'isparta', include: /src/ } ] }, resolve: { modulesDirectories: [__dirname, 'node_modules'] } }, webpackMiddleware: { noInfo: true } }); };
Add attribute 'is_unset' so that the interface is consistent with MissingTohuItemsCls
import attr __all__ = ["make_tohu_items_class"] def make_tohu_items_class(clsname, field_names): """ Parameters ---------- clsname: string Name of the class to be created. field_names: list of strings Names of the field attributes of the class to be created. """ item_cls = attr.make_class(clsname, {name: attr.ib() for name in field_names}, repr=True, cmp=True, frozen=True) func_eq_orig = item_cls.__eq__ def func_eq_new(self, other): """ Custom __eq__() method which also allows comparisons with tuples and dictionaries. This is mostly for convenience during testing. """ if isinstance(other, self.__class__): return func_eq_orig(self, other) else: if isinstance(other, tuple): return attr.astuple(self) == other elif isinstance(other, dict): return attr.asdict(self) == other else: raise TypeError( f"Tohu items have types that cannot be compared: " "{self.__class__.__name__}, {other.__class__.__name__}" ) item_cls.__eq__ = func_eq_new item_cls.field_names = field_names item_cls.as_dict = lambda self: attr.asdict(self) item_cls.as_tuple = lambda self: attr.astuple(self) item_cls.is_unset = False return item_cls
import attr __all__ = ["make_tohu_items_class"] def make_tohu_items_class(clsname, field_names): """ Parameters ---------- clsname: string Name of the class to be created. field_names: list of strings Names of the field attributes of the class to be created. """ item_cls = attr.make_class(clsname, {name: attr.ib() for name in field_names}, repr=True, cmp=True, frozen=True) func_eq_orig = item_cls.__eq__ def func_eq_new(self, other): """ Custom __eq__() method which also allows comparisons with tuples and dictionaries. This is mostly for convenience during testing. """ if isinstance(other, self.__class__): return func_eq_orig(self, other) else: if isinstance(other, tuple): return attr.astuple(self) == other elif isinstance(other, dict): return attr.asdict(self) == other else: raise TypeError( f"Tohu items have types that cannot be compared: " "{self.__class__.__name__}, {other.__class__.__name__}" ) item_cls.__eq__ = func_eq_new item_cls.field_names = field_names item_cls.as_dict = lambda self: attr.asdict(self) item_cls.as_tuple = lambda self: attr.astuple(self) return item_cls
Change to package.json to enable source map
var path = require('path'); var webpack = require('webpack'); var configFile = require('./settings/config.json'); module.exports = { entry: [ path.resolve(__dirname, 'app/main.js') ], devtool: "#cheap-eval-source-map", output: { path: path.resolve(__dirname, 'dist'), publicPath: '/', filename: 'bundle.js', }, module: { loaders: [ {test: /\.woff|\.woff2|\.svg|.eot|\.ttf|\.png|\.gif|\.ico|\.html/, loader: 'file-loader'}, {test: /\.json$/, loader: 'file-loader'}, {test: /\.css$/, loader: "style!css"}, {test: /\.scss$/, loader: 'style!css!sass'}, {test: /\.js$/, exclude: /node_modules/, loader: "babel"}, {test: /\.jsx$/, exclude: /node_modules/, loader: "babel"} ] }, resolve: { extensions: ['', '.js', '.json', '.css', '.jsx', '.json'] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }), new webpack.IgnorePlugin(/\/iconv-loader$/) ], externals: { 'config': JSON.stringify(configFile) } };
var path = require('path'); var webpack = require('webpack'); var configFile = require('./settings/config.json'); module.exports = { entry: [ path.resolve(__dirname, 'app/main.js') ], output: { path: path.resolve(__dirname, 'dist'), publicPath: '/', filename: 'bundle.js', }, module: { loaders: [ {test: /\.woff|\.woff2|\.svg|.eot|\.ttf|\.png|\.gif|\.ico|\.html/, loader: 'file-loader'}, {test: /\.json$/, loader: 'file-loader'}, {test: /\.css$/, loader: "style!css"}, {test: /\.scss$/, loader: 'style!css!sass'}, {test: /\.js$/, exclude: /node_modules/, loader: "babel"}, {test: /\.jsx$/, exclude: /node_modules/, loader: "babel"} ] }, resolve: { extensions: ['', '.js', '.json', '.css', '.jsx', '.json'] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }), new webpack.IgnorePlugin(/\/iconv-loader$/) ], externals: { 'config': JSON.stringify(configFile) } };
Handle null case for client id
"use strict"; var restify = require('restify'); var async = require('async'); var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { if(!req.query.context) { return next(new restify.ConflictError("Missing query parameter")); } async.waterfall([ function getDocuments(cb) { var params = { search: req.query.context, render_templates: true, sort: "-modificationDate", strict: true, fields: "data", }; if(req.query.limit) { params.limit = req.query.limit; } var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments(params, cb); }, function remapDocuments(documentsRes, cb) { res.set("Cache-Control", "max-age=3600"); res.send(200, documentsRes.body.data.map(function mapDocuments(document) { return { documentId: document.id, typeId: document.document_type.id, providerId: document.provider.client ? document.provider.client.id : null, date: document.modification_date, snippet: document.rendered_snippet, title: document.rendered_title }; })); cb(); } ], next); };
"use strict"; var restify = require('restify'); var async = require('async'); var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { if(!req.query.context) { return next(new restify.ConflictError("Missing query parameter")); } async.waterfall([ function getDocuments(cb) { var params = { search: req.query.context, render_templates: true, sort: "-modificationDate", strict: true, fields: "data", }; if(req.query.limit) { params.limit = req.query.limit; } var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments(params, cb); }, function remapDocuments(documentsRes, cb) { res.set("Cache-Control", "max-age=3600"); res.send(200, documentsRes.body.data.map(function mapDocuments(document) { return { documentId: document.id, typeId: document.document_type.id, providerId: document.provider.client.id, date: document.modification_date, snippet: document.rendered_snippet, title: document.rendered_title }; })); cb(); } ], next); };
Rename state variable to baseState
import React from 'react'; const mapValuesToDefaultState = (defaultState, item) => { if (typeof item === 'string') { defaultState[item] = ''; } if (typeof item === 'object') { const { key, value } = item; defaultState[key] = value; } } const withLinkState = (baseState = []) => Component => { const defaultState = {}; if (!Array.isArray(baseState)) { throw new Error('keys must be an Array of Strings/Objects!'); } baseState.forEach(item => mapValuesToDefaultState(defaultState, item)); class LinkStateComponent extends React.Component { state = defaultState; render() { return ( <Component getState={this.getState} linkState={this.linkState} getValue={this.getValue} updateState={this.updateState} {...this.props} /> ); } linkState = (key, callback) => ({ value: this.state[key] || '', onChange: event => { let value = event.target.value; if (callback && typeof(callback) === 'function') { const modifiedValue = callback(event.target.value); value = modifiedValue ? modifiedValue : value; } this.updateState({ [key]: value }); } }); getState = () => this.state; getValue = key => this.state[key] || ''; updateState = (object, callback = undefined) => this.setState(object, callback); } return LinkStateComponent; }; export default withLinkState;
import React from 'react'; const mapValuesToDefaultState = (defaultState, item) => { if (typeof item === 'string') { defaultState[item] = ''; } if (typeof item === 'object') { const { key, value } = item; defaultState[key] = value; } } const withLinkState = (state = []) => Component => { const defaultState = {}; if (!Array.isArray(state)) { throw new Error('keys must be an Array of Strings/Objects!'); } state.forEach(item => mapValuesToDefaultState(defaultState, item)); class LinkStateComponent extends React.Component { state = defaultState; render() { return ( <Component getState={this.getState} linkState={this.linkState} getValue={this.getValue} updateState={this.updateState} {...this.props} /> ); } linkState = (key, callback) => ({ value: this.state[key] || '', onChange: event => { let value = event.target.value; if (callback && typeof(callback) === 'function') { const modifiedValue = callback(event.target.value); value = modifiedValue ? modifiedValue : value; } this.updateState({ [key]: value }); } }); getState = () => this.state; getValue = key => this.state[key] || ''; updateState = (object, callback = undefined) => this.setState(object, callback); } return LinkStateComponent; }; export default withLinkState;
Fix select element global listener
$(function() { $('.dropdown').each(function() { var me = $(this); var dropdownList = me.find(".dropdownList"); if(dropdownList.children().length === 0) { me.find("option").each(function(i, e) { $(e).addClass("opt-" + i); dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>')); }); } var select = me.find("select").val(); me.find(".dropdownValue").text(me.find('option[value="' + select + '"]').text()) }); $(document).on("click", ".dropdown", function() { var me = $(this); var list = me.find(".dropdownList"); var opts = me.find(".hiddenDropdown"); if(list.css("display") == "block") { list.hide(); } else { $(".dropdownList").hide(); list.show(); list.find("li").one("click", function(event) { event.stopPropagation(); list.hide().find("li").off("click"); var me2 = $(this); var opt = me2.attr("class").replace("item", "opt"); me.find(".dropdownValue").text(me2.text()); opts.find("[selected=selected]").removeAttr("selected"); var val = opts.find("." + opt).attr("selected", "selected").val(); opts.val(val).trigger('change'); }) } $(document).one("click", function() { list.hide().find("li").off("mouseout").off("click"); }); return false; }); });
$(function() { $('.dropdown').each(function() { var element = $(this); var dropdownList = element.find(".dropdownList"); if(dropdownList.children().length === 0) { element.find("option").each(function(i, e) { $(e).addClass("opt-" + i); dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>')); }); } var select = element.find("select").val(); element.find(".dropdownValue").text(element.find('option[value="' + select + '"]').text()) }).on('click', function() { var me = $(this); var list = me.find(".dropdownList"); var opts = me.find(".hiddenDropdown"); if(list.css("display") == "block") { list.hide(); } else { $(".dropdownList").hide(); list.show(); list.find("li").one("click", function(event) { event.stopPropagation(); list.hide().find("li").off("click"); var me2 = $(this); var opt = me2.attr("class").replace("item", "opt"); me.find(".dropdownValue").text(me2.text()); opts.find("[selected=selected]").removeAttr("selected"); var val = opts.find("." + opt).attr("selected", "selected").val(); opts.val(val).trigger('change'); }) } $(document).one("click", function() { list.hide().find("li").off("mouseout").off("click"); }); return false; }) });
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. git-svn-id: http://code.djangoproject.com/svn/django/trunk@14359 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --HG-- extra : convert_revision : e026073455a73c9fe9a9f026b76ac783b2a12d23
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's admin module. try: before_import_registry = copy.copy(site._registry) import_module('%s.admin' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). site._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'admin'): raise
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's admin module. try: before_import_registry = copy.copy(site._registry) import_module('%s.admin' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). site._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'admin'): raise
Change in warning message when user attempts to change task storage directory
package seedu.task.alerts; import java.util.Optional; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; //@@author A0142360U public class TransferTaskAlert extends Alert { public static final String CHANGE_DIRECTORY_COMMAND_TITLE = "Change of Task Storage Directory"; public static final String CHANGE_DIRECTORY_HEADER_TEXT = "Would you like your existing tasks to be transferred over to the new directory?\nNOTE: Never Forget will need to be relaunched."; public static final ButtonType buttonTypeYes = new ButtonType("Yes"); public static final ButtonType buttonTypeNo = new ButtonType("No"); public static final ButtonType buttonTypeCancel = new ButtonType("Cancel"); public static final String yes = "Yes"; public static final String no = "No"; public static final String noAction = "noAction"; public TransferTaskAlert(AlertType alertType) { super(alertType); } public static String transferTaskOptionAlert() { try { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle(CHANGE_DIRECTORY_COMMAND_TITLE); alert.setHeaderText(CHANGE_DIRECTORY_HEADER_TEXT); alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeYes) { return yes; } else if (result.get() == buttonTypeNo) { return no; } else { return noAction; } } catch (ExceptionInInitializerError | IllegalStateException e) { return noAction; } } }
package seedu.task.alerts; import java.util.Optional; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; //@@author A0142360U public class TransferTaskAlert extends Alert { public static final String CHANGE_DIRECTORY_COMMAND_TITLE = "Change of Task Storage Directory"; public static final String CHANGE_DIRECTORY_HEADER_TEXT = "Would you like your existing tasks to be transferred over to the new directory?"; public static final ButtonType buttonTypeYes = new ButtonType("Yes"); public static final ButtonType buttonTypeNo = new ButtonType("No"); public static final ButtonType buttonTypeCancel = new ButtonType("Cancel"); public static final String yes = "Yes"; public static final String no = "No"; public static final String noAction = "noAction"; public TransferTaskAlert(AlertType alertType) { super(alertType); } public static String transferTaskOptionAlert() { try { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle(CHANGE_DIRECTORY_COMMAND_TITLE); alert.setHeaderText(CHANGE_DIRECTORY_HEADER_TEXT); alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeYes) { return yes; } else if (result.get() == buttonTypeNo) { return no; } else { return noAction; } } catch (ExceptionInInitializerError | IllegalStateException e) { return noAction; } } }
Use ParticleData class in file reader File reader now creates lists of ParticleData objects. Signed-off-by: Jussi Auvinen <[email protected]>
#!/usr/bin/python # Functions for reading hybrid model output(s) import os import copy from .. import dataobjects.particledata def read_afterburner_output(filename, read_initial=False): id_event = 0 if os.path.isfile(filename): read_data = False initial_list = False eventlist = [] particlelist = [] for line in open(filename, "r"): inputline = line.split() if (inputline and inputline[0] == "#event"): id_event += 1 read_data = False if (len(particlelist) > 0): eventlist.append(copy.copy(particlelist)) del particlelist[:] if (inputline and inputline[0] == "#cols:"): if not initial_list: initial_list = True if read_initial: read_data = True else: initial_list = False if read_initial: read_data = False else: read_data = True if read_data: try: px = float(inputline[4]) py = float(inputline[5]) pz = float(inputline[6]) E = float(inputline[7]) ptype = int(inputline[8]) charge = int(inputline[10]) except ValueError: continue particledata = ParticleData([E, px, py, pz], ptype, charge) particlelist.append(particledata) if (len(particlelist) > 0): eventlist.append(copy.copy(particlelist)) del particlelist[:] return eventlist
#!/usr/bin/python # Functions for reading hybrid model output(s) import os def read_afterburner_output(filename, read_initial=False): id_event = 0 particlelist = [] if os.path.isfile(filename): read_data = False initial_list = False for line in open(filename, "r"): inputline = line.split() if (inputline and inputline[0] == "#event"): id_event += 1 read_data = False if (inputline and inputline[0] == "#cols:"): if not initial_list: initial_list = True if read_initial: read_data = True else: initial_list = False if read_initial: read_data = False else: read_data = True if read_data: try: x = float(inputline[0]) ptype = int(inputline[8]) except ValueError: continue particlelist.append((tuple(inputline), id_event)) return particlelist
Use github URL instead of documentation.
""" Powerful and Lightweight Python Tree Data Structure with various plugins. """ # Always prefer setuptools over distutils from setuptools import setup # To use a consistent encoding from codecs import open from os import path config = { 'name': "anytree", 'version': "1.0.1", 'author': 'c0fec0de', 'author_email': '[email protected]', 'description': "Powerful and Lightweight Python Tree Data Structure with various plugins.", 'url': "https://github.com/c0fec0de/anytree", 'license': 'Apache 2.0', 'classifiers': [ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], 'keywords': 'tree, tree data, treelib, tree walk', 'packages': ['anytree'], 'install_requires': ['six'], 'extras_require': { 'dev': ['check-manifest'], 'test': ['coverage'], }, 'test_suite': 'nose.collector', } # Get the long description from the README file here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: config['long_description'] = f.read() setup(**config)
""" Powerful and Lightweight Python Tree Data Structure with various plugins. """ # Always prefer setuptools over distutils from setuptools import setup # To use a consistent encoding from codecs import open from os import path config = { 'name': "anytree", 'version': "1.0.1", 'author': 'c0fec0de', 'author_email': '[email protected]', 'description': "Powerful and Lightweight Python Tree Data Structure with various plugins.", 'url': "http://anytree.readthedocs.io", 'license': 'Apache 2.0', 'classifiers': [ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], 'keywords': 'tree, tree data, treelib, tree walk', 'packages': ['anytree'], 'install_requires': ['six'], 'extras_require': { 'dev': ['check-manifest'], 'test': ['coverage'], }, 'test_suite': 'nose.collector', } # Get the long description from the README file here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: config['long_description'] = f.read() setup(**config)
Fix exception when task result is null
from selinon import StoragePool from cucoslib.models import WorkerResult, Analysis from .base import BaseHandler class CleanPostgres(BaseHandler): """ Clean JSONB columns in Postgres """ def execute(self): s3 = StoragePool.get_connected_storage('S3Data') start = 0 while True: results = self.postgres.session.query(WorkerResult).\ join(Analysis).\ filter(Analysis.finished_at != None).\ filter(WorkerResult.external_request_id == None).\ order_by(WorkerResult.id).\ slice(start, start + 10).all() if not results: self.log.info("Cleaning postgres finished") break self.log.info("Updating results, slice offset is %s", start) start += 10 for entry in results: if entry.worker[0].isupper() or entry.worker in ('recommendation', 'stack_aggregator'): continue if not entry.task_result or 'VersionId' in entry.task_result: continue result_object_key = s3._construct_task_result_object_key(entry.ecosystem.name, entry.package.name, entry.version.identifier, entry.worker) if s3.object_exists(result_object_key): entry.task_result = {'VersionId': s3.retrieve_latest_version_id(result_object_key)} else: entry.task_result = None entry.error = True self.postgres.session.commit() del entry
from selinon import StoragePool from cucoslib.models import WorkerResult, Analysis from .base import BaseHandler class CleanPostgres(BaseHandler): """ Clean JSONB columns in Postgres """ def execute(self): s3 = StoragePool.get_connected_storage('S3Data') start = 0 while True: results = self.postgres.session.query(WorkerResult).\ join(Analysis).\ filter(Analysis.finished_at != None).\ filter(WorkerResult.external_request_id == None).\ order_by(WorkerResult.id).\ slice(start, start + 10).all() if not results: self.log.info("Cleaning postgres finished") break self.log.info("Updating results, slice offset is %s", start) start += 10 for entry in results: if entry.worker[0].isupper() or entry.worker in ('recommendation', 'stack_aggregator'): continue if 'VersionId' in entry.task_result: continue result_object_key = s3._construct_task_result_object_key(entry.ecosystem.name, entry.package.name, entry.version.identifier, entry.worker) if s3.object_exists(result_object_key): entry.task_result = {'VersionId': s3.retrieve_latest_version_id(result_object_key)} else: entry.task_result = None entry.error = True self.postgres.session.commit() del entry
Set each bookmark's identifier on its DOM element 'id' attribute.
( function( global, chrome, d ) { // I know, UGLY, but it's just a prototype. // FIXME: Refactor, improve, rewrite from scrath, whatever but make it pretty and efficient ! function View( $element, manager ) { this.manager = manager; this.$left = $element.find( '.left' ); this.$right = $element.find( '.right' ); } View.prototype.display = function() { var self = this; self.manager.getSections( function( sections ) { sections.forEach( function( section ) { var $column = ( section.title.substring( 0, 1 ) === '+' ) ? self.$left : self.$right, $s = $( '<section></section>' ); $s[ 0 ].id = section.id; $s.append( '<h1>' + section.title.substring( 1 ) + '</h1>' ); $column.append( $s ); ( function( $section ) { self.manager.getBookmarks( section, function( bookmarks ) { bookmarks.forEach( function( bookmark ) { var $link = $( '<a>' + bookmark.title + '</a>' ); $link[ 0 ].id = bookmark.id; $link[ 0 ].href = bookmark.url; $section.append( $link ); } ); } ); } )( $s ); } ); } ); } d.View = View; } )( this, chrome, this.Dashboard = this.Dashboard || {} ); var $c = $( '#container' ), $s;
( function( global, chrome, d ) { // I know, UGLY, but it's just a prototype. function View( $element, manager ) { this.manager = manager; this.$left = $element.find( '.left' ); this.$right = $element.find( '.right' ); } View.prototype.display = function() { var self = this; self.manager.getSections( function( sections ) { sections.forEach( function( section ) { var $column = ( section.title.substring( 0, 1 ) === '+' ) ? self.$left : self.$right; $s = $( '<section></section>' ); $s.append( '<h1>' + section.title.substring( 1 ) + '</h1>' ); $column.append( $s ); ( function( $section ) { self.manager.getBookmarks( section, function( bookmarks ) { bookmarks.forEach( function( bookmark ) { var $link = $( '<a href="' + bookmark.url + '">' + bookmark.title + '</a>' ); $section.append( $link ); } ); } ); } )( $s ); } ); } ); } d.View = View; } )( this, chrome, this.Dashboard = this.Dashboard || {} ); var $c = $( '#container' ), $s;
Update logging to log async functions properly
import sys import inspect from functools import wraps, _make_key import redis def logging(*triggers, out=sys.stdout): """Will log function if all triggers are True""" log = min(triggers) # will be False if any trigger is false def wrapper(function): @wraps(function) def wrapped_function(*args, **kwargs): result = function(*args, **kwargs) if log: print(function.__name__, args, kwargs, result, file=out) return result return wrapped_function def async_wrapper(async_function): @wraps(async_function) async def wrapped_async_function(*args, **kwargs): result = await async_function(*args, **kwargs) if log: print(async_function.__name__, args, kwargs, result, file=out) return result return wrapped_async_function def cool_wrapper(function): is_async_function = inspect.iscoroutinefunction(function) if is_async_function: return async_wrapper(function) else: return wrapper(function) return cool_wrapper def redis_timeout_async_method_cache(timeout, redis_url): def wrapper(async_method): cache = redis.from_url(redis_url) @wraps(async_method) async def wrapped_method(self, *args, **kwargs): name_and_args = (async_method.__name__,) + tuple(a for a in args) key = _make_key(name_and_args, kwargs, False) cached_result = cache.get(key) if cached_result is not None: return cached_result.decode('utf-8') result = await async_method(self, *args, **kwargs) cache.setex(key, result, timeout) return result return wrapped_method return wrapper
import sys from functools import wraps, _make_key import redis def logging(*triggers, out=sys.stdout): """Will log function if all triggers are True""" log = min(triggers) # will be False if any trigger is false def wrapper(function): @wraps(function) def wrapped_function(*args, **kwargs): if log: print('calling', function.__name__, args, kwargs, file=out) result = function(*args, **kwargs) if log: print('result', function.__name__, result, file=out) return result return wrapped_function return wrapper def redis_timeout_async_method_cache(timeout, redis_url): def wrapper(async_method): cache = redis.from_url(redis_url) @wraps(async_method) async def wrapped_method(self, *args, **kwargs): name_and_args = (async_method.__name__,) + tuple(a for a in args) key = _make_key(name_and_args, kwargs, False) cached_result = cache.get(key) if cached_result is not None: return cached_result.decode('utf-8') result = await async_method(self, *args, **kwargs) cache.setex(key, result, timeout) return result return wrapped_method return wrapper
Update to Apache Airflow 1.8.1
from setuptools import setup from os import path import codecs here = path.abspath(path.dirname(__file__)) with codecs.open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='data-tracking', version='1.5.11', zip_safe=False, url='https://github.com/LREN-CHUV/data-tracking', description='Extract meta-data from DICOM and NIFTI files', long_description=long_description, author='Mirco Nasuti', author_email='[email protected]', license='Apache 2.0', packages=['data_tracking'], keywords='mri dicom nifti', install_requires=[ 'apache-airflow>=1.8.1', 'pydicom>=0.9.9', 'SQLAlchemy>=1.1.6', 'python-magic>=0.4.12', 'nibabel>=2.1.0', 'psycopg2>=2.7.1'], classifiers=( 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Operating System :: Unix', 'License :: OSI Approved :: Apache Software License', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ) )
from setuptools import setup from os import path import codecs here = path.abspath(path.dirname(__file__)) with codecs.open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='data-tracking', version='1.5.11', zip_safe=False, url='https://github.com/LREN-CHUV/data-tracking', description='Extract meta-data from DICOM and NIFTI files', long_description=long_description, author='Mirco Nasuti', author_email='[email protected]', license='Apache 2.0', packages=['data_tracking'], keywords='mri dicom nifti', install_requires=[ 'airflow>=1.7.0', 'pydicom>=0.9.9', 'SQLAlchemy>=1.1.6', 'python-magic>=0.4.12', 'nibabel>=2.1.0', 'psycopg2>=2.7.1'], classifiers=( 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Operating System :: Unix', 'License :: OSI Approved :: Apache Software License', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ) )
Add page_* prefix to values set in the PageInfo js
<?php /** * @package Mautic * @copyright 2016 Mautic Contributors. All rights reserved. * @author Mautic * @link http://mautic.org * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ namespace Mautic\PageBundle\EventListener; use Mautic\CoreBundle\EventListener\CommonSubscriber; use Mautic\CoreBundle\CoreEvents; use Mautic\CoreBundle\Event\BuildJsEvent; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; /** * Class BuildJsSubscriber */ class BuildJsSubscriber extends CommonSubscriber { /** * @return array */ public static function getSubscribedEvents() { return array( CoreEvents::BUILD_MAUTIC_JS => array('onBuildJs', 256) ); } /** * @param BuildJsEvent $event * * @return void */ public function onBuildJs(BuildJsEvent $event) { $js = <<<JS (function(m, l, n, d){ var params = { page_title: d.title, page_language: n.language, page_referrer: (d.referrer) ? d.referrer.split('/')[2] : '', page_url: l.href }; m.trackingPixelParams = m.serialize(params); })(MauticJS, location, navigator, document); JS; $event->appendJs($js, 'Page Info'); } }
<?php /** * @package Mautic * @copyright 2016 Mautic Contributors. All rights reserved. * @author Mautic * @link http://mautic.org * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ namespace Mautic\PageBundle\EventListener; use Mautic\CoreBundle\EventListener\CommonSubscriber; use Mautic\CoreBundle\CoreEvents; use Mautic\CoreBundle\Event\BuildJsEvent; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; /** * Class BuildJsSubscriber */ class BuildJsSubscriber extends CommonSubscriber { /** * @return array */ public static function getSubscribedEvents() { return array( CoreEvents::BUILD_MAUTIC_JS => array('onBuildJs', 256) ); } /** * @param BuildJsEvent $event * * @return void */ public function onBuildJs(BuildJsEvent $event) { $js = <<<JS (function(m, l, n, d){ var params = { title: d.title, language: n.language, referrer: (d.referrer) ? d.referrer.split('/')[2] : '', url: l.href }; m.trackingPixelParams = m.serialize(params); })(MauticJS, location, navigator, document); JS; $event->appendJs($js, 'Page Info'); } }
Fix bug when using a custom class (defined via string in config)
<?php namespace Spatie\MediaLibrary\UrlGenerator; use Spatie\MediaLibrary\Media; use Spatie\MediaLibrary\PathGenerator\PathGeneratorFactory; class UrlGeneratorFactory { public static function createForMedia(Media $media) { $urlGeneratorClass = 'Spatie\MediaLibrary\UrlGenerator\\'.ucfirst($media->getDiskDriverName()).'UrlGenerator'; $customUrlClass = config('laravel-medialibrary.custom_url_generator_class'); $urlGenerator = self::isAValidUrlGeneratorClass($customUrlClass) ? app($customUrlClass) : app($urlGeneratorClass); $pathGenerator = PathGeneratorFactory::create(); $urlGenerator->setMedia($media)->setPathGenerator($pathGenerator); return $urlGenerator; } /** * Determine if the the given class is a valid UrlGenerator. * * @param $customUrlClass * * @return bool */ protected static function isAValidUrlGeneratorClass($customUrlClass) { if (!$customUrlClass) { return false; } if (!class_exists($customUrlClass)) { return false; } if (!is_subclass_of($customUrlClass, UrlGenerator::class)) { return false; } return true; } }
<?php namespace Spatie\MediaLibrary\UrlGenerator; use Spatie\MediaLibrary\Media; use Spatie\MediaLibrary\PathGenerator\PathGeneratorFactory; class UrlGeneratorFactory { public static function createForMedia(Media $media) { $urlGeneratorClass = 'Spatie\MediaLibrary\UrlGenerator\\'.ucfirst($media->getDiskDriverName()).'UrlGenerator'; $customUrlClass = config('laravel-medialibrary.custom_url_generator_class'); $urlGenerator = self::isAValidUrlGeneratorClass($customUrlClass) ? $customUrlClass : app($urlGeneratorClass); $pathGenerator = PathGeneratorFactory::create(); $urlGenerator->setMedia($media)->setPathGenerator($pathGenerator); return $urlGenerator; } /** * Determine if the the given class is a valid UrlGenerator. * * @param $customUrlClass * * @return bool */ protected static function isAValidUrlGeneratorClass($customUrlClass) { if (!$customUrlClass) { return false; } if (!class_exists($customUrlClass)) { return false; } if (!is_subclass_of($customUrlClass, UrlGenerator::class)) { return false; } return true; } }
Fix indentation + remove underscore to private member
<?php /** * @title User API Ajax Class * * @author Pierre-Henry Soria <[email protected]> * @copyright (c) 2013-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / User / Asset / Ajax */ namespace PH7; defined('PH7') or exit('Restricted access'); use PH7\Framework\Mvc\Request\Http; class ApiAjax { /** @var UserCore */ private $_oUser; /** @var mixed */ private $mOutput; public function __construct() { $this->_oUser = new UserCore; $this->_init(); } public function display() { return $this->mOutput; } private function _init() { $oHttpRequest = new Http; $sParam = $oHttpRequest->post('param'); $sType = $oHttpRequest->post('type'); unset($oHttpRequest); switch($sType) { case 'profile_link': $this->mOutput = $this->_oUser->getProfileLink($sParam); break; // If we receive another invalid value, we display a message with a HTTP header. default: Framework\Http\Http::setHeadersByCode(400); exit('Bad Request Error!'); } } } echo (new ApiAjax)->display();
<?php /** * @title User API Ajax Class * * @author Pierre-Henry Soria <[email protected]> * @copyright (c) 2013-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / User / Asset / Ajax */ namespace PH7; defined('PH7') or exit('Restricted access'); use PH7\Framework\Mvc\Request\Http; class ApiAjax { private $_oUser, $_mOutput; public function __construct() { $this->_oUser = new UserCore; $this->_init(); } public function display() { return $this->_mOutput; } private function _init() { $oHttpRequest = new Http; $sParam = $oHttpRequest->post('param'); $sType = $oHttpRequest->post('type'); unset($oHttpRequest); switch($sType) { case 'profile_link': $this->_mOutput = $this->_oUser->getProfileLink($sParam); break; // If we receive another invalid value, we display a message with a HTTP header. default: Framework\Http\Http::setHeadersByCode(400); exit('Bad Request Error!'); } } } echo (new ApiAjax)->display();
Add timer and remove confirm buttonk, overall cleanup for better ux
var deleteOpenSession = function(timeslot_id){ event.preventDefault(); $("#modal_remote").modal('hide'); swal({ title: "Are you sure you wish to cancel?", text: "This will delete your mentoring timeslot.", type: "warning", showCancelButton: true, confirmButtonColor: "#EF5350", confirmButtonText: "Yes, cancel this mentoring timeslot.", cancelButtonText: "No, I've changed my mind.", closeOnConfirm: false, closeOnCancel: true }, function(isConfirm){ if (isConfirm) { $.ajax({ type: "DELETE", url: "/api/timeslots/" + timeslot_id }).done(function(){ swal({ title: "Deleted!", text: "Your mentoring availabilty has been removed.", confirmButtonColor: "#FFFFFF", showConfirmButton: false, allowOutsideClick: true, timer: 1500, type: "info" }); $('#tutor-cal').fullCalendar('refetchEvents'); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); } }); }
var deleteOpenSession = function(timeslot_id){ event.preventDefault(); $("#modal_remote").modal('hide'); swal({ title: "Are you sure you wish to cancel?", text: "This will delete your mentoring timeslot.", type: "warning", showCancelButton: true, confirmButtonColor: "#EF5350", confirmButtonText: "Yes, cancel this mentoring timeslot.", cancelButtonText: "No, I've changed my mind.", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){ if (isConfirm) { $.ajax({ type: "DELETE", url: "/api/timeslots/" + timeslot_id }).done(function(){ swal({ title: "Deleted!", text: "Your mentoring availabilty has been removed.", confirmButtonColor: "#66BB6A", type: "info" }); $('#tutor-cal').fullCalendar('refetchEvents'); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); } else { swal({ title: "Cancelled", text: "Your availabilty is still scheduled.", confirmButtonColor: "#2196F3", type: "error" }); } }); }
Move extra log params under 'janus' namespace
var _ = require('underscore'); var layouts = require('log4js').layouts; var sprintf = require("sprintf-js").sprintf; var stringify = require('json-stringify-safe'); var NestedError = require('nested-error-stacks'); var isPlainObject = require('is-plain-object'); var Log4jsJsonLayout = { process: function(logEvent) { var logEntry = { timestamp: logEvent.startTime.toISOString(), level: logEvent.level && logEvent.level.levelStr.toLowerCase() || null }; try { _.extend(logEntry, this.extractParams(logEvent.data)); return stringify(logEntry); } catch (e) { return JSON.stringify(new NestedError('Error converting log message to JSON', e)); } }, extractParams: function(logData) { var messages = []; var params = {}; logData.forEach(function(element) { if (isPlainObject(element)) { params = _.extend(params, element); } else { messages.push(element); } }); var message = this.parseMessages(messages); return {message: message, janus: params}; }, parseMessages: function(messages) { if (messages.length == 1) { return messages[0]; } if (typeof messages[0] === 'string' && messages[0].indexOf('%') >= 0) { return sprintf.apply(this, messages); } return messages.join(''); } }; layouts.addLayout('json', function() { return Log4jsJsonLayout.process.bind(Log4jsJsonLayout); });
var _ = require('underscore'); var layouts = require('log4js').layouts; var sprintf = require("sprintf-js").sprintf; var stringify = require('json-stringify-safe'); var NestedError = require('nested-error-stacks'); var isPlainObject = require('is-plain-object'); var Log4jsJsonLayout = { process: function(logEvent) { var logEntry = { timestamp: logEvent.startTime.toISOString(), level: logEvent.level && logEvent.level.levelStr.toLowerCase() || null }; try { _.extend(logEntry, this.extractParams(logEvent.data)); return stringify(logEntry); } catch (e) { return JSON.stringify(new NestedError('Error converting log message to JSON', e)); } }, extractParams: function(logData) { var messages = []; var params = {}; logData.forEach(function(element) { if (isPlainObject(element)) { params = _.extend(params, element); } else { messages.push(element); } }); var message = this.parseMessages(messages); return _.extend({message: message}, params); }, parseMessages: function(messages) { if (messages.length == 1) { return messages[0]; } if (typeof messages[0] === 'string' && messages[0].indexOf('%') >= 0) { return sprintf.apply(this, messages); } return messages.join(''); } }; layouts.addLayout('json', function() { return Log4jsJsonLayout.process.bind(Log4jsJsonLayout); });
Break infinite loop with Gradle 5.6 when adding configuration for core bom support
package netflix.nebula.dependency.recommender; import netflix.nebula.dependency.recommender.provider.RecommendationProviderContainer; import org.gradle.api.Action; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; public class ExtendRecommenderConfigurationAction implements Action<Configuration> { private Logger logger = Logging.getLogger(ExtendRecommenderConfigurationAction.class); private final Configuration bom; private final Project project; private final RecommendationProviderContainer container; public ExtendRecommenderConfigurationAction(Configuration bom, Project project, RecommendationProviderContainer container) { this.bom = bom; this.project = project; this.container = container; } @Override public void execute(Configuration configuration) { if (container.getExcludedConfigurations().contains(configuration.getName()) || isCopyOfBomConfiguration(configuration)) { return; } if (configuration.getState() == Configuration.State.UNRESOLVED) { Configuration toExtend = bom; if (!project.getRootProject().equals(project)) { toExtend = bom.copy(); toExtend.setVisible(false); project.getConfigurations().add(toExtend); } configuration.extendsFrom(toExtend); } else { logger.info("Configuration '" + configuration.getName() + "' has already been resolved and cannot be included for recommendation"); } } //this action creates clones of bom configuration from root and gradle will also apply the action to them which would //lead to another copy of copy and so on creating infinite loop. We won't apply the action when configuration is copy from bom configuration. private boolean isCopyOfBomConfiguration(Configuration configuration) { return configuration.getName().startsWith(bom.getName()); } }
package netflix.nebula.dependency.recommender; import netflix.nebula.dependency.recommender.provider.RecommendationProviderContainer; import org.gradle.api.Action; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; public class ExtendRecommenderConfigurationAction implements Action<Configuration> { private Logger logger = Logging.getLogger(ExtendRecommenderConfigurationAction.class); private final Configuration bom; private final Project project; private final RecommendationProviderContainer container; public ExtendRecommenderConfigurationAction(Configuration bom, Project project, RecommendationProviderContainer container) { this.bom = bom; this.project = project; this.container = container; } @Override public void execute(Configuration configuration) { if (container.getExcludedConfigurations().contains(configuration.getName())) { return; } if (configuration.getState() == Configuration.State.UNRESOLVED) { Configuration toExtend = bom; if (!project.getRootProject().equals(project)) { toExtend = bom.copy(); toExtend.setVisible(false); project.getConfigurations().add(toExtend); } configuration.extendsFrom(toExtend); } else { logger.info("Configuration '" + configuration.getName() + "' has already been resolved and cannot be included for recommendation"); } } }
Support when actionhero is installed on read-only filesystem - Delay creation of log directory until after all config has been loaded
var fs = require('fs'); var cluster = require('cluster'); exports['default'] = { logger: function(api){ var logger = {transports: []}; // console logger if(cluster.isMaster){ logger.transports.push(function(api, winston){ return new (winston.transports.Console)({ colorize: true, level: 'info', timestamp: true, }); }); } // file logger logger.transports.push(function(api, winston){ if(api.config.general.paths.log.length === 1){ var logDirectory = api.config.general.paths.log[0]; try{ fs.mkdirSync(logDirectory); }catch(e){ if(e.code !== 'EEXIST'){ throw(new Error('Cannot create log directory @ ' + logDirectory)); } } } return new (winston.transports.File)({ filename: api.config.general.paths.log[0] + '/' + api.pids.title + '.log', level: 'info', timestamp: true }); }); // the maximum length of param to log (we will truncate) logger.maxLogStringLength = 100; // you can optionally set custom log levels // logger.levels = {good: 0, bad: 1}; // you can optionally set custom log colors // logger.colors = {good: 'blue', bad: 'red'}; return logger; } }; exports.test = { logger: function(api){ return { transports: null }; } };
var fs = require('fs'); var cluster = require('cluster'); exports['default'] = { logger: function(api){ var logger = {transports: []}; // console logger if(cluster.isMaster){ logger.transports.push(function(api, winston){ return new (winston.transports.Console)({ colorize: true, level: 'info', timestamp: true, }); }); } // file logger if(api.config.general.paths.log.length === 1){ var logDirectory = api.config.general.paths.log[0]; try{ fs.mkdirSync(logDirectory); }catch(e){ if(e.code !== 'EEXIST'){ throw(new Error('Cannot create log directory @ ' + logDirectory)); } } } logger.transports.push(function(api, winston){ return new (winston.transports.File)({ filename: api.config.general.paths.log[0] + '/' + api.pids.title + '.log', level: 'info', timestamp: true }); }); // the maximum length of param to log (we will truncate) logger.maxLogStringLength = 100; // you can optionally set custom log levels // logger.levels = {good: 0, bad: 1}; // you can optionally set custom log colors // logger.colors = {good: 'blue', bad: 'red'}; return logger; } }; exports.test = { logger: function(api){ return { transports: null }; } };
Allow config override for the sm
<?php namespace mxdiModuleTest; use mxdiModule\Factory\DiAbstractFactory; use mxdiModuleTest\TestObjects; use Zend\ServiceManager as SM; abstract class TestCase extends \PHPUnit_Framework_TestCase { /** @var SM\ServiceManager */ private $sm; /** @var array */ private $config = [ 'invokables' => [ TestObjects\DependencyA::class => TestObjects\DependencyA::class, TestObjects\DependencyB::class => TestObjects\DependencyB::class, TestObjects\DependencyC::class => TestObjects\DependencyC::class, TestObjects\DependencyD::class => TestObjects\DependencyD::class, 'dependency_e' => TestObjects\DependencyE::class, ], 'abstract_factories' => [ DiAbstractFactory::class, ], ]; /** * @return SM\ServiceManager */ protected function getServiceManager() { if (! $this->sm) { $this->sm = new SM\ServiceManager(new SM\Config($this->config)); } return $this->sm; } /** * @param array $config */ public function setServiceManagerConfig(array $config) { $this->config = $config; } }
<?php namespace mxdiModuleTest; use mxdiModule\Factory\DiAbstractFactory; use mxdiModuleTest\TestObjects; use Zend\ServiceManager as SM; abstract class TestCase extends \PHPUnit_Framework_TestCase { /** @var SM\ServiceManager */ private $sm; /** @var array */ private $config = [ 'invokables' => [ TestObjects\DependencyA::class => TestObjects\DependencyA::class, TestObjects\DependencyB::class => TestObjects\DependencyB::class, TestObjects\DependencyC::class => TestObjects\DependencyC::class, TestObjects\DependencyD::class => TestObjects\DependencyD::class, 'dependency_e' => TestObjects\DependencyE::class, ], 'abstract_factories' => [ DiAbstractFactory::class, ], ]; /** * @return SM\ServiceManager */ protected function getServiceManager() { if (! $this->sm) { $this->sm = new SM\ServiceManager(new SM\Config($this->config)); } return $this->sm; } }