text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add a warning for sorting keys
module.exports = { "extends": [ "./index.js", ], plugins: ["fp"], rules: { "fp/no-arguments": "error", "fp/no-class": "warn", "fp/no-delete": "error", "fp/no-events": "error", "fp/no-get-set": "error", "fp/no-let": "error", "fp/no-loops": "error", "fp/no-mutating-assign": "error", "fp/no-mutating-methods": "error", "fp/no-mutation": ["error", {commonjs:true}], "fp/no-nil": "error", "fp/no-proxy": "error", "fp/no-rest-parameters": "warn", "fp/no-this": "warn", "fp/no-throw": "warn", "fp/no-unused-expression": "warn", "fp/no-valueof-field": "error", "no-new-object": "warn", "no-magic-numbers": [2, { "ignore": [0,1] }], "no-unused-expressions": 2, // disallow usage of expressions in statement position "no-lonely-if": 2, // disallow if as the only statement in an else block "sort-keys": [1, "asc", {"caseSensitive": true, "natural": false}], }, }
module.exports = { "extends": [ "./index.js", ], plugins: ["fp"], rules: { "fp/no-arguments": "error", "fp/no-class": "warn", "fp/no-delete": "error", "fp/no-events": "error", "fp/no-get-set": "error", "fp/no-let": "error", "fp/no-loops": "error", "fp/no-mutating-assign": "error", "fp/no-mutating-methods": "error", "fp/no-mutation": ["error", {commonjs:true}], "fp/no-nil": "error", "fp/no-proxy": "error", "fp/no-rest-parameters": "warn", "fp/no-this": "warn", "fp/no-throw": "warn", "fp/no-unused-expression": "warn", "fp/no-valueof-field": "error", "no-new-object": "warn", "no-magic-numbers": [2, { "ignore": [0,1] }], "no-unused-expressions": 2, // disallow usage of expressions in statement position "no-lonely-if": 2, // disallow if as the only statement in an else block }, }
Use partyId to display PartyBadge for mps on front page
import React from 'react' import PropTypes from 'prop-types' import ListItem from '../list-item' import ListItemImage from '../list-item-image' import ListItemContent from '../list-item-content' import PartyBadge from '../partybadge' import './styles.css' const Mp = ({ id, imagePath, lthing, name, partyId, }) => { let url = `/thingmenn/${id}/thing/allt` if (lthing) { url = `/thingmenn/${id}/thing/${lthing}` } return ( <ListItem url={url}> <ListItemImage path={imagePath} cover={true}> <PartyBadge party={partyId} className="Mp-badge"/> </ListItemImage> <ListItemContent title={name} /> </ListItem> ) } Mp.propTypes = { id: PropTypes.any, name: PropTypes.string, profilePicture: PropTypes.string, partyId: PropTypes.number, } export default Mp
import React from 'react' import PropTypes from 'prop-types' import ListItem from '../list-item' import ListItemImage from '../list-item-image' import ListItemContent from '../list-item-content' import PartyBadge from '../partybadge' import './styles.css' const Mp = ({ id, imagePath, lthing, name, party, partySlug, }) => { let url = `/thingmenn/${id}/thing/allt` if (lthing) { url = `/thingmenn/${id}/thing/${lthing}` } return ( <ListItem url={url}> <ListItemImage path={imagePath} cover={true}> <PartyBadge party={partySlug} className="Mp-badge"/> </ListItemImage> <ListItemContent title={name} /> </ListItem> ) } Mp.propTypes = { id: PropTypes.any, name: PropTypes.string, profilePicture: PropTypes.string, party: PropTypes.string, } export default Mp
Change debug action to production
import os import logging from rtrss.basedaemon import BaseDaemon _logger = logging.getLogger(__name__) class WorkerDaemon(BaseDaemon): def run(self): _logger.info('Daemon started ith pid %d', os.getpid()) from rtrss.worker import worker_action worker_action('run') _logger.info('Daemon is done and exiting') def start(self): _logger.info('Starting daemon') super(WorkerDaemon, self).start() def stop(self): _logger.info('Stopping daemon') super(WorkerDaemon, self).stop() def restart(self): _logger.info('Restarting daemon') super(WorkerDaemon, self).restart() def make_daemon(config): '''Returns WorkerDaemon instance''' pidfile = os.path.join(config.DATA_DIR, 'daemon.pid') logdir = os.environ.get('OPENSHIFT_LOG_DIR') or config.DATA_DIR logfile = os.path.join(logdir, 'daemon.log') return WorkerDaemon(pidfile, stdout=logfile, stderr=logfile)
import sys import os import logging import atexit from rtrss.basedaemon import BaseDaemon _logger = logging.getLogger(__name__) class WorkerDaemon(BaseDaemon): def run(self): _logger.info('Daemon started ith pid %d', os.getpid()) from rtrss.worker import app_init, worker_action worker_action('import_categories') # TODO run() _logger.info('Daemon is done and exiting') def start(self): _logger.info('Starting daemon') super(WorkerDaemon, self).start() def stop(self): _logger.info('Stopping daemon') super(WorkerDaemon, self).stop() def restart(self): _logger.info('Restarting daemon') super(WorkerDaemon, self).restart() def make_daemon(config): '''Returns WorkerDaemon instance''' pidfile = os.path.join(config.DATA_DIR, 'daemon.pid') logdir = os.environ.get('OPENSHIFT_LOG_DIR') or config.DATA_DIR logfile = os.path.join(logdir, 'daemon.log') return WorkerDaemon(pidfile, stdout=logfile, stderr=logfile)
Make Python example output identical to C++ and Java by removing redundant spaces.
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #:", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #:", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #:", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #: ", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #: ", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #: ", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
Remove file extension from href's
(function( $ ) { $.fn.activeNavigation = function(selector) { var pathname = window.location.pathname var extension_position; var href; var hrefs = [] $(selector).find("a").each(function(){ // Remove href file extension extension_position = $(this).attr("href").lastIndexOf('.'); href = (extension_position >= 0) ? $(this).attr("href").substr(0, extension_position) : $(this).attr("href"); if (pathname.indexOf(href) > -1) { hrefs.push($(this)); } }) if (hrefs.length) { hrefs.sort(function(a,b){ return b.attr("href").length - a.attr("href").length }) hrefs[0].closest('li').addClass("active") } }; })(jQuery);
(function( $ ) { $.fn.activeNavigation = function(selector) { var pathname = window.location.pathname var hrefs = [] $(selector).find("a").each(function(){ if (pathname.indexOf($(this).attr("href")) > -1) hrefs.push($(this)) }) if (hrefs.length) { hrefs.sort(function(a,b){ return b.attr("href").length - a.attr("href").length }) hrefs[0].closest('li').addClass("active") } }; })(jQuery);
Add python 3 compatibility in pip install
from os.path import dirname, abspath, join, exists from setuptools import setup long_description = None if exists("README.md"): long_description = open("README.md").read() install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))] tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))] setup( name="mpegdash", packages=["mpegdash"], description="MPEG-DASH MPD(Media Presentation Description) Parser", long_description=long_description, author="supercast", author_email="gamzabaw@gmail.com", version="0.1.5", license="MIT", zip_safe=False, include_package_data=True, install_requires=install_reqs, url="https://github.com/caststack/python-mpegdash", tests_require=tests_reqs, test_suite="tests.my_module_suite", classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], )
from os.path import dirname, abspath, join, exists from setuptools import setup long_description = None if exists("README.md"): long_description = open("README.md").read() install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))] tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))] setup( name="mpegdash", packages=["mpegdash"], description="MPEG-DASH MPD(Media Presentation Description) Parser", long_description=long_description, author="supercast", author_email="gamzabaw@gmail.com", version="0.1.0", license="MIT", zip_safe=False, include_package_data=True, install_requires=install_reqs, url="https://github.com/caststack/python-mpegdash", tests_require=tests_reqs, test_suite="tests.my_module_suite", )
Fix minor bug with directory ignoring
package ee.shy.core; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.nio.file.*; import java.util.ArrayList; import java.util.List; public final class ShyIgnore { private static final List<String> globs = new ArrayList<>(); static { Path path = Paths.get(".shyignore"); if (Files.exists(path)) { try { globs.addAll(IOUtils.readLines(Files.newInputStream(path))); } catch (IOException e) { throw new RuntimeException(e); } } } public static boolean isIgnored(Path path) { for (String glob : globs) { PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:**" + glob); if (pathMatcher.matches(path)) return true; } return false; } }
package ee.shy.core; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.nio.file.*; import java.util.ArrayList; import java.util.List; public final class ShyIgnore { private static final List<String> globs = new ArrayList<>(); static { Path path = Paths.get(".shyignore"); if (Files.exists(path)) { try { globs.addAll(IOUtils.readLines(Files.newInputStream(path))); } catch (IOException e) { throw new RuntimeException(e); } } } public static boolean isIgnored(Path path) { for (String glob : globs) { PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*" + glob); if (pathMatcher.matches(path)) return true; } return false; } }
Fix missing const keyword in test code
'use strict'; const VIRTUAL_DEP_IDS = ['\0helper']; module.exports = { name: 'virtual-dep-injector', resolveId: (importee, importer) => { if (VIRTUAL_DEP_IDS.indexOf(importee) !== -1) return importee; }, load: (id) => { if(VIRTUAL_DEP_IDS.indexOf(id) !== -1) return 'export default "hello world";'; }, transform: (code, id) => { if (VIRTUAL_DEP_IDS.indexOf(id) === -1) { let addedImports = ''; let i = 0; for (let id of VIRTUAL_DEP_IDS) { addedImports += `import * as dependency${i++} from '${id}';\n`; } code = addedImports + code; } return {code, map: null}; } };
'use strict'; VIRTUAL_DEP_IDS = ['\0helper']; module.exports = { name: 'virtual-dep-injector', resolveId: (importee, importer) => { if (VIRTUAL_DEP_IDS.indexOf(importee) !== -1) return importee; }, load: (id) => { if(VIRTUAL_DEP_IDS.indexOf(id) !== -1) return 'export default "hello world";'; }, transform: (code, id) => { if (VIRTUAL_DEP_IDS.indexOf(id) === -1) { let addedImports = ''; let i = 0; for (let id of VIRTUAL_DEP_IDS) { addedImports += `import * as dependency${i++} from '${id}';\n`; } code = addedImports + code; } return {code, map: null}; } };
Use string as a default value for PIPENV_MAX_DEPTH
import os # Prevent invalid shebangs with Homebrew-installed Python: # https://bugs.python.org/issue22490 os.environ.pop('__PYVENV_LAUNCHER__', None) # Shell compatibility mode, for mis-configured shells. PIPENV_SHELL_COMPAT = os.environ.get('PIPENV_SHELL_COMPAT') # Create the virtualenv in the project, isntead of with pew. PIPENV_VENV_IN_PROJECT = os.environ.get('PIPENV_VENV_IN_PROJECT') # No color mode, for unfun people. PIPENV_COLORBLIND = os.environ.get('PIPENV_COLORBLIND') # Disable spinner for better test and deploy logs (for the unworthy). PIPENV_NOSPIN = os.environ.get('PIPENV_NOSPIN') # User-configuraable max-depth for Pipfile searching. # Note: +1 because of a temporary bug in Pipenv. PIPENV_MAX_DEPTH = int(os.environ.get('PIPENV_MAX_DEPTH', '3')) + 1 # Use shell compatibility mode when using venv in project mode. if PIPENV_VENV_IN_PROJECT: PIPENV_SHELL_COMPAT = True
import os # Prevent invalid shebangs with Homebrew-installed Python: # https://bugs.python.org/issue22490 os.environ.pop('__PYVENV_LAUNCHER__', None) # Shell compatibility mode, for mis-configured shells. PIPENV_SHELL_COMPAT = os.environ.get('PIPENV_SHELL_COMPAT') # Create the virtualenv in the project, isntead of with pew. PIPENV_VENV_IN_PROJECT = os.environ.get('PIPENV_VENV_IN_PROJECT') # No color mode, for unfun people. PIPENV_COLORBLIND = os.environ.get('PIPENV_COLORBLIND') # Disable spinner for better test and deploy logs (for the unworthy). PIPENV_NOSPIN = os.environ.get('PIPENV_NOSPIN') # User-configuraable max-depth for Pipfile searching. # Note: +1 because of a temporary bug in Pipenv. PIPENV_MAX_DEPTH = int(os.environ.get('PIPENV_MAX_DEPTH', 3)) + 1 # Use shell compatibility mode when using venv in project mode. if PIPENV_VENV_IN_PROJECT: PIPENV_SHELL_COMPAT = True
Add eager-loaded links for Section
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: # Maintained By: from ggrc import db from .associationproxy import association_proxy from .mixins import BusinessObject, Hierarchical class Section(Hierarchical, BusinessObject, db.Model): __tablename__ = 'sections' directive_id = db.Column(db.Integer, db.ForeignKey('directives.id')) na = db.Column(db.Boolean, default=False, nullable=False) notes = db.Column(db.Text) control_sections = db.relationship('ControlSection', backref='section') controls = association_proxy('control_sections', 'control', 'ControlSection') _publish_attrs = [ 'directive', 'na', 'notes', 'control_sections', 'controls', ] _update_attrs = [ 'directive', 'na', 'notes', 'controls', ] @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Section, cls).eager_query() return query.options( orm.joinedload('directive'), orm.subqueryload_all('control_sections.control'))
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: # Maintained By: from ggrc import db from .associationproxy import association_proxy from .mixins import BusinessObject, Hierarchical class Section(Hierarchical, BusinessObject, db.Model): __tablename__ = 'sections' directive_id = db.Column(db.Integer, db.ForeignKey('directives.id')) na = db.Column(db.Boolean, default=False, nullable=False) notes = db.Column(db.Text) control_sections = db.relationship('ControlSection', backref='section') controls = association_proxy('control_sections', 'control', 'ControlSection') _publish_attrs = [ 'directive', 'na', 'notes', 'control_sections', 'controls', ] _update_attrs = [ 'directive', 'na', 'notes', 'controls', ]
Use old array notation for PHP < 5.4
<?php namespace Diarmuidie\NiceID\Tests\Utilities; use Diarmuidie\NiceID\Utilities; /** * Class NiceIDTest * @package Diarmuidie\NiceID\Tests */ class FisherYatesTest extends \PHPUnit_Framework_TestCase { /** * @var array Test unshuffled array */ private $unShuffledArray = array('a','b','c','d','e','f'); /** * @var array Test shuffled array */ private $shuffledtestArray = array('a','c','e','f','b','d'); /** * @var string Test shuffle secret */ private $testSecret = 'My Test Secret'; /** * Test shuffling */ public function testShuffleArray() { $shuffled = Utilities\FisherYates::shuffle($this->unShuffledArray, $this->testSecret); $this->assertEquals($shuffled, $this->shuffledtestArray); } /** * Test unshuffling */ public function testUnShuffleArray() { $unshuffled = Utilities\FisherYates::unshuffle($this->shuffledtestArray, $this->testSecret); $this->assertEquals($unshuffled, $this->unShuffledArray); } }
<?php namespace Diarmuidie\NiceID\Tests\Utilities; use Diarmuidie\NiceID\Utilities; /** * Class NiceIDTest * @package Diarmuidie\NiceID\Tests */ class FisherYatesTest extends \PHPUnit_Framework_TestCase { /** * @var array Test unshuffled array */ private $unShuffledArray = ['a','b','c','d','e','f']; /** * @var array Test shuffled array */ private $shuffledtestArray = ['a','c','e','f','b','d']; /** * @var string Test shuffle secret */ private $testSecret = 'My Test Secret'; /** * Test shuffling */ public function testShuffleArray() { $shuffled = Utilities\FisherYates::shuffle($this->unShuffledArray, $this->testSecret); $this->assertEquals($shuffled, $this->shuffledtestArray); } /** * Test unshuffling */ public function testUnShuffleArray() { $unshuffled = Utilities\FisherYates::unshuffle($this->shuffledtestArray, $this->testSecret); $this->assertEquals($unshuffled, $this->unShuffledArray); } }
Fix post id in _post view
<div class="post" id="post-<?php echo $post['id'];?>"> <h2><?php echo h($post['title'])?></h2> <p class="date">Modified at: <?php echo strftime('%c', strtotime($post['modified_at']))?></p> <div class="content"> <?php echo h($post['body'])?> </div> <p> <a href="<?php echo url_for('posts', $post['id']); ?>">show</a> | <a href="<?php echo url_for('posts', $post['id'], 'edit'); ?>">edit</a> | <a href="<?php echo url_for('posts', $post['id']);?>" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'DELETE'); f.appendChild(m); f.submit(); };return false;">delete</a> </p> </div>
<div class="post" id="post-<?php echo post['id'];?>"> <h2><?php echo h($post['title'])?></h2> <p class="date">Modified at: <?php echo strftime('%c', strtotime($post['modified_at']))?></p> <div class="content"> <?php echo h($post['body'])?> </div> <p> <a href="<?php echo url_for('posts', $post['id']); ?>">show</a> | <a href="<?php echo url_for('posts', $post['id'], 'edit'); ?>">edit</a> | <a href="<?php echo url_for('posts', $post['id']);?>" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'DELETE'); f.appendChild(m); f.submit(); };return false;">delete</a> </p> </div>
Add the filename to ejs for `include` directive EJS has a newer `include` directive to replace the old `partial` function in express. This just includes a file relative to the current. The engine has to know the path of the template in order for this to happen.
/** * class EjsEngine * * Engine for the EJS compiler. You will need `ejs` Node module installed * in order to use [[Mincer]] with `*.ejs` files: * * npm install ejs * * * ##### SUBCLASS OF * * [[Template]] **/ 'use strict'; // 3rd-party var ejs; // initialized later // internal var Template = require('../template'); //////////////////////////////////////////////////////////////////////////////// // Class constructor var EjsEngine = module.exports = function EjsEngine() { Template.apply(this, arguments); }; require('util').inherits(EjsEngine, Template); // Check whenever ejs module is loaded EjsEngine.prototype.isInitialized = function () { return !!ejs; }; // Autoload ejs library EjsEngine.prototype.initializeEngine = function () { ejs = this.require('ejs'); }; // Render data EjsEngine.prototype.evaluate = function (context, locals, callback) { try { callback(null, ejs.render(this.data, {scope: context, locals: locals, filename: context.pathname})); } catch (err) { callback(err); } };
/** * class EjsEngine * * Engine for the EJS compiler. You will need `ejs` Node module installed * in order to use [[Mincer]] with `*.ejs` files: * * npm install ejs * * * ##### SUBCLASS OF * * [[Template]] **/ 'use strict'; // 3rd-party var ejs; // initialized later // internal var Template = require('../template'); //////////////////////////////////////////////////////////////////////////////// // Class constructor var EjsEngine = module.exports = function EjsEngine() { Template.apply(this, arguments); }; require('util').inherits(EjsEngine, Template); // Check whenever ejs module is loaded EjsEngine.prototype.isInitialized = function () { return !!ejs; }; // Autoload ejs library EjsEngine.prototype.initializeEngine = function () { ejs = this.require('ejs'); }; // Render data EjsEngine.prototype.evaluate = function (context, locals, callback) { try { callback(null, ejs.render(this.data, {scope: context, locals: locals})); } catch (err) { callback(err); } };
Use locmem cache for tests.
# -*- coding: utf-8 -*- INSTALLED_APPS = ['post_office'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } }
# -*- coding: utf-8 -*- INSTALLED_APPS = ['post_office'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 36000, 'KEY_PREFIX': 'stamps:', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } }
Enable passing in handler_url via capture url querystring variable Allows use with providers that require you pass in notify url with each request
var follow = require('follow'); var request = require('request'); module.exports = function(db_url, handler_url) { function isSuccessCode(code) { return code >= 200 && code < 300; } function forwardHook(doc) { var url = doc.req.query.handler_url || handler_url; if (!url) { console.log("No handler_url defined for webhook id: " + doc._id); return; } request({ url: url, method: doc.req.method, body: doc.req.body, headers: { 'Content-type': doc.req.headers["Content-Type"] } }, function (error, response, body) { if (error) { console.log("Error forwarding hook: " + error); } else if (!isSuccessCode(response.statusCode)) { console.log("Error forwarding hook: server returned " + response.statusCode); } else { console.log("Forwarded webhook id: " + doc._id); } }); } follow({db: db_url, include_docs:true, since: 'now'}, function(error, change) { if (error) { console.log("Error following changes: " + error); } else { var doc = change.doc; if (doc.type === 'webhook') { forwardHook(doc); } } }); console.log("Hookforward is listening for changes..."); }
var follow = require('follow'); var request = require('request'); module.exports = function(db_url, handler_url) { function isSuccessCode(code) { return code >= 200 && code < 300; } function forwardHook(doc) { request({ url: handler_url, method: doc.req.method, body: doc.req.body, headers: { 'Content-type': doc.req.headers["Content-Type"] } }, function (error, response, body) { if (error) { console.log("Error forwarding hook: " + error); } else if (!isSuccessCode(response.statusCode)) { console.log("Error forwarding hook: server returned " + response.statusCode); } else { console.log("Forwarded webhook id: " + doc._id); } }); } follow({db: db_url, include_docs:true, since: 'now'}, function(error, change) { if (error) { console.log("Error following changes: " + error); } else { var doc = change.doc; if (doc.type === 'webhook') { forwardHook(doc); } } }); console.log("Hookforward is listening for changes..."); }
Use correct check for serving elements route
// eslint-disable-next-line new-cap const router = require('express').Router(); const config = require('../config/config'); const indexController = require('../app/controllers/index'); const elementsController = require('../app/controllers/elements'); const cookiesController = require('../app/controllers/cookies'); const assuranceController = require('../app/controllers/clinical-assurance'); const healthcheckController = require('../app/controllers/healthcheck'); const fungalNailInfectionController = require('../app/controllers/fungal-nail-infection'); const stomachAcheController = require('../app/controllers/stomach-ache'); const rashesInChildrenController = require('../app/controllers/rashes-in-babies-and-children'); router.get('/', indexController.index); router.get('/healthcheck', healthcheckController.index); router.get('/help/cookies', cookiesController.index); router.get('/help/clinical-assurance', assuranceController.index); router.all('/conditions/fungal-nail-infection', fungalNailInfectionController.index); router.all('/symptoms/rashes-in-babies-and-children', rashesInChildrenController.index); router.all('/symptoms/stomach-ache', stomachAcheController.index); if (config.env === 'development') { router.get('/elements', elementsController.index); } module.exports = router;
// eslint-disable-next-line new-cap const router = require('express').Router(); const config = require('../config/config'); const indexController = require('../app/controllers/index'); const elementsController = require('../app/controllers/elements'); const cookiesController = require('../app/controllers/cookies'); const assuranceController = require('../app/controllers/clinical-assurance'); const healthcheckController = require('../app/controllers/healthcheck'); const fungalNailInfectionController = require('../app/controllers/fungal-nail-infection'); const stomachAcheController = require('../app/controllers/stomach-ache'); const rashesInChildrenController = require('../app/controllers/rashes-in-babies-and-children'); router.get('/', indexController.index); router.get('/healthcheck', healthcheckController.index); router.get('/help/cookies', cookiesController.index); router.get('/help/clinical-assurance', assuranceController.index); router.all('/conditions/fungal-nail-infection', fungalNailInfectionController.index); router.all('/symptoms/rashes-in-babies-and-children', rashesInChildrenController.index); router.all('/symptoms/stomach-ache', stomachAcheController.index); if (config !== 'production') { router.get('/elements', elementsController.index); } module.exports = router;
Add user check to add ranking
import StoriesItemType from '../types/StoriesItemType' import RankingInputItemType from '../types/RankingInputItemType' import {Story, User, Ranking} from '../models' const addRanking = { name: 'addRanking', type: StoriesItemType, args: { story: {type: RankingInputItemType} }, async resolve (value, {story}) { let userId = value.request.user.id let storyId = story.id let user = await User.findById(userId) if (user){ let ranking = await Ranking.findOne({where: {userId, storyId}}) if (! ranking){ Ranking.create({userId, storyId}) } let result = await Story.findById(storyId, { include: [{ model: User, as: 'user' },{ model: Ranking, as: 'rankings' }] }) return result }else{ throw 'Invalid user!' } } } export default addRanking
import StoriesItemType from '../types/StoriesItemType' import RankingInputItemType from '../types/RankingInputItemType' import {Story, User, Ranking} from '../models' const addRanking = { name: 'addRanking', type: StoriesItemType, args: { story: {type: RankingInputItemType} }, async resolve (value, {story}) { let userId = value.request.user.id let storyId = story.id let ranking = await Ranking.findOne({where: {userId, storyId}}) if (! ranking){ Ranking.create({userId, storyId}) } let result = await Story.findById(storyId, { include: [{ model: User, as: 'user' },{ model: Ranking, as: 'rankings' }] }) return result } } export default addRanking
Enable back git output redirection in _get_version
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--dirty") with open(os.devnull, "w") as devnull: output = subprocess.check_output(git_args, stderr=devnull) version = output.decode("utf-8").strip() return version __version__ = _get_version()
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--dirty") with open(os.devnull, "w") as devnull: output = subprocess.check_output(git_args) version = output.decode("utf-8").strip() return version __version__ = _get_version()
Create approval file path that works on Linux and Windows.
import inspect import os class Namer(object): ClassName = '' MethodName = '' Directory = '' def setForStack(self, caller): stackFrame = caller[self.frame] self.MethodName = stackFrame[3] self.ClassName = stackFrame[0].f_globals["__name__"] self.Directory = os.path.dirname(stackFrame[1]) def __init__(self, frame=1): self.frame = frame self.setForStack(inspect.stack(1)) def getClassName(self): return self.ClassName def getMethodName(self): return self.MethodName def getDirectory(self): return self.Directory def get_basename(self): return os.path.join(self.Directory, self.ClassName + "." + self.MethodName)
import inspect import os class Namer(object): ClassName = '' MethodName = '' Directory = '' def setForStack(self, caller): stackFrame = caller[self.frame] self.MethodName = stackFrame[3] self.ClassName = stackFrame[0].f_globals["__name__"] self.Directory = os.path.dirname(stackFrame[1]) def __init__(self, frame=1): self.frame = frame self.setForStack(inspect.stack(1)) def getClassName(self): return self.ClassName def getMethodName(self): return self.MethodName def getDirectory(self): return self.Directory def get_basename(self): return self.Directory + "\\" + self.ClassName + "." + self.MethodName
Move target MC version for mods to CCL.
package codechicken.lib; import codechicken.lib.render.CCRenderEventHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.relauncher.Side; /** * Created by covers1624 on 12/10/2016. */ @Mod(modid = CodeChickenLib.MOD_ID, name = CodeChickenLib.MOD_NAME, acceptedMinecraftVersions = CodeChickenLib.mcVersion) public class CodeChickenLib { public static final String MOD_ID = "CodeChickenLib"; public static final String MOD_NAME = "CodeChicken Lib"; public static final String version = "${mod_version}"; public static final String mcVersion = "[1.10.2]"; @EventHandler public void preInit(FMLPreInitializationEvent event) { if (event.getSide().equals(Side.CLIENT)){ CCRenderEventHandler.init(); } } }
package codechicken.lib; import codechicken.lib.render.CCRenderEventHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.relauncher.Side; /** * Created by covers1624 on 12/10/2016. */ @Mod(modid = CodeChickenLib.MOD_ID, name = CodeChickenLib.MOD_NAME) public class CodeChickenLib { public static final String MOD_ID = "CodeChickenLib"; public static final String MOD_NAME = "CodeChicken Lib"; public static final String version = "${mod_version}"; @EventHandler public void preInit(FMLPreInitializationEvent event) { if (event.getSide().equals(Side.CLIENT)){ CCRenderEventHandler.init(); } } }
Use the Unexpected v10 addAssertion syntax.
var BufferedStream = require('bufferedstream'); var createMockCouchAdapter = require('./createMockCouchAdapter'); var http = require('http'); var mockCouch = require('mock-couch-alexjeffburke'); var url = require('url'); function generateCouchdbResponse(databases, req, res) { var responseObject = null; var couchdbHandler = createMockCouchAdapter(); var couchdb = new mockCouch.MockCouch(couchdbHandler, {}); Object.keys(databases).forEach(function (databaseName) { couchdb.addDB(databaseName, databases[databaseName].docs || []); }); // run the handler couchdbHandler(req, res, function () {}); } module.exports = { name: 'unexpected-couchdb', installInto: function (expect) { expect.installPlugin(require('unexpected-mitm')); expect.addAssertion('<any> with couchdb mocked out <object> <assertion>', function (expect, subject, couchdb) { expect.errorMode = 'nested'; var nextAssertionArgs = this.args.slice(1); var args = [subject, 'with http mocked out', { response: generateCouchdbResponse.bind(null, couchdb) }].concat(nextAssertionArgs); return expect.apply(expect, args); }); } };
var BufferedStream = require('bufferedstream'); var createMockCouchAdapter = require('./createMockCouchAdapter'); var http = require('http'); var mockCouch = require('mock-couch-alexjeffburke'); var url = require('url'); function generateCouchdbResponse(databases, req, res) { var responseObject = null; var couchdbHandler = createMockCouchAdapter(); var couchdb = new mockCouch.MockCouch(couchdbHandler, {}); Object.keys(databases).forEach(function (databaseName) { couchdb.addDB(databaseName, databases[databaseName].docs || []); }); // run the handler couchdbHandler(req, res, function () {}); } module.exports = { name: 'unexpected-couchdb', installInto: function (expect) { expect.installPlugin(require('unexpected-mitm')); expect.addAssertion('with couchdb mocked out', function (expect, subject, couchdb) { this.errorMode = 'nested'; var nextAssertionArgs = this.args.slice(1); var args = [subject, 'with http mocked out', { response: generateCouchdbResponse.bind(null, couchdb) }].concat(nextAssertionArgs); return expect.apply(expect, args); }); } };
Add call to construct manager in test mod
package info.u_team.u_team_test; import org.apache.logging.log4j.*; import info.u_team.u_team_core.construct.ConstructManager; import info.u_team.u_team_core.integration.IntegrationManager; import info.u_team.u_team_core.util.verify.JarSignVerifier; import net.minecraftforge.fml.common.Mod; @Mod(TestMod.MODID) public class TestMod { public static final String MODID = "uteamtest"; public static final Logger LOGGER = LogManager.getLogger("UTeamTest"); public TestMod() { JarSignVerifier.checkSigned(MODID); LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------"); // TestCommonBusRegister.register(); // DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> TestClientBusRegister::register); ConstructManager.constructConstructs(MODID); IntegrationManager.constructIntegrations(MODID); } }
package info.u_team.u_team_test; import org.apache.logging.log4j.*; import info.u_team.u_team_core.integration.IntegrationManager; import info.u_team.u_team_core.util.verify.JarSignVerifier; import info.u_team.u_team_test.init.*; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; @Mod(TestMod.MODID) public class TestMod { public static final String MODID = "uteamtest"; public static final Logger LOGGER = LogManager.getLogger("UTeamTest"); public TestMod() { JarSignVerifier.checkSigned(MODID); LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------"); TestCommonBusRegister.register(); DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> TestClientBusRegister::register); IntegrationManager.constructIntegrations(MODID); } }
Use primaryKeyAttribute to resolve globalIdField
import * as typeMapper from './typeMapper'; import { GraphQLNonNull, GraphQLEnumType } from 'graphql'; import { globalIdField } from 'graphql-relay'; module.exports = function (Model, options) { options = options || {}; var result = Object.keys(Model.rawAttributes).reduce(function (memo, key) { if (options.exclude && ~options.exclude.indexOf(key)) return memo; if (options.only && !~options.only.indexOf(key)) return memo; var attribute = Model.rawAttributes[key] , type = attribute.type; memo[key] = { type: typeMapper.toGraphQL(type, Model.sequelize.constructor) }; if (memo[key].type instanceof GraphQLEnumType ) { memo[key].type.name = `${Model.name}${key}EnumType`; } if (attribute.allowNull === false || attribute.primaryKey === true) { memo[key].type = new GraphQLNonNull(memo[key].type); } return memo; }, {}); if (options.globalId) { result.id = globalIdField(Model.name, instance => instance[Model.primaryKeyAttribute]); } return result; };
import * as typeMapper from './typeMapper'; import { GraphQLNonNull, GraphQLEnumType } from 'graphql'; import { globalIdField } from 'graphql-relay'; module.exports = function (Model, options) { options = options || {}; var result = Object.keys(Model.rawAttributes).reduce(function (memo, key) { if (options.exclude && ~options.exclude.indexOf(key)) return memo; if (options.only && !~options.only.indexOf(key)) return memo; var attribute = Model.rawAttributes[key] , type = attribute.type; memo[key] = { type: typeMapper.toGraphQL(type, Model.sequelize.constructor) }; if (memo[key].type instanceof GraphQLEnumType ) { memo[key].type.name = `${Model.name}${key}EnumType`; } if (attribute.allowNull === false || attribute.primaryKey === true) { memo[key].type = new GraphQLNonNull(memo[key].type); } return memo; }, {}); if (options.globalId) { result.id = globalIdField(Model.name); } return result; };
Revert "Update mbutil to 0.2.0" This reverts commit c3834af13fb14d0961e7e8ce29c3bbbe91ebb5ce.
from setuptools import setup, find_packages import sys import mbtoolbox with open('mbtoolbox/__init__.py') as f: for line in f: if line.find("__version__") >= 0: version = line.split("=")[1].strip() version = version.strip('"') version = version.strip("'") continue open_kwds = {} if sys.version_info > (3,): open_kwds['encoding'] = 'utf-8' with open('README.md', **open_kwds) as f: readme = f.read() setup( name='mbtoolbox', version=mbtoolbox.__version__, description="MBTiles toolbox tool for optimizing and verifying MBTiles files", long_description=readme, classifiers=[], keywords='', author='Lukas Martinelli', author_email='me@lukasmartinelli.ch', url='https://github.com/lukasmartinelli/mbtoolbox', license='BSD', packages=find_packages(exclude=[]), include_package_data=True, install_requires=['docopt==0.6.2', 'mercantile==0.8.3', 'humanize==0.5.1', 'mbutil==0.2.0beta'], dependency_links=['https://github.com/mapbox/mbutil/tarball/master#egg=mbutil-0.2.0beta'], scripts = ['bin/mbverify', 'bin/mboptimize'] )
from setuptools import setup, find_packages import sys import mbtoolbox with open('mbtoolbox/__init__.py') as f: for line in f: if line.find("__version__") >= 0: version = line.split("=")[1].strip() version = version.strip('"') version = version.strip("'") continue open_kwds = {} if sys.version_info > (3,): open_kwds['encoding'] = 'utf-8' with open('README.md', **open_kwds) as f: readme = f.read() setup( name='mbtoolbox', version=mbtoolbox.__version__, description="MBTiles toolbox tool for optimizing and verifying MBTiles files", long_description=readme, classifiers=[], keywords='', author='Lukas Martinelli', author_email='me@lukasmartinelli.ch', url='https://github.com/lukasmartinelli/mbtoolbox', license='BSD', packages=find_packages(exclude=[]), include_package_data=True, install_requires=['docopt==0.6.2', 'mercantile==0.8.3', 'humanize==0.5.1', 'mbutil==0.2.0'], dependency_links=['https://github.com/mapbox/mbutil/tarball/master#egg=mbutil-0.2.0beta'], scripts = ['bin/mbverify', 'bin/mboptimize'] )
Add E226 to default ignores for pep8 E226 - missing whitespace around arithmetic operator 2*3 + 5*6 must pass
"""Check files with flake8.""" import flake8.main import re DEFAULTS = { 'ignore': 'E226', 'complexity': '10', } PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''') def check(file_staged_for_commit, options): if file_staged_for_commit.path.endswith('.py') or \ PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents): status = flake8.main.check_code( file_staged_for_commit.contents, ignore=( c for c in options.flake8_ignore.split(',') if c ), complexity=int(options.flake8_complexity), ) return status == 0 else: return True
"""Check files with flake8.""" import flake8.main import re DEFAULTS = { 'ignore': '', 'complexity': '10', } PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''') def check(file_staged_for_commit, options): if file_staged_for_commit.path.endswith('.py') or \ PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents): status = flake8.main.check_code( file_staged_for_commit.contents, ignore=( c for c in options.flake8_ignore.split(',') if c ), complexity=int(options.flake8_complexity), ) return status == 0 else: return True
Fix example-17, was using subscription where a subscription id was expected.
<?php /* * Example 17 - How to cancel a subscription. */ try { /* * Initialize the Mollie API library with your API key or OAuth access token. */ include "initialize.php"; /** * Retrieve the last created customer for this example. * If no customers are created yet, run example 11. */ $customer = $mollie->customers->all(0, 1)->data[0]; /* * Generate a unique subscription id for this example. It is important to include this unique attribute * in the webhookUrl (below) so new payments can be associated with this subscription. */ $subscriptionId = isset($_GET['subscription_id']) ? $_GET['subscription_id'] : ''; /* * Customer Subscription deletion parameters. * * See: https://www.mollie.com/nl/docs/reference/subscriptions/delete */ $cancelledSubscription = $mollie->customers_subscriptions->with($customer)->cancel($subscriptionId); /* * The subscription status should now be cancelled */ echo "<p>The subscription status is now: '" . htmlspecialchars($cancelledSubscription->status) . "'.</p>\n"; } catch (Mollie_API_Exception $e) { echo "API call failed: " . htmlspecialchars($e->getMessage()); }
<?php /* * Example 17 - How to cancel a subscription. */ try { /* * Initialize the Mollie API library with your API key or OAuth access token. */ include "initialize.php"; /** * Retrieve the last created customer for this example. * If no customers are created yet, run example 11. */ $customer = $mollie->customers->all(0, 1)->data[0]; /* * Generate a unique subscription id for this example. It is important to include this unique attribute * in the webhookUrl (below) so new payments can be associated with this subscription. */ $subscriptionId = isset($_GET['subscription_id']) ? $_GET['subscription_id'] : ''; // retrieve subscription $subscription = $mollie->customers_subscriptions->with($customer)->get($subscriptionId); /* * Customer Subscription deletion parameters. * * See: https://www.mollie.com/nl/docs/reference/subscriptions/delete */ $cancelledSubscription = $mollie->customers_subscriptions->with($customer)->cancel($subscription); /* * The subscription status should now be cancelled */ echo "<p>The subscription status is now: '" . htmlspecialchars($cancelledSubscription->status) . "'.</p>\n"; } catch (Mollie_API_Exception $e) { echo "API call failed: " . htmlspecialchars($e->getMessage()); }
Remove fermion.config.json event logic applying available components to store
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import Root from './containers/Root'; import { configureStore, history } from './store/configureStore'; import './app.global.css'; import { ipcRenderer } from 'electron'; const store = configureStore({}); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept('./containers/Root', () => { const NextRoot = require('./containers/Root'); // eslint-disable-line global-require render( <AppContainer> <NextRoot store={store} history={history} /> </AppContainer>, document.getElementById('root') ); }); }
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import Root from './containers/Root'; import { configureStore, history } from './store/configureStore'; import './app.global.css'; import { ipcRenderer } from 'electron'; ipcRenderer.on('ConfigApp', (event, data) => { data = JSON.parse(data); const initialState = { availableComponents: data.availableComponents, }; const store = configureStore(initialState); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept('./containers/Root', () => { const NextRoot = require('./containers/Root'); // eslint-disable-line global-require render( <AppContainer> <NextRoot store={store} history={history} /> </AppContainer>, document.getElementById('root') ); }); } });
Trim error were thrown when linked ember-cli had deatched HEAD. If the contents of the ./git/HEAD file does not return a ref path, it's a SHA value so that is what will be used.
'use strict'; var fs = require('fs'); var path = require('path'); module.exports = function () { var output = [require('../../package.json').version]; var gitPath = path.join(__dirname, '..','..','.git'); var headFilePath = path.join(gitPath, 'HEAD'); try { if (fs.existsSync(headFilePath)) { var branchSHA; var headFile = fs.readFileSync(headFilePath, {encoding: 'utf8'}); var branchName = headFile.split('/').slice(-1)[0].trim(); var refPath = headFile.split(' ')[1]; if (refPath) { var branchPath = path.join(gitPath, refPath.trim()); branchSHA = fs.readFileSync(branchPath); } else { branchSHA = branchName; } output.push(branchName); output.push(branchSHA.slice(0,10)); } } catch (err) { console.error(err.stack); } return output.join('-'); };
'use strict'; var fs = require('fs'); var path = require('path'); module.exports = function () { var output = [require('../../package.json').version]; var gitPath = path.join(__dirname, '..','..','.git'); var headFilePath = path.join(gitPath, 'HEAD'); try { if (fs.existsSync(headFilePath)) { var headFile = fs.readFileSync(headFilePath, {encoding: 'utf8'}); var branchName = headFile.split('/').slice(-1)[0].trim(); var branchPath = path.join(gitPath, headFile.split(' ')[1].trim()); output.push(branchName); var branchSHA = fs.readFileSync(branchPath); output.push(branchSHA.slice(0,10)); } } catch (err) { console.error(err.stack); } return output.join('-'); };
Tweak whitespace for DocuSign acknowledgement email
Hi {{ $envelope->signedBy->preferred_first_name }}, We received your Travel Authority Request for {{ $envelope->signable->travel->name }}. Once everyone has submitted their documents, we'll forward all of them to Georgia Tech for review and approval. You can view your completed form within DocuSign at {{ $envelope->sender_view_url }}. @if(!$envelope->signable->is_paid) You still need to make a ${{ intval($envelope->signable->travel->fee_amount) }} payment for the travel fee. You can pay online with a credit or debit card at {{ route('pay.travel') }}. Note that we add an additional ${{ number_format(\App\Models\Payment::calculateSurcharge($envelope->signable->travel->fee_amount * 100) / 100, 2) }} surcharge for online payments. If you would prefer to pay by cash or check, make arrangements with {{ $envelope->signable->travel->primaryContact->full_name }}. Write checks to Georgia Tech, with RoboJackets on the memo line. Don't forget to sign it! @endif For more information, visit {{ route('travel.index') }}. If you have any questions, please contact {{ $envelope->signable->travel->primaryContact->full_name }}. ---- To stop receiving emails from {{ config('app.name') }}, visit @{{{ pm:unsubscribe }}}.
Hi {{ $envelope->signedBy->preferred_first_name }}, We received your Travel Authority Request for {{ $envelope->signable->travel->name }}. Once everyone has submitted their documents, we'll forward all of them to Georgia Tech for review and approval. You can view your completed form within DocuSign at {{ $envelope->sender_view_url }}. @if(!$envelope->signable->is_paid) You still need to make a ${{ intval($envelope->signable->travel->fee_amount) }} payment for the travel fee. You can pay online with a credit or debit card at {{ route('pay.travel') }}. Note that we add an additional ${{ number_format(\App\Models\Payment::calculateSurcharge($envelope->signable->travel->fee_amount * 100) / 100, 2) }} surcharge for online payments. If you would prefer to pay by cash or check, make arrangements with {{ $envelope->signable->travel->primaryContact->full_name }}. Write checks to Georgia Tech, with RoboJackets on the memo line. Don't forget to sign it! @endif For more information, visit {{ route('travel.index') }}. If you have any questions, please contact {{ $envelope->signable->travel->primaryContact->full_name }}. ---- To stop receiving emails from {{ config('app.name') }}, visit @{{{ pm:unsubscribe }}}.
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-hovers/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-hovers/tachyons-hovers.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_hovers.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/hovers/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/themes/hovers/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-hovers/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-hovers/tachyons-hovers.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_hovers.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/hovers/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/themes/hovers/index.html', html)
Fix an exception when loading project
package de.prob2.ui.verifications.cbc; import java.util.Objects; import de.prob.statespace.Trace; public class CBCFormulaFindStateItem extends CBCFormulaItem { private transient Trace example; public CBCFormulaFindStateItem(String name, String code, CBCType type) { super(name, code, type); this.example = null; } public void setExample(Trace example) { this.example = example; } public Trace getExample() { return example; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CBCFormulaFindStateItem)) { return false; } CBCFormulaFindStateItem otherItem = (CBCFormulaFindStateItem) obj; return otherItem.getName().equals(this.getName()) && otherItem.getCode().equals(this.getCode()) && otherItem.getType().equals(this.getType()); } @Override public int hashCode() { return Objects.hash(name, code, type); } }
package de.prob2.ui.verifications.cbc; import java.util.Objects; import de.prob.statespace.Trace; public class CBCFormulaFindStateItem extends CBCFormulaItem { private Trace example; public CBCFormulaFindStateItem(String name, String code, CBCType type) { super(name, code, type); this.example = null; } public void setExample(Trace example) { this.example = example; } public Trace getExample() { return example; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CBCFormulaFindStateItem)) { return false; } CBCFormulaFindStateItem otherItem = (CBCFormulaFindStateItem) obj; return otherItem.getName().equals(this.getName()) && otherItem.getCode().equals(this.getCode()) && otherItem.getType().equals(this.getType()); } @Override public int hashCode() { return Objects.hash(name, code, type); } }
Fix imaginary constant gate not being drawn as an octagon
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {GateBuilder} from "src/circuit/Gate.js" import {Matrix} from "src/math/Matrix.js" import {Complex} from "src/math/Complex.js" import {GatePainting} from "src/draw/GatePainting.js" const ImaginaryGate = new GateBuilder(). setSerializedIdAndSymbol("i"). setTitle("Imaginary Gate"). setBlurb("Phases everything by i."). setDrawer(args => { GatePainting.paintLocationIndependentFrame(args); GatePainting.paintGateSymbol(args); }). setKnownEffectToMatrix(Matrix.square(Complex.I, 0, 0, Complex.I)). gate; export {ImaginaryGate}
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {GateBuilder} from "src/circuit/Gate.js" import {Matrix} from "src/math/Matrix.js" import {Complex} from "src/math/Complex.js" const ImaginaryGate = new GateBuilder(). setSerializedIdAndSymbol("i"). setTitle("Imaginary Gate"). setBlurb("Phases everything by i."). setKnownEffectToMatrix(Matrix.square(Complex.I, 0, 0, Complex.I)). gate; export {ImaginaryGate}
Add secret key to env viarables
import os class MainConfig(object): DEBUG = False WTF_CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.getenv('SECRET_KEY') class DevelopmentEnviron(MainConfig): DEBUG = True TESTING = True # URI to our development database SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/bucketlist_db' class TestingConfig(MainConfig): TESTING = True DEBUG = True # URI to our testing database SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/test_db' class ProductionConfig(MainConfig): DEBUG = False TESTING = False # Dictionary with keys mapping to the different configuration environments app_config = { 'MainConfig': MainConfig, 'DevelopmentEnviron': DevelopmentEnviron, 'TestingConfig': TestingConfig, 'ProductionConfig': ProductionConfig }
import os class MainConfig(object): DEBUG = False WTF_CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False # Will generate a random secret key with a sequence of random chaarcters SECRET_KEY = os.urandom(24) class DevelopmentEnviron(MainConfig): DEBUG = True TESTING = True # URI to our development database SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/bucketlist_db' class TestingConfig(MainConfig): TESTING = True DEBUG = True # URI to our testing database SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/test_db' class ProductionConfig(MainConfig): DEBUG = False TESTING = False # Dictionary with keys mapping to the different configuration environments app_config = { 'MainConfig': MainConfig, 'DevelopmentEnviron': DevelopmentEnviron, 'TestingConfig': TestingConfig, 'ProductionConfig': ProductionConfig }
Check availability of console before using it (Fix IE9)
/* @flow */ 'use strict'; export default class Logger { start: number; constructor() { this.start = Date.now(); } // eslint-disable-next-line flowtype/no-weak-types log(...args: any) { if (window.console && window.console.log) { Function.prototype.bind .call(window.console.log, window.console) .apply( window.console, [Date.now() - this.start + 'ms', 'html2canvas:'].concat([].slice.call(args, 0)) ); } } // eslint-disable-next-line flowtype/no-weak-types error(...args: any) { if (window.console && window.console.error) { Function.prototype.bind .call(window.console.error, window.console) .apply( window.console, [Date.now() - this.start + 'ms', 'html2canvas:'].concat([].slice.call(args, 0)) ); } } }
/* @flow */ 'use strict'; export default class Logger { start: number; constructor() { this.start = Date.now(); } // eslint-disable-next-line flowtype/no-weak-types log(...args: any) { Function.prototype.bind .call(window.console.log, window.console) .apply( window.console, [Date.now() - this.start + 'ms', 'html2canvas:'].concat([].slice.call(args, 0)) ); } // eslint-disable-next-line flowtype/no-weak-types error(...args: any) { Function.prototype.bind .call(window.console.error, window.console) .apply( window.console, [Date.now() - this.start + 'ms', 'html2canvas:'].concat([].slice.call(args, 0)) ); } }
Add presenter as last argument(?)
<?php if (is_dir($vendor = __DIR__ . '/../vendor')) { require_once($vendor . '/autoload.php'); } elseif (is_dir($vendor = __DIR__ . '/../../../vendor')) { require_once($vendor . '/autoload.php'); } elseif (is_dir($vendor = __DIR__ . '/vendor')) { require_once($vendor . '/autoload.php'); } else { die( 'You must set up the project dependencies, run the following commands:' . PHP_EOL . 'curl -s http://getcomposer.org/installer | php' . PHP_EOL . 'php composer.phar install' . PHP_EOL ); } use PHPSpec2\Wrapper\ArgumentsUnwrapper, PHPSpec2\Matcher\MatchersCollection, PHPSpec2\Formatter\Presenter\TaggedPresenter, PHPSpec2\Formatter\Presenter\Differ\Differ; require_once "Bossa/PHPSpec2/Expect/ObjectProphet.php"; if (!function_exists('expect')) { function expect($sus) { $presenter = new TaggedPresenter(new Differ); return new Bossa\PHPSpec2\Expect\ObjectProphet($sus, new MatchersCollection($presenter), new ArgumentsUnwrapper, $presenter); } }
<?php if (is_dir($vendor = __DIR__ . '/../vendor')) { require_once($vendor . '/autoload.php'); } elseif (is_dir($vendor = __DIR__ . '/../../../vendor')) { require_once($vendor . '/autoload.php'); } elseif (is_dir($vendor = __DIR__ . '/vendor')) { require_once($vendor . '/autoload.php'); } else { die( 'You must set up the project dependencies, run the following commands:' . PHP_EOL . 'curl -s http://getcomposer.org/installer | php' . PHP_EOL . 'php composer.phar install' . PHP_EOL ); } use PHPSpec2\Wrapper\ArgumentsUnwrapper, PHPSpec2\Matcher\MatchersCollection, PHPSpec2\Formatter\Presenter\TaggedPresenter, PHPSpec2\Formatter\Presenter\Differ\Differ; require_once "Bossa/PHPSpec2/Expect/ObjectProphet.php"; if (!function_exists('expect')) { function expect($sus) { return new Bossa\PHPSpec2\Expect\ObjectProphet($sus, new MatchersCollection(new TaggedPresenter(new Differ)), new ArgumentsUnwrapper); } }
Add new method to delete file
package uk.ac.ebi.spot.goci.curation.service.batchloader; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import uk.ac.ebi.spot.goci.curation.model.batchloader.BatchUploadError; import uk.ac.ebi.spot.goci.curation.model.batchloader.BatchUploadRow; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.Study; import java.io.IOException; import java.util.Collection; /** * Created by emma on 21/03/2016. * * @author emma * <p> * Upload, error check and create persistance obejects that can be saved in DB from a batch of SNPs from a .xlsx * spreadsheet. Note that the spreadsheet must be of .xlsx format! * <p> * Created from code originally written by Dani. Adapted to fit with new curation system. */ public interface AssociationBatchLoaderService { Collection<BatchUploadRow> processFile(String fileName, Study study) throws InvalidFormatException, IOException; Collection<Association> processFileRows(Collection<BatchUploadRow> batchUploadRows); Collection<BatchUploadError> checkUploadForErrors(Collection<BatchUploadRow> batchUploadRows); void saveAssociations(Collection<Association> associations, Study study); void deleteFile(String fileName); }
package uk.ac.ebi.spot.goci.curation.service.batchloader; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import uk.ac.ebi.spot.goci.curation.model.BatchUploadError; import uk.ac.ebi.spot.goci.curation.model.batchloader.BatchUploadRow; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.Study; import java.io.IOException; import java.util.Collection; /** * Created by emma on 21/03/2016. * * @author emma * <p> * Upload, error check and create persistance obejects that can be saved in DB from a batch of SNPs from a .xlsx * spreadsheet. Note that the spreadsheet must be of .xlsx format! * <p> * Created from code originally written by Dani. Adapted to fit with new curation system. */ public interface AssociationBatchLoaderService { Collection<BatchUploadError> processFile(String fileName, Study study) throws InvalidFormatException, IOException; Collection<Association> processFileRows(Collection<BatchUploadRow> batchUploadRows); Collection<BatchUploadError> checkUploadForErrors(Collection<BatchUploadRow> batchUploadRows); void saveAssociations(Collection<Association> associations, Study study); }
Refactor to seperate state from operations
'use strict'; module.exports = function () { const state = createInitialState(); return { track () { const thisIdx = state.trackers.push({executed: false}) - 1; return function () { state.trackers[thisIdx] = {executed: true, args: argsToArray(arguments)}; tryToFinish(state); }; }, finished (callback) { state.onFinished = callback; } }; }; function createInitialState () { return { trackers: [], isFinished: false, onFinished: () => {} }; } function tryToFinish (state) { if (all(pluck(state.trackers, 'executed')) && !state.isFinished) { state.isFinished = true; state.onFinished(pluck(state.trackers, 'args')); } } function pluck (collection, property) { return collection.map(item => item[property]); } function all (conditions) { for (const condition of conditions) { if (!condition) return false; } return true; } function argsToArray (argumentsObject) { return Array.prototype.slice.call(argumentsObject); }
'use strict'; module.exports = function () { const trackers = []; let isFinished = false; let onFinished = () => {}; function tryToFinish () { if (all(pluck(trackers, 'executed')) && !isFinished) { isFinished = true; onFinished(pluck(trackers, 'args')); } } return { track () { const thisIdx = trackers.push({executed: false}) - 1; return function () { trackers[thisIdx] = {executed: true, args: argsToArray(arguments)}; tryToFinish(); }; }, finished (callback) { onFinished = callback; } }; }; function pluck (collection, property) { return collection.map(item => item[property]); } function all (conditions) { for (const condition of conditions) { if (!condition) return false; } return true; } function argsToArray (argumentsObject) { return Array.prototype.slice.call(argumentsObject); }
Rewrite initExceptionTest to be less stupid
package spark; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import static spark.Service.ignite; public class InitExceptionHandlerTest { private static Service service1; private static Service service2; private static String errorMessage = ""; @BeforeClass public static void setUpClass() throws Exception { service1 = ignite(); service1.port(1122); service1.init(); service1.awaitInitialization(); service2 = ignite(); service2.port(1122); service2.initExceptionHandler((e) -> errorMessage = "Custom init error"); service2.init(); service2.awaitInitialization(); } @Test public void testGetPort_withRandomPort() throws Exception { Assert.assertEquals("Custom init error", errorMessage); } @AfterClass public static void tearDown() throws Exception { service1.stop(); service2.stop(); } }
package spark; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Assert; import org.junit.Test; import static spark.Service.ignite; public class InitExceptionHandlerTest { @Test public void testInitExceptionHandler() throws Exception { ExecutorService executorService = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = new CompletableFuture<>(); executorService.submit(() -> { Service service1 = ignite().port(1122); service1.init(); nap(); Service service2 = ignite().port(1122); service2.initExceptionHandler((e) -> future.complete("Custom init error")); service2.init(); service1.stop(); service2.stop(); }); Assert.assertEquals("Custom init error", future.get()); } private void nap() { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } }
Update JSONGeneratorEncoder to subclass DjangoJSONEncoder This handles Decimals and datetimes
import inspect from django.core.serializers.json import DjangoJSONEncoder from _base import BaseExporter class JSONGeneratorEncoder(DjangoJSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
import json import inspect from _base import BaseExporter class JSONGeneratorEncoder(json.JSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
Rename command addon to bdist_blender_addon
from setuptools import setup, find_packages from buildcmds.addon import bdist_blender_addon setup( name='io_scene_previz', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.0.7', description='Blender Previz addon', url='https://app.previz.co', author='Previz', author_email='info@previz.co', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='previz development 3d scene exporter', packages=find_packages(exclude=['buildcmds', 'tests']), install_requires=['previz'], extras_require={}, package_data={}, data_files=[], cmdclass={ 'bdist_blender_addon': bdist_blender_addon } )
from setuptools import setup, find_packages from buildcmds.addon import addon setup( name='io_scene_previz', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.0.7', description='Blender Previz addon', url='https://app.previz.co', author='Previz', author_email='info@previz.co', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='previz development 3d scene exporter', packages=find_packages(exclude=['tests']), install_requires=['previz'], extras_require={}, package_data={}, data_files=[], cmdclass={ 'addon': addon } )
Add return UUID,Created,Modified to putQuestionnaire
'use strict' const MongoClient = require('mongodb').MongoClient; const ObjectId = require('mongodb').ObjectID; module.exports = (mongodbUrl) => { async function getQuestionnaires() { // TODO: Mongodb-kutsu return new Promise(function(resolve, reject){ setTimeout(function(){ resolve("Hello World"); }, 1000) }); } async function putQuestionnaire(payload) { return new Promise(function(resolve, reject){ let insertQuestionnaire = function(db, callback) { db.collection('questionnaires').insertOne(payload, function(err, result) { console.log("Inserted a questionnaire into the questionnaires collection."); callback(); }); }; MongoClient.connect(mongodbUrl, function(err, db) { insertQuestionnaire(db, function() { db.close(); }); }); let returnJson = new Object(); returnJson.uuid = payload.uuid; returnJson.created = payload.created; returnJson.modified = payload.modified; resolve(JSON.stringify(returnJson)); }); } return { getQuestionnaires: getQuestionnaires, putQuestionnaire: putQuestionnaire }; }
'use strict' const MongoClient = require('mongodb').MongoClient; const ObjectId = require('mongodb').ObjectID; module.exports = (mongodbUrl) => { async function getQuestionnaires() { // TODO: Mongodb-kutsu return new Promise(function(resolve, reject){ setTimeout(function(){ resolve("Hello World"); }, 1000) }); } async function putQuestionnaire(payload) { return new Promise(function(resolve, reject){ let insertQuestionnaire = function(db, callback) { db.collection('questionnaires').insertOne(payload, function(err, result) { console.log("Inserted a questionnaire into the questionnaires collection."); callback(); }); }; MongoClient.connect(mongodbUrl, function(err, db) { insertQuestionnaire(db, function() { db.close(); }); }); resolve(payload.uuid); }); } return { getQuestionnaires: getQuestionnaires, putQuestionnaire: putQuestionnaire }; }
Use Dash's new CamelCase convention to lookup words that contain whitespace - Example: converting "create table" into "createTable" will lookup "CREATE TABLE"
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def camel_case(word): return ''.join(w.capitalize() if i > 0 else w for i, w in enumerate(word.split())) def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax = syntax_name(view) if syntax in syntax_docset_map: return syntax_docset_map[syntax] + ':' return None class DashDocCommand(sublime_plugin.TextCommand): def run(self, edit, syntax_sensitive=False): selection = self.view.sel()[0] if len(selection) == 0: selection = self.view.word(selection) word = self.view.substr(selection) settings = sublime.load_settings('DashDoc.sublime-settings') if syntax_sensitive or settings.get('syntax_sensitive', False): docset = docset_prefix(self.view, settings) else: docset = None subprocess.call(["open", "dash://%s%s" % (docset or '', camel_case(word))])
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax = syntax_name(view) if syntax in syntax_docset_map: return syntax_docset_map[syntax] + ':' return None class DashDocCommand(sublime_plugin.TextCommand): def run(self, edit, syntax_sensitive=False): selection = self.view.sel()[0] if len(selection) == 0: selection = self.view.word(selection) word = self.view.substr(selection) settings = sublime.load_settings('DashDoc.sublime-settings') if syntax_sensitive or settings.get('syntax_sensitive', False): docset = docset_prefix(self.view, settings) else: docset = None subprocess.call(["open", "dash://%s%s" % (docset or '', word)])
Add session check to all pages except login. git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@849 54a900ba-8191-11dd-a5c9-f1483cedc3eb
<?php include 'db.php'; include 'lib/php/load.php'; include 'html/templates/Header.php'; include 'lib/php/html/tabs.php'; //Check to see which template is needed if (isset($_GET['i'])) { //load session checker to ensure user is authorized to see page. include 'lib/php/auth/session_check.php'; $pg = load($_GET['i']); } else { $pg = load('Login.php'); } //Include the template if ($pg === false) {echo "Invalid File Request";} else {include($pg);} //Check to see if the user has been logged out for inactivity and notify them if (isset($_GET['force_close'])) { echo <<<FC <script type = 'text/javascript'> $('#idletimeout').css('display','block'); </script> FC; } include 'html/templates/Footer.php';
<?php include 'db.php'; include 'lib/php/load.php'; include 'html/templates/Header.php'; include 'lib/php/html/tabs.php'; //Check to see which template is needed if (isset($_GET['i'])) { $pg = load($_GET['i']); } else { $pg = load('Login.php'); } //Include the template if ($pg === false) {echo "Invalid File Request";} else {include($pg);} //Check to see if the user has been logged out for inactivity and notify them if (isset($_GET['force_close'])) { echo <<<FC <script type = 'text/javascript'> $('#idletimeout').css('display','block'); </script> FC; } include 'html/templates/Footer.php';
Fix the data format of our metrics consumer
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Moksha Metrics Consumer ======================= .. moduleauthor:: Luke Macken <lmacken@redhat.com> """ from moksha.api.hub import Consumer class MokshaMessageMetricsConsumer(Consumer): """ This consumer listens to all messages on the `moksha_message_metrics` topic, and relays the message to the message.body['topic'] topic. """ topic = 'moksha_message_metrics' def consume(self, message): self.send_message(message['body']['topic'], message['body']['data'])
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Moksha Metrics Consumer ======================= .. moduleauthor:: Luke Macken <lmacken@redhat.com> """ from moksha.api.hub import Consumer class MokshaMessageMetricsConsumer(Consumer): """ This consumer listens to all messages on the `moksha_message_metrics` topic, and relays the message to the message.body['topic'] topic. """ topic = 'moksha_message_metrics' def consume(self, message): self.send_message(message['topic'], message['data'])
Fix error for the first days of the month.
function update_audio() { var audioplayer = document.getElementById("audioplayer"); var src = "http://telechargement.rfi.fr.edgesuite.net/rfi/francais/audio/journaux/r001/journal_francais_facile_20h00_-_20h10_tu_"; var today = new Date(); console.log(today.getUTCHours()); if (today.getUTCHours() < 20 || (today.getUTCHours() == 20 && today.getUTCMinutes() < 20)) { today -= 3600 * 24 * 1000; today = new Date(today); } src += today.getFullYear(); if (today.getMonth() < 9) { src += "0"; } src += today.getMonth()+1; if (today.getDate() < 10) { src += "0"; } src += today.getDate(); src += ".mp3"; console.log(src); if (audioplayer.src != src) { audioplayer.src = src; } } window.addEventListener("focus", update_audio); document.addEventListener("DOMContentLoaded", update_audio);
function update_audio() { var audioplayer = document.getElementById("audioplayer"); var src = "http://telechargement.rfi.fr.edgesuite.net/rfi/francais/audio/journaux/r001/journal_francais_facile_20h00_-_20h10_tu_"; var today = new Date(); console.log(today.getUTCHours()); if (today.getUTCHours() < 20 || (today.getUTCHours() == 20 && today.getUTCMinutes() < 20)) { today -= 3600 * 24 * 1000; today = new Date(today); } src += today.getFullYear(); if (today.getMonth() < 9) { src += "0"; } src += today.getMonth()+1; src += today.getDate(); src += ".mp3"; console.log(src); if (audioplayer.src != src) { audioplayer.src = src; } } window.addEventListener("focus", update_audio); document.addEventListener("DOMContentLoaded", update_audio);
Allow stream ids != 1 in frame factory.
# -*- coding: utf-8 -*- """ helpers ~~~~~~~ This module contains helpers for the h2 tests. """ from hyperframe.frame import HeadersFrame, DataFrame from hpack.hpack import Encoder class FrameFactory(object): """ A class containing lots of helper methods and state to build frames. This allows test cases to easily build correct HTTP/2 frames to feed to hyper-h2. """ def __init__(self): self.encoder = Encoder() def preamble(self): return b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n' def build_headers_frame(self, headers, flags=None, stream_id=1): """ Builds a single valid headers frame out of the contained headers. """ f = HeadersFrame(stream_id) f.data = self.encoder.encode(headers) f.flags.add('END_HEADERS') if flags: f.flags.update(flags) return f def build_data_frame(self, data, flags=None, stream_id=1): """ Builds a single data frame out of a chunk of data. """ flags = set(flags) if flags is not None else set() f = DataFrame(stream_id) f.data = data f.flags = flags return f
# -*- coding: utf-8 -*- """ helpers ~~~~~~~ This module contains helpers for the h2 tests. """ from hyperframe.frame import HeadersFrame, DataFrame from hpack.hpack import Encoder class FrameFactory(object): """ A class containing lots of helper methods and state to build frames. This allows test cases to easily build correct HTTP/2 frames to feed to hyper-h2. """ def __init__(self): self.encoder = Encoder() def preamble(self): return b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n' def build_headers_frame(self, headers, flags=None): """ Builds a single valid headers frame out of the contained headers. """ f = HeadersFrame(1) f.data = self.encoder.encode(headers) f.flags.add('END_HEADERS') if flags: f.flags.update(flags) return f def build_data_frame(self, data, flags=None): """ Builds a single data frame out of a chunk of data. """ flags = set(flags) if flags is not None else set() f = DataFrame(1) f.data = data f.flags = flags return f
Add stream() method to collection compile-time interface
package java.util; import edu.columbia.cs.psl.phosphor.struct.ControlTaintTagStack; import edu.columbia.cs.psl.phosphor.struct.TaintedBooleanWithObjTag; import java.util.stream.Stream; public interface Collection<E> extends Iterable<E> { int size(); boolean isEmpty(); boolean contains(Object o); Iterator<E> iterator(); Object[] toArray(); <T> T[] toArray(T[] a); boolean add(E e); Stream<E> stream(); TaintedBooleanWithObjTag add$$PHOSPHORTAGGED(E e, TaintedBooleanWithObjTag ret); TaintedBooleanWithObjTag add$$PHOSPHORTAGGED(E e, ControlTaintTagStack ctrl, TaintedBooleanWithObjTag ret); boolean remove(Object o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); boolean removeAll(Collection<?> c); boolean retainAll(Collection<?> c); void clear(); boolean equals(Object o); int hashCode(); }
package java.util; import edu.columbia.cs.psl.phosphor.struct.ControlTaintTagStack; import edu.columbia.cs.psl.phosphor.struct.TaintedBooleanWithObjTag; public interface Collection<E> extends Iterable<E> { int size(); boolean isEmpty(); boolean contains(Object o); Iterator<E> iterator(); Object[] toArray(); <T> T[] toArray(T[] a); boolean add(E e); TaintedBooleanWithObjTag add$$PHOSPHORTAGGED(E e, TaintedBooleanWithObjTag ret); TaintedBooleanWithObjTag add$$PHOSPHORTAGGED(E e, ControlTaintTagStack ctrl, TaintedBooleanWithObjTag ret); boolean remove(Object o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); boolean removeAll(Collection<?> c); boolean retainAll(Collection<?> c); void clear(); boolean equals(Object o); int hashCode(); }
Fix Unit Test build environment
# Copyright 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from os.path import join import pytest from platformio import util def test_local_env(): result = util.exec_command(["platformio", "test", "-d", join("examples", "unit-testing", "calculator"), "-e", "native"]) if result['returncode'] != 1: pytest.fail(result) assert all( [s in result['out'] for s in ("PASSED", "IGNORED", "FAILED")])
# Copyright 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from os.path import join import pytest from platformio import util def test_local_env(): result = util.exec_command(["platformio", "test", "-d", join("examples", "unit-testing", "calculator"), "-e", "local"]) if result['returncode'] != 1: pytest.fail(result) assert all( [s in result['out'] for s in ("PASSED", "IGNORED", "FAILED")])
Fix typo in test description
var assert = require('assert'); var Metalsmith = require('metalsmith'); var frontmatter = require('../lib'); describe('metalsmith-matters', function(){ it('should add metadata based on the frontmatter in the file', function(done){ Metalsmith('test/fixtures/basic') .frontmatter(false) .use(frontmatter()) .build(function(err, files){ if (err) return done(err); assert.equal(files["test.md"].someKey, "value"); done(); }); }); it('should remove frontmatter from the file contents', function(done){ Metalsmith('test/fixtures/basic') .frontmatter(false) .use(frontmatter()) .build(function(err, files){ if (err) return done(err); assert.equal(files["test.md"].contents.toString(), "# Header\n\nContent\n"); done(); }); }); });
var assert = require('assert'); var Metalsmith = require('metalsmith'); var frontmatter = require('../lib'); describe('metalsmith-matters', function(){ it('should add add metadata based on the frontmatter in the file', function(done){ Metalsmith('test/fixtures/basic') .frontmatter(false) .use(frontmatter()) .build(function(err, files){ if (err) return done(err); assert.equal(files["test.md"].someKey, "value"); done(); }); }); it('should remove frontmatter from the file contents', function(done){ Metalsmith('test/fixtures/basic') .frontmatter(false) .use(frontmatter()) .build(function(err, files){ if (err) return done(err); assert.equal(files["test.md"].contents.toString(), "# Header\n\nContent\n"); done(); }); }); });
Add parentheses around all lists so that nested lists are supported (without them Sass throws an error).
'use strict'; var opts = { prefix: '', suffix: '', suffixLastItem: true, }; function objToValue(obj, opts) { var keys = Object.keys(obj); var fields = keys.map(function(key) { var value = formatValue(obj[key]); return opts.prefix + key + ":" + value; }); var result = fields.join(opts.suffix + "\n"); if (opts.suffixLastItem) { return result + opts.suffix; } return result; } function formatValue(value) { if (value instanceof Array) { var result = value.map(function(v) { return formatValue(v); }); return '(' + result.join(', ') + ')'; } if (typeof value === 'object') { var opts = { prefix: '', suffix: ',', suffixLastItem: false, }; return '(\n' + objToValue(value, opts) + '\n)'; } if (typeof value === 'string') { return value; } return JSON.stringify(value); } module.exports = objToValue;
'use strict'; var opts = { prefix: '', suffix: '', suffixLastItem: true, }; function objToValue(obj, opts) { var keys = Object.keys(obj); var fields = keys.map(function(key) { var value = formatValue(obj[key]); return opts.prefix + key + ":" + value; }); var result = fields.join(opts.suffix + "\n"); if (opts.suffixLastItem) { return result + opts.suffix; } return result; } function formatValue(value) { if (value instanceof Array) { var result = value.map(function(v) { return formatValue(v); }); return result.join(', '); } if (typeof value === 'object') { var opts = { prefix: '', suffix: ',', suffixLastItem: false, }; return '(\n' + objToValue(value, opts) + '\n)'; } if (typeof value === 'string') { return value; } return JSON.stringify(value); } module.exports = objToValue;
Use body instead of json attribute
// Push records from JSON to Data Service var fs = require('fs'); var request = require('request'); var argv = require('yargs') .usage('Usage: $0 [options] <input records> <destination URL>') .count('verbose') .boolean('verbose') .alias('v', 'verbose') .demand(2) .argv; VERBOSE_LEVEL = argv.verbose; var file = argv._[0]; var uploadEndpoint = argv._[1]; function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); } function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); } function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); } fs.readFile(file, 'utf8', function (err, data) { if (err) { WARN("Error: " + err); return; } uploadRecords(JSON.parse(data)); }); var uploadRecords = function (records) { records.forEach(function (record) { uploadRecord(record); }); }; var uploadRecord = function (record) { request.post({ uri: uploadEndpoint, body: JSON.stringify(record) }, function (e, r, body) { WARN("Upload complete", r.statusCode); INFO("Error info: ", e); DEBUG("Response body:\n", body); }); };
// Push records from JSON to Data Service var fs = require('fs'); var request = require('request'); var argv = require('yargs') .usage('Usage: $0 [options] <input records> <destination URL>') .count('verbose') .boolean('verbose') .alias('v', 'verbose') .demand(2) .argv; VERBOSE_LEVEL = argv.verbose; var file = argv._[0]; var uploadEndpoint = argv._[1]; function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); } function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); } function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); } fs.readFile(file, 'utf8', function (err, data) { if (err) { WARN("Error: " + err); return; } uploadRecords(JSON.parse(data)); }); var uploadRecords = function (records) { records.forEach(function (record) { uploadRecord(record); }); }; var uploadRecord = function (record) { request.post({ uri: uploadEndpoint, json: JSON.stringify(record) }, function (e, r, body) { WARN("Upload complete", r.statusCode); INFO("Error info: ", e); DEBUG("Response body:\n", body); }); };
Modify excel screenshot test so that it works with the new directory structure
#!/usr/bin/python """Program to execute a VBA macro in MS Excel """ import os import shutil import win32com.client import pythoncom def execute_macro(): """Execute VBA macro in MS Excel """ pythoncom.CoInitialize() current_path = os.path.dirname(os.getcwd()) path_to_file = ".\\data\\excelsheet.xlsm" if os.path.exists(path_to_file): xl_file = win32com.client.Dispatch("Excel.Application") xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file), ReadOnly=1) xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro xl_run.Save() xl_run.Close() xl_file.Quit() del xl_file shutil.move(path_to_file, ".\\output\\excelsheet.xlsm") shutil.move(".\\data\\output.txt", ".\\output\\output.txt") print("Action successfully executed") if __name__ == "__main__": execute_macro()
#!/usr/bin/python """Program to execute a VBA macro in MS Excel """ import os import shutil import win32com.client import pythoncom import repackage repackage.up() def execute_macro(): """Execute VBA macro in MS Excel """ pythoncom.CoInitialize() current_path = os.path.dirname(os.getcwd()) path_to_file = current_path + "\\action\\data\\excelsheet.xlsm" if os.path.exists(path_to_file): xl_file = win32com.client.Dispatch("Excel.Application") xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file), ReadOnly=1) xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro xl_run.Save() xl_run.Close() xl_file.Quit() del xl_file shutil.move(path_to_file, current_path + "\\action\\output\\excelsheet.xlsm") shutil.move(current_path + "\\action\\data\\output.txt", current_path + "\\action\\output\\output.txt") print("Action successfully executed") if __name__ == "__main__": execute_macro()
Add a test for upper-to-lower conversion on parsing Windows env vars
// +build windows,unit // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. package config import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestParseGMSACapability(t *testing.T) { os.Setenv("ECS_GMSA_SUPPORTED", "False") defer os.Unsetenv("ECS_GMSA_SUPPORTED") assert.False(t, parseGMSACapability()) } func TestParseBooleanEnvVar(t *testing.T) { os.Setenv("EXAMPLE_SETTING", "True") defer os.Unsetenv("EXAMPLE_SETTING") assert.True(t, parseBooleanDefaultFalseConfig("EXAMPLE_SETTING")) assert.True(t, parseBooleanDefaultTrueConfig("EXAMPLE_SETTING")) os.Setenv("EXAMPLE_SETTING", "False") assert.False(t, parseBooleanDefaultFalseConfig("EXAMPLE_SETTING")) assert.False(t, parseBooleanDefaultTrueConfig("EXAMPLE_SETTING")) }
// +build windows,unit // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. package config import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestParseGMSACapability(t *testing.T) { os.Setenv("ECS_GMSA_SUPPORTED", "False") defer os.Unsetenv("ECS_GMSA_SUPPORTED") assert.False(t, parseGMSACapability()) }
Refactor out functions from rps1
""" A simple rock, paper, scissors script submitted as a demo of easy game-making In Python. """ import random # We need thr random module for the computer to play # This dictionary relates a choice to what it defeats for easy comparison later. beats = { "rock":"scissors", "paper":"rock", "scissors":"paper" } # Now we make an easy-to-use list of choices from the beats choices = list(beats.keys()) # Get the player choice from the input command. # The lower() is used to correct for people typing with capitals. # The strip() removes any trailing space that might mess us up. player_choice = input("Rock, paper, or scissors?").lower().strip() # Finally, time to compare! But we have to account for cheaters/mistakes. if player_choice not in choices: print("You must choose r, p, or s!") else: # Here we make the computer choose, then compare the two. computer_choice = random.choice(choices) if beats[player_choice] == computer_choice print("You win!") else: print("You lose") """ This program works, but it's quite limited. Probably its biggest limitation is that it will only run once. It also doesn't keep score—why would it, since it only runs once? Our next version of the game will make it more user-friendly. """
# A simple rock, paper, scissors script submitted as a demo of easy game-making # In Python # Certain parts of this program are functional—that is, written in functions that # work together. Some parts aren't. As we improve the program, you'll find that # This functional way of doing things has some real advantages. import random # We need thr random module for the computer to play # This dictionary relates a choice to what it defeats for easy comparison later. beats = { "rock":"scissors", "paper":"rock", "scissors":"paper" } # Now we make an easy-to-use list of choices from the beats choices = list(beats.keys()) # Get the player choice from the input command. # The lower() is used to correct for people typing with capitals. # The strip() removes any trailing space that might mess us up. player_choice = input("Rock, paper, or scissors?").lower().strip() # Finally, time to compare! But we have to account for cheaters/mistakes. if player_choice not in choices: print("You must choose r, p, or s!") else: # Here we make the computer choose, then compare the two. computer_choice = random.choice(choices) if beats[player_choice] == computer_choice print("You win!") else: print("You lose") """ This program works, but it's quite limited. Probably its biggest limitation is that it will only run once. It also doesn't keep score—why would it, since it only runs once? Our next version of the game will make it more user-friendly. """
Fix method docstring (copy paste error) Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47 As the method does not return user info.
# Copyright 2020 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Information API for version 1 of the Timesketch API.""" from flask import jsonify from flask_restful import Resource from flask_login import login_required from timesketch import version from timesketch.api.v1 import resources from timesketch.lib.definitions import HTTP_STATUS_CODE_OK class VersionResource(resources.ResourceMixin, Resource): """Resource to get Timesketch API version information.""" @login_required def get(self): """Handles GET request to the resource. Returns: JSON object including version info """ schema = { 'meta': { 'version': version.get_version() }, 'objects': [] } response = jsonify(schema) response.status_code = HTTP_STATUS_CODE_OK return response
# Copyright 2020 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Information API for version 1 of the Timesketch API.""" from flask import jsonify from flask_restful import Resource from flask_login import login_required from timesketch import version from timesketch.api.v1 import resources from timesketch.lib.definitions import HTTP_STATUS_CODE_OK class VersionResource(resources.ResourceMixin, Resource): """Resource to get Timesketch API version information.""" @login_required def get(self): """Handles GET request to the resource. Returns: List of usernames """ schema = { 'meta': { 'version': version.get_version() }, 'objects': [] } response = jsonify(schema) response.status_code = HTTP_STATUS_CODE_OK return response
Use a better example error message
# -*- coding: utf-8 -*- """These JSON-formatted views require authentication.""" from flask import Blueprint, jsonify, request, current_app, g from werkzeug.exceptions import NotFound from os.path import join from ..dl import download from ..error import handle_errors from ..util import enforce_auth private = Blueprint(__name__, 'private') private.before_request(enforce_auth) @handle_errors(private) def json_error(e): """Return an error response like {"msg":"Not Found"}.""" return jsonify({'msg': e.name}), e.code @private.route('/download/<site_id>/<int:param>', methods=['POST']) def home(site_id, param): """Attempt to download the file.""" if site_id in current_app.config['SITES']: site = current_app.config['SITES'][site_id] g.site = site url = site['url'].format(param) filename = site['filename'].format(param) path = join(site['path'], filename) download(url, path) return jsonify({}) raise NotFound @private.after_request def cors(response): """Handle browser cross-origin requests.""" if 'origin' in request.headers: site = g.get('site') if site: allowed_origin = site['origin'] response.headers['Access-Control-Allow-Origin'] = allowed_origin return response
# -*- coding: utf-8 -*- """These JSON-formatted views require authentication.""" from flask import Blueprint, jsonify, request, current_app, g from werkzeug.exceptions import NotFound from os.path import join from ..dl import download from ..error import handle_errors from ..util import enforce_auth private = Blueprint(__name__, 'private') private.before_request(enforce_auth) @handle_errors(private) def json_error(e): """Return an error response like {"msg":"Method not allowed"}.""" return jsonify({'msg': e.name}), e.code @private.route('/download/<site_id>/<int:param>', methods=['POST']) def home(site_id, param): """Attempt to download the file.""" if site_id in current_app.config['SITES']: site = current_app.config['SITES'][site_id] g.site = site url = site['url'].format(param) filename = site['filename'].format(param) path = join(site['path'], filename) download(url, path) return jsonify({}) raise NotFound @private.after_request def cors(response): """Handle browser cross-origin requests.""" if 'origin' in request.headers: site = g.get('site') if site: allowed_origin = site['origin'] response.headers['Access-Control-Allow-Origin'] = allowed_origin return response
Fix docker registry docker login test
package integration import ( "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("kismatic docker registry feature", func() { BeforeEach(func() { dir := setupTestWorkingDir() os.Chdir(dir) }) Describe("using an existing private docker registry", func() { ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) { WithInfrastructure(NodeCount{2, 1, 1, 0, 0}, Ubuntu1604LTS, aws, func(nodes provisionedNodes, sshKey string) { By("Installing an external Docker registry on one of the nodes") dockerRegistryPort := 8443 caFile, err := deployDockerRegistry(nodes.etcd[1], dockerRegistryPort, sshKey) Expect(err).ToNot(HaveOccurred()) opts := installOptions{ dockerRegistryCAPath: caFile, dockerRegistryIP: nodes.etcd[1].PrivateIP, dockerRegistryPort: dockerRegistryPort, dockerRegistryUsername: "kismaticuser", dockerRegistryPassword: "kismaticpassword", } nodes.etcd = []NodeDeets{nodes.etcd[0]} err = installKismatic(nodes, opts, sshKey) Expect(err).ToNot(HaveOccurred()) }) }) }) })
package integration import ( "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("kismatic docker registry feature", func() { BeforeEach(func() { dir := setupTestWorkingDir() os.Chdir(dir) }) Describe("using an existing private docker registry", func() { ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) { WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, Ubuntu1604LTS, aws, func(nodes provisionedNodes, sshKey string) { By("Installing an external Docker registry on one of the nodes") dockerRegistryPort := 8443 caFile, err := deployDockerRegistry(nodes.etcd[0], dockerRegistryPort, sshKey) Expect(err).ToNot(HaveOccurred()) opts := installOptions{ dockerRegistryCAPath: caFile, dockerRegistryIP: nodes.etcd[0].PrivateIP, dockerRegistryPort: dockerRegistryPort, dockerRegistryUsername: "kismaticuser", dockerRegistryPassword: "kismaticpassword", } err = installKismatic(nodes, opts, sshKey) Expect(err).ToNot(HaveOccurred()) }) }) }) })
Fix rule name in space after comma
'use strict'; var gonzales = require('gonzales-pe'), util = require('util'), merge = require('merge'); module.exports = { 'name': 'space-after-comma', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = [], determineResult; ast.traverseByType('operator', function (operator, i, parent) { var next; if (operator.content === ',') { next = parent.content[i + 1]; if (next.is('space')) { if (!parser.options.include) { result.push({ 'ruleId': parser.rule.name, 'line': next.start.line, 'column': next.start.column, 'message': 'Commas should not be followed by a space', 'severity': parser.severity }); } } else { if (parser.options.include) { result.push({ 'ruleId': parser.rule.name, 'line': operator.start.line, 'column': operator.start.column, 'message': 'Commas should be followed by a space', 'severity': parser.severity }); } } } }); return result; } }
'use strict'; var gonzales = require('gonzales-pe'), util = require('util'), merge = require('merge'); module.exports = { 'name': 'space-after-colon', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = [], determineResult; ast.traverseByType('operator', function (operator, i, parent) { var next; if (operator.content === ',') { next = parent.content[i + 1]; if (next.is('space')) { if (!parser.options.include) { result.push({ 'ruleId': parser.rule.name, 'line': next.start.line, 'column': next.start.column, 'message': 'Commas should not be followed by a space', 'severity': parser.severity }); } } else { if (parser.options.include) { result.push({ 'ruleId': parser.rule.name, 'line': operator.start.line, 'column': operator.start.column, 'message': 'Commas should be followed by a space', 'severity': parser.severity }); } } } }); return result; } }
Change all freepbx die() calls to die_freepbx()
<?php global $db; // Manage upgrade from DISA 1.0 // r2.0 Add Timeouts and add wait for confirmation $sql = "SELECT digittimeout FROM disa"; $check = $db->getRow($sql, DB_FETCHMODE_ASSOC); if(DB::IsError($check)) { // add new fields - Digit Timeout $sql = 'ALTER TABLE disa ADD COLUMN digittimeout INT DEFAULT "5"'; $result = $db->query($sql); if(DB::IsError($result)) { die_freepbx($result->getDebugInfo()); } // Response Timeout $sql = 'ALTER TABLE disa ADD COLUMN resptimeout INT DEFAULT "10"'; $result = $db->query($sql); if(DB::IsError($result)) { die_freepbx($result->getDebugInfo()); } $sql = 'ALTER TABLE disa ADD COLUMN needconf VARCHAR ( 10 ) DEFAULT ""'; $result = $db->query($sql); if(DB::IsError($result)) { die_freepbx($result->getDebugInfo()); } } ?>
<?php global $db; // Manage upgrade from DISA 1.0 // r2.0 Add Timeouts and add wait for confirmation $sql = "SELECT digittimeout FROM disa"; $check = $db->getRow($sql, DB_FETCHMODE_ASSOC); if(DB::IsError($check)) { // add new fields - Digit Timeout $sql = 'ALTER TABLE disa ADD COLUMN digittimeout INT DEFAULT "5"'; $result = $db->query($sql); if(DB::IsError($result)) { die($result->getDebugInfo()); } // Response Timeout $sql = 'ALTER TABLE disa ADD COLUMN resptimeout INT DEFAULT "10"'; $result = $db->query($sql); if(DB::IsError($result)) { die($result->getDebugInfo()); } $sql = 'ALTER TABLE disa ADD COLUMN needconf VARCHAR ( 10 ) DEFAULT ""'; $result = $db->query($sql); if(DB::IsError($result)) { die($result->getDebugInfo()); } } ?>
Fix inaccuracy caused by imprecision
var EventEmitter = require('events').EventEmitter , inherits = require('inherits') module.exports = fps // Try use performance.now(), otherwise try // +new Date. var now = ( (function(){ return this }()).performance && 'function' === typeof performance.now ) ? function() { return performance.now() } : function() { return +new Date } function fps(opts) { if (!(this instanceof fps)) return new fps(opts) EventEmitter.call(this) opts = opts || {} this.last = now() this.rate = 0 this.time = 0 this.decay = opts.decay || 1 this.every = opts.every || 1 this.ticks = 0 } inherits(fps, EventEmitter) fps.prototype.tick = function() { var time = now() , diff = time - this.last , fps = diff this.ticks += 1 this.last = time this.time += (fps - this.time) * this.decay this.rate = 1000 / this.time if (!(this.ticks % this.every)) this.emit('data', this.rate) }
var EventEmitter = require('events').EventEmitter , inherits = require('inherits') module.exports = fps // Try use performance.now(), otherwise try // +new Date. var now = ( (function(){ return this }()).performance && 'function' === typeof performance.now ) ? function() { return performance.now() } : function() { return +new Date } function fps(opts) { if (!(this instanceof fps)) return new fps(opts) EventEmitter.call(this) opts = opts || {} this.last = now() this.rate = 0 this.decay = opts.decay || 1 this.every = opts.every || 1 this.ticks = 0 } inherits(fps, EventEmitter) fps.prototype.tick = function() { var time = now() , diff = time - this.last , fps = 1000 / diff this.ticks += 1 this.last = time this.rate = this.rate + (fps - this.rate) * this.decay if (!(this.ticks % this.every)) this.emit('data', this.rate) }
Fix up imports after module has moved
#!/usr/bin/env python import ed25519 import hmac import baseconv class Crypt: """ Crypt - Creating site specific key pair - Signing SRQL response - Providing public key """ def __init__(self, masterkey): self.masterkey = masterkey def _site_key_pair(self, domain): seed = self._site_seed(domain) sk = ed25519.SigningKey(seed) vk = sk.get_verifying_key() return sk, vk def _site_seed(self, domain): """ Generates a seed to based on the masterkey and the current site you authenicating with The seed is used to generate the key pair used for signing the request body """ key = self.masterkey local_hmac = hmac.new(key) local_hmac.update(domain) return local_hmac.hexdigest() def sign(self, value): signed = self.sk.sign(value) return baseconv.encode(signed) def getPublicKey(self, domain): self.sk, self.vk = self._site_key_pair(domain) key = self.vk.to_bytes() return baseconv.encode(key)
#!/usr/bin/env python import ed25519 import hmac from sqrl.utils import baseconv class Crypt: """ Crypt - Creating site specific key pair - Signing SRQL response - Providing public key """ def __init__(self, masterkey): self.masterkey = masterkey def _site_key_pair(self, domain): seed = self._site_seed(domain) sk = ed25519.SigningKey(seed) vk = sk.get_verifying_key() return sk, vk def _site_seed(self, domain): """ Generates a seed to based on the masterkey and the current site you authenicating with The seed is used to generate the key pair used for signing the request body """ key = self.masterkey local_hmac = hmac.new(key) local_hmac.update(domain) return local_hmac.hexdigest() def sign(self, value): signed = self.sk.sign(value) return baseconv.encode(signed) def getPublicKey(self, domain): self.sk, self.vk = self._site_key_pair(domain) key = self.vk.to_bytes() return baseconv.encode(key)
Allow GrabPay to have payment in THB
define( [ 'ko', 'Omise_Payment/js/view/payment/omise-offsite-method-renderer', 'Magento_Checkout/js/view/payment/default', 'Magento_Checkout/js/model/quote', ], function ( ko, Base, Component, quote ) { 'use strict'; return Component.extend(Base).extend({ defaults: { template: 'Omise_Payment/payment/offsite-grabpay-form' }, isPlaceOrderActionAllowed: ko.observable(quote.billingAddress() != null), code: 'omise_offsite_grabpay', restrictedToCurrencies: ['thb', 'sgd', 'myr'] }); } );
define( [ 'ko', 'Omise_Payment/js/view/payment/omise-offsite-method-renderer', 'Magento_Checkout/js/view/payment/default', 'Magento_Checkout/js/model/quote', ], function ( ko, Base, Component, quote ) { 'use strict'; return Component.extend(Base).extend({ defaults: { template: 'Omise_Payment/payment/offsite-grabpay-form' }, isPlaceOrderActionAllowed: ko.observable(quote.billingAddress() != null), code: 'omise_offsite_grabpay', restrictedToCurrencies: ['sgd', 'myr'] }); } );
TST: Test of error estimation of Runge-Kutta methods
import pytest from numpy.testing import assert_allclose, assert_ import numpy as np from scipy.integrate import RK23, RK45, DOP853 from scipy.integrate._ivp import dop853_coefficients @pytest.mark.parametrize("solver", [RK23, RK45, DOP853]) def test_coefficient_properties(solver): assert_allclose(np.sum(solver.B), 1, rtol=1e-15) assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14) def test_coefficient_properties_dop853(): assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15) assert_allclose(np.sum(dop853_coefficients.A, axis=1), dop853_coefficients.C, rtol=1e-14) @pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853]) def test_error_estimation(solver_class): step = 0.2 solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step) solver.step() error_estimate = solver._estimate_errors(solver.K, step) error = solver.y - np.exp([step]) assert_(np.abs(error) < np.abs(error_estimate))
import pytest from numpy.testing import assert_allclose import numpy as np from scipy.integrate import RK23, RK45, DOP853 from scipy.integrate._ivp import dop853_coefficients @pytest.mark.parametrize("solver", [RK23, RK45, DOP853]) def test_coefficient_properties(solver): assert_allclose(np.sum(solver.B), 1, rtol=1e-15) assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14) def test_coefficient_properties_dop853(): assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15) assert_allclose(np.sum(dop853_coefficients.A, axis=1), dop853_coefficients.C, rtol=1e-14)
Allow resolverNoCache config option to be passed to envelope headers
/* global _postal, SubscriptionDefinition, _config, _ */ var ChannelDefinition = function( channelName, bus ) { this.bus = bus; this.channel = channelName || _config.DEFAULT_CHANNEL; }; ChannelDefinition.prototype.subscribe = function() { return this.bus.subscribe( { channel: this.channel, topic: ( arguments.length === 1 ? arguments[ 0 ].topic : arguments[ 0 ] ), callback: ( arguments.length === 1 ? arguments[ 0 ].callback : arguments[ 1 ] ) } ); }; /* publish( envelope [, callback ] ); publish( topic, data [, callback ] ); */ ChannelDefinition.prototype.publish = function() { var envelope = {}; var callback; if ( typeof arguments[ 0 ] === "string" ) { envelope.topic = arguments[ 0 ]; envelope.data = arguments[ 1 ]; callback = arguments[ 2 ]; } else { envelope = arguments[ 0 ]; callback = arguments[ 1 ]; } if ( typeof envelope !== "object" ) { throw new Error( "The first argument to ChannelDefinition.publish should be either an envelope object or a string topic." ); } envelope.headers = _.extend( envelope.headers || {}, _.pick( _config, [ "resolverNoCache" ] ) ); envelope.channel = this.channel; this.bus.publish( envelope, callback ); };
/* global _postal, SubscriptionDefinition, _config, _ */ var ChannelDefinition = function( channelName, bus ) { this.bus = bus; this.channel = channelName || _config.DEFAULT_CHANNEL; }; ChannelDefinition.prototype.subscribe = function() { return this.bus.subscribe( { channel: this.channel, topic: ( arguments.length === 1 ? arguments[ 0 ].topic : arguments[ 0 ] ), callback: ( arguments.length === 1 ? arguments[ 0 ].callback : arguments[ 1 ] ) } ); }; /* publish( envelope [, callback ] ); publish( topic, data [, callback ] ); */ ChannelDefinition.prototype.publish = function() { var envelope = {}; var callback; if ( typeof arguments[ 0 ] === "string" ) { envelope.topic = arguments[ 0 ]; envelope.data = arguments[ 1 ]; callback = arguments[ 2 ]; } else { envelope = arguments[ 0 ]; callback = arguments[ 1 ]; } if ( typeof envelope !== "object" ) { throw new Error( "The first argument to ChannelDefinition.publish should be either an envelope object or a string topic." ); } envelope.channel = this.channel; this.bus.publish( envelope, callback ); };
Change to LinkedHashSet to keep insertion order.
package typecheck; import java.util.*; public class SubtypingRelation { private static Map<Symbol, Set<Symbol>> relation = new LinkedHashMap<>(); public static void insert(Symbol base, Symbol child) { relation.putIfAbsent(base, new LinkedHashSet<>()); relation.get(base).add(child); // Subtyping is transitive for (Iterator<Symbol> it = relation.keySet().iterator(); it.hasNext(); ) { Symbol s = it.next(); if (s.equals(base)) { Set<Symbol> children = relation.get(s); if (children.contains(base)) children.add(child); } } } public static boolean isSubtyping(Symbol child, Symbol base) { if (relation.containsKey(base)) return relation.get(base).contains(child); else return false; } public static boolean contains(Symbol c) { return relation.containsKey(c); } }
package typecheck; import java.util.*; public class SubtypingRelation { private static Map<Symbol, Set<Symbol>> relation = new LinkedHashMap<>(); public static void insert(Symbol base, Symbol child) { relation.putIfAbsent(base, new HashSet<>()); relation.get(base).add(child); // Subtyping is transitive for (Iterator<Symbol> it = relation.keySet().iterator(); it.hasNext(); ) { Symbol s = it.next(); if (s.equals(base)) { Set<Symbol> children = relation.get(s); if (children.contains(base)) children.add(child); } } } public static boolean isSubtyping(Symbol child, Symbol base) { if (relation.containsKey(base)) return relation.get(base).contains(child); else return false; } public static boolean contains(Symbol c) { return relation.containsKey(c); } }
Change selector string so the query only returns headings with ids
var addHeadingAnchors = { init: function (selector) { this.target = document.querySelector(selector); if (this.target) { this.addAnchorsToHeadings(); } }, addAnchorsToHeadings: function () { var selectorString = 'h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]', headings = this.target.querySelectorAll(selectorString) headings.forEach(function (heading) { var anchor = this.createAnchor(heading.id); heading.appendChild(anchor); }.bind(this)); }, createAnchor: function (id) { var anchor = document.createElement('a'), anchorText = document.createTextNode('¶'), attributes = { href: id, class: 'headerLink', title: 'Permalink to this headline' }; anchor.appendChild(anchorText); for (var attr in attributes) { anchor.setAttribute(attr, attributes[attr]); } return anchor; } };
var addHeadingAnchors = { init: function (selector) { this.target = document.querySelector(selector); if (this.target) { this.addAnchorsToHeadings(); } }, addAnchorsToHeadings: function () { var headings = this.target.querySelectorAll('h1, h2, h3, h4, h5, h6'), id; headings.forEach(function (heading) { if (id = heading.id) { var anchor = this.createAnchor(id); heading.appendChild(anchor); } }.bind(this)); }, createAnchor: function (id) { var anchor = document.createElement('a'), anchorText = document.createTextNode('¶'), attributes = { href: id, class: 'headerLink', title: 'Permalink to this headline' }; anchor.appendChild(anchorText); for (var attr in attributes) { anchor.setAttribute(attr, attributes[attr]); } return anchor; } };
Add band members as unassigned to new bands
from rest_framework import serializers from members.models import Band from members.models import BandMember class BandMemberSerializer(serializers.ModelSerializer): class Meta: model = BandMember fields = ('id', 'account', 'section', 'instrument_number', 'band', 'created_at', 'updated_at',) read_only_fields = ('account', 'created_at', 'updated_at',) class BandSerializer(serializers.ModelSerializer): class Meta: model = Band fields = ('id', 'identifier', 'created_at', 'updated_at',) read_only_fields = ('created_at', 'updated_at',) def create(self, validated_data): band = Band.objects.create(**validated_data) band.unassigned_members = BandMember.objects.all() band.save() return band
from rest_framework import serializers from members.models import Band from members.models import BandMember class BandMemberSerializer(serializers.ModelSerializer): class Meta: model = BandMember fields = ('id', 'account', 'section', 'instrument_number', 'band', 'created_at', 'updated_at',) read_only_fields = ('account', 'created_at', 'updated_at',) class BandSerializer(serializers.ModelSerializer): class Meta: model = Band fields = ('id', 'identifier', 'created_at', 'updated_at',) read_only_fields = ('created_at', 'updated_at',)
Add 'nan' to list of packages to remove from shrinkwrap
/* eslint-disable no-var */ // NPM 5 now adds optional dependencies, which older versions of npm // try to install even if it is the wrong architecture. var fs = require('fs'); var toRemove = ['fsevents', 'nan']; var shrinkwrap = JSON.parse(fs.readFileSync('../npm-shrinkwrap.json')); function cleanRequires(requires) { toRemove.forEach(dep => { if (dep in requires) { console.log('removing requires', dep); delete requires[dep]; } }); } function cleanDependencies(dependencies) { Object.keys(dependencies).forEach(dep => { if (toRemove.indexOf(dep) > -1) { console.log('removing dep', dep); delete dependencies[dep]; } else { if (dependencies[dep].dependencies) { cleanDependencies(dependencies[dep].dependencies); } if (dependencies[dep].requires) { cleanRequires(dependencies[dep].requires); } } }); } cleanDependencies(shrinkwrap.dependencies); fs.writeFileSync('../npm-shrinkwrap.json', `${JSON.stringify(shrinkwrap, null, 2)}\n`);
/* eslint-disable no-var */ // NPM 5 now adds optional dependencies, which older versions of npm // try to install even if it is the wrong architecture. var fs = require('fs'); var toRemove = ['fsevents']; var shrinkwrap = JSON.parse(fs.readFileSync('../npm-shrinkwrap.json')); function cleanRequires(requires) { toRemove.forEach(dep => { if (dep in requires) { console.log('removing requires', dep); delete requires[dep]; } }); } function cleanDependencies(dependencies) { Object.keys(dependencies).forEach(dep => { if (toRemove.indexOf(dep) > -1) { console.log('removing dep', dep); delete dependencies[dep]; } else { if (dependencies[dep].dependencies) { cleanDependencies(dependencies[dep].dependencies); } if (dependencies[dep].requires) { cleanRequires(dependencies[dep].requires); } } }); } cleanDependencies(shrinkwrap.dependencies); fs.writeFileSync('../npm-shrinkwrap.json', `${JSON.stringify(shrinkwrap, null, 2)}\n`);
feat(TrelloProvider): Use 'scope' in TrelloProvider auth params. Allows overriding from django settings.
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): id = 'trello' name = 'Trello' account_class = TrelloAccount def get_default_scope(self): return ['read'] def extract_uid(self, data): return data['id'] def get_auth_params(self, request, action): data = super(TrelloProvider, self).get_auth_params(request, action) app = self.get_app(request) data['type'] = 'web_server' data['name'] = app.name data['scope'] = self.get_scope(request) # define here for how long it will be, this can be configured on the # social app data['expiration'] = 'never' return data provider_classes = [TrelloProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): id = 'trello' name = 'Trello' account_class = TrelloAccount def get_default_scope(self): return ['read'] def extract_uid(self, data): return data['id'] def get_auth_params(self, request, action): data = super(TrelloProvider, self).get_auth_params(request, action) app = self.get_app(request) data['type'] = 'web_server' data['name'] = app.name # define here for how long it will be, this can be configured on the # social app data['expiration'] = 'never' return data provider_classes = [TrelloProvider]
Include semantic ui as extra asset
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var Funnel = require('broccoli-funnel'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Any other options }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.js'); // Included as separate file in index.html // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.css'); // Included as separate file in index.html var extraAssets = new Funnel(app.bowerDirectory + '/semantic-ui', { srcDir: '/dist', include: ['**/*.*'], destDir: '/assets/semantic-ui' }); return app.toTree(extraAssets); };
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Any other options }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.js'); app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.css'); return app.toTree(); };
Use GeoLIte2 in benchmark example
import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.Random; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.net.InetAddresses; import com.maxmind.maxminddb.InvalidDatabaseException; import com.maxmind.maxminddb.MaxMindDbReader; import com.maxmind.maxminddb.MaxMindDbReader.FileMode; public class Benchmark { public static void main(String[] args) throws IOException, InvalidDatabaseException { File file = new File("GeoLite2-City.mmdb"); MaxMindDbReader r = new MaxMindDbReader(file, FileMode.MEMORY_MAPPED); Random random = new Random(); int count = 1000000; long startTime = System.nanoTime(); for (int i = 0; i < count; i++) { InetAddress ip = InetAddresses.fromInteger(random.nextInt()); if (i % 50000 == 0) { System.out.println(i + " " + ip); } JsonNode t = r.get(ip); } long endTime = System.nanoTime(); long duration = endTime - startTime; System.out.println("Requests per second: " + count * 1000000000.0 / (duration)); } }
import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.Random; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.net.InetAddresses; import com.maxmind.maxminddb.InvalidDatabaseException; import com.maxmind.maxminddb.MaxMindDbReader; import com.maxmind.maxminddb.MaxMindDbReader.FileMode; public class Benchmark { public static void main(String[] args) throws IOException, InvalidDatabaseException { File file = new File("GeoIP2-City.mmdb"); MaxMindDbReader r = new MaxMindDbReader(file, FileMode.MEMORY_MAPPED); Random random = new Random(); int count = 1000000; long startTime = System.nanoTime(); for (int i = 0; i < count; i++) { InetAddress ip = InetAddresses.fromInteger(random.nextInt()); if (i % 50000 == 0) { System.out.println(i + " " + ip); } JsonNode t = r.get(ip); } long endTime = System.nanoTime(); long duration = endTime - startTime; System.out.println("Requests per second: " + count * 1000000000.0 / (duration)); } }
Fix bootstrap class for qTip2 master
define(['backbone', 'timetable_data'], function(Backbone, timetable_data) { 'use strict'; var AppView = Backbone.View.extend({ el: 'body', events: { 'show a[href="#module-finder"]': 'showModuleFinder', 'show a[href="#timetable-builder"]': 'showTimetableBuilder' }, initialize: function() { $.ajaxSetup({ cache: true }); // [Override](http://craigsworks.com/projects/qtip2/tutorials/advanced/#override) // default tooltip settings. $.fn.qtip.defaults.position.my = 'bottom center'; $.fn.qtip.defaults.position.at = 'top center'; $.fn.qtip.defaults.position.viewport = true; $.fn.qtip.defaults.show.solo = true; $.fn.qtip.defaults.style.classes = 'qtip-bootstrap'; $('#correct-as-at').text(timetable_data.correctAsAt); $('.container-fluid').show(); }, showModuleFinder: function() { Backbone.history.navigate('modules'); $('#selected-mods').prependTo('#module-finder .span3'); }, showTimetableBuilder: function() { Backbone.history.navigate('timetable'); $('#selected-mods').appendTo('#show-hide-selected-mods-container'); } }); return AppView; });
define(['backbone', 'timetable_data'], function(Backbone, timetable_data) { 'use strict'; var AppView = Backbone.View.extend({ el: 'body', events: { 'show a[href="#module-finder"]': 'showModuleFinder', 'show a[href="#timetable-builder"]': 'showTimetableBuilder' }, initialize: function() { $.ajaxSetup({ cache: true }); // [Override](http://craigsworks.com/projects/qtip2/tutorials/advanced/#override) // default tooltip settings. $.fn.qtip.defaults.position.my = 'bottom center'; $.fn.qtip.defaults.position.at = 'top center'; $.fn.qtip.defaults.position.viewport = true; $.fn.qtip.defaults.show.solo = true; $.fn.qtip.defaults.style.classes = 'ui-tooltip-bootstrap'; $('#correct-as-at').text(timetable_data.correctAsAt); $('.container-fluid').show(); }, showModuleFinder: function() { Backbone.history.navigate('modules'); $('#selected-mods').prependTo('#module-finder .span3'); }, showTimetableBuilder: function() { Backbone.history.navigate('timetable'); $('#selected-mods').appendTo('#show-hide-selected-mods-container'); } }); return AppView; });
Change service state to real
package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ServiceState; import java.io.IOException; import java.security.GeneralSecurityException; public class ProxyFactory { protected ServiceState getServiceState() { return ServiceState.REAL; } public static ProxyFactory getProxyFactory() { return new ProxyFactory(); } public CameraProxy getCamera() { return new CameraProxy(getServiceState()); } public GoogleApiServiceProxy getGoogleApiProxy() { return new GoogleApiServiceProxy(getServiceState()); } public HouseRegistryServiceProxy getHouseRegistryService() { return new HouseRegistryServiceProxy(getServiceState()); } }
package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ServiceState; import java.io.IOException; import java.security.GeneralSecurityException; public class ProxyFactory { protected ServiceState getServiceState() { return ServiceState.DEV; } public static ProxyFactory getProxyFactory() { return new ProxyFactory(); } public CameraProxy getCamera() { return new CameraProxy(getServiceState()); } public GoogleApiServiceProxy getGoogleApiProxy() { return new GoogleApiServiceProxy(getServiceState()); } public HouseRegistryServiceProxy getHouseRegistryService() { return new HouseRegistryServiceProxy(getServiceState()); } }
Speed up webpack process by removing sourcemap from test process - needs more work here
var webpack = require('webpack'); module.exports = function (config) { config.set({ browsers: [ 'PhantomJS' ], // Use PhantomJS for now (@gordyd - I'm using a VM) singleRun: true, frameworks: [ 'mocha', 'sinon' ], // Mocha is our testing framework of choice files: [ 'tests.webpack.js' // We're using Webpack to build ], preprocessors: { 'tests.webpack.js': [ 'webpack', 'sourcemap' ] // Preprocess with webpack and our sourcemap loader }, reporters: [ 'mocha' ], webpack: { // Simplified Webpack configuration module: { loaders: [ { test: /\.js$/, loader: 'jsx-loader' }, { test: /\.json$/, loader: 'json-loader' } ] } }, webpackServer: { noInfo: true // We don't want webpack output } }); };
var webpack = require('webpack'); module.exports = function (config) { config.set({ browsers: [ 'PhantomJS' ], // use PhantomJS for now (@gordyd - I'm using a VM) singleRun: true, frameworks: [ 'mocha', 'sinon' ], // Mocha is our testing framework of choice files: [ 'tests.webpack.js' //just load this file ], preprocessors: { 'tests.webpack.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader }, reporters: [ 'mocha' ], webpack: { // kind of a copy of your webpack config devtool: 'inline-source-map', //just do inline source maps instead of the default module: { loaders: [ { test: /\.js$/, loader: 'jsx-loader' }, { test: /\.json$/, loader: 'json-loader' } ] } }, webpackServer: { noInfo: true //please don't spam the console when running in karma! } }); };
hain-plugin-math: Copy result into clipboard on execute equation
'use strict'; const lo_isNumber = require('lodash.isnumber'); const lo_isString = require('lodash.isstring'); const lo_isObject = require('lodash.isobject'); const lo_has = require('lodash.has'); const math = require('mathjs'); module.exports = (context) => { const app = context.app; const clipboard = context.clipboard; const toast = context.toast; function search(query, res) { try { const ans = math.eval(query); if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) { res.add({ title: `${query.trim()} = ${ans.toString()}`, group: 'Math', payload: ans.toString() }); } } catch (e) { } } function execute(id, payload) { app.setQuery(`=${payload}`); clipboard.writeText(payload); toast.enqueue(`${payload} has copied into clipboard`); } return { search, execute }; };
'use strict'; const lo_isNumber = require('lodash.isnumber'); const lo_isString = require('lodash.isstring'); const lo_isObject = require('lodash.isobject'); const lo_has = require('lodash.has'); const math = require('mathjs'); module.exports = ({ app }) => { function search(query, res) { try { const ans = math.eval(query); if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) { res.add({ title: `${query.trim()} = ${ans.toString()}`, group: 'Math', payload: ans.toString() }); } } catch (e) { } } function execute(id, payload) { app.setInput(`=${payload}`); } return { search, execute }; };
Add .full to text module if no box
<?php if (get_field('hide_box_frame', $module->ID)) : ?> <article class="no-margin full <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>"> <?php if (!$module->hideTitle && !empty($module->post_title)) : ?> <h1><?php echo apply_filters('the_title', $module->post_title); ?></h1> <?php endif; ?> <?php echo apply_filters('the_content', $module->post_content); ?> </article> <?php else : ?> <div class="<?php echo implode(' ', apply_filters('Modularity/Module/Classes', array('box', 'box-panel'), $module->post_type, $args)); ?> <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>"> <?php if (!$module->hideTitle && !empty($module->post_title)) : ?> <h4 class="box-title"><?php echo apply_filters('the_title', $module->post_title); ?></h4> <?php endif; ?> <div class="box-content"> <?php echo apply_filters('the_content', $module->post_content); ?> </div> </div> <?php endif; ?>
<?php if (get_field('hide_box_frame', $module->ID)) : ?> <article class="no-margin <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>"> <?php if (!$module->hideTitle && !empty($module->post_title)) : ?> <h1><?php echo apply_filters('the_title', $module->post_title); ?></h1> <?php endif; ?> <?php echo apply_filters('the_content', $module->post_content); ?> </article> <?php else : ?> <div class="<?php echo implode(' ', apply_filters('Modularity/Module/Classes', array('box', 'box-panel'), $module->post_type, $args)); ?> <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>"> <?php if (!$module->hideTitle && !empty($module->post_title)) : ?> <h4 class="box-title"><?php echo apply_filters('the_title', $module->post_title); ?></h4> <?php endif; ?> <div class="box-content"> <?php echo apply_filters('the_content', $module->post_content); ?> </div> </div> <?php endif; ?>
Remove the debug option, it didn't do anything.
<?php defined('SYSPATH') or die('No direct script access.'); return array( /** * Gzip can dramatically reduce the size of the sitemap. We recommend you use * this option with more than 1,000 entries. Gzipped entries are computed by * appending the .gz extension to the url (sitemap.xml.gz) */ 'gzip' => array ( 'enabled' => TRUE, /* * From 1-9 */ 'level' => 9 ), /** * Array of URLs to ping. This lets the provider know you have updated your * sitemap. sprintf string. */ 'ping' => array ( 'Google' => 'http://www.google.com/webmasters/tools/ping?sitemap=%s', 'Yahoo' => 'http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=%s', 'Ask' => 'http://submissions.ask.com/ping?sitemap=%s', 'Bing' => 'http://www.bing.com/webmaster/ping.aspx?siteMap=%s', 'MoreOver' => 'http://api.moreover.com/ping?u=%s' ) );
<?php defined('SYSPATH') or die('No direct script access.'); return array( /** * Gzip can dramatically reduce the size of the sitemap. We recommend you use * this option with more than 1,000 entries. Gzipped entries are computed by * appending the .gz extension to the url (sitemap.xml.gz) */ 'gzip' => array ( 'enabled' => TRUE, /* * From 1-9 */ 'level' => 9 ), /** * Array of URLs to ping. This lets the provider know you have updated your * sitemap. sprintf string. */ 'ping' => array ( 'Google' => 'http://www.google.com/webmasters/tools/ping?sitemap=%s', 'Yahoo' => 'http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=%s', 'Ask' => 'http://submissions.ask.com/ping?sitemap=%s', 'Bing' => 'http://www.bing.com/webmaster/ping.aspx?siteMap=%s', 'MoreOver' => 'http://api.moreover.com/ping?u=%s' ), /** * When enabled, extra detail is logged * HTTP status code from ping */ 'debug' => FALSE );
Remove unnecessary line to load configs Remove line that loads RegistryConfigSettings from RegistryConfigTest. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=148236844
// Copyright 2017 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.config; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class RegistryConfigTest { public RegistryConfigTest() {} @Test public void test_clientSecretFilename() { // Verify that we're pulling this from the default. assertThat(RegistryConfig.getClientSecretFilename()).isEqualTo( "/google/registry/tools/resources/client_secret.json"); } }
// Copyright 2017 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.config; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class RegistryConfigTest { public RegistryConfigTest() {} @Test public void test_clientSecretFilename() { RegistryConfigSettings unused = YamlUtils.getConfigSettings(); // Verify that we're pulling this from the default. assertThat(RegistryConfig.getClientSecretFilename()).isEqualTo( "/google/registry/tools/resources/client_secret.json"); } }
Use fread() instead of socket_recv_from()
<?php namespace React\Socket; use Evenement\EventEmitter; use React\EventLoop\LoopInterface; use React\Stream\WritableStreamInterface; use React\Stream\Buffer; use React\Stream\Stream; use React\Stream\Util; class Connection extends Stream implements ConnectionInterface { public function handleData($stream) { $data = fread($stream, $this->bufferSize); if ('' === $data || false === $data) { $this->end(); } else { $this->emit('data', array($data, $this)); } } public function handleClose() { if (is_resource($this->stream)) { stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR); fclose($this->stream); } } public function getRemoteAddress() { return $this->parseAddress(stream_socket_get_name($this->stream, true)); } private function parseAddress($address) { return trim(substr($address, 0, strrpos($address, ':')), '[]'); } }
<?php namespace React\Socket; use Evenement\EventEmitter; use React\EventLoop\LoopInterface; use React\Stream\WritableStreamInterface; use React\Stream\Buffer; use React\Stream\Stream; use React\Stream\Util; class Connection extends Stream implements ConnectionInterface { public function handleData($stream) { $data = stream_socket_recvfrom($stream, $this->bufferSize); if ('' === $data || false === $data) { $this->end(); } else { $this->emit('data', array($data, $this)); } } public function handleClose() { if (is_resource($this->stream)) { stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR); fclose($this->stream); } } public function getRemoteAddress() { return $this->parseAddress(stream_socket_get_name($this->stream, true)); } private function parseAddress($address) { return trim(substr($address, 0, strrpos($address, ':')), '[]'); } }
Make test hooks optonal to run example/fib.jsx
/* test launcher invoked by jsx --test */ function $__jsx_runTests(testClass, tests) { if (!testClass) return; // skip if there's no test class if(tests.length === 0) { var p = testClass.prototype; for (var m in p) { if (p[m] instanceof Function && /^test.*[$]$/.test(m)) { tests.push(m); } } } if (tests.length === 0) { return; } var tasks = []; var test = new testClass(); if (test.beforeClass$AS != null) test.beforeClass$AS(tests); for (var i = 0; i < tests.length; ++i) { (function (m) { tasks.push(function() { if (test.before$S != null) test.before$S(m); test.done$ = function () { if (test.after$S != null) test.after$S(m); if (tasks.length !== 0) { var next = tasks.shift(); next(); } else { // all the tasks finished if (test.afterClass$ != null) test.afterClass$(); } }; test[m](); }); }(tests[i])); } var start = tasks.shift(); start(); }
/* test launcher invoked by jsx --test */ function $__jsx_runTests(testClass, tests) { if (!testClass) return; // skip if there's no test class if(tests.length === 0) { var p = testClass.prototype; for (var m in p) { if (p[m] instanceof Function && /^test.*[$]$/.test(m)) { tests.push(m); } } } if (tests.length === 0) { return; } var tasks = []; var test = new testClass(); test.beforeClass$AS(tests); for(var i = 0; i < tests.length; ++i) { (function (m) { tasks.push(function() { test.done$ = function () { test.after$S(m); if (tasks.length !== 0) { var next = tasks.shift(); next(); } else { // all the tasks finished test.afterClass$(); } }; test.before$S(m); test[m](); }); }(tests[i])); } var start = tasks.shift(); start(); }
Make babelify generate source maps with relative paths
const gulp = require("gulp"); const del = require("del"); const browserify = require("browserify"); const babelify = require("babelify"); const src = require("vinyl-source-stream"); const source = "src"; const target = "build"; gulp.task("js", function () { return browserify({entries: `${source}/js/app.js`, debug: true}) .transform(babelify.configure({sourceMapRelative: `${__dirname}/`})) .bundle() .pipe(src("app.js")) .pipe(gulp.dest(`${target}/js`)); }); gulp.task("files", function () { return gulp.src(`${source}/files/**/*`) .pipe(gulp.dest(target)); }); gulp.task("clean", function (cb) { del(`${target}/*`, cb); }); gulp.task("default", ["clean"], function () { gulp.start("js", "files"); }); gulp.task("watch", ["default"], function () { gulp.watch(`${source}/js/**/*.js`, ["js"]); gulp.watch(`${source}/files/**/*`, ["files"]); });
const gulp = require("gulp"); const del = require("del"); const browserify = require("browserify"); const babelify = require("babelify"); const src = require("vinyl-source-stream"); const source = "src"; const target = "build"; gulp.task("js", function () { return browserify({entries: `${source}/js/app.js`, debug: true}) .transform(babelify) .bundle() .pipe(src("app.js")) .pipe(gulp.dest(`${target}/js`)); }); gulp.task("files", function () { return gulp.src(`${source}/files/**/*`) .pipe(gulp.dest(target)); }); gulp.task("clean", function (cb) { del(`${target}/*`, cb); }); gulp.task("default", ["clean"], function () { gulp.start("js", "files"); }); gulp.task("watch", ["default"], function () { gulp.watch(`${source}/js/**/*.js`, ["js"]); gulp.watch(`${source}/files/**/*`, ["files"]); });
Add request to API auth
<?php namespace Bishopm\Connexion\Http\Controllers\Auth; use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class ApiAuthController extends Controller { public function login(Request $request) { // grab credentials from the request $credentials = $request->only('name', 'password'); Log::info('API login attempt: ' . $credentials); try { // attempt to verify the credentials and create a token for the user if (! $token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could_not_create_token'], 500); } // all good so return the token return response()->json(compact('token')); } }
<?php namespace Bishopm\Connexion\Http\Controllers\Auth; use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Log; class ApiAuthController extends Controller { public function login(Request $request) { // grab credentials from the request $credentials = $request->only('name', 'password'); Log::info('API login attempt: ' . $credentials); try { // attempt to verify the credentials and create a token for the user if (! $token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could_not_create_token'], 500); } // all good so return the token return response()->json(compact('token')); } }
[COLAB-2469] Fix class for member activities
package org.xcolab.client.activities.enums; import java.util.Arrays; public enum ActivityCategory { MEMBER(MemberActivityType.values()), DISCUSSION(DiscussionActivityType.values()), PROPOSAL(ProposalActivityType.values()), CONTEST(ContestActivityType.values()); private final ActivityType[] activityTypes; ActivityCategory(ActivityType[] activityTypes) { this.activityTypes = activityTypes; } public ActivityType getActivityType(String activityType) { return Arrays.stream(activityTypes) .filter(s -> s.name().equalsIgnoreCase(activityType)) .findAny() .orElseThrow(() -> new IllegalArgumentException( "No enum constant " + name() + "." + activityType)); } }
package org.xcolab.client.activities.enums; import java.util.Arrays; public enum ActivityCategory { MEMBER(ContestActivityType.values()), DISCUSSION(DiscussionActivityType.values()), PROPOSAL(ProposalActivityType.values()), CONTEST(ContestActivityType.values()); private final ActivityType[] activityTypes; ActivityCategory(ActivityType[] activityTypes) { this.activityTypes = activityTypes; } public ActivityType getActivityType(String activityType) { return Arrays.stream(activityTypes) .filter(s -> s.name().equalsIgnoreCase(activityType)) .findAny() .orElseThrow(() -> new IllegalArgumentException( "No enum constant " + name() + "." + activityType)); } }
Fix variable name (clashes with process)
var exec = require('child_process').exec; var Tunnel = function Tunnel (key, port, callback, err) { var tunnelCommand = 'java -jar ~/.browserstack/BrowserStackTunnel.jar '; tunnelCommand += key + ' '; tunnelCommand += 'localhost' + ','; tunnelCommand += port.toString() + ','; tunnelCommand += '0'; if (typeof callback !== 'function') { callback = function () {}; } console.log("Launching tunnel.."); var subProcess = exec(tunnelCommand, function (error, stdout, stderr) { if (stdout.indexOf('Error') >= 0) { console.log("..Failed"); console.log(stdout); } }); var data = ''; var running = false; var runMatcher = "You can now access your local server(s)"; subProcess.stdout.on('data', function (_data) { if (running) { return; } data += _data; if (data.indexOf(runMatcher) >= 0) { running = true; console.log("..Done"); callback(); } running = true; }); var that = { process: subProcess, }; return that; } exports.Tunnel = Tunnel;
var exec = require('child_process').exec; var Tunnel = function Tunnel (key, port, callback, err) { var tunnelCommand = 'java -jar ~/.browserstack/BrowserStackTunnel.jar '; tunnelCommand += key + ' '; tunnelCommand += 'localhost' + ','; tunnelCommand += port.toString() + ','; tunnelCommand += '0'; if (typeof callback !== 'function') { callback = function () {}; } console.log("Launching tunnel.."); var process = exec(tunnelCommand, function (error, stdout, stderr) { if (stdout.indexOf('Error') >= 0) { console.log("..Failed"); console.log(stdout); } }); var data = ''; var running = false; var runMatcher = "You can now access your local server(s)"; process.stdout.on('data', function (_data) { if (running) { return; } data += _data; if (data.indexOf(runMatcher) >= 0) { running = true; console.log("..Done"); callback(); } running = true; }); var that = { process: process, }; return that; } exports.Tunnel = Tunnel;
Set the transaction for the hash explorer in history page details
angular.module('omniControllers') .controller('WalletHistoryController', ["$scope", "$q", "$http", "hashExplorer", "$translate", function WalletHistoryController($scope, $q, $http, hashExplorer, $translate) { $scope.showtesteco = $scope.account.getSetting('showtesteco'); $scope.history = $scope.wallet.transactions($scope.showtesteco); $scope.changeAddress=function(address){ if(address){ $scope.selectedAddress = address; $scope.history = address.transactions.filter(function(tx){ return ((tx.currency.propertyid < 2147483648 && tx.currency.propertyid != 2) || $scope.showtesteco === 'true'); }); } else { $scope.selectedAddress = undefined; $scope.history = $scope.wallet.transactions($scope.showtesteco); } } $scope.setHashExplorer=function(transaction){ $http.get('/v1/transaction/tx/' + transaction.hash + '.json'). success(function(data) { hashExplorer.setHash(data[0]); }); } }])
angular.module('omniControllers') .controller('WalletHistoryController', ["$scope", "$q", "$http", "hashExplorer", "$translate", function WalletHistoryController($scope, $q, $http, hashExplorer, $translate) { $scope.setHashExplorer = hashExplorer.setHash.bind(hashExplorer); $scope.showtesteco = $scope.account.getSetting('showtesteco'); $scope.history = $scope.wallet.transactions($scope.showtesteco); $scope.changeAddress=function(address){ if(address){ $scope.selectedAddress = address; $scope.history = address.transactions.filter(function(tx){ return ((tx.currency.propertyid < 2147483648 && tx.currency.propertyid != 2) || $scope.showtesteco === 'true'); }); } else { $scope.selectedAddress = undefined; $scope.history = $scope.wallet.transactions($scope.showtesteco); } } }])
Add error message for 401
<?php /** * Copyright 2015 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed in the hopes of * attracting more community contributions to the core ecosystem of osu! * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'codes' => [ 'http-403' => 'Access denied.', 'http-401' => 'Please login to proceed.', ], 'supporter_only' => 'You must be a supporter to use this feature.', 'unknown' => 'Unknown error occurred.', ];
<?php /** * Copyright 2015 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed in the hopes of * attracting more community contributions to the core ecosystem of osu! * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'codes' => [ 'http-403' => 'Access denied.', ], 'supporter_only' => 'You must be a supporter to use this feature.', 'unknown' => 'Unknown error occurred.', ];
Refactor LargestQ.combine() to use built-ins.
/** * checks if there are scores which can be combined */ function checkValidity (scores) { if (scores == null) { throw new Error('There must be a scores object parameter') } if (Object.keys(scores).length <= 0) { throw new Error('At least one score must be passed') } } /** * Score canidate based on the mean value of two or more parent Qs. */ class MeanQ { /** * Returns the mean value of the given scores. * @param scores - obect that contains the keys and scores * for each used scoring method * @return mean value of given scores */ combine (scores) { checkValidity(scores) var sum = 0 Object.keys(scores).map((key, index, arr) => { sum += scores[key] }) return sum / Object.keys(scores).length } } /** * Chooses the biggest score out of all possible scores */ class LargestQ { /** * combines all scores by choosing the largest score */ combine (scores) { checkValidity(scores) return Math.max.apply(null, Object.values(scores)) } } module.exports = { Mean: MeanQ, Largest: LargestQ }
/** * checks if there are scores which can be combined */ function checkValidity (scores) { if (scores == null) { throw new Error('There must be a scores object parameter') } if (Object.keys(scores).length <= 0) { throw new Error('At least one score must be passed') } } /** * Score canidate based on the mean value of two or more parent Qs. */ class MeanQ { /** * Returns the mean value of the given scores. * @param scores - obect that contains the keys and scores * for each used scoring method * @return mean value of given scores */ combine (scores) { checkValidity(scores) var sum = 0 Object.keys(scores).map((key, index, arr) => { sum += scores[key] }) return sum / Object.keys(scores).length } } /** * Chooses the biggest score out of all possible scores */ class LargestQ { /** * combines all scores by choosing the largest score */ combine (scores) { checkValidity(scores) var largest = 0.0 Object.keys(scores).map((key, index, arr) => { if (scores[key] >= largest) { largest = scores[key] } }) return largest } } module.exports = { Mean: MeanQ, Largest: LargestQ }
Move code around to put functions at bottom.
Application.Controllers.controller('projectsProject', ["$scope", "provStep", "ui", "project", "current", "pubsub", "recent", projectsProject]); function projectsProject ($scope, provStep, ui, project, current, pubsub, recent) { recent.resetLast(project.id); current.setProject(project); pubsub.send("sidebar.project"); provStep.addProject(project.id); $scope.project = project; $scope.showTabs = function() { return ui.showToolbarTabs(project.id); }; $scope.showFiles = function() { return ui.showFiles(project.id); }; $scope.isActive = function (tab) { return tab === $scope.activeTab; }; }
Application.Controllers.controller('projectsProject', ["$scope", "provStep", "ui", "project", "current", "pubsub", projectsProject]); function projectsProject ($scope, provStep, ui, project, current, pubsub) { $scope.isActive = function (tab) { return tab === $scope.activeTab; }; current.setProject(project); pubsub.send("sidebar.project"); provStep.addProject(project.id); $scope.project = project; $scope.showTabs = function() { return ui.showToolbarTabs(project.id); }; $scope.showFiles = function() { return ui.showFiles(project.id); }; }
Make yui doc generate links from the project root instead of the filesystem root
var YUIDoc = require('broccoli-yuidoc'); var calculateVersion = require('./calculate-version'); var path = require('path'); module.exports = function yui() { return new YUIDoc(['addon', 'node_modules/ember-inflector/addon'], { destDir: 'docs', yuidoc: { "name": "The ember-data API", "description": "The ember-data API: a data persistence library for Ember.js", "version": calculateVersion(), "logo": "http://f.cl.ly/items/1A1L432s022u1O1q1V3p/ember%20logo.png", "url": "https://github.com/emberjs/data", "options": { "exclude": "vendor", "outdir": "docs/build" } } }); };
var YUIDoc = require('broccoli-yuidoc'); var calculateVersion = require('./calculate-version'); var path = require('path'); module.exports = function yui() { var emberData = path.join(__dirname, '..', 'addon'); var emberInflector = path.join(path.dirname(require.resolve('ember-inflector'), 'addon')); return new YUIDoc([emberData, emberInflector], { srcDir: '/', destDir: 'docs', yuidoc: { "name": "The ember-data API", "description": "The ember-data API: a data persistence library for Ember.js", "version": calculateVersion(), "logo": "http://f.cl.ly/items/1A1L432s022u1O1q1V3p/ember%20logo.png", "url": "https://github.com/emberjs/data", "options": { "paths": [ "ember-data/lib", "ember-inflector/addon" ], "exclude": "vendor", "outdir": "docs/build" } } }); };
Fix ExtensionManagementApiBrowserTest.LaunchApp to no longer be order-dependent. With the break, it fails if the app happens to come before the extension in items. BUG=104091 TEST=none TBR=asargent@chromium.org Review URL: http://codereview.chromium.org/8801037 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@113141 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. window.onload = function() { chrome.management.getAll(function(items) { for (var i in items) { var item = items[i]; if (item.name == "packaged_app") { chrome.management.launchApp(item.id); } if (item.name == "simple_extension") { // Try launching a non-app extension, which should fail. var expected_error = "Extension " + item.id + " is not an App"; chrome.management.launchApp(item.id, function() { if (chrome.extension.lastError && chrome.extension.lastError.message == expected_error) { chrome.test.sendMessage("got_expected_error"); } }); } } }); };
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. window.onload = function() { chrome.management.getAll(function(items) { for (var i in items) { var item = items[i]; if (item.name == "packaged_app") { chrome.management.launchApp(item.id); break; } if (item.name == "simple_extension") { // Try launching a non-app extension, which should fail. var expected_error = "Extension " + item.id + " is not an App"; chrome.management.launchApp(item.id, function() { if (chrome.extension.lastError && chrome.extension.lastError.message == expected_error) { chrome.test.sendMessage("got_expected_error"); } }); } } }); };
Use null as indicator for unconditional action. Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sablecc.sablecc.lrautomaton; import java.util.*; public abstract class Action { private final Map<Integer, Set<Item>> distanceToItemSetMap; Action( Map<Integer, Set<Item>> distanceToItemSetMap) { this.distanceToItemSetMap = distanceToItemSetMap; } }
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sablecc.sablecc.lrautomaton; import java.util.*; public abstract class Action { private final Map<Integer, Set<Item>> distanceToItemSetMap; Action( Map<Integer, Set<Item>> distanceToItemSetMap) { if (distanceToItemSetMap != null) { this.distanceToItemSetMap = distanceToItemSetMap; } else { this.distanceToItemSetMap = new LinkedHashMap<Integer, Set<Item>>(); } } }
Fix wrong naming in tests
'use strict'; const chai = require('chai'); const postalCode = require('../index'); const expect = chai.expect; describe('Those postal codes', function() { it('should be valid', function() { expect(postalCode.validate('10188')).to.be.true; expect(postalCode.validate('49080')).to.be.true; }); }); describe('Those postal codes', function() { it('should be invalid', function() { expect(postalCode.validate('90000')).to.be.false; expect(postalCode.validate('00000')).to.be.false; expect(postalCode.validate('1abcd')).to.be.false; expect(postalCode.validate('123456')).to.be.false; expect(postalCode.validate('1234')).to.be.false; expect(postalCode.validate('1 2 3 4')).to.be.false; }); }); describe('Those dirty postal codes', function() { it('should be cleaned', function() { expect(postalCode.clean(' 123 45 ')).to.equal('12345'); }); });
'use strict'; const chai = require('chai'); const plate = require('../index'); const expect = chai.expect; describe('Those postal codes', function() { it('should be valid', function() { expect(plate.validate('10188')).to.be.true; expect(plate.validate('49080')).to.be.true; }); }); describe('Those postal codes', function() { it('should be invalid', function() { expect(plate.validate('90000')).to.be.false; expect(plate.validate('00000')).to.be.false; expect(plate.validate('1abcd')).to.be.false; expect(plate.validate('123456')).to.be.false; expect(plate.validate('1234')).to.be.false; expect(plate.validate('1 2 3 4')).to.be.false; }); }); describe('Those dirty postal codes', function() { it('should be cleaned', function() { expect(plate.clean(' 123 45 ')).to.equal('12345'); }); });
Use stopPropagation instead of stopImmediatePropagation.
var $stack = $('.stack'), CLASS_LIST = 'contain-0-items contain-1-items contain-2-items contain-3-items contain-4-items'; var getPlatesFrom = function(stack){ return $(stack).find('.plate').not('.ui-sortable-helper') } var updateClass = function(){ $stack.removeClass(CLASS_LIST).each(function(){ var count = getPlatesFrom(this).size(); $(this).addClass('contain-' + count + '-items'); }); } $stack.disableSelection(); $('.plate').mousedown(function(e){ var $stack = $(this).parent(); if(! $(this).is($stack.children('.plate:first')) ){ e.stopPropagation(); } }) var isValidSort = false; $stack.sortable({ connectWith: '.stack', sort: updateClass, stop: function(e, ui){ updateClass(); if(!isValidSort){ $(this).sortable('cancel'); return; } isValidSort = false; }, receive: function(e, ui){ ui.item.prependTo($(this)); isValidSort = true; var size = ui.item.data('size'), $platesOnNewStack = getPlatesFrom(this); if( $platesOnNewStack.size() > 1 && $platesOnNewStack.eq(1).data('size') < size ){ ui.sender.sortable('cancel'); } }, placeholder: 'no-space' });
var $stack = $('.stack'), CLASS_LIST = 'contain-0-items contain-1-items contain-2-items contain-3-items contain-4-items'; var getPlatesFrom = function(stack){ return $(stack).find('.plate').not('.ui-sortable-helper') } var updateClass = function(){ $stack.removeClass(CLASS_LIST).each(function(){ var count = getPlatesFrom(this).size(); $(this).addClass('contain-' + count + '-items'); }); } $('.plate').mousedown(function(e){ var $stack = $(this).parent(); if(! $(this).is($stack.children('.plate:first')) ){ e.stopImmediatePropagation(); } }) var isValidSort = false; $stack.sortable({ connectWith: '.stack', sort: updateClass, stop: function(e, ui){ updateClass(); if(!isValidSort){ $(this).sortable('cancel'); return; } isValidSort = false; }, receive: function(e, ui){ ui.item.prependTo($(this)); isValidSort = true; var size = ui.item.data('size'), $platesOnNewStack = getPlatesFrom(this); if( $platesOnNewStack.size() > 1 && $platesOnNewStack.eq(1).data('size') < size ){ ui.sender.sortable('cancel'); } }, placeholder: 'no-space' }); $stack.disableSelection();
Change MongoDB URI for production environment (Clever)
const mongoose = require('mongoose'); const log = require('./logger.helper'); const appHelper = require('./application.helper'); const options = { useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true, }; let db; /** * Init the database connection and log events */ function initDatabaseConnection() { let uri = `${process.env.MONGODB_ADDON_URI}`; if (appHelper.isProd()) { options.user = process.env.MONGODB_ADDON_USER; options.pass = process.env.MONGODB_ADDON_PASSWORD; } if (appHelper.isDev()) { uri = `${uri}/${process.env.MONGODB_ADDON_DB}`; } mongoose.connect(uri, options); // Use native promises mongoose.Promise = global.Promise; db = mongoose.connection; db.on('error', (err) => { log.error('Database connection error', err); }); db.once('open', () => { log.info('Connection with database succeeded.'); }); } function getDB() { if (!db) { throw new Error('DB not initialized'); } return db; } module.exports = { initDatabaseConnection, getDB, };
const mongoose = require('mongoose'); const log = require('./logger.helper'); const appHelper = require('./application.helper'); const options = { useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true, }; let db; /** * Init the database connection and log events */ function initDatabaseConnection() { if (appHelper.isProd()) { options.user = process.env.MONGODB_ADDON_USER; options.pass = process.env.MONGODB_ADDON_PASSWORD; } const uri = `${process.env.MONGODB_ADDON_URI}/${process.env.MONGODB_ADDON_DB}`; mongoose.connect(uri, options); // Use native promises mongoose.Promise = global.Promise; db = mongoose.connection; db.on('error', (err) => { log.error('Database connection error', err); }); db.once('open', () => { log.info('Connection with database succeeded.'); }); } function getDB() { if (!db) { throw new Error('DB not initialized'); } return db; } module.exports = { initDatabaseConnection, getDB, };
PLAT-9061: Add Thai to reach supported languages
<?php /** * @package plugins.reach * @subpackage api.enum */ class KalturaCatalogItemLanguage extends KalturaStringEnum { const EN = KalturaLanguage::EN; const EN_US = KalturaLanguage::EN_US; const EN_GB = KalturaLanguage::EN_GB; const NL = KalturaLanguage::NL; const FR = KalturaLanguage::FR; const DE = KalturaLanguage::DE; const IT = KalturaLanguage::IT; const ES = KalturaLanguage::ES; const AR = KalturaLanguage::AR; const ZH = KalturaLanguage::ZH; const CMN = KalturaLanguage::CMN; const YUE = KalturaLanguage::YUE; const HE = KalturaLanguage::HE; const HI = KalturaLanguage::HI; const JA = KalturaLanguage::JA; const KO = KalturaLanguage::KO; const PT = KalturaLanguage::PT; const RU = KalturaLanguage::RU; const TR = KalturaLanguage::TR; const TH = KalturaLanguage::TH; }
<?php /** * @package plugins.reach * @subpackage api.enum */ class KalturaCatalogItemLanguage extends KalturaStringEnum { const EN = KalturaLanguage::EN; const EN_US = KalturaLanguage::EN_US; const EN_GB = KalturaLanguage::EN_GB; const NL = KalturaLanguage::NL; const FR = KalturaLanguage::FR; const DE = KalturaLanguage::DE; const IT = KalturaLanguage::IT; const ES = KalturaLanguage::ES; const AR = KalturaLanguage::AR; const ZH = KalturaLanguage::ZH; const CMN = KalturaLanguage::CMN; const YUE = KalturaLanguage::YUE; const HE = KalturaLanguage::HE; const HI = KalturaLanguage::HI; const JA = KalturaLanguage::JA; const KO = KalturaLanguage::KO; const PT = KalturaLanguage::PT; const RU = KalturaLanguage::RU; const TR = KalturaLanguage::TR; }
Set alternative link if browser not support iframe.
<div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="flexible-container"> <iframe src="<?php echo (empty($_GET['file'])?'':Core::getInstance()->basepath.'/plugins/pdf/viewer.php?file='.$_GET['file'])?>" type="application/pdf" width="100%" height="100%" allowFullScreen> <p>Your browser doesn't support iframes. For direct link viewer, just <a href="<?php echo (empty($_GET['file'])?'':$_GET['file'])?>">click here</a>.</p> </iframe> </div> <br> <p class="text-center"><a href="<?php echo (empty($_GET['file'])?'':$_GET['file'])?>/download" download class="btn btn-success"><?php echo Core::lang('download')?></a></p> </div> </div> </div> </div>
<div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="flexible-container"> <iframe src="<?php echo (empty($_GET['file'])?'':Core::getInstance()->basepath.'/plugins/pdf/viewer.php?file='.$_GET['file'])?>" type="application/pdf" width="100%" height="100%" allowFullScreen> <p>It appears your web browser doesn't support iframes.</p> </iframe> </div> <br> <p class="text-center"><a href="<?php echo (empty($_GET['file'])?'':$_GET['file'])?>/download" download class="btn btn-success"><?php echo Core::lang('download')?></a></p> </div> </div> </div> </div>
Conan: Support package in editable mode Add a method to the recipe that maps the include path to "src" when the package is put into "editable mode". See: https://docs.conan.io/en/latest/developing_packages/editable_packages.html
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author = "Michele Caini <michele.caini@gmail.com>" license = "MIT" exports = ["LICENSE"] exports_sources = ["src/*"] no_copy_source = True def package(self): self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="*", dst="include", src="src", keep_path=True) def package_info(self): if not self.in_local_cache: self.cpp_info.includedirs = ["src"] def package_id(self): self.info.header_only()
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author = "Michele Caini <michele.caini@gmail.com>" license = "MIT" exports = ["LICENSE"] exports_sources = ["src/*"] no_copy_source = True def package(self): self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="*", dst="include", src="src", keep_path=True) def package_id(self): self.info.header_only()
Remove trailing slash from template url
from flask import Blueprint from flask import (jsonify) from sqlalchemy.exc import DataError from sqlalchemy.orm.exc import NoResultFound from app.dao.templates_dao import get_model_templates from app.schemas import (template_schema, templates_schema) template = Blueprint('template', __name__) # I am going to keep these for admin like operations # Permissions should restrict who can access this endpoint # TODO auth to be added. @template.route('/<int:template_id>', methods=['GET']) @template.route('', methods=['GET']) def get_template(template_id=None): try: templates = get_model_templates(template_id=template_id) except DataError: return jsonify(result="error", message="Invalid template id"), 400 except NoResultFound: return jsonify(result="error", message="Template not found"), 404 if isinstance(templates, list): data, errors = templates_schema.dump(templates) else: data, errors = template_schema.dump(templates) if errors: return jsonify(result="error", message=str(errors)) return jsonify(data=data)
from flask import Blueprint from flask import (jsonify) from sqlalchemy.exc import DataError from sqlalchemy.orm.exc import NoResultFound from app.dao.templates_dao import get_model_templates from app.schemas import (template_schema, templates_schema) template = Blueprint('template', __name__) # I am going to keep these for admin like operations # Permissions should restrict who can access this endpoint # TODO auth to be added. @template.route('/<int:template_id>', methods=['GET']) @template.route('/', methods=['GET']) def get_template(template_id=None): try: templates = get_model_templates(template_id=template_id) except DataError: return jsonify(result="error", message="Invalid template id"), 400 except NoResultFound: return jsonify(result="error", message="Template not found"), 404 if isinstance(templates, list): data, errors = templates_schema.dump(templates) else: data, errors = template_schema.dump(templates) if errors: return jsonify(result="error", message=str(errors)) return jsonify(data=data)
ENH: Remove errant printout in python cone layout example.
from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True) view.SetLayoutStrategyToCone() view.SetInteractionModeTo3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToLabelPlacer() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() window = vtkRenderWindow() window.SetSize(600, 600) view.SetupRenderWindow(window) view.GetRenderer().ResetCamera() window.Render() window.GetInteractor().Start()
from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") reader.Update() print reader.GetOutput() view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True) view.SetLayoutStrategyToCone() view.SetInteractionModeTo3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToLabelPlacer() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() window = vtkRenderWindow() window.SetSize(600, 600) view.SetupRenderWindow(window) view.GetRenderer().ResetCamera() window.Render() window.GetInteractor().Start()
Use appendExpr on simple expressions
/* * Copyright 2014 gandola. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pg.creg.expr.character; import com.pg.creg.exception.CregException; import static com.pg.creg.util.OperatorPosition.*; import static com.pg.creg.util.StringUtils.*; /** * Applies negation operator over the given CharacterExpression. [^a-z] * @author Pedro Gandola <pedro.gandola@gmail.com> */ public class Negation implements CharacterExpression { private final CharacterExpression expr; public Negation(CharacterExpression expr) { this.expr = expr; } public void eval(StringBuilder builder) throws CregException { appendExpr(expr, "^", builder, BEGIN); } }
/* * Copyright 2014 gandola. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pg.creg.expr.character; import com.pg.creg.exception.CregException; /** * Applies negation operator over the given CharacterExpression. [^a-z] * @author Pedro Gandola <pedro.gandola@gmail.com> */ public class Negation implements CharacterExpression { private final CharacterExpression expr; public Negation(CharacterExpression expr) { this.expr = expr; } public void eval(StringBuilder builder) throws CregException { builder.append("^"); expr.eval(builder); } }