text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add suspension capabilities to MessageComparator
var logger = require('../utils/logger')('MessageComparator'), Response = require('./response'); /** * Represents a MessageComparator capable of determining whether an * incoming message must be relayed to a module or not. * @param {RegExp} regex Regex to which every incoming * message will be tested against * @param {Function} callback Callback function that will be called * when a given message is matched by the * provided regex * @constructor */ var MessageComparator = function(moduleName, regex, callback) { this.regex = regex; this.callback = callback; this.moduleName = moduleName; this.suspended = false; logger.verbose('Registered message: ' + regex); }; MessageComparator.prototype = { /** * Checks and executes the callback on a given message in an Envelope * @param {Envelope} envelope Envelope containing a message * to be checked * @return {Bool} Whether the callback was called or not */ call: function(envelope) { if(this.suspended) { return false; } var match = this.regex.exec(envelope.text); if(!!match) { logger.verbose('Message ' + envelope.text + ' matched regex ' + this.regex); envelope.stopPropagation = true; this.callback(new Response(envelope, match)); return true; } return false; }, /** * Sets the suspension state of this MessageComparator. Setting it to true, prevents it * from matching messages and calling its module. * @param {Boolean} newState New suspension state of this MessageComparator * @since 2.0 */ setSuspensionState: function(newState) { this.suspended = newState; } }; module.exports = MessageComparator;
var logger = require('../utils/logger')('MessageComparator'), Response = require('./response'); /** * Represents a MessageComparator capable of determining whether an * incoming message must be relayed to a module or not. * @param {RegExp} regex Regex to which every incoming * message will be tested against * @param {Function} callback Callback function that will be called * when a given message is matched by the * provided regex * @constructor */ var MessageComparator = function(regex, callback) { this.regex = regex; this.callback = callback; logger.verbose('Registered message: ' + regex); }; MessageComparator.prototype = { /** * Checks and executes the callback on a given message in an Envelope * @param {Envelope} envelope Envelope containing a message * to be checked * @return {Bool} Whether the callback was called or not */ call: function(envelope) { var match = this.regex.exec(envelope.text); if(!!match) { logger.verbose('Message ' + envelope.text + ' matched regex ' + this.regex); envelope.stopPropagation = true; this.callback(new Response(envelope, match)); return true; } return false; } }; module.exports = MessageComparator;
fix(suspension/actionButton): Reorder action button in toolbar related to CAM-1403
ngDefine('cockpit.plugin.base.views', ['require'], function(module, require) { var Controller = [ '$scope', '$dialog', function($scope, $dialog) { $scope.openDialog = function () { var dialog = $dialog.dialog({ resolve: { processData: function() { return $scope.processData; }, processInstance: function() { return $scope.processInstance; } }, controller: 'UpdateProcessInstanceSuspensionStateController', templateUrl: require.toUrl('./update-suspension-state-dialog.html') }); dialog.open().then(function(result) { // dialog closed. YEA! if (result.status === 'SUCCESS') { $scope.processInstance.suspended = result.suspended; $scope.processData.set('filter', angular.extend({}, $scope.filter)); } }); }; }]; var Configuration = function PluginConfiguration(ViewsProvider) { ViewsProvider.registerDefaultView('cockpit.processInstance.action', { id: 'update-suspension-state-action', label: 'Update Suspension State', url: 'plugin://base/static/app/views/processInstance/update-suspension-state-action.html', controller: Controller, priority: 5 }); }; Configuration.$inject = ['ViewsProvider']; module.config(Configuration); });
ngDefine('cockpit.plugin.base.views', ['require'], function(module, require) { var Controller = [ '$scope', '$dialog', function($scope, $dialog) { $scope.openDialog = function () { var dialog = $dialog.dialog({ resolve: { processData: function() { return $scope.processData; }, processInstance: function() { return $scope.processInstance; } }, controller: 'UpdateProcessInstanceSuspensionStateController', templateUrl: require.toUrl('./update-suspension-state-dialog.html') }); dialog.open().then(function(result) { // dialog closed. YEA! if (result.status === 'SUCCESS') { $scope.processInstance.suspended = result.suspended; $scope.processData.set('filter', angular.extend({}, $scope.filter)); } }); }; }]; var Configuration = function PluginConfiguration(ViewsProvider) { ViewsProvider.registerDefaultView('cockpit.processInstance.action', { id: 'update-suspension-state-action', label: 'Update Suspension State', url: 'plugin://base/static/app/views/processInstance/update-suspension-state-action.html', controller: Controller, priority: 50 }); }; Configuration.$inject = ['ViewsProvider']; module.config(Configuration); });
Fix quantity not updating properly
import { ADD_PRODUCT, REMOVE_PRODUCT, } from './../mutation-types' import Vue from 'vue' export default { state: { products: [], total: 0, count: 0 }, mutations: { [ADD_PRODUCT] (state, product) { let productExist = state.products.find(p => p.id === product.id) if (productExist) { state.products = state.products.map(p => { if (p.id === product.id) { p.quantity += 1 } return p }) } else { Vue.set(product, 'quantity', 1) state.products.push(product) } state.total += product.price state.count += 1 }, [REMOVE_PRODUCT] (state, id) { state.products = state.products.filter(p => p.id !== id) state.total = state.products.reduce((a, b) => a + (b.price * b.quantity), 0) state.count = state.products.length } }, actions: { addProduct ({ commit }, product) { commit(ADD_PRODUCT, product) }, removeProduct ({ commit }, id) { commit(REMOVE_PRODUCT, id) } } }
import { ADD_PRODUCT, REMOVE_PRODUCT, } from './../mutation-types' export default { state: { products: [], total: 0, count: 0 }, mutations: { [ADD_PRODUCT] (state, product) { let index = state.products.findIndex(p => p.id === product.id) if (index >= 0) { state.products = state.products.map(p => { if (p.id === product.id) { p.quantity = p.quantity + 1 } return p }) } else { product.quantity = 1 state.products.push(product) } state.total += product.price state.count += 1 }, [REMOVE_PRODUCT] (state, id) { state.products = state.products.filter(p => p.id !== id) state.total = state.products.reduce((a, b) => a + (b.price * b.quantity), 0) state.count = state.products.length } }, actions: { addProduct ({ commit }, product) { commit(ADD_PRODUCT, product) }, removeProduct ({ commit }, id) { commit(REMOVE_PRODUCT, id) } } }
Change extensions to use pathlib in helpers instead of lists
# -*- coding: utf-8 -*- """ Extension that omits the creation of file `skeleton.py` """ from pathlib import PurePath as Path from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = Path(opts['project'], 'src', opts['package'], 'skeleton.py') struct = helpers.reject(struct, file) file = Path(opts['project'], 'tests', 'test_skeleton.py') struct = helpers.reject(struct, file) return struct, opts
# -*- coding: utf-8 -*- """ Extension that omits the creation of file `skeleton.py` """ from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = [opts['project'], 'src', opts['package'], 'skeleton.py'] struct = helpers.reject(struct, file) file = [opts['project'], 'tests', 'test_skeleton.py'] struct = helpers.reject(struct, file) return struct, opts
Add logging to debug hanging auth
from django.conf import settings from accounts.models import ( RcLdapUser, User ) import pam import logging logger = logging.getLogger('accounts') class PamBackend(): def authenticate(self, request, username=None, password=None): rc_user = RcLdapUser.objects.get_user_from_suffixed_username(username) if not rc_user: return None logging.info('User {} auth attempt'.format(username)) p = pam.pam() authed = p.authenticate(username, password, service=settings.PAM_SERVICES['default']) logging.info('User {} auth attempt status: {}'.format(username, authed)) if authed: user_dict = { 'first_name': rc_user.first_name, 'last_name': rc_user.last_name, 'email': rc_user.email, } user, created = User.objects.update_or_create( username=username, defaults=user_dict ) return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
from django.conf import settings from accounts.models import ( RcLdapUser, User ) import pam import logging logger = logging.getLogger('accounts') class PamBackend(): def authenticate(self, request, username=None, password=None): rc_user = RcLdapUser.objects.get_user_from_suffixed_username(username) if not rc_user: return None p = pam.pam() authed = p.authenticate(username, password, service=settings.PAM_SERVICES['default']) logging.info('User {} auth attempt: {}'.format(username, authed)) if authed: user_dict = { 'first_name': rc_user.first_name, 'last_name': rc_user.last_name, 'email': rc_user.email, } user, created = User.objects.update_or_create( username=username, defaults=user_dict ) return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
Add prelogin hook and postlogin hook emit
<?php namespace OCA\SingleSignOn; class Util { public static function login($username) { $manager = \OC::$server->getUserManager(); $manager->emit('\OC\User', 'preLogin', array($username, $password)); $user = $manager->get($username); \OC::$server->getUserSession()->setUser($user); $manager->emit('\OC\User', 'postLogin', array($user, $password)); return true; } public static function firstLogin($userInfo) { $password = RequestManager::getRequest(ISingleSignOnRequest::USERPASSWORDGENERATOR) ? RequestManager::send(ISingleSignOnRequest::USERPASSWORDGENERATOR) : $userInfo->getUserId(); \OC_User::createUser($userInfo->getUserId(), $password); \OC_User::setDisplayName($userInfo->getUserId(), $userInfo->getDisplayName()); \OC::$server->getConfig()->setUserValue($userInfo->getUserId(), "settings", "email", $userInfo->getEmail()); \OC_User::login($userInfo->getUserId(), $password); } public static function webDavLogin($username, $password) { $processor = SingleSignOnPreFilter::getInstance(); $data["userId"] = $username; $data["password"] = $password; return self::login($username); } public static function redirect($url) { if($url === false) { \OC_Util::redirectToDefaultPage(); } else { header("location: " . $url); exit(); } } }
<?php namespace OCA\SingleSignOn; class Util { public static function login($username) { $user = \OC::$server->getUserManager()->get($username); \OC::$server->getUserSession()->setUser($user); return true; } public static function firstLogin($userInfo) { $password = RequestManager::getRequest(ISingleSignOnRequest::USERPASSWORDGENERATOR) ? RequestManager::send(ISingleSignOnRequest::USERPASSWORDGENERATOR) : $userInfo->getUserId(); \OC_User::createUser($userInfo->getUserId(), $password); \OC_User::setDisplayName($userInfo->getUserId(), $userInfo->getDisplayName()); \OC::$server->getConfig()->setUserValue($userInfo->getUserId(), "settings", "email", $userInfo->getEmail()); \OC_User::login($userInfo->getUserId(), $password); } public static function webDavLogin($username, $password) { $processor = SingleSignOnPreFilter::getInstance(); $data["userId"] = $username; $data["password"] = $password; // $token = $processor->ssos[ISingleSignOnRequest::GETTOKEN]->send($data); $token = "81d97be71dac58d7d56272d150551ec3"; return self::login($username); } public static function redirect($url) { if($url === false) { \OC_Util::redirectToDefaultPage(); } else { header("location: " . $url); exit(); } } }
Clarify compileAppend's handling of expressions.
package io.collap.bryg.compiler.helper; import io.collap.bryg.compiler.ast.expression.Expression; import io.collap.bryg.compiler.parser.BrygMethodVisitor; import io.collap.bryg.compiler.type.Type; import io.collap.bryg.compiler.type.TypeHelper; public class StringBuilderCompileHelper extends ObjectCompileHelper { public StringBuilderCompileHelper (BrygMethodVisitor method) { super (method, new Type (StringBuilder.class)); } /** * Compiles the expression by default! */ public void compileAppend (Expression expression) { compileAppend (expression, true); } /** * StringBuilder -> StringBuilder */ public void compileAppend (Expression expression, boolean compileExpression) { Type argumentType = expression.getType (); if (!argumentType.getJavaType ().isPrimitive ()) { /* All objects are supplied as either String or Object. */ if (!argumentType.equals (String.class)) { argumentType = new Type (Object.class); } }else { /* Byte and Short primitives need to be appended as integers. */ if (argumentType.equals (Byte.TYPE) || argumentType.equals (Short.TYPE)) { argumentType = new Type (Integer.TYPE); } } if (compileExpression) { expression.compile (); // -> T } compileInvokeVirtual ("append", TypeHelper.generateMethodDesc ( new Type[] { argumentType }, type )); // StringBuilder, T -> StringBuilder } public void compileToString () { compileInvokeVirtual ("toString", TypeHelper.generateMethodDesc (null, String.class)); // StringBuilder -> String } }
package io.collap.bryg.compiler.helper; import io.collap.bryg.compiler.ast.expression.Expression; import io.collap.bryg.compiler.parser.BrygMethodVisitor; import io.collap.bryg.compiler.type.Type; import io.collap.bryg.compiler.type.TypeHelper; public class StringBuilderCompileHelper extends ObjectCompileHelper { public StringBuilderCompileHelper (BrygMethodVisitor method) { super (method, new Type (StringBuilder.class)); } public void compileAppend (Expression expression) { compileAppend (expression, true); } /** * StringBuilder -> StringBuilder */ public void compileAppend (Expression expression, boolean compileExpression) { Type argumentType = expression.getType (); if (!argumentType.getJavaType ().isPrimitive ()) { /* All objects are supplied as either String or Object. */ if (!argumentType.equals (String.class)) { argumentType = new Type (Object.class); } }else { /* Byte and Short primitives need to be appended as integers. */ if (argumentType.equals (Byte.TYPE) || argumentType.equals (Short.TYPE)) { argumentType = new Type (Integer.TYPE); } } if (compileExpression) { expression.compile (); // -> T } compileInvokeVirtual ("append", TypeHelper.generateMethodDesc ( new Type[] { argumentType }, type )); // StringBuilder, T -> StringBuilder } public void compileToString () { compileInvokeVirtual ("toString", TypeHelper.generateMethodDesc (null, String.class)); // StringBuilder -> String } }
Reset redux state on log out
import { combineReducers } from 'redux' import { routerReducer } from 'react-router-redux' import * as c from './constants' import * as auth from './auth' function receiveTodos (state = [], action) { switch (action.type) { case c.RECEIVE_TODO_LIST: return action.data case c.RECEIVE_TODO: let existingItem = false let newState = state.map(function (todo) { if (todo.id === action.data.id) { existingItem = true return action.data } else { return todo } }) if (!existingItem) { return state.concat(action.data) } return newState default: return state } } const filterReducer = (state = 'active', { type, data }) => { if (type === c.SET_FILTER) { return data } return state } const notifyReducer = (state = null, { type, data }) => { if (type === c.NOTIFY_SET) { return data } else if (type === c.NOTIFY_DISMISS) { return null } return state } const appReducer = combineReducers({ user: auth.userReducer, filter: filterReducer, routing: routerReducer, todos: receiveTodos, notification: notifyReducer }) const rootReducer = (state, action) => { // Reset redux state if the user logged out. // // This state reset is required. Otherwise logging in as user X, logging // out and logging in as user Y will show user Y data from the previously // logged in user X. if (action.type === auth.USER_LOGGED_OUT) { state = undefined } return appReducer(state, action) } export default rootReducer
import { combineReducers } from 'redux' import { routerReducer } from 'react-router-redux' import * as c from './constants' import * as auth from './auth' function receiveTodos (state = [], action) { switch (action.type) { case c.RECEIVE_TODO_LIST: return action.data case c.RECEIVE_TODO: let existingItem = false let newState = state.map(function (todo) { if (todo.id === action.data.id) { existingItem = true return action.data } else { return todo } }) if (!existingItem) { return state.concat(action.data) } return newState default: return state } } const filterReducer = (state = 'active', { type, data }) => { if (type === c.SET_FILTER) { return data } return state } const notifyReducer = (state = null, { type, data }) => { if (type === c.NOTIFY_SET) { return data } else if (type === c.NOTIFY_DISMISS) { return null } return state } const rootReducer = combineReducers({ user: auth.userReducer, filter: filterReducer, routing: routerReducer, todos: receiveTodos, notification: notifyReducer }) export default rootReducer
Create lazy launcher in setUp.
import unittest from gtlaunch import Launcher class MockOptions(object): def __init__(self): self.verbose = False self.config = '' self.project = '' class LauncherTestCase(unittest.TestCase): def setUp(self): self.options = MockOptions() self.launcher = Launcher(self.options, lazy=True) def test_lazy_init(self): self.assertIsNone(self.launcher.project) def test_no_cwd(self): project = { 'tabs': [], } args = self.launcher.build_args(project) self.assertNotIn('--working-directory', args) def test_cwd(self): project = { 'cwd': '/home/test', 'tabs': [], } args = self.launcher.build_args(project) idx = args.index('--working-directory') self.assertEqual(args[idx + 1], project['cwd']) def test_args_maximize(self): project = { 'cwd': '~', 'tabs': [], } args = self.launcher.build_args(project) self.assertIn('--maximize', args) if __name__ == '__main__': unittest.main()
import unittest from gtlaunch import Launcher class MockOptions(object): def __init__(self): self.verbose = False self.config = '' self.project = '' class LauncherTestCase(unittest.TestCase): def setUp(self): self.options = MockOptions() def test_lazy_init(self): launcher = Launcher(self.options, lazy=True) self.assertIsNone(launcher.project) def test_no_cwd(self): project = { 'tabs': [], } launcher = Launcher(self.options, lazy=True) args = launcher.build_args(project) self.assertNotIn('--working-directory', args) def test_cwd(self): project = { 'cwd': '/home/test', 'tabs': [], } launcher = Launcher(self.options, lazy=True) args = launcher.build_args(project) idx = args.index('--working-directory') self.assertEqual(args[idx + 1], project['cwd']) def test_args_maximize(self): project = { 'cwd': '~', 'tabs': [], } launcher = Launcher(self.options, lazy=True) args = launcher.build_args(project) self.assertIn('--maximize', args) if __name__ == '__main__': unittest.main()
Remove `username` from keycloack payload.
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'username': response.get('preferred_username'), 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
Delete the databases between tests rather than nuking all entries since that doesn't remove indexes
/* * Helper class for cleaning nedb state */ "use strict"; var Promise = require("bluebird"); var fs = require("fs"); var promiseutil = require("../../lib/promiseutil"); var Datastore = require("nedb"); /** * Reset the database, wiping all data. * @param {String} databaseUri : The database URI to wipe all data from. * @return {Promise} Which is resolved when the database has been cleared. */ module.exports._reset = function(databaseUri) { if (databaseUri.indexOf("nedb://") !== 0) { return Promise.reject("Must be nedb:// URI"); } var baseDbName = databaseUri.substring("nedb://".length); function delDatabase(name) { var dbPath = baseDbName + name; return new Promise(function(resolve, reject) { // nuke the world fs.unlink(dbPath, function(err) { if (err) { if (err.code == "ENOENT") { // already deleted resolve(); } else { reject(err); } } else { resolve(); } }); }); } return Promise.all([ delDatabase("/rooms.db"), delDatabase("/users.db"), ]); };
/* * Helper class for cleaning nedb state */ "use strict"; var Promise = require("bluebird"); var promiseutil = require("../../lib/promiseutil"); var Datastore = require("nedb"); /** * Reset the database, wiping all data. * @param {String} databaseUri : The database URI to wipe all data from. * @return {Promise} Which is resolved when the database has been cleared. */ module.exports._reset = function(databaseUri) { if (databaseUri.indexOf("nedb://") !== 0) { return Promise.reject("Must be nedb:// URI"); } var baseDbName = databaseUri.substring("nedb://".length); function delDatabase(name) { var d = promiseutil.defer(); var db = new Datastore({ filename: baseDbName + name, autoload: true, onload: function() { db.remove({}, {multi: true}, function(err, docs) { if (err) { console.error("db-helper %s Failed to delete: %s", name, err); console.error(err.stack); d.reject(err); return; } d.resolve(docs); }); } }); return d.promise; } return Promise.all([ delDatabase("/rooms.db"), delDatabase("/users.db"), ]); };
Convert postag to long form in morph selector
'use strict'; angular.module('arethusa.table').directive('morphSelector',[ 'state', 'morph', function (state, morph) { return { restrict: 'A', scope: { token: "=morphToken" }, link: function(scope, element, attrs) { scope.analyses = morph.analyses[scope.token.id].forms; scope.form = scope.token.morphology; scope.longForm = function(form) { var longPostag = Object.keys(form.attributes).filter(function(k) { return /[A-Za-z0-9]/.test(form.attributes[k]); }).map(function(k) { return morph.longAttributeValue(k,form.attributes[k]); }).join('-'); var lemma = form.lemma; return lemma + ':' + longPostag; } function undoFn(tkn, frm) { var token = tkn; var form = frm; return function() { scope.form = form; state.change(token.id,'morphology',form) } } function preExecFn(frm) { var form = frm; return function() { scope.form = form; } } scope.onChange = function() { state.change(scope.token.id, 'morphology', scope.form, undoFn(scope.token,scope.token.morphology), preExecFn(scope.form)); } }, template: '<select class="no-margin compact" ng-model="form" ng-options="analysis as longForm(analysis) for analysis in analyses" ng-change="onChange()"></select>' }; }]);
'use strict'; angular.module('arethusa.table').directive('morphSelector',[ 'state', 'morph', function (state, morph) { return { restrict: 'A', scope: { token: "=morphToken" }, link: function(scope, element, attrs) { scope.analyses = morph.analyses[scope.token.id].forms; scope.form = scope.token.morphology; function undoFn(tkn, frm) { var token = tkn; var form = frm; return function() { scope.form = form; state.change(token.id,'morphology',form) } } function preExecFn(frm) { var form = frm; return function() { scope.form = form; } } scope.onChange = function() { state.change(scope.token.id, 'morphology', scope.form, undoFn(scope.token,scope.token.morphology), preExecFn(scope.form)); } }, template: '<select class="no-margin compact" ng-model="form" ng-options="analysis as analysis.lemma+\':\'+analysis.postag for analysis in analyses" ng-change="onChange()"></select>' }; }]);
Increase pool size to 5, later this should be DB POOL SIZE / 2
package org.buddycloud.channelserver.queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.xmpp.packet.Packet; public abstract class QueueConsumer { private static final Logger LOGGER = Logger.getLogger(QueueConsumer.class); private ExecutorService executorService = Executors.newFixedThreadPool(5); private final BlockingQueue<Packet> queue; public QueueConsumer(BlockingQueue<Packet> queue) { this.queue = queue; } public void start() { executorService.submit(new Runnable() { @Override public void run() { while (true) { try { Packet packet = queue.take(); consume(packet); } catch (InterruptedException e) { LOGGER.error(e); } } } }); } protected abstract void consume(Packet p); }
package org.buddycloud.channelserver.queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.xmpp.packet.Packet; public abstract class QueueConsumer { private static final Logger LOGGER = Logger.getLogger(QueueConsumer.class); private ExecutorService executorService = Executors.newFixedThreadPool(1); private final BlockingQueue<Packet> queue; public QueueConsumer(BlockingQueue<Packet> queue) { this.queue = queue; } public void start() { executorService.submit(new Runnable() { @Override public void run() { while (true) { try { Packet packet = queue.take(); consume(packet); } catch (InterruptedException e) { LOGGER.error(e); } } } }); } protected abstract void consume(Packet p); }
Make test names more readable and add missing test case (Cowan's review comments)
package com.custardsource.parfait; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Collection; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class CompositeMonitoringViewTest { @Mock MonitoringView monitoringView1; @Mock MonitoringView monitoringView2; CompositeMonitoringView compositeMonitoringView; @Mock Collection<Monitorable<?>> monitorables; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(monitoringView1.isRunning()).thenReturn(false); when(monitoringView2.isRunning()).thenReturn(true); when(monitorables.size()).thenReturn(2); this.compositeMonitoringView = new CompositeMonitoringView(monitoringView1, monitoringView2); } @Test public void startMonitoringShouldStartAllViews() { compositeMonitoringView.startMonitoring(monitorables); verify(monitoringView1).startMonitoring(monitorables); verify(monitoringView2).startMonitoring(monitorables); } @Test public void stopMonitoringShouldStopAllViews() { compositeMonitoringView.stopMonitoring(monitorables); verify(monitoringView1).stopMonitoring(monitorables); verify(monitoringView2).stopMonitoring(monitorables); } @Test public void isRunningReturnsTrueIfAnyRunning() { assertTrue(compositeMonitoringView.isRunning()); } @Test public void isRunningReturnsFalseIfAllAreNotRunning() { CompositeMonitoringView monitoringView = new CompositeMonitoringView(monitoringView1); assertFalse(monitoringView.isRunning()); } }
package com.custardsource.parfait; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Collection; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class CompositeMonitoringViewTest { @Mock MonitoringView monitoringView1; @Mock MonitoringView monitoringView2; CompositeMonitoringView compositeMonitoringView; @Mock Collection<Monitorable<?>> monitorables; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(monitoringView1.isRunning()).thenReturn(false); when(monitoringView2.isRunning()).thenReturn(true); when(monitorables.size()).thenReturn(2); this.compositeMonitoringView = new CompositeMonitoringView(monitoringView1, monitoringView2); } @Test public void testStartMonitoring() { compositeMonitoringView.startMonitoring(monitorables); verify(monitoringView1).startMonitoring(monitorables); verify(monitoringView2).startMonitoring(monitorables); } @Test public void testStopMonitoring() { compositeMonitoringView.stopMonitoring(monitorables); verify(monitoringView1).stopMonitoring(monitorables); verify(monitoringView2).stopMonitoring(monitorables); } @Test public void testIsRunning() { assertTrue(compositeMonitoringView.isRunning()); } }
Add line predicate to filter output lines
package com.github.blindpirate.gogradle.build; import com.github.blindpirate.gogradle.util.ExceptionHandler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.concurrent.CountDownLatch; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import static com.github.blindpirate.gogradle.GogradleGlobal.DEFAULT_CHARSET; public class SubprocessReader extends Thread { private Supplier<InputStream> is; private CountDownLatch latch; private Consumer<String> consumer; private Predicate<String> lineFilter = line -> true; public SubprocessReader(Supplier<InputStream> is, Consumer<String> consumer, CountDownLatch latch) { this.is = is; this.latch = latch; this.consumer = consumer; } public SubprocessReader(Supplier<InputStream> is, Consumer<String> consumer, CountDownLatch latch, Predicate<String> lineFilter) { this.is = is; this.latch = latch; this.consumer = consumer; this.lineFilter = lineFilter; } @Override public void run() { try (BufferedReader br = new BufferedReader(new InputStreamReader(is.get(), DEFAULT_CHARSET))) { String line; try { while ((line = br.readLine()) != null) { if (lineFilter.test(line)) { consumer.accept(line); } } } catch (IOException e) { consumer.accept(ExceptionHandler.getStackTrace(e)); } } catch (IOException e) { throw ExceptionHandler.uncheckException(e); } finally { latch.countDown(); } } }
package com.github.blindpirate.gogradle.build; import com.github.blindpirate.gogradle.util.ExceptionHandler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.concurrent.CountDownLatch; import java.util.function.Consumer; import java.util.function.Supplier; import static com.github.blindpirate.gogradle.GogradleGlobal.DEFAULT_CHARSET; public class SubprocessReader extends Thread { private Supplier<InputStream> is; private CountDownLatch latch; private Consumer<String> consumer; public SubprocessReader(Supplier<InputStream> is, Consumer<String> consumer, CountDownLatch latch) { this.is = is; this.latch = latch; this.consumer = consumer; } @Override public void run() { try (BufferedReader br = new BufferedReader(new InputStreamReader(is.get(), DEFAULT_CHARSET))) { String line; try { while ((line = br.readLine()) != null) { consumer.accept(line); } } catch (IOException e) { consumer.accept(ExceptionHandler.getStackTrace(e)); } } catch (IOException e) { throw ExceptionHandler.uncheckException(e); } finally { latch.countDown(); } } }
Fix bug in function that lists existing jterator projects
from tmlib.workflow.args import Argument from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import ExtraArguments from tmlib.workflow.registry import batch_args from tmlib.workflow.registry import submission_args from tmlib.workflow.registry import extra_args @batch_args('jterator') class JteratorBatchArguments(BatchArguments): plot = Argument( type=bool, default=False, flag='p', disabled=True, help='whether plotting should be activated' ) @submission_args('jterator') class JteratorSubmissionArguments(SubmissionArguments): pass def get_names_of_existing_pipelines(experiment): '''Gets names of all existing jterator pipelines for a given experiment. Parameters ---------- experiment: tmlib.models.Experiment processed experiment Returns ------- List[str] names of jterator pipelines ''' import os from tmlib.workflow.jterator.project import list_projects directory = os.path.join(experiment.workflow_location, 'jterator') if not os.path.exists(directory): return [] else: return [ os.path.basename(project) for project in list_projects(directory) ] @extra_args('jterator') class JteratorExtraArguments(ExtraArguments): pipeline = Argument( type=str, help='name of the pipeline that should be processed', required=True, flag='p', get_choices=get_names_of_existing_pipelines )
from tmlib.workflow.args import Argument from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import ExtraArguments from tmlib.workflow.registry import batch_args from tmlib.workflow.registry import submission_args from tmlib.workflow.registry import extra_args @batch_args('jterator') class JteratorBatchArguments(BatchArguments): plot = Argument( type=bool, default=False, flag='p', disabled=True, help='whether plotting should be activated' ) @submission_args('jterator') class JteratorSubmissionArguments(SubmissionArguments): pass def get_names_of_existing_pipelines(experiment): '''Gets names of all existing jterator pipelines for a given experiment. Parameters ---------- experiment: tmlib.models.Experiment processed experiment Returns ------- List[str] names of jterator pipelines ''' import os from tmlib.workflow.jterator.project import list_projects return [ os.path.basename(project) for project in list_projects(os.path.join(experiment.workflow_location, 'jterator')) ] @extra_args('jterator') class JteratorExtraArguments(ExtraArguments): pipeline = Argument( type=str, help='name of the pipeline that should be processed', required=True, flag='p', get_choices=get_names_of_existing_pipelines )
Update fri dump script to delete docs
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from custom.fri.models import FRIMessageBankMessage, FRIRandomizedMessage, FRIExtraMessage from django.core.management.base import BaseCommand from six import moves class Command(BaseCommand): def delete_docs(self, model_name, result): print("\nHandling %s" % model_name) result = list(result) answer = moves.input("Delete %s docs? y/n" % len(result)) if answer == 'y': count = 0 for doc in result: if doc.doc_type != model_name: print("Deleted %s docs" % count) raise ValueError("Expected %s, got %s" % (model_name, doc.doc_type)) doc.delete() count += 1 print("Deleted %s docs" % count) def handle(self, **options): self.delete_docs( 'FRIMessageBankMessage', FRIMessageBankMessage.view('fri/message_bank', include_docs=True).all() ) self.delete_docs( 'FRIRandomizedMessage', FRIRandomizedMessage.view('fri/randomized_message', include_docs=True).all() ) self.delete_docs( 'FRIExtraMessage', FRIExtraMessage.view('fri/extra_message', include_docs=True).all() )
from __future__ import absolute_import from __future__ import unicode_literals from couchexport.export import export_raw from custom.fri.models import FRIMessageBankMessage, FRIRandomizedMessage, FRIExtraMessage from django.core.management.base import BaseCommand from io import open class Command(BaseCommand): def write_result_to_file(self, model_name, result, fields): with open('%s.xlsx' % model_name, 'wb') as f: headers = fields excel_data = [] for obj in result: excel_data.append((getattr(obj, field) for field in fields)) export_raw( ((model_name, headers), ), ((model_name, excel_data), ), f ) def handle(self, **options): self.write_result_to_file( 'FRIMessageBankMessage', FRIMessageBankMessage.view('fri/message_bank', include_docs=True).all(), ('_id', 'domain', 'risk_profile', 'message', 'fri_id') ) self.write_result_to_file( 'FRIRandomizedMessage', FRIRandomizedMessage.view('fri/randomized_message', include_docs=True).all(), ('_id', 'domain', 'case_id', 'message_bank_message_id', 'order') ) self.write_result_to_file( 'FRIExtraMessage', FRIExtraMessage.view('fri/extra_message', include_docs=True).all(), ('_id', 'domain', 'message_id', 'message') )
Add support for switching dpms
# pylint: disable=C0111,R0903 """Enable/disable automatic screen locking. Requires the following executables: * xset * notify-send """ import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): super(Module, self).__init__(engine, config, bumblebee.output.Widget(full_text=self.caffeine) ) engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE, cmd=self._toggle ) def caffeine(self, widget): return "" def state(self, widget): if self._active(): return "activated" return "deactivated" def _active(self): for line in bumblebee.util.execute("xset q").split("\n"): if "timeout" in line: timeout = int(line.split(" ")[4]) if timeout == 0: return True return False return False def _toggle(self, widget): if self._active(): bumblebee.util.execute("xset +dpms") bumblebee.util.execute("xset s default") bumblebee.util.execute("notify-send \"Out of coffee\"") else: bumblebee.util.execute("xset -dpms") bumblebee.util.execute("xset s off") bumblebee.util.execute("notify-send \"Consuming caffeine\"") # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# pylint: disable=C0111,R0903 """Enable/disable automatic screen locking. Requires the following executables: * xset * notify-send """ import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): super(Module, self).__init__(engine, config, bumblebee.output.Widget(full_text=self.caffeine) ) engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE, cmd=self._toggle ) def caffeine(self, widget): return "" def state(self, widget): if self._active(): return "activated" return "deactivated" def _active(self): for line in bumblebee.util.execute("xset q").split("\n"): if "timeout" in line: timeout = int(line.split(" ")[4]) if timeout == 0: return True return False return False def _toggle(self, widget): if self._active(): bumblebee.util.execute("xset s default") bumblebee.util.execute("notify-send \"Out of coffee\"") else: bumblebee.util.execute("xset s off") bumblebee.util.execute("notify-send \"Consuming caffeine\"") # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Fix incorrect reference to opts dict
''' Make me some salt! ''' # Import python libs import os import optparse # Import salt libs import salt.master import salt.minion import salt.utils class Master(object): ''' Creates a master server ''' class Minion(object): ''' Create a minion server ''' def __init__(self): self.cli = self.__parse_cli() self.opts = salt.utils.minion_config(self.cli) def __parse_cli(self): ''' Parse the cli input ''' parser = optparse.OptionParser() parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true', help='Run the minion in the foreground') parser.add_option('-c', '--config', dest='config', default='/etc/salt/minion', help='Pass in an alternative configuration file') options, args = parser.parse_args() cli = {'foreground': options.foreground, 'config': options.config} return cli def start(self): ''' Execute this method to start up a minion. ''' minion = salt.Minion(self.opts) minion.tune_in()
''' Make me some salt! ''' # Import python libs import os import optparse # Import salt libs import salt.master import salt.minion import salt.utils class Master(object): ''' Creates a master server ''' class Minion(object): ''' Create a minion server ''' def __init__(self): self.cli = self.__parse_cli() self.opts = salt.utils.minion_config(self.cli) def __parse_cli(self): ''' Parse the cli input ''' parser = optparse.OptionParser() parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true', help='Run the minion in the foreground') parser.add_option('-c', '--config', dest='config', default='/etc/salt/minion', help='Pass in an alternative configuration file') options, args = parser.parse_args() cli = {'foreground': options.foreground, 'config': options.config} return cli def start(self): ''' Execute this method to start up a minion. ''' minion = salt.Minion(opts) minion.tune_in()
Use HttpsURLConnection for Spotify previews
package me.soundlocker.soundlocker; import android.os.AsyncTask; import org.apache.commons.lang3.ArrayUtils; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.net.ssl.HttpsURLConnection; public class DownloadSongByteData extends AsyncTask<URL, Integer, Byte[]> { @Override protected Byte[] doInBackground(URL... params) { URL url = params[0]; HttpsURLConnection urlConnection = null; try { urlConnection = (HttpsURLConnection) url.openConnection(); InputStream fileInputStream = new BufferedInputStream(urlConnection.getInputStream()); byte[] result = inputStreamToByteArray(fileInputStream); return ArrayUtils.toObject(result); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } return null; } private byte[] inputStreamToByteArray(InputStream inStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = inStream.read(buffer)) > 0) { baos.write(buffer, 0, bytesRead); } return baos.toByteArray(); } }
package me.soundlocker.soundlocker; import android.os.AsyncTask; import org.apache.commons.lang3.ArrayUtils; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class DownloadSongByteData extends AsyncTask<URL, Integer, Byte[]> { @Override protected Byte[] doInBackground(URL... params) { URL url = params[0]; HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url.openConnection(); InputStream fileInputStream = new BufferedInputStream(urlConnection.getInputStream()); byte[] result = inputStreamToByteArray(fileInputStream); return ArrayUtils.toObject(result); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } return null; } private byte[] inputStreamToByteArray(InputStream inStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = inStream.read(buffer)) > 0) { baos.write(buffer, 0, bytesRead); } return baos.toByteArray(); } }
Fix y axis tick labels for boxplot
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cbook as cbook from .geom import geom from ggplot.utils import is_string from ggplot.utils import is_categorical class geom_boxplot(geom): DEFAULT_AES = {'y': None, 'color': 'black', 'flier_marker': '+'} REQUIRED_AES = {'x'} DEFAULT_PARAMS = {'stat': 'identity', 'position': 'identity'} def __group(self, x, y): out = {} for xx, yy in zip(x,y): if yy not in out: out[yy] = [] out[yy].append(xx) return out def _plot_unit(self, pinfo, ax): x = pinfo.pop('x') y = pinfo.pop('y') color = pinfo.pop('color') fliermarker = pinfo.pop('flier_marker') if y is not None: g = self.__group(x,y) l = sorted(g.keys()) x = [g[k] for k in l] q = ax.boxplot(x, vert=False) plt.setp(q['boxes'], color=color) plt.setp(q['whiskers'], color=color) plt.setp(q['fliers'], color=color, marker=fliermarker) if l: plt.setp(ax, yticklabels=l)
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cbook as cbook from .geom import geom from ggplot.utils import is_string from ggplot.utils import is_categorical class geom_boxplot(geom): DEFAULT_AES = {'y': None, 'color': 'black', 'flier_marker': '+'} REQUIRED_AES = {'x'} DEFAULT_PARAMS = {'stat': 'identity', 'position': 'identity'} def __group(self, x, y): out = {} for xx, yy in zip(x,y): if yy not in out: out[yy] = [] out[yy].append(xx) return out def _plot_unit(self, pinfo, ax): x = pinfo.pop('x') y = pinfo.pop('y') color = pinfo.pop('color') fliermarker = pinfo.pop('flier_marker') if y is not None: g = self.__group(x,y) l = sorted(g.keys()) x = [g[k] for k in l] plt.setp(ax, yticklabels=l) q = ax.boxplot(x, vert=False) plt.setp(q['boxes'], color=color) plt.setp(q['whiskers'], color=color) plt.setp(q['fliers'], color=color, marker=fliermarker)
Replace login link with the audio link
<html> <head> <title>VAW</title> <link href="app/bootstrap/css/bootstrap.css" rel="stylesheet" /> <style> #main{ margin-top: 60px; } #information_input_form{ margin-top: 20px; } </style> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <div class="nav-collapse collapse"> <ul class="nav pull-left"> <li class="active"> <a href="http://vawhackdevel.com/">Home</a> </li> <li> <a href="http://vawhackdevel.com?page=audio">Audio</a> </li> </ul> </div><!-- nav-collapse --> </div><!-- container --> </div><!-- navbar-inner --> </div> <div class="clearfix"></div> <div id="main" class="container"> <?php if(isset($_GET["page"])) require_once('app/pages/'.$_GET['page'].".php"); else require_once('app/pages/home.php'); ?> </div> <div id="footer"> </div> <script src="app/bootstrap/js/bootstrap.min.js"></script> </body> </html>
<html> <head> <title>VAW</title> <link href="app/bootstrap/css/bootstrap.css" rel="stylesheet" /> <style> #main{ margin-top: 60px; } #information_input_form{ margin-top: 20px; } </style> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <div class="nav-collapse collapse"> <ul class="nav pull-left"> <li class="active"> <a href="http://vawhackdevel.com/">Home</a> </li> <li> <a href="http://vawhackdevel.com?page=login">Login</a> </li> </ul> </div><!-- nav-collapse --> </div><!-- container --> </div><!-- navbar-inner --> </div> <div class="clearfix"></div> <div id="main" class="container"> <?php if(isset($_GET["page"])) require_once('app/pages/'.$_GET['page'].".php"); else require_once('app/pages/home.php'); ?> </div> <div id="footer"> </div> <script src="app/bootstrap/js/bootstrap.min.js"></script> </body> </html>
Fix navbar loading (for real this time)
(function() { 'use strict'; angular.module('facetApp') .directive('wsNavbar', wsNavbarDirective); /* @ngInject */ function wsNavbarDirective($location, $templateRequest, $compile, $uibModal) { return { link: link, controller: NavbarController, controllerAs: 'vm' }; function link(scope, elem) { var templateUrl; if ($location.host() === 'www.norssit.fi') { templateUrl = '/navbar-fi.html'; } else { templateUrl = 'navbar-fi.html'; } return $templateRequest(templateUrl) .then(function(template) { elem.html(template); return $templateRequest('views/subnavbar.html'); }).then(function(template) { angular.element('#subnav').html(template); return $compile(elem.contents())(scope); }); } function NavbarController() { var vm = this; vm.showHelp = showHelp; function showHelp() { $uibModal.open({ templateUrl: 'views/help.html', size: 'lg' }); } } } })();
(function() { 'use strict'; angular.module('facetApp') .directive('wsNavbar', wsNavbarDirective); /* @ngInject */ function wsNavbarDirective($location, $templateRequest, $compile, $uibModal) { return { link: link, controller: NavbarController, controllerAs: 'vm' }; function link(scope, elem) { var templateUrl; if ($location.host() === 'norssit.fi') { templateUrl = '/navbar-fi.html'; } else { templateUrl = 'navbar-fi.html'; } return $templateRequest(templateUrl) .then(function(template) { elem.html(template); return $templateRequest('views/subnavbar.html'); }).then(function(template) { angular.element('#subnav').html(template); return $compile(elem.contents())(scope); }); } function NavbarController() { var vm = this; vm.showHelp = showHelp; function showHelp() { $uibModal.open({ templateUrl: 'views/help.html', size: 'lg' }); } } } })();
[examples] Use Index instead of App
// @flow import React, { Component } from 'react'; import Button from 'material-ui/Button'; import Dialog, { DialogTitle, DialogContent, DialogContentText, DialogActions, } from 'material-ui/Dialog'; import Typography from 'material-ui/Typography'; import withRoot from '../components/withRoot'; const styles = { container: { textAlign: 'center', paddingTop: 200, }, }; class Index extends Component { state = { open: false, }; handleRequestClose = () => { this.setState({ open: false, }); }; handleClick = () => { this.setState({ open: true, }); }; render() { return ( <div style={styles.container}> <Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle>Super Secret Password</DialogTitle> <DialogContent> <DialogContentText>1-2-3-4-5</DialogContentText> </DialogContent> <DialogActions> <Button color="primary" onClick={this.handleRequestClose}> OK </Button> </DialogActions> </Dialog> <Typography type="display1" gutterBottom> Material-UI </Typography> <Typography type="subheading" gutterBottom> example project </Typography> <Button raised color="accent" onClick={this.handleClick}> Super Secret Password </Button> </div> ); } } export default withRoot(Index);
// @flow import React, { Component } from 'react'; import Button from 'material-ui/Button'; import Dialog, { DialogTitle, DialogContent, DialogContentText, DialogActions, } from 'material-ui/Dialog'; import Typography from 'material-ui/Typography'; import withRoot from '../components/withRoot'; const styles = { container: { textAlign: 'center', paddingTop: 200, }, }; class App extends Component { state = { open: false, }; handleRequestClose = () => { this.setState({ open: false, }); }; handleClick = () => { this.setState({ open: true, }); }; render() { return ( <div style={styles.container}> <Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle>Super Secret Password</DialogTitle> <DialogContent> <DialogContentText>1-2-3-4-5</DialogContentText> </DialogContent> <DialogActions> <Button color="primary" onClick={this.handleRequestClose}> OK </Button> </DialogActions> </Dialog> <Typography type="display1" gutterBottom> Material-UI </Typography> <Typography type="subheading" gutterBottom> example project </Typography> <Button raised color="accent" onClick={this.handleClick}> Super Secret Password </Button> </div> ); } } export default withRoot(App);
Support collection statistics in data usage tests
# pylint: disable=missing-docstring from resdk.tests.functional.base import BaseResdkFunctionalTest class TestDataUsage(BaseResdkFunctionalTest): expected_fields = { 'user_id', 'username', 'full_name', 'data_size', 'data_size_normalized', 'data_count', 'data_count_normalized', 'collection_count', 'collection_count_normalized', 'sample_count', 'sample_count_normalized', } def test_normal_user(self): usage_info = self.user_res.data_usage() self.assertEqual(len(usage_info), 1) self.assertEqual(set(usage_info[0].keys()), self.expected_fields) def test_admin_user(self): usage_info = self.res.data_usage() self.assertGreaterEqual(len(usage_info), 2) self.assertEqual(set(usage_info[0].keys()), self.expected_fields) def test_ordering(self): usage_info = self.res.data_usage(ordering=['full_name', '-data_size']) self.assertGreaterEqual(len(usage_info), 2) first = usage_info[0] second = usage_info[1] self.assertEqual(first['full_name'], second['full_name']) self.assertGreaterEqual(first['data_size'], second['data_size'])
# pylint: disable=missing-docstring from resdk.tests.functional.base import BaseResdkFunctionalTest class TestDataUsage(BaseResdkFunctionalTest): expected_fields = { 'user_id', 'username', 'full_name', 'data_size', 'data_size_normalized', 'data_count', 'data_count_normalized', 'sample_count', 'sample_count_normalized', } def test_normal_user(self): usage_info = self.user_res.data_usage() self.assertEqual(len(usage_info), 1) self.assertEqual(set(usage_info[0].keys()), self.expected_fields) def test_admin_user(self): usage_info = self.res.data_usage() self.assertGreaterEqual(len(usage_info), 2) self.assertEqual(set(usage_info[0].keys()), self.expected_fields) def test_ordering(self): usage_info = self.res.data_usage(ordering=['full_name', '-data_size']) self.assertGreaterEqual(len(usage_info), 2) first = usage_info[0] second = usage_info[1] self.assertEqual(first['full_name'], second['full_name']) self.assertGreaterEqual(first['data_size'], second['data_size'])
Remove user password from req.user
let passport = require('passport'); let LocalStrategy = require('passport-local').Strategy; let bcrypt = require('bcrypt-nodejs'); let _ = require('lodash'); let uuid = require('uuid/v1'); module.exports = (app, db, log) => { app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser((user, done) => { done(null, user._id); });   passport.deserializeUser((id, done) => { db.get(id).then((user) => { if (!user || !user.enabled) done(null, false); else{ delete user.password; done(null, user); }   }, (err) => { if (err.error === 'not_found') done(null, false); else{ log.error(err); done(err, null); } }); }); passport.use('login', new LocalStrategy({ passReqToCallback : true, usernameField: 'email' }, function (req, email, password, done) { db.query('users/byEmail', { key: email, include_docs: true }).then(_users => { let users = _users.rows.map(r => r.doc); if (!users.length) { return done(null, false); } let user = users[0]; if (!user.enabled || !bcrypt.compareSync(password, user.password)) { return done(null, false); } return done(null, user); }); })); return passport; }
let passport = require('passport'); let LocalStrategy = require('passport-local').Strategy; let bcrypt = require('bcrypt-nodejs'); let _ = require('lodash'); let uuid = require('uuid/v1'); module.exports = (app, db, log) => { app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser((user, done) => { done(null, user._id); });   passport.deserializeUser((id, done) => { db.get(id).then((user) => { if (!user || !user.enabled) done(null, false); else done(null, user);   }, (err) => { if (err.error === 'not_found') done(null, false); else{ log.error(err); done(err, null); } }); }); passport.use('login', new LocalStrategy({ passReqToCallback : true, usernameField: 'email' }, function (req, email, password, done) { db.query('users/byEmail', { key: email, include_docs: true }).then(_users => { let users = _users.rows.map(r => r.doc); if (!users.length) { return done(null, false); } let user = users[0]; if (!user.enabled || !bcrypt.compareSync(password, user.password)) { return done(null, false); } return done(null, user); }); })); return passport; }
Add whitespace at end of classname strings in order to separate color classes
import React, { PropTypes } from 'react'; import colorByCharacter from '~/constants/colorByCharacter'; function WordCard(props) { const { word, isClues } = props; let cardClasses = `bo--1 bor--5 flex flex--jc--c align-items--center height--80 `; if (isClues) { cardClasses += word.isRevealed ? 'opacity--4-10 ' : 'cursor--pointer '; cardClasses += colorByCharacter[word.character] || 'white '; } else { cardClasses += word.isRevealed && colorByCharacter[word.character] ? colorByCharacter[word.character] : 'white '; } function toggleIsRevealed(word) { props.toggleIsRevealed && props.toggleIsRevealed(word); } return ( <div className={`grid__item col-1-5 mv-`} > <div className="ph-"> <div onClick={() => word.isRevealed ? null : toggleIsRevealed(word)} className={cardClasses} > <div className="grid grid--full col-1-1 pv"> <div className="grid__item col-1-1 text--center font--lg"> {word.text} </div> </div> </div> </div> </div> ); } WordCard.propTypes = { word: PropTypes.object.isRequired, toggleIsRevealed: PropTypes.func.isRequired, isClues: PropTypes.bool, }; export default WordCard;
import React, { PropTypes } from 'react'; import colorByCharacter from '~/constants/colorByCharacter'; function WordCard(props) { const { word, isClues } = props; let cardClasses = `bo--1 bor--5 flex flex--jc--c align-items--center height--80`; if (isClues) { cardClasses += word.isRevealed ? ' opacity--4-10' : ' cursor--pointer'; cardClasses += colorByCharacter[word.character] || ' white'; } else { cardClasses += word.isRevealed && colorByCharacter[word.character] ? colorByCharacter[word.character] : ' white'; } function toggleIsRevealed(word) { props.toggleIsRevealed && props.toggleIsRevealed(word); } return ( <div className={`grid__item col-1-5 mv-`} > <div className="ph-"> <div onClick={() => word.isRevealed ? null : toggleIsRevealed(word)} className={cardClasses} > <div className="grid grid--full col-1-1 pv"> <div className="grid__item col-1-1 text--center font--lg"> {word.text} </div> </div> </div> </div> </div> ); } WordCard.propTypes = { word: PropTypes.object.isRequired, toggleIsRevealed: PropTypes.func.isRequired, isClues: PropTypes.bool, }; export default WordCard;
Remove callable for php 5.3 compat.
<?php namespace Dflydev\Hawk\Header; class HeaderFactory { public static function create($fieldName, array $attributes = null) { $fieldValue = 'Hawk'; if (null !== $attributes) { $index = 0; foreach ($attributes as $key => $value) { if ($index++ > 0) { $fieldValue .= ','; } $fieldValue .= ' ' . $key . '="' . $value . '"'; } } return new Header($fieldName, $fieldValue, $attributes); } public static function createFromString($fieldName, $fieldValue, array $requiredKeys = null) { return static::create( $fieldName, HeaderParser::parseFieldValue($fieldValue, $requiredKeys) ); } public static function createFromHeaderObjectOrString($fieldName, $headerObjectOrString, $onError) { if (is_string($headerObjectOrString)) { return static::createFromString($fieldName, $headerObjectOrString); } elseif ($headerObjectOrString instanceof Header) { return $headerObjectOrString; } else { call_user_func($onError); } } }
<?php namespace Dflydev\Hawk\Header; class HeaderFactory { public static function create($fieldName, array $attributes = null) { $fieldValue = 'Hawk'; if (null !== $attributes) { $index = 0; foreach ($attributes as $key => $value) { if ($index++ > 0) { $fieldValue .= ','; } $fieldValue .= ' ' . $key . '="' . $value . '"'; } } return new Header($fieldName, $fieldValue, $attributes); } public static function createFromString($fieldName, $fieldValue, array $requiredKeys = null) { return static::create( $fieldName, HeaderParser::parseFieldValue($fieldValue, $requiredKeys) ); } public static function createFromHeaderObjectOrString($fieldName, $headerObjectOrString, callable $onError) { if (is_string($headerObjectOrString)) { return static::createFromString($fieldName, $headerObjectOrString); } elseif ($headerObjectOrString instanceof Header) { return $headerObjectOrString; } else { throw new \InvalidArgumentException( 'Header must either be a string or an instance of "Dflydev\Hawk\Header\Header"' ); } } }
Add test to cover the case where `needs` isn't an array
describe('lib/rules/disallow-positionalparams-extend', function () { var checker = global.checker({ plugins: ['./lib/index'] }); describe('not configured', function() { it('should report with undefined', function() { global.expect(function() { checker.configure({disallowControllerNeeds: undefined}); }).to.throws(/requires a true value/i); }); it('should report with an object', function() { global.expect(function() { checker.configure({disallowControllerNeeds: {}}); }).to.throws(/requires a true value/i); }); }); describe('with true', function() { checker.rules({disallowControllerNeeds: true}); checker.cases([ /* jshint ignore:start */ { it: 'should not report controller injection', code: function() { Ember.Controller.extend({ comments: Ember.inject.controller(), newComments: Ember.computed.alias('comments.newest') }); } }, { it: 'should not report needs other value', code: function() { Ember.Controller.extend({ needs: null, }); } }, { it: 'should report needs array', errors: 1, code: function() { Ember.Controller.extend({ needs: ['comments'], newComments: Ember.computed.alias('controllers.comments.newest') }); } } /* jshint ignore:end */ ]); }); });
describe('lib/rules/disallow-positionalparams-extend', function () { var checker = global.checker({ plugins: ['./lib/index'] }); describe('not configured', function() { it('should report with undefined', function() { global.expect(function() { checker.configure({disallowControllerNeeds: undefined}); }).to.throws(/requires a true value/i); }); it('should report with an object', function() { global.expect(function() { checker.configure({disallowControllerNeeds: {}}); }).to.throws(/requires a true value/i); }); }); describe('with true', function() { checker.rules({disallowControllerNeeds: true}); checker.cases([ /* jshint ignore:start */ { it: 'should not report controller injection', code: function() { Ember.Controller.extend({ comments: Ember.inject.controller(), newComments: Ember.computed.alias('comments.newest') }); } }, { it: 'should report needs array', errors: 1, code: function() { Ember.Controller.extend({ needs: ['comments'], newComments: Ember.computed.alias('controllers.comments.newest') }); } } /* jshint ignore:end */ ]); }); });
Add testcase to Acronym test for single letter word
import org.junit.Test; import static org.junit.Assert.assertEquals; public class AcronymTest { @Test public void fromTitleCasedPhrases() { final String phrase = "Portable Network Graphics"; final String expected = "PNG"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromOtherTitleCasedPhrases() { final String phrase = "Ruby on Rails"; final String expected = "ROR"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromInconsistentlyCasedPhrases() { final String phrase = "HyperText Markup Language"; final String expected = "HTML"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromPhrasesWithPunctuation() { final String phrase = "First In, First Out"; final String expected = "FIFO"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromOtherPhrasesWithPunctuation() { final String phrase = "PHP: Hypertext Preprocessor"; final String expected = "PHP"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromPhrasesWithPunctuationAndSentenceCasing() { final String phrase = "Complementary metal-oxide semiconductor"; final String expected = "CMOS"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromPhraseWithSingleLetterWord() { final String phrase = "Cat in a Hat"; final String expected = "CIAH"; assertEquals(expected, Acronym.generate(phrase)); } }
import org.junit.Test; import static org.junit.Assert.assertEquals; public class AcronymTest { @Test public void fromTitleCasedPhrases() { final String phrase = "Portable Network Graphics"; final String expected = "PNG"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromOtherTitleCasedPhrases() { final String phrase = "Ruby on Rails"; final String expected = "ROR"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromInconsistentlyCasedPhrases() { final String phrase = "HyperText Markup Language"; final String expected = "HTML"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromPhrasesWithPunctuation() { final String phrase = "First In, First Out"; final String expected = "FIFO"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromOtherPhrasesWithPunctuation() { final String phrase = "PHP: Hypertext Preprocessor"; final String expected = "PHP"; assertEquals(expected, Acronym.generate(phrase)); } @Test public void fromPhrasesWithPunctuationAndSentenceCasing() { final String phrase = "Complementary metal-oxide semiconductor"; final String expected = "CMOS"; assertEquals(expected, Acronym.generate(phrase)); } }
Sort out the server announce message Tidy up the server announce message a bit. In particular, we might as well announce the absent-entries capability - we support the commands even if they currently aren't implemented.
import parse import generate as gen from repos import find_repos from errors import * server_capabilities = [ 'edit-pipeline', # This is required. 'svndiff1', # We support svndiff1 'absent-entries', # We support absent-dir and absent-dir editor commands #'commit-revprops', # We don't currently have _any_ revprop support #'mergeinfo', # Nope, not yet #'depth', # Nope, not yet ] def parse_client_greeting(msg_str): msg = parse.msg(msg_str) proto_ver = int(msg[0]) client_caps = msg[1] url = parse.string(msg[2]) print "ver: %d" % proto_ver print "caps: %s" % client_caps print "url: %s" % url return proto_ver, client_caps, url def connect(link): # Send the announce message - we only support protocol version 2. link.send_msg(gen.success(2, 2, gen.list(), gen.list(*server_capabilities))) client_resp = link.read_msg() ver, caps, url = parse_client_greeting(client_resp) if ver != 2: raise BadProtoVersion() repos = find_repos(url) if repos is None: link.send_msg(gen.failure(gen.list(210005, gen.string("No repository found in '%s'" % url), gen.string('message.py'), 0))) return url, caps, repos
import parse import generate as gen from repos import find_repos from errors import * def parse_client_greeting(msg_str): msg = parse.msg(msg_str) proto_ver = int(msg[0]) client_caps = msg[1] url = parse.string(msg[2]) print "ver: %d" % proto_ver print "caps: %s" % client_caps print "url: %s" % url return proto_ver, client_caps, url def connect(link): link.send_msg(gen.success(2, 2, gen.list('ANONYMOUS'), gen.list('edit-pipeline', 'svndiff1'))) client_resp = link.read_msg() ver, caps, url = parse_client_greeting(client_resp) if ver != 2: raise BadProtoVersion() repos = find_repos(url) if repos is None: link.send_msg(gen.failure(gen.list(210005, gen.string("No repository found in '%s'" % url), gen.string('message.py'), 0))) return url, caps, repos
Add hash to webpack bundle name
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const pathsToClean = ['dist']; const config = { entry: [ './src/index.js' // entry point of the app ], output: { filename: '[name].[chunkhash:8].js', path: path.resolve(__dirname, 'dist'), publicPath: '' // necessary for HMR to know where to load the hot update chunks }, module: { rules: [ { test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/ }, { test: /\.scss$/, use: [{ loader: 'style-loader' // creates style nodes from JS strings }, { loader: 'css-loader' // translates CSS into CommonJS }, { loader: 'sass-loader' // compiles Sass to CSS }] }, { test: /\.(jpg|png|svg)$/, use: { loader: 'url-loader', options: { limit: 25000, name: '[name].[ext]' } } } ] }, plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }), new webpack.optimize.UglifyJsPlugin({ beautify: false, comments: false }), new HtmlWebpackPlugin({ template: 'index.html' }), new CleanWebpackPlugin(pathsToClean, { verbose: true }) ] }; module.exports = config;
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const pathsToClean = ['dist']; const config = { entry: [ './src/index.js' // entry point of the app ], output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: '' // necessary for HMR to know where to load the hot update chunks }, module: { rules: [ { test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/ }, { test: /\.scss$/, use: [{ loader: 'style-loader' // creates style nodes from JS strings }, { loader: 'css-loader' // translates CSS into CommonJS }, { loader: 'sass-loader' // compiles Sass to CSS }] }, { test: /\.(jpg|png|svg)$/, use: { loader: 'url-loader', options: { limit: 25000, name: '[name].[ext]' } } } ] }, plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }), new webpack.optimize.UglifyJsPlugin({ beautify: false, comments: false }), new HtmlWebpackPlugin({ template: 'index.html' }), new CleanWebpackPlugin(pathsToClean, { verbose: true }) ] }; module.exports = config;
Use rest param instead of slice
'use strict'; let spawn = require('cross-spawn'); module.exports = function spawnAsync(...args) { let child; let promise = new Promise((fulfill, reject) => { child = spawn.apply(spawn, args); let stdout = ''; let stderr = ''; if (child.stdout) { child.stdout.on('data', data => { stdout += data; }); } if (child.stderr) { child.stderr.on('data', data => { stderr += data; }); } child.on('close', (code, signal) => { child.removeAllListeners(); let result = { pid: child.pid, output: [stdout, stderr], stdout, stderr, status: code, signal, }; if (code) { let error = new Error(`Process exited with non-zero code: ${code}`); Object.assign(error, result); reject(error); } else { fulfill(result); } }); child.on('error', error => { child.removeAllListeners(); error.pid = child.pid; error.output = [stdout, stderr]; error.stdout = stdout; error.stderr = stderr; error.status = null; reject(error); }); }); promise.child = child; return promise; };
'use strict'; let spawn = require('cross-spawn'); module.exports = function spawnAsync() { let args = Array.prototype.slice.call(arguments, 0); let child; let promise = new Promise((fulfill, reject) => { child = spawn.apply(spawn, args); let stdout = ''; let stderr = ''; if (child.stdout) { child.stdout.on('data', data => { stdout += data; }); } if (child.stderr) { child.stderr.on('data', data => { stderr += data; }); } child.on('close', (code, signal) => { child.removeAllListeners(); let result = { pid: child.pid, output: [stdout, stderr], stdout, stderr, status: code, signal, }; if (code) { let error = new Error(`Process exited with non-zero code: ${code}`); Object.assign(error, result); reject(error); } else { fulfill(result); } }); child.on('error', error => { child.removeAllListeners(); error.pid = child.pid; error.output = [stdout, stderr]; error.stdout = stdout; error.stderr = stderr; error.status = null; reject(error); }); }); promise.child = child; return promise; };
Handle google api client authentication
/** @jsx React.DOM */ var GoogleApiAuthForm = React.createClass({ getInitialState: function() { return {apiKey: null, clientId: null}; }, render: function () { return ( <form role="form"> <div className="form-group"> <label for="client_id">Client Id</label> <input ref="clientId" id="client_id" className="form-control" type="text" name="client_id" placeholder="Google API Client ID" /> </div> <div className="form-group"> <label for="api_key">API Key</label> <input ref="apiKey" id="api_key" className="form-control" type="text" name="api_key" placeholder="Google API Key"/> </div> <button className="btn btn-lg btn-primary" type="submit" onSubmit={this.handleSubmit}> Authenticate </button> </form> ); }, handleSubmit: function(ev) { ev.preventDefault(); var scopes = ['https://www.googleapis.com/auth/drive.readonly']; var clientId = this.refs.clientId.getDOMNode().value.trim(); var apiKey = this.refs.apiKey.getDOMNode().value.trim(); gapi.client.setApiKey(apiKey); function checkAuth() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}); } } }); React.renderComponent(<GoogleApiAuthForm />, document.getElementById('app'));
/** @jsx React.DOM */ var GoogleApiAuthForm = React.createClass({ render: function () { return ( <form role="form"> <div className="form-group"> <label for="client_id">Client Id</label> <input id="client_id" className="form-control" type="text" name="client_id" placeholder="Google API Client ID" /> </div> <div className="form-group"> <label for="api_key">API Key</label> <input id="api_key" className="form-control" type="text" name="api_key" placeholder="Google API Key"/> </div> <button className="btn btn-lg btn-primary" type="submit">Authenticate</button> </form> ); } }); React.renderComponent(<GoogleApiAuthForm />, document.getElementById('app'));
Update exception message with Interfacename
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\View\Helper; use Zend\Authentication\AuthenticationServiceInterface; use Zend\View\Exception; /** * View helper plugin to fetch the authenticated identity. */ class Identity extends AbstractHelper { /** * AuthenticationService instance * * @var AuthenticationServiceInterface */ protected $authenticationService; /** * Retrieve the current identity, if any. * * If none available, returns null. * * @throws Exception\RuntimeException * @return mixed|null */ public function __invoke() { if (!$this->authenticationService instanceof AuthenticationServiceInterface) { throw new Exception\RuntimeException('No AuthenticationServiceInterface instance provided'); } if (!$this->authenticationService->hasIdentity()) { return null; } return $this->authenticationService->getIdentity(); } /** * Set AuthenticationService instance * * @param AuthenticationServiceInterface $authenticationService * @return Identity */ public function setAuthenticationService(AuthenticationServiceInterface $authenticationService) { $this->authenticationService = $authenticationService; return $this; } /** * Get AuthenticationService instance * * @return AuthenticationServiceInterface */ public function getAuthenticationService() { return $this->authenticationService; } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\View\Helper; use Zend\Authentication\AuthenticationServiceInterface; use Zend\View\Exception; /** * View helper plugin to fetch the authenticated identity. */ class Identity extends AbstractHelper { /** * AuthenticationService instance * * @var AuthenticationServiceInterface */ protected $authenticationService; /** * Retrieve the current identity, if any. * * If none available, returns null. * * @throws Exception\RuntimeException * @return mixed|null */ public function __invoke() { if (!$this->authenticationService instanceof AuthenticationServiceInterface) { throw new Exception\RuntimeException('No AuthenticationService instance provided'); } if (!$this->authenticationService->hasIdentity()) { return null; } return $this->authenticationService->getIdentity(); } /** * Set AuthenticationService instance * * @param AuthenticationServiceInterface $authenticationService * @return Identity */ public function setAuthenticationService(AuthenticationServiceInterface $authenticationService) { $this->authenticationService = $authenticationService; return $this; } /** * Get AuthenticationService instance * * @return AuthenticationServiceInterface */ public function getAuthenticationService() { return $this->authenticationService; } }
[Cms] Use query cache for find page by route.
<?php namespace Ekyna\Bundle\CmsBundle\Entity; use Ekyna\Component\Resource\Doctrine\ORM\TranslatableResourceRepositoryInterface; use Ekyna\Component\Resource\Doctrine\ORM\Util\TranslatableResourceRepositoryTrait; use Gedmo\Tree\Entity\Repository\NestedTreeRepository; /** * Class PageRepository * @package Ekyna\Bundle\CmsBundle\Entity * @author Étienne Dauvergne <[email protected]> */ class PageRepository extends NestedTreeRepository implements TranslatableResourceRepositoryInterface { use TranslatableResourceRepositoryTrait; /** * {@inheritdoc} */ public function createQueryBuilder($alias, $indexBy = null) { return parent::createQueryBuilder($alias, $indexBy) ->innerJoin($alias.'.seo', 'seo'); } /** * Finds a page by request. * * @param string $routeName * @return null|\Ekyna\Bundle\CmsBundle\Model\PageInterface */ public function findOneByRoute($routeName) { $qb = $this->createQueryBuilder('p'); return $qb ->andWhere($qb->expr()->eq('p.route', $qb->expr()->literal($routeName))) ->setMaxResults(1) ->getQuery() ->useQueryCache(true) ->useResultCache(true, 3600, 'ekyna_cms.page[route:'.$routeName.']') ->getOneOrNullResult() ; } }
<?php namespace Ekyna\Bundle\CmsBundle\Entity; use Ekyna\Component\Resource\Doctrine\ORM\TranslatableResourceRepositoryInterface; use Ekyna\Component\Resource\Doctrine\ORM\Util\TranslatableResourceRepositoryTrait; use Gedmo\Tree\Entity\Repository\NestedTreeRepository; /** * Class PageRepository * @package Ekyna\Bundle\CmsBundle\Entity * @author Étienne Dauvergne <[email protected]> */ class PageRepository extends NestedTreeRepository implements TranslatableResourceRepositoryInterface { use TranslatableResourceRepositoryTrait; /** * {@inheritdoc} */ public function createQueryBuilder($alias, $indexBy = null) { return parent::createQueryBuilder($alias, $indexBy) ->innerJoin($alias.'.seo', 'seo'); } /** * Finds a page by request. * * @param string $routeName * @return null|\Ekyna\Bundle\CmsBundle\Model\PageInterface */ public function findOneByRoute($routeName) { $qb = $this->createQueryBuilder('p'); return $qb ->andWhere($qb->expr()->eq('p.route', $qb->expr()->literal($routeName))) ->setMaxResults(1) ->getQuery() ->useResultCache(true, 3600, 'ekyna_cms.page[route:'.$routeName.']') ->getOneOrNullResult() ; } }
BAP-8491: Send mass notifications to application users—CLI only - update CLI Command
<?php namespace Oro\Bundle\NotificationBundle\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; /** * Class MassNotificationCommand * Console command implementation * * @package Oro\Bundle\NavigationBundle\Command */ class MassNotificationCommand extends ContainerAwareCommand { /** * Console command configuration */ public function configure() { $this->setName('oro:mass_notification:send') ->addArgument( 'title', InputArgument::REQUIRED, 'Set title for message' ) ->addArgument( 'body', InputArgument::REQUIRED, 'Set body message' ) ->addArgument( 'from', InputArgument::OPTIONAL, 'Who send message' ); $this->setDescription('Send mass notification for user'); } /** * Runs command * * @param InputInterface $input * @param OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $output->writeln($this->getDescription()); $output->writeln('Completed'); } public function getHelpMessage() { } }
<?php namespace Oro\Bundle\NavigationBundle\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; /** * Class MassNotificationCommand * Console command implementation * * @package Oro\Bundle\NavigationBundle\Command */ class MassNotificationCommand extends ContainerAwareCommand { /** * Console command configuration */ public function configure() { $this->setName('oro:mass_notification:send') ->addArgument( 'title', InputArgument::REQUIRED, 'Set title for message' ) ->addArgument( 'body', InputArgument::REQUIRED, 'Set body message' ) ->addArgument( 'from', InputArgument::OPTIONAL, 'Who send message' ); $this->setDescription('Send mass notification for user'); } /** * Runs command * * @param InputInterface $input * @param OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $output->writeln($this->getDescription()); $output->writeln('Completed'); } }
Fix typo preventing build to proceed
package org.elasticsearch.rest.action.readonlyrest.acl.test; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import com.google.common.base.Charsets; import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.RestRequest.Method; import org.elasticsearch.rest.action.readonlyrest.acl.ACL; import org.elasticsearch.rest.action.readonlyrest.acl.ACLRequest; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class MarvelPassthroughACL { private static ACL acl; @BeforeClass public static void setUpBeforeClass() throws Exception { try { byte[] encoded = Files.readAllBytes(Paths.get(System.getProperty("user.dir") + "/src/test/marvel_passthrough.yml")); String str = Charsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString(); Settings s = Settings.builder().loadFromSource(str).build(); acl = new ACL(ESLoggerFactory.getLogger(ACL.class.getName()), s); } catch (IOException e) { e.printStackTrace(); } } @Test public final void testInternalMethods(){ Assert.assertNull(acl.check( new ACLRequest(".marvel-2015.11.10/_search", "127.0.0.1", "", "", 0, Method.POST, null))); } }
package org.elasticsearch.rest.action.readonlyrest.acl.test; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import com.google.common.base.Charsets; import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.RestRequest.Method; import org.elasticsearch.rest.action.readonlyrest.acl.ACL; import org.elasticsearch.rest.action.readonlyrest.acl.ACLRequest; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class MarvelPassThroughACL { private static ACL acl; @BeforeClass public static void setUpBeforeClass() throws Exception { try { byte[] encoded = Files.readAllBytes(Paths.get(System.getProperty("user.dir") + "/src/test/marvel_passthrough.yml")); String str = Charsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString(); Settings s = Settings.builder().loadFromSource(str).build(); acl = new ACL(ESLoggerFactory.getLogger(ACL.class.getName()), s); } catch (IOException e) { e.printStackTrace(); } } @Test public final void testInternalMethods(){ Assert.assertNull(acl.check( new ACLRequest(".marvel-2015.11.10/_search", "127.0.0.1", "", "", 0, Method.POST, null))); } }
Rename Message container component because type error
/** * Created by ivan on 8/10/16. */ var MessageContainerComponent = React.createClass({ render: function () { return ( <div id="message-container"> </div> ) } }); var MessageFormComponent = React.createClass({ render: function () { return ( <form id="send-message-form"> <div className="row"> <div className="col s10"> <input type="text" name="message" id="message"/> </div> <div className="col s2"> <button className="btn waves-effect waves-light" type="submit" name="action"> Enviar <i className="material-icons right">send</i> </button> </div> </div> </form> ) } }); var ChatComponent = React.createClass({ render: function () { return ( <div id="chat"> <MessageContainerComponent /> <MessageFormComponent /> </div> ) } }); var HeaderComponent = React.createClass({ render: function () { return ( <nav> <div className="nav-wrapper indigo darken-3"> <a href="#" className="brand-logo">Chat con React</a> </div> </nav> ) } }); var AppComponent = React.createClass({ render: function () { return ( <main> <HeaderComponent /> <ChatComponent /> </main> ) } }); ReactDOM.render( <AppComponent />, document.getElementById('app') );
/** * Created by ivan on 8/10/16. */ var MessageContarinerComponent = React.createClass({ render: function () { return ( <div id="message-container"> </div> ) } }); var MessageFormComponent = React.createClass({ render: function () { return ( <form id="send-message-form"> <div className="row"> <div className="col s10"> <input type="text" name="message" id="message"/> </div> <div className="col s2"> <button className="btn waves-effect waves-light" type="submit" name="action"> Enviar <i className="material-icons right">send</i> </button> </div> </div> </form> ) } }); var ChatComponent = React.createClass({ render: function () { return ( <div id="chat"> <MessageContarinerComponent /> <MessageFormComponent /> </div> ) } }); var HeaderComponent = React.createClass({ render: function () { return ( <nav> <div className="nav-wrapper indigo darken-3"> <a href="#" className="brand-logo">Chat con React</a> </div> </nav> ) } }); var AppComponent = React.createClass({ render: function () { return ( <main> <HeaderComponent /> <ChatComponent /> </main> ) } }); ReactDOM.render( <AppComponent />, document.getElementById('app') );
Define default values for host and port
from flask import Flask from flask import request from flask import jsonify import json import subprocess app = Flask(__name__) config = None @app.route('/', methods=['POST']) def hook_listen(): if request.method == 'POST': token = request.args.get('token') if token == config['token']: hook = request.args.get('hook') if hook: hook_value = config['hooks'].get(hook) if hook_value: #payload = request.get_json() try: subprocess.call(hook_value) return jsonify(success=True), 200 except OSError as e: return jsonify(success=False, error=str(e)), 400 else: return jsonify(success=False, error="Hook not found"), 404 else: return jsonify(success=False, error="Invalid request: missing hook"), 400 else: return jsonify(success=False, error="Invalid token"), 400 def load_config(): with open('config.json') as config_file: return json.load(config_file) if __name__ == '__main__': config = load_config() app.run(host=config.get('host', 'localhost'), port=config.get('port', 8000))
from flask import Flask from flask import request from flask import jsonify import json import subprocess app = Flask(__name__) config = None @app.route('/', methods=['POST']) def hook_listen(): if request.method == 'POST': token = request.args.get('token') if token == config['token']: hook = request.args.get('hook') if hook: hook_value = config['hooks'].get(hook) if hook_value: #payload = request.get_json() try: subprocess.call(hook_value) return jsonify(success=True), 200 except OSError as e: return jsonify(success=False, error=str(e)), 400 else: return jsonify(success=False, error="Hook not found"), 404 else: return jsonify(success=False, error="Invalid request: missing hook"), 400 else: return jsonify(success=False, error="Invalid token"), 400 def load_config(): with open('config.json') as config_file: return json.load(config_file) if __name__ == '__main__': config = load_config() app.run(host=config['host'], port=config['port'])
Add watch to Canistreamit header.
function ddg_spice_canistreamit(movies) { // console.log(xk); var result,img,snippet,link,div; var items = new Array(); for(var i = 0; i<movies.length; i++) { result = movies[i]; // Make title for header var header = 'Watch ' + result.title + " ("+result.year+")"; // Call nra function as per Spice Plugin Guidelines var item = new Array(); var content = "<div><i>Starring:</i> "+result.actors+".</div>"; content += "<div><i>Streaming:</i> "; var count = 0; for(var subtype in result.affiliates) { var service = result.affiliates[subtype]; content += "<a href='"+service.url+"'>"+service.friendlyName; var price = parseFloat(service.price); if(price > 0) content += " ($"+service.price+")"; content += "</a>, " count++; } if(count > 0) content = content.substring(0,content.length-2); content += ".</div>" item['a'] = content; item['h'] = header; // Source name and url for the More at X link. item['s'] = 'CanIStream.It'; item['u'] = result.links.shortUrl; // Force no compression. item['f'] = 1; // Thumbnail url item['i'] = result.image; items.push(item); } // The rendering function is nra. nra(items); }
function ddg_spice_canistreamit(movies) { // console.log(xk); var result,img,snippet,link,div; var items = new Array(); for(var i = 0; i<movies.length; i++) { result = movies[i]; // Make title for header var header = result.title + " ("+result.year+")"; // Call nra function as per Spice Plugin Guidelines var item = new Array(); var content = "<div><i>Starring:</i> "+result.actors+".</div>"; content += "<div><i>Streaming:</i> "; var count = 0; for(var subtype in result.affiliates) { var service = result.affiliates[subtype]; content += "<a href='"+service.url+"'>"+service.friendlyName; var price = parseFloat(service.price); if(price > 0) content += " ($"+service.price+")"; content += "</a>, " count++; } if(count > 0) content = content.substring(0,content.length-2); content += ".</div>" item['a'] = content; item['h'] = header; // Source name and url for the More at X link. item['s'] = 'CanIStream.It'; item['u'] = result.links.shortUrl; // Force no compression. item['f'] = 1; // Thumbnail url item['i'] = result.image; items.push(item); } // The rendering function is nra. nra(items); }
Add cpus directive unit test
(function () { 'use strict'; describe('directives module', function () { var $compile, $rootScope, DropletMock; beforeEach(module('directives')); beforeEach(inject(function ($injector) { $compile = $injector.get('$compile'); $rootScope = $injector.get('$rootScope'); DropletMock = { 'status': 'active', 'memory': '512', 'vcpus': 1 }; })); describe('status', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<status></status>')($scope); $rootScope.$digest(); }); it('should contains the "Status: active" string in a child node', function () { expect(element[0].innerText).toBe('Status: active'); }); }); describe('memory', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<memory></memory>')($scope); $rootScope.$digest(); }); it('should contains the "Memory: 512MB" string in a child node', function () { expect(element[0].innerText).toBe('Memory: 512 MB'); }); }); describe('cpus', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<cpus></cpus>')($scope); $rootScope.$digest(); }); it('should contains the "CPUs: 1" string in a child node', function () { expect(element[0].innerText).toBe("CPUs: 1"); }); }); }); })();
(function () { 'use strict'; describe('directives module', function () { var $compile, $rootScope, DropletMock; beforeEach(module('directives')); beforeEach(inject(function ($injector) { $compile = $injector.get('$compile'); $rootScope = $injector.get('$rootScope'); DropletMock = { 'status': 'active', 'memory': '512' }; })); describe('status', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<status></status>')($scope); $rootScope.$digest(); }); it('should contains the "Status: active" string in a child node', function () { expect(element[0].innerText).toBe('Status: active'); }); }); describe('memory', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<memory></memory>')($scope); $rootScope.$digest(); }); it('should contains the "Memory: 512MB" string in a child node', function () { expect(element[0].innerText).toBe('Memory: 512 MB'); }); }); }); })();
Remove unused option for client-side bundle
const url = require('url'); const config = { builders: { web: { entry: './src/index.tsx', stack: ['web'], openBrowser: true, dllExcludes: ['bootstrap'], defines: { __CLIENT__: true }, // Wait for backend to start prior to letting webpack load frontend page waitOn: ['tcp:localhost:8080'], enabled: true }, test: { stack: ['server'], roles: ['test'], defines: { __TEST__: true } } }, options: { stack: ['apollo', 'react', 'styled-components', 'css', 'sass', 'less', 'es6', 'ts', 'webpack', 'i18next'], cache: '../../.cache', ssr: true, webpackDll: true, reactHotLoader: false, defines: { __DEV__: process.env.NODE_ENV !== 'production', __API_URL__: '"/graphql"' }, webpackConfig: { devServer: { disableHostCheck: true } } } }; config.options.devProxy = config.options.ssr; if (process.env.NODE_ENV === 'production') { // Generating source maps for production will slowdown compilation for roughly 25% config.options.sourceMap = false; } const extraDefines = { __SSR__: config.options.ssr }; config.options.defines = Object.assign(config.options.defines, extraDefines); module.exports = config;
const url = require('url'); const config = { builders: { web: { entry: './src/index.tsx', stack: ['web'], openBrowser: true, dllExcludes: ['bootstrap'], defines: { __CLIENT__: true }, // Wait for backend to start prior to letting webpack load frontend page waitOn: ['tcp:localhost:8080'], enabled: true }, test: { stack: ['server'], roles: ['test'], defines: { __TEST__: true } } }, options: { stack: ['apollo', 'react', 'styled-components', 'css', 'sass', 'less', 'es6', 'ts', 'webpack', 'i18next'], cache: '../../.cache', ssr: true, webpackDll: true, reactHotLoader: false, frontendRefreshOnBackendChange: true, defines: { __DEV__: process.env.NODE_ENV !== 'production', __API_URL__: '"/graphql"' }, webpackConfig: { devServer: { disableHostCheck: true } } } }; config.options.devProxy = config.options.ssr; if (process.env.NODE_ENV === 'production') { // Generating source maps for production will slowdown compilation for roughly 25% config.options.sourceMap = false; } const extraDefines = { __SSR__: config.options.ssr }; config.options.defines = Object.assign(config.options.defines, extraDefines); module.exports = config;
Change the string format for last-updated property of a register. This now just uses toString() to return the whole timestamp. We may need to change this at a later date once we have decided whether or not the last-updated time will be an object with or without a timezone.
package uk.gov.register.presentation; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.LocalDateTime; public class RegisterDetail { private final String domain; private final int totalRecords; private final int totalEntries; private final int totalItems; private final LocalDateTime lastUpdated; private final EntryView entryView; public RegisterDetail( String domain, int totalRecords, int totalEntries, int totalItems, LocalDateTime lastUpdated, EntryView entryView) { this.domain = domain; this.totalRecords = totalRecords; this.totalEntries = totalEntries; this.totalItems = totalItems; this.lastUpdated = lastUpdated; this.entryView = entryView; } @JsonProperty("domain") public String getDomain() { return domain; } @JsonProperty("last-updated") public String getLastUpdatedTime(){ return lastUpdated.toString(); } @JsonProperty("record") public EntryView getEntry() { return entryView; } @JsonProperty("total-entries") public int getTotalEntries() { return totalEntries; } @JsonProperty("total-items") public int getTotalItems() { return totalItems; } @JsonProperty("total-records") public int getTotalRecords(){ return totalRecords; } }
package uk.gov.register.presentation; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class RegisterDetail { private final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("d MMM uuuu"); private final String domain; private final int totalRecords; private final int totalEntries; private final int totalItems; private final LocalDateTime lastUpdated; private final EntryView entryView; public RegisterDetail( String domain, int totalRecords, int totalEntries, int totalItems, LocalDateTime lastUpdated, EntryView entryView) { this.domain = domain; this.totalRecords = totalRecords; this.totalEntries = totalEntries; this.totalItems = totalItems; this.lastUpdated = lastUpdated; this.entryView = entryView; } @JsonProperty("domain") public String getDomain() { return domain; } @JsonProperty("last-updated") public String getLastUpdatedTime(){ return DATE_TIME_FORMATTER.format(lastUpdated); } @JsonProperty("record") public EntryView getEntry() { return entryView; } @JsonProperty("total-entries") public int getTotalEntries() { return totalEntries; } @JsonProperty("total-items") public int getTotalItems() { return totalItems; } @JsonProperty("total-records") public int getTotalRecords(){ return totalRecords; } }
Add offset to clickable square
BEST.module('famous:examples:demos:clickable-square', 'HEAD', { tree: 'clickable-square.html', behaviors: { '#context': { 'size': [200, 200], 'position': function(offset) { return [offset, offset] } }, '#surface': { 'template': function(count) { return { count: count }; }, 'style' : function(backgroundColor) { return { 'background-color' : backgroundColor, 'cursor' : 'pointer' } }, 'unselectable': true } }, events: { '#context': { 'famous:events:click': function($state, $payload) { $state.set('count', $state.get('count') + 1); console.log('Click event on context: ', $payload); } }, '$public': { 'hello' : function() { console.log('hello!'); }, 'background-color' : 'setter|camel' } }, states: { count: 0, offset: 100, backgroundColor: 'gray' } });
BEST.module('famous:examples:demos:clickable-square', 'HEAD', { tree: 'clickable-square.html', behaviors: { '#context': { 'size': [200, 200], 'position': function(offset) { return [offset, offset] } }, '#surface': { 'template': function(count) { return { count: count }; }, 'style' : function(backgroundColor) { return { 'background-color' : backgroundColor, 'cursor' : 'pointer' } }, 'unselectable': true } }, events: { '#context': { 'famous:events:click': function($state, $payload) { $state.set('count', $state.get('count') + 1); console.log('Click event on context: ', $payload); } }, '$public': { 'hello' : function() { console.log('hello!'); }, 'background-color' : 'setter|camel' } }, states: { count: 0, offset: 0, backgroundColor: 'gray' } });
Revert "Make migration SQLite compatible" This reverts commit 768d85cccb17c8757dd8d14dad220d0b87568264.
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-05-09 09:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('attempts', '0007_auto_20161004_0927'), ] operations = [ migrations.AddField( model_name='attempt', name='submission_date', field=models.DateTimeField(null=True), ), migrations.AddField( model_name='historicalattempt', name='submission_date', field=models.DateTimeField(null=True), ), migrations.RunSQL( 'UPDATE attempts_historicalattempt SET submission_date = history_date' ), migrations.RunSQL( '''UPDATE attempts_attempt SET submission_date = subquery.submission_date FROM ( SELECT user_id, part_id, max(history_date) AS submission_date FROM attempts_historicalattempt GROUP BY user_id, part_id ) AS subquery WHERE attempts_attempt.user_id = subquery.user_id AND attempts_attempt.part_id = subquery.part_id ''' ), migrations.AlterField( model_name='attempt', name='submission_date', field=models.DateTimeField(auto_now=True), ), migrations.AlterField( model_name='historicalattempt', name='submission_date', field=models.DateTimeField(blank=True, editable=False), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-05-09 09:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('attempts', '0007_auto_20161004_0927'), ] operations = [ migrations.AddField( model_name='attempt', name='submission_date', field=models.DateTimeField(null=True), ), migrations.AddField( model_name='historicalattempt', name='submission_date', field=models.DateTimeField(null=True), ), migrations.RunSQL( 'UPDATE attempts_historicalattempt SET submission_date = history_date' ), migrations.RunSQL( '''UPDATE attempts_attempt SET submission_date = ( SELECT max(history_date) FROM attempts_historicalattempt WHERE attempts_attempt.user_id = user_id AND attempts_attempt.part_id = part_id ) ''' ), migrations.AlterField( model_name='attempt', name='submission_date', field=models.DateTimeField(auto_now=True), ), migrations.AlterField( model_name='historicalattempt', name='submission_date', field=models.DateTimeField(blank=True, editable=False), ), ]
Set nomination limit for dev user in seeder
<?php use Illuminate\Database\Seeder; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker\Factory::create(); for ($i=0; $i<5; $i++) { $firstName = $faker->firstName; $lastName = $faker->lastName; $newUser = App\User::create( [ 'name_first' => $firstName, 'name_last' => $lastName, "affiliation_id"=> $faker->numberBetween(1,57), "email" => $faker->email, 'password' => 'admin', 'nomination_limit'=> 5 ] ); $this->command->info("Seeded user {$firstName} {$lastName}"); $role_id = $faker->numberBetween(1, 5); $role = \App\Role::find($role_id); $newUser->attachRole($role); } // Add dev account until we enable registration $newUser = App\User::create( [ 'name_first' => "Developer", 'name_last' => "lastName", "affiliation_id" => 1, "email" => "[email protected]", 'password' => 'admin', 'nomination_limit' => 5 ] ); $role = \App\Role::find(1); $newUser->attachRole($role); } }
<?php use Illuminate\Database\Seeder; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker\Factory::create(); for ($i=0; $i<5; $i++) { $firstName = $faker->firstName; $lastName = $faker->lastName; $newUser = App\User::create( [ 'name_first' => $firstName, 'name_last' => $lastName, "affiliation_id"=> $faker->numberBetween(1,57), "email" => $faker->email, 'password' => 'admin', 'nomination_limit'=> 5 ] ); $this->command->info("Seeded user {$firstName} {$lastName}"); $role_id = $faker->numberBetween(1, 5); $role = \App\Role::find($role_id); $newUser->attachRole($role); } // Add dev account until we enable registration $newUser = App\User::create( [ 'name_first' => "Developer", 'name_last' => "lastName", "affiliation_id"=> 1, "email" => "[email protected]", 'password' => 'admin' ] ); $role = \App\Role::find(1); $newUser->attachRole($role); } }
Remove table markup for lists of events
<div class="vcalendar"> <?php foreach ($context as $eventinstance) { //Start building an array of row classes $row_classes = array('vevent'); if ($eventinstance->isAllDay()) { $row_classes[] = 'all-day'; } if ($eventinstance->isInProgress()) { $row_classes[] = 'in-progress'; } if ($eventinstance->isOnGoing()) { $row_classes[] = 'ongoing'; } ?> <div class="<?php echo implode(' ', $row_classes) ?>"> <?php echo $savvy->render($eventinstance, 'EventInstance/Summary.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Date.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Location.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Description.tpl.php') ?> </div> <?php } ?> </div>
<table> <thead> <tr> <th scope="col" class="date">Time</th> <th scope="col" class="title">Event Title</th> </tr> </thead> <tbody class="vcalendar"> <?php foreach ($context as $eventinstance) { //Start building an array of row classes $row_classes = array('vevent'); if ($eventinstance->isAllDay()) { $row_classes[] = 'all-day'; } if ($eventinstance->isInProgress()) { $row_classes[] = 'in-progress'; } if ($eventinstance->isOnGoing()) { $row_classes[] = 'ongoing'; } ?> <tr class="<?php echo implode(' ', $row_classes) ?>"> <td class="date"> <?php echo $savvy->render($eventinstance, 'EventInstance/Date.tpl.php') ?> </td> <td> <?php echo $savvy->render($eventinstance, 'EventInstance/Summary.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Location.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Description.tpl.php') ?> </td> </tr> <?php } ?> </tbody> </table>
Reduce the number of test for Kociemba Solver
from src.Move import Move from src.NaiveCube import NaiveCube from src.Cubie imort Cube from src.Solver import Kociemba import timeout_decorator import unittest class TestKociembaSolver(unittest.TestCase): @timeout_decorator.timeout(300) def _test_solution(self, c): solver = Kociemba.KociembaSolver(c) return solver.solution() def test_solution(self): for i in range(20): c = Cube() cr = Cube() c.shuffle(i) solution = self._test_solution(c) for s in solution: c.move(s) # Align faces while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']: c.move(Move('Y')) for cubie in cr.cubies: for facing in cr.cubies[cubie].facings: self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing]) def test_timeout(self): c = Cube() nc = NaiveCube() nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy") c.from_naive_cube(nc) with self.assertRaises(Kociemba.Search.TimeoutError): solver = Kociemba.KociembaSolver(c) solver.solution(timeOut = 1)
from src.Move import Move from src.NaiveCube import NaiveCube from src.Cubie imort Cube from src.Solver import Kociemba import timeout_decorator import unittest class TestKociembaSolver(unittest.TestCase): @timeout_decorator.timeout(300) def _test_solution(self, c): solver = Kociemba.KociembaSolver(c) return solver.solution() def test_solution(self): for i in range(100): c = Cube() cr = Cube() c.shuffle(i) solution = self._test_solution(c) for s in solution: c.move(s) # Align faces while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']: c.move(Move('Y')) for cubie in cr.cubies: for facing in cr.cubies[cubie].facings: self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing]) def test_timeout(self): c = Cube() nc = NaiveCube() nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy") c.from_naive_cube(nc) with self.assertRaises(Kociemba.Search.TimeoutError): solver = Kociemba.KociembaSolver(c) solver.solution(timeOut = 1)
Update release number to 0.2.3
#!/usr/bin/env python import subprocess from setuptools import setup, find_packages import os def git_version(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen( cmd, stdout=subprocess.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) GIT_REVISION = out.strip().decode('ascii') except OSError: GIT_REVISION = "" return GIT_REVISION def getVersion(version, release=True): if os.path.exists('.git'): _git_version = git_version()[:7] else: _git_version = '' if release: return version else: return version + '-dev.' + _git_version setup(name='pymks', version=getVersion('0.2.3', release=True), description='Materials Knowledge Systems in Python (PyMKS)', author='David Brough, Daniel Wheeler', author_email='[email protected]', url='http://pymks.org', packages=find_packages(), package_data={'': ['tests/*.py']}, )
#!/usr/bin/env python import subprocess from setuptools import setup, find_packages import os def git_version(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen( cmd, stdout=subprocess.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) GIT_REVISION = out.strip().decode('ascii') except OSError: GIT_REVISION = "" return GIT_REVISION def getVersion(version, release=True): if os.path.exists('.git'): _git_version = git_version()[:7] else: _git_version = '' if release: return version else: return version + '-dev.' + _git_version setup(name='pymks', version=getVersion('0.2.1', release=True), description='Materials Knowledge Systems in Python (PyMKS)', author='David Brough, Daniel Wheeler', author_email='[email protected]', url='http://pymks.org', packages=find_packages(), package_data={'': ['tests/*.py']}, )
Convert page or post to int
<?php require_once( dirname( __FILE__ ) . '/B3_RoutesHelper.php' ); class B3_SettingsHelper { /** * [get_options description] * @return [type] [description] */ public function __construct () { } /** * Option getter. * * By default, options will take their value from WordPress's * `get_bloginfo()`. Options specific to B3 are handled manually. * * @param [type] $option [description] * @return [type] [description] */ public function __get( $option ) { switch ($option) { case 'api_url': return home_url( json_get_url_prefix() ); case 'root_url': return get_stylesheet_directory_uri(); case 'routes': $routes = new B3_RoutesHelper(); return $routes->get_routes(); case 'site_url': return get_bloginfo( 'url' ); case 'site_path': $site_url_components = parse_url( site_url() ); return (string) $site_url_components['path']; case 'wp_url': return get_bloginfo( 'wpurl' ); case 'show_on_front': case 'page_on_front': case 'page_for_posts': return (int) get_option( $option ); default: return get_bloginfo( $option ); } } }
<?php require_once( dirname( __FILE__ ) . '/B3_RoutesHelper.php' ); class B3_SettingsHelper { /** * [get_options description] * @return [type] [description] */ public function __construct () { } /** * Option getter. * * By default, options will take their value from WordPress's * `get_bloginfo()`. Options specific to B3 are handled manually. * * @param [type] $option [description] * @return [type] [description] */ public function __get( $option ) { switch ($option) { case 'api_url': return home_url( json_get_url_prefix() ); case 'root_url': return get_stylesheet_directory_uri(); case 'routes': $routes = new B3_RoutesHelper(); return $routes->get_routes(); case 'site_url': return get_bloginfo( 'url' ); case 'site_path': $site_url_components = parse_url( site_url() ); return (string) $site_url_components['path']; case 'wp_url': return get_bloginfo( 'wpurl' ); case 'show_on_front': case 'page_on_front': case 'page_for_posts': return get_option( $option ); default: return get_bloginfo( $option ); } } }
Make migration logging more verbose
""" Run all migrations """ import imp import os import sys import pymongo from os.path import join import logging logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) def load_config(env): config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config') fp = None try: sys.path.append(config_path) fp, pathname, description = imp.find_module( "backdrop/write/config/%s" % env) return imp.load_module(env, fp, pathname, description) finally: sys.path.pop() if fp: fp.close() def get_database(config): client = pymongo.MongoClient(config.MONGO_HOST, config.MONGO_PORT) return client[config.DATABASE_NAME] def get_migrations(): migrations_path = join(ROOT_PATH, 'migrations') for migration_file in os.listdir(migrations_path): if migration_file.endswith('.py'): migration_path = join(migrations_path, migration_file) yield imp.load_source('migration', migration_path) if __name__ == '__main__': config = load_config(os.getenv('GOVUK_ENV', 'development')) database = get_database(config) for migration in get_migrations(): log.info("Running migration %s" % migration) migration.up(database)
""" Run all migrations """ import imp import os import sys import pymongo from os.path import join import logging logging.basicConfig(level=logging.DEBUG) ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) def load_config(env): config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config') fp = None try: sys.path.append(config_path) fp, pathname, description = imp.find_module( "backdrop/write/config/%s" % env) return imp.load_module(env, fp, pathname, description) finally: sys.path.pop() if fp: fp.close() def get_database(config): client = pymongo.MongoClient(config.MONGO_HOST, config.MONGO_PORT) return client[config.DATABASE_NAME] def get_migrations(): migrations_path = join(ROOT_PATH, 'migrations') for migration_file in os.listdir(migrations_path): if migration_file.endswith('.py'): migration_path = join(migrations_path, migration_file) yield imp.load_source('migration', migration_path) if __name__ == '__main__': config = load_config(os.getenv('GOVUK_ENV', 'development')) database = get_database(config) for migration in get_migrations(): migration.up(database)
Use the root_page.depth to determine filter value to identify section root pages
# -*- coding: utf-8 -*- import logging from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Site from wagtailmenus import app_settings logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Create a 'main menu' for any 'Site' that doesn't already have one. " "If main menus for any site do not have menu items, identify the " "'home' and 'section root' pages for the site, and menu items linking " "to those to the menu. Assumes 'site.root_page' is the 'home page' " "and its children are the 'section root' pages") def add_arguments(self, parser): parser.add_argument( '--add-home-links', action='store_true', dest='add-home-links', default=True, help="Add menu items for 'home' pages", ) def handle(self, *args, **options): for site in Site.objects.all(): menu = app_settings.MAIN_MENU_MODEL_CLASS.get_for_site(site) if not menu.get_menu_items_manager().exists(): menu.add_menu_items_for_pages( site.root_page.get_descendants( inclusive=options['add-home-links'] ).filter(depth__lte=site.root_page.depth + 1) )
# -*- coding: utf-8 -*- import logging from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Site from wagtailmenus import app_settings logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Create a 'main menu' for any 'Site' that doesn't already have one. " "If main menus for any site do not have menu items, identify the " "'home' and 'section root' pages for the site, and menu items linking " "to those to the menu. Assumes 'site.root_page' is the 'home page' " "and its children are the 'section root' pages") def add_arguments(self, parser): parser.add_argument( '--add-home-links', action='store_true', dest='add-home-links', default=True, help="Add menu items for 'home' pages", ) def handle(self, *args, **options): for site in Site.objects.all(): menu = app_settings.MAIN_MENU_MODEL_CLASS.get_for_site(site) if not menu.get_menu_items_manager().exists(): menu.add_menu_items_for_pages( site.root_page.get_descendants( inclusive=options['add-home-links'] ).filter(depth__lte=3) )
Enable library paths to be explicitly specified. All shared libraries loaded through the load_library function can bow be specified explicitly through a suitable environmental variable PYFR_<LIB>_LIBRARY_PATH=/path/to/lib.here where <LIB> corresponds to the name of the library, e.g. METIS.
# -*- coding: utf-8 -*- import ctypes import ctypes.util import os import sys def find_libc(): if sys.platform == 'win32': return ctypes.util.find_msvcrt() else: return ctypes.util.find_library('c') def load_library(name): # If an explicit override has been given then use it lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper())) if lpath: return ctypes.CDLL(lpath) # Otherwise synthesise the library name and start searching lname = platform_libname(name) # Start with system search path try: return ctypes.CDLL(lname) # ..and if this fails then run our own search except OSError: for sd in platform_libdirs(): try: return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname))) except OSError: pass else: raise OSError('Unable to load {0}'.format(name)) def platform_libname(name): if sys.platform == 'darwin': return 'lib{0}.dylib'.format(name) elif sys.platform == 'win32': return '{0}.dll'.format(name) else: return 'lib{0}.so'.format(name) def platform_libdirs(): path = os.environ.get('PYFR_LIBRARY_PATH', '') dirs = [d for d in path.split(':') if d] # On Mac OS X append the default path used by MacPorts if sys.platform == 'darwin': return dirs + ['/opt/local/lib'] # Otherwise just return else: return dirs
# -*- coding: utf-8 -*- import ctypes import ctypes.util import os import sys def find_libc(): if sys.platform == 'win32': return ctypes.util.find_msvcrt() else: return ctypes.util.find_library('c') def load_library(name): lname = platform_libname(name) sdirs = platform_libdirs() # First attempt to utilise the system search path try: return ctypes.CDLL(lname) # Otherwise, if this fails then run our own search except OSError: for sd in sdirs: try: return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname))) except OSError: pass else: raise OSError('Unable to load {0}'.format(name)) def platform_libname(name): if sys.platform == 'darwin': return 'lib{0}.dylib'.format(name) elif sys.platform == 'win32': return '{0}.dll'.format(name) else: return 'lib{0}.so'.format(name) def platform_libdirs(): path = os.environ.get('PYFR_LIBRARY_PATH', '') dirs = [d for d in path.split(':') if d] # On Mac OS X append the default path used by MacPorts if sys.platform == 'darwin': return dirs + ['/opt/local/lib'] # Otherwise just return else: return dirs
Fix crash if config value is not set
<?php namespace PragmaRX\Google2FALaravel\Support; use Illuminate\Support\MessageBag; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; trait ErrorBag { /** * Create an error bag and store a message on int. * * @param $message * * @return MessageBag */ protected function createErrorBagForMessage($message) { return new MessageBag([ 'message' => $message, ]); } /** * Get a message bag with a message for a particular status code. * * @param $statusCode * * @return MessageBag */ protected function getErrorBagForStatusCode($statusCode) { $errorMap = [ SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY => 'google2fa.error_messages.wrong_otp', SymfonyResponse::HTTP_BAD_REQUEST => 'google2fa.error_messages.cannot_be_empty', ]; return $this->createErrorBagForMessage( trans( config( array_key_exists($statusCode, $errorMap) ? $errorMap[$statusCode] : 'google2fa.error_messages.unknown', 'google2fa.error_messages.unknown' ) ) ); } }
<?php namespace PragmaRX\Google2FALaravel\Support; use Illuminate\Support\MessageBag; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; trait ErrorBag { /** * Create an error bag and store a message on int. * * @param $message * * @return MessageBag */ protected function createErrorBagForMessage($message) { return new MessageBag([ 'message' => $message, ]); } /** * Get a message bag with a message for a particular status code. * * @param $statusCode * * @return MessageBag */ protected function getErrorBagForStatusCode($statusCode) { $errorMap = [ SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY => 'google2fa.error_messages.wrong_otp', SymfonyResponse::HTTP_BAD_REQUEST => 'google2fa.error_messages.cannot_be_empty', ]; return $this->createErrorBagForMessage( trans( config( array_key_exists($statusCode, $errorMap) ? $errorMap[$statusCode] : 'google2fa.error_messages.unknown' ) ) ); } }
Fix bug on variable names. Remove return value from connect() because objects are passed by reference.
<?php namespace OnlyBits\Inputs; use OnlyBits\Connectors\ConnectInterface; use OnlyBits\Connectors\Wire; class TwoStateButton implements InputInterface, ConnectInterface { /** * Button state 1. * @var mixed */ private $state1; /** * Button state 2. * @var mixed */ private $state2; /** * Button's current state. * @var mixed */ private $current_state; /** * The value outputted by the button. * @var mixed */ private $output; /** * Constructor. The state 1 should be default state. * * @param mixed $state1 Button state 1 * @param mixed $state2 Button state 2 */ public function __construct($state1, $state2) { $this->state1 = $state1; $this->state2 = $state2; $this->current_state = $state1; $this->output = $state1; } /** * {@inheritdoc} */ public function trigger() { $this->current_state = ($this->current_state == $this->state1) ? $this->state2 : $this->state1; $this->output = $this->current_state; } /** * {@inheritdoc} */ public function connect(Wire $wire, $pin = null) { $wire->setValue($this->output); } }
<?php namespace OnlyBits\Inputs; use OnlyBits\Connectors\ConnectInterface; use OnlyBits\Connectors\Wire; class TwoStateButton implements InputInterface, ConnectInterface { /** * Button state 1. * @var mixed */ private $state1; /** * Button state 2. * @var mixed */ private $state2; /** * Button's current state. * @var mixed */ private $current_state; /** * The value outputted by the button. * @var mixed */ private $output; /** * Constructor. The state 1 should be default state. * * @param mixed $state1 Button state 1 * @param mixed $state2 Button state 2 */ public function __construct($state1, $state2) { $this->state1 = $state1; $this->state2 = $state2; $this->current_state = $state1; $this->output = $state1; } /** * {@inheritdoc} */ public function trigger() { $this->current_state = ($this->current_state == $state1) ? $state2 : $state1; $this->output = $this->current_state; } /** * {@inheritdoc} */ public function connect(Wire $wire, $pin = null) { $wire->setValue($this->output); return $wire; } }
Test ´wordbreakerRussian´: fix code style
'use strict' import chai from 'chai' import wordbreakerRussian from '@/wordbreaker-russian/index' import SOFT_HYPHEN from '@/wordbreaker-russian/consts/soft-hyphen' describe( 'wordbreakerRussian', () => { it( 'Это функция', () => chai.assert.isFunction(wordbreakerRussian) ) it( 'Возвращает строку', () => chai.assert.isString(wordbreakerRussian('test')) ) describe( 'Правильно расставляет переносы', () => { // TODO: Написать тесты на все правила const testData = [ { input: 'собака', expectedOutput: `со${SOFT_HYPHEN}ба${SOFT_HYPHEN}ка`, }, { input: 'кот', expectedOutput: 'кот', }, { input: 'Колорадо', expectedOutput: `Ко${SOFT_HYPHEN}ло${SOFT_HYPHEN}ра${SOFT_HYPHEN}до`, }, ] testData.forEach( ({input, expectedOutput}) => { it( `${input} → ${expectedOutput}`, () => chai.assert.equal( wordbreakerRussian(input), expectedOutput ) ) } ) } ) } )
'use strict' import chai from 'chai' import wordbreakerRussian from '@/wordbreaker-russian/index' describe( 'wordbreakerRussian', () => { it( 'Это функция', () => { chai.assert.isFunction(wordbreakerRussian) } ) it( 'Возвращает строку', () => { chai.assert.isString(wordbreakerRussian('test')) } ) // TODO: Написать тесты на все правила describe( 'Правильно расставляет переносы', () => { it( 'собака → со­ба­ка', () => { chai.assert.equal(wordbreakerRussian('собака'), 'со­ба­ка') } ) it( 'кот → кот', () => { chai.assert.equal(wordbreakerRussian('кот'), 'кот') } ) it( 'Колорадо → Ко­ло­ра­до', () => { chai.assert.equal(wordbreakerRussian('Колорадо'), 'Ко­ло­ра­до') } ) } ) } )
Add support for "innerRef" prop
import React from "react"; import R from "ramda"; import T from "prop-types"; export default function createStyledComponent(displayName, use) { return class StyledComponent extends React.Component { static displayName = displayName; static propTypes = { use: T.oneOfType([T.string, T.func]), visual: T.oneOfType([T.object, T.func]), animations: T.objectOf(T.object), innerRef: T.func, children: T.node, }; static defaultProps = { use, visual: {}, }; static contextTypes = { renderer: T.object.isRequired, theme: T.object, }; renderClassName = (visual, animations) => { const { renderer, theme = {} } = this.context; if (typeof visual === "function") { return renderer.renderRule(visual, { animations: this.renderKeyframes(animations), theme, }); } return renderer.renderRule(() => visual); }; renderKeyframes = (animations = {}) => { const { renderer } = this.context; return R.map( animation => renderer.renderKeyframe(() => animation), animations ); }; render() { const { use: Component, visual, animations, innerRef, ...props } = this.props; const ref = innerRef ? { ref: r => innerRef(r) } : {} return ( <Component {...ref} {...props} className={this.renderClassName(visual, animations)} /> ); } }; }
import React from "react"; import R from "ramda"; import T from "prop-types"; export default function createStyledComponent(displayName, use) { return class StyledComponent extends React.Component { static displayName = displayName; static propTypes = { use: T.oneOfType([T.string, T.func]), visual: T.oneOfType([T.object, T.func]), animations: T.objectOf(T.object), children: T.node, }; static defaultProps = { use, visual: {}, }; static contextTypes = { renderer: T.object.isRequired, theme: T.object, }; renderClassName = (visual, animations) => { const { renderer, theme = {} } = this.context; if (typeof visual === "function") { return renderer.renderRule(visual, { animations: this.renderKeyframes(animations), theme, }); } return renderer.renderRule(() => visual); }; renderKeyframes = (animations = {}) => { const { renderer } = this.context; return R.map( animation => renderer.renderKeyframe(() => animation), animations ); }; render() { const { use: Component, visual, animations, ...props } = this.props; return ( <Component {...props} className={this.renderClassName(visual, animations)} /> ); } }; }
Set default output dir to output_data
'use strict'; const childProcess = require('child_process'); const fs = require('fs'); module.exports = function(type) { process.argv.shift(); process.argv.shift(); var path = process.argv.length < 1 ? 'output_data' : process.argv[0]; var process_generate = childProcess.spawn('./node_modules/podigg/bin/generate-' + type + '.js', process.argv); process_generate.stdout.pipe(process.stdout); process_generate.stderr.pipe(process.stderr); process_generate.on('close', (code_generate) => { if(!code_generate) { var process_convert = childProcess.spawn('./node_modules/gtfs2lc/bin/gtfs2lc.js', [path + '/gtfs', '-f', 'turtle', '-r', '-t', '-a']); process_convert.stdout.pipe(fs.createWriteStream(path + '/lc.ttl')); process_convert.stderr.pipe(process.stderr); process_convert.on('close', (code_convert) => { if (code_generate) { throw new Error('Conversion exited with exit code ' + code_convert); } }); } else { throw new Error('Generation exited with exit code ' + code_generate); } }); }
'use strict'; const childProcess = require('child_process'); const fs = require('fs'); module.exports = function(type) { process.argv.shift(); process.argv.shift(); var path = process.argv.length < 1 ? '.' : process.argv[0]; var process_generate = childProcess.spawn('./node_modules/podigg/bin/generate-' + type + '.js', process.argv); process_generate.stdout.pipe(process.stdout); process_generate.stderr.pipe(process.stderr); process_generate.on('close', (code_generate) => { if(!code_generate) { var process_convert = childProcess.spawn('./node_modules/gtfs2lc/bin/gtfs2lc.js', [path + '/gtfs', '-f', 'turtle', '-r', '-t', '-a']); process_convert.stdout.pipe(fs.createWriteStream(path + '/lc.ttl')); process_convert.stderr.pipe(process.stderr); process_convert.on('close', (code_convert) => { if (code_generate) { throw new Error('Conversion exited with exit code ' + code_convert); } }); } else { throw new Error('Generation exited with exit code ' + code_generate); } }); }
Correct definition of path to version information for package.
import io import os import re from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'src', 'opencmiss', 'utils', '__init__.py')) as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') def readfile(filename, split=False): with io.open(filename, encoding="utf-8") as stream: if split: return stream.read().split("\n") return stream.read() readme = readfile("README.rst", split=True) readme.append('License') readme.append('=======') readme.append('') readme.append('') requires = ['opencmiss.zinc'] software_licence = readfile("LICENSE") setup( name='opencmiss.utils', version=version, description='OpenCMISS Utilities for Python.', long_description='\n'.join(readme) + software_licence, classifiers=[], author='Hugh Sorby', author_email='[email protected]', url='https://github.com/OpenCMISS-Bindings/opencmiss.utils', license='Apache Software License', packages=find_packages("src"), package_dir={"": "src"}, include_package_data=True, zip_safe=False, install_requires=requires, )
import io import os import re from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'opencmiss', 'utils', '__init__.py')) as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') def readfile(filename, split=False): with io.open(filename, encoding="utf-8") as stream: if split: return stream.read().split("\n") return stream.read() readme = readfile("README.rst", split=True) readme.append('License') readme.append('=======') readme.append('') readme.append('') requires = ['opencmiss.zinc'] software_licence = readfile("LICENSE") setup( name='opencmiss.utils', version=version, description='OpenCMISS Utilities for Python.', long_description='\n'.join(readme) + software_licence, classifiers=[], author='Hugh Sorby', author_email='[email protected]', url='https://github.com/OpenCMISS-Bindings/opencmiss.utils', license='Apache Software License', packages=find_packages("src"), package_dir={"": "src"}, include_package_data=True, zip_safe=False, install_requires=requires, )
Remove category slug from the API
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from rest_framework import serializers from catalog.models import Course, Category from documents.serializers import DocumentSerializer from telepathy.serializers import SmallThreadSerializer class CourseSerializer(serializers.HyperlinkedModelSerializer): document_set = DocumentSerializer(many=True) thread_set = SmallThreadSerializer(many=True) class Meta: model = Course fields = ( 'id', 'name', 'slug', 'url', 'categories', 'document_set', 'thread_set' ) extra_kwargs = { 'url': {'lookup_field': 'slug'} } class ShortCourseSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Course fields = ('id', 'url', 'slug', 'name', ) extra_kwargs = { 'url': {'lookup_field': 'slug'} } class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ('id', 'url', 'name', 'parent', 'children', 'course_set') extra_kwargs = { 'course_set': {'lookup_field': 'slug'}, } class ShortCategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ('id', 'url', 'name', )
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from rest_framework import serializers from catalog.models import Course, Category from documents.serializers import DocumentSerializer from telepathy.serializers import SmallThreadSerializer class CourseSerializer(serializers.HyperlinkedModelSerializer): document_set = DocumentSerializer(many=True) thread_set = SmallThreadSerializer(many=True) class Meta: model = Course fields = ( 'id', 'name', 'slug', 'url', 'categories', 'document_set', 'thread_set' ) extra_kwargs = { 'url': {'lookup_field': 'slug'} } class ShortCourseSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Course fields = ('id', 'url', 'slug', 'name', ) extra_kwargs = { 'url': {'lookup_field': 'slug'} } class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ('id', 'url', 'slug', 'name', 'parent', 'children', 'course_set') extra_kwargs = { 'course_set': {'lookup_field': 'slug'}, } class ShortCategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ('id', 'url', 'slug', 'name', )
Change more detailed dev exception message
<?php declare(strict_types=1); namespace Onion\Framework\Http\Middleware; use Interop\Http\Middleware\DelegateInterface; use Interop\Http\Middleware\ServerMiddlewareInterface; use Psr\Http\Message; final class Delegate implements DelegateInterface { /** * @var ServerMiddlewareInterface */ protected $middleware; /** * @var Message\ResponseInterface */ protected $response; /** * MiddlewareDelegate constructor. * * @param ServerMiddlewareInterface[] $middleware Middleware of the frame */ public function __construct(array $middleware, Message\ResponseInterface $response = null) { $this->middleware = $middleware; $this->response = $response; } /** * @param Message\RequestInterface $request * * @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface * @return Message\ResponseInterface */ public function process(Message\ServerRequestInterface $request): Message\ResponseInterface { if ($this->middleware !== []) { $middleware = array_shift($this->middleware); if ($middleware !== null) { assert( $middleware instanceof ServerMiddlewareInterface, new \TypeError('All members of middleware must implement ServerMiddlewareInterface, ' . gettype($middleware) . ': ' . print_r($middleware, true) . ' given') ); return $middleware->process($request, $this); } } if (null === $this->response) { throw new \RuntimeException('No response template provided'); } return $this->response; } }
<?php declare(strict_types=1); namespace Onion\Framework\Http\Middleware; use Interop\Http\Middleware\DelegateInterface; use Interop\Http\Middleware\ServerMiddlewareInterface; use Psr\Http\Message; final class Delegate implements DelegateInterface { /** * @var ServerMiddlewareInterface */ protected $middleware; /** * @var Message\ResponseInterface */ protected $response; /** * MiddlewareDelegate constructor. * * @param ServerMiddlewareInterface[] $middleware Middleware of the frame */ public function __construct(array $middleware, Message\ResponseInterface $response = null) { $this->middleware = $middleware; $this->response = $response; } /** * @param Message\RequestInterface $request * * @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface * @return Message\ResponseInterface */ public function process(Message\ServerRequestInterface $request): Message\ResponseInterface { if ($this->middleware !== []) { $middleware = array_shift($this->middleware); if ($middleware !== null) { assert( $middleware instanceof ServerMiddlewareInterface, new \TypeError('All members of middleware must implement ServerMiddlewareInterface') ); return $middleware->process($request, $this); } } if (null === $this->response) { throw new \RuntimeException('No response template provided'); } return $this->response; } }
Check csrf token before running a mass action tags module
<?php namespace Backend\Modules\Tags\Actions; use Backend\Core\Engine\Base\Action as BackendBaseAction; use Backend\Core\Engine\Model as BackendModel; use Backend\Modules\Tags\Engine\Model as BackendTagsModel; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; /** * This action is used to perform mass actions on tags (delete, ...) */ class MassAction extends BackendBaseAction { public function execute(): void { parent::execute(); if ($this->getRequest()->query->get('token') !== BackendModel::getToken()) { throw new BadRequestHttpException('Invalid csrf token'); } // action to execute $action = $this->getRequest()->query->get('action'); if (!in_array($action, ['delete'])) { $this->redirect(BackendModel::createUrlForAction('Index') . '&error=no-action-selected'); } // no id's provided if (!$this->getRequest()->query->has('id')) { $this->redirect( BackendModel::createUrlForAction('Index') . '&error=no-selection' ); } else { // at least one id // redefine id's $aIds = (array) $this->getRequest()->query->get('id'); // delete comment(s) if ($action == 'delete') { BackendTagsModel::delete($aIds); } } // redirect $this->redirect( BackendModel::createUrlForAction('Index') . '&report=deleted' ); } }
<?php namespace Backend\Modules\Tags\Actions; use Backend\Core\Engine\Base\Action as BackendBaseAction; use Backend\Core\Engine\Model as BackendModel; use Backend\Modules\Tags\Engine\Model as BackendTagsModel; /** * This action is used to perform mass actions on tags (delete, ...) */ class MassAction extends BackendBaseAction { public function execute(): void { parent::execute(); // action to execute $action = $this->getRequest()->query->get('action'); if (!in_array($action, ['delete'])) { $this->redirect(BackendModel::createUrlForAction('Index') . '&error=no-action-selected'); } // no id's provided if (!$this->getRequest()->query->has('id')) { $this->redirect( BackendModel::createUrlForAction('Index') . '&error=no-selection' ); } else { // at least one id // redefine id's $aIds = (array) $this->getRequest()->query->get('id'); // delete comment(s) if ($action == 'delete') { BackendTagsModel::delete($aIds); } } // redirect $this->redirect( BackendModel::createUrlForAction('Index') . '&report=deleted' ); } }
Change location of lower case conversion to fix issue.
Template.foundbill.created = function(){ Meteor.subscribe("allbills"); Session.set('message', ''); }; Template.foundbill.events({ "submit form": function(e){ e.preventDefault(); var serial = e.target.serialnumber.value; //serial = serial.toLowerCase(); var zip = e.target.zip.value; var have = e.target.have.checked; var note = e.target.note.value; var email = Meteor.user().emails[0].address; var thisbill = bills.findOne({'serial': serial.toLowerCase()}); // check to see if this bill exists if (thisbill){ var billId = thisbill._id; bills.update({_id:billId}, {$push: { "history": { timestamp: new Date(), zip: zip, recordedby: Meteor.userId(), note: note } } }); e.target.serialnumber.value = ''; e.target.zip.value = ''; e.target.note.value = ''; e.target.have.checked = false; Session.set('message', '<div class="no-data alert alert-success">Thanks for registering this bill!</div>') }else{ Session.set('message', '<div class="no-data alert alert-danger">Couldn\'t find this bill in our records. <a href="/new-bill">Register it as new here!</a></div>'); } } }); Template.foundbill.helpers({ alertbox: function(){ return Session.get('message'); } });
Template.foundbill.created = function(){ Meteor.subscribe("allbills"); Session.set('message', ''); }; Template.foundbill.events({ "submit form": function(e){ e.preventDefault(); var serial = e.target.serialnumber.value; serial = serial.toLowerCase(); var zip = e.target.zip.value; var have = e.target.have.checked; var note = e.target.note.value; var email = Meteor.user().emails[0].address; var thisbill = bills.findOne({'serial': serial}); // check to see if this bill exists if (thisbill){ var billId = thisbill._id; bills.update({_id:billId}, {$push: { "history": { timestamp: new Date(), zip: zip, recordedby: Meteor.userId(), note: note } } }); e.target.serialnumber.value = ''; e.target.zip.value = ''; e.target.note.value = ''; e.target.have.checked = false; Session.set('message', '<div class="no-data alert alert-success">Thanks for registering this bill!</div>') }else{ Session.set('message', '<div class="no-data alert alert-danger">Couldn\'t find this bill in our records. <a href="/new-bill">Register it as new here!</a></div>'); } } }); Template.foundbill.helpers({ alertbox: function(){ return Session.get('message'); } });
Add checkpoints to the stationboard objects
const initState = {}; export default (state = initState, action) => { switch (action.type) { case "GET_STATIONBOARD_REQUESTED": const { stationId } = action.payload; return { ...state, [stationId]: { data: [], pending: true, }, }; case "GET_STATIONBOARD_FULFILLED": const { stationboard } = action.payload; return { ...state, [action.payload.stationId]: { ...state[action.payload.stationId], data: stationboard.map( ({ category, number, to, stop: { departureTimestamp }, passList: checkpoints, }) => ({ category, number, to, departureTimestamp, checkpoints, }), ), pending: false, }, }; default: return state; } };
const initState = {}; export default (state = initState, action) => { switch (action.type) { case "GET_STATIONBOARD_REQUESTED": const { stationId } = action.payload; return { ...state, [stationId]: { data: [], pending: true, }, }; case "GET_STATIONBOARD_FULFILLED": const { stationboard } = action.payload; return { ...state, [action.payload.stationId]: { ...state[action.payload.stationId], data: stationboard.map( ({ category, number, to, stop: { departureTimestamp }, }) => ({ category, number, to, departureTimestamp, }), ), pending: false, }, }; default: return state; } };
Replace hard-coded instantiations with bundle service definitions loader service
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\DependencyInjection; use Picodexter\ParameterEncryptionBundle\DependencyInjection\Loader\BundleServiceDefinitionsLoaderFactory; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension; /** * PcdxParameterEncryptionExtension. */ class PcdxParameterEncryptionExtension extends ConfigurableExtension { /** * Initialize service definitions. * * @param array $mergedConfig * @param ContainerBuilder $container */ private function initializeServiceDefinitions(array $mergedConfig, ContainerBuilder $container) { $initManager = $container->get(ServiceNames::SERVICE_DEFINITION_INITIALIZATION_MANAGER); $initManager->initializeServiceDefinitions($mergedConfig, $container); } /** * Load bundle service definitions. * * @param ContainerBuilder $container */ private function loadBundleServiceDefinitions(ContainerBuilder $container) { $definitionsLoader = BundleServiceDefinitionsLoaderFactory::createBundleServiceDefinitionsLoader(); $definitionsLoader->loadBundleServiceDefinitions($container); } /** * @inheritDoc */ public function loadInternal(array $mergedConfig, ContainerBuilder $container) { $this->loadBundleServiceDefinitions($container); $this->initializeServiceDefinitions($mergedConfig, $container); } }
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension; /** * PcdxParameterEncryptionExtension. */ class PcdxParameterEncryptionExtension extends ConfigurableExtension { /** * Initialize service definitions. * * @param array $mergedConfig * @param ContainerBuilder $container */ private function initializeServiceDefinitions(array $mergedConfig, ContainerBuilder $container) { $initManager = $container->get(ServiceNames::SERVICE_DEFINITION_INITIALIZATION_MANAGER); $initManager->initializeServiceDefinitions($mergedConfig, $container); } /** * Load bundle service definitions. * * @param ContainerBuilder $container */ private function loadBundleServiceDefinitions(ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.xml'); } /** * @inheritDoc */ public function loadInternal(array $mergedConfig, ContainerBuilder $container) { $this->loadBundleServiceDefinitions($container); $this->initializeServiceDefinitions($mergedConfig, $container); } }
Revert "There is no need for a separate session for each transaction" This reverts commit 5863051c57182ee6fc61a6b63061cf63b95308e2.
package hu.bme.mit.codemodel.rifle.database; import java.util.Map; import hu.bme.mit.codemodel.rifle.database.querybuilder.Query; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.StatementResult; import org.neo4j.driver.v1.Transaction; import org.neo4j.graphdb.GraphDatabaseService; import neo4j.driver.testkit.EmbeddedTestkitDriver; /** * Provides database services like transaction handling and query executing. */ public class DbServices { protected final Driver driver; protected Transaction transaction; public DbServices(Driver driver) { this.driver = driver; } public Transaction beginTx() { Session session = driver.session(); this.transaction = session.beginTransaction(); return this.transaction; } public StatementResult execute(String statement) { return this.transaction.run(statement); } public StatementResult execute(String statementTemplate, Map<String, Object> statementParameters) { return this.transaction.run(statementTemplate, statementParameters); } public StatementResult execute(Query q) { return this.execute(q.getStatementTemplate(), q.getStatementParameters()); } public GraphDatabaseService getUnderlyingDatabaseService() { if (driver instanceof EmbeddedTestkitDriver) { return ((EmbeddedTestkitDriver) driver).getUnderlyingDatabaseService(); } else { throw new IllegalStateException("Cannot get underyling database service."); } } }
package hu.bme.mit.codemodel.rifle.database; import java.util.Map; import hu.bme.mit.codemodel.rifle.database.querybuilder.Query; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.StatementResult; import org.neo4j.driver.v1.Transaction; import org.neo4j.graphdb.GraphDatabaseService; import neo4j.driver.testkit.EmbeddedTestkitDriver; /** * Provides database services like transaction handling and query executing. */ public class DbServices { protected final Driver driver; protected Session session; protected Transaction transaction; public DbServices(Driver driver) { this.driver = driver; this.session = this.driver.session(); } public Transaction beginTx() { this.transaction = session.beginTransaction(); return this.transaction; } public StatementResult execute(String statement) { return this.transaction.run(statement); } public StatementResult execute(String statementTemplate, Map<String, Object> statementParameters) { return this.transaction.run(statementTemplate, statementParameters); } public StatementResult execute(Query q) { return this.execute(q.getStatementTemplate(), q.getStatementParameters()); } public GraphDatabaseService getUnderlyingDatabaseService() { if (driver instanceof EmbeddedTestkitDriver) { return ((EmbeddedTestkitDriver) driver).getUnderlyingDatabaseService(); } else { throw new IllegalStateException("Cannot get underyling database service."); } } }
Change double quotes to single quotes
'use strict'; angular.module('core').controller('MusicalBackgroundController', ['$scope', 'TrialData', function($scope, TrialData) { // Expose TrialData on scope $scope.trialData = TrialData; // Save data to Trial Data $scope.musicianChanged = function(isMusician) { TrialData.data.answers.musical_background = isMusician.toLowerCase() === 'true' ? true : false; }; $scope.hearingImpairmentsChanged = function(hasHearingImpairments) { TrialData.data.answers.hearing_impairments = hasHearingImpairments.toLowerCase() === 'true' ? true : false; }; $scope.visualImpairmentsChanged = function(hasVisualImpairments) { TrialData.data.answers.visual_impairments = hasVisualImpairments.toLowerCase() === 'true' ? true : false; }; $scope.$watch('musicalExpertise', function musicalExpertiseChanged(musicalExpertise) { TrialData.data.answers.musical_expertise = musicalExpertise; }); $scope.stylesChanged = function() { var newStyles = []; for (var prop in $scope.subject.styles) { var style = prop.toString(); if ($scope.subject.styles[style]) { newStyles.push(style); } } TrialData.data.answers.music_styles = newStyles.sort(); }; $scope.trialDataJson = function() { return TrialData.toJson(); }; } ]);
'use strict'; angular.module('core').controller('MusicalBackgroundController', ['$scope', 'TrialData', function($scope, TrialData) { // Expose TrialData on scope $scope.trialData = TrialData; // Save data to Trial Data $scope.musicianChanged = function(isMusician) { TrialData.data.answers.musical_background = isMusician.toLowerCase() === "true" ? true : false; }; $scope.hearingImpairmentsChanged = function(hasHearingImpairments) { TrialData.data.answers.hearing_impairments = hasHearingImpairments.toLowerCase() === "true" ? true : false; }; $scope.visualImpairmentsChanged = function(hasVisualImpairments) { TrialData.data.answers.visual_impairments = hasVisualImpairments.toLowerCase() === "true" ? true : false; }; $scope.$watch('musicalExpertise', function musicalExpertiseChanged(musicalExpertise) { TrialData.data.answers.musical_expertise = musicalExpertise; }); $scope.stylesChanged = function() { var newStyles = []; for (var prop in $scope.subject.styles) { var style = prop.toString(); if ($scope.subject.styles[style]) { newStyles.push(style); } } TrialData.data.answers.music_styles = newStyles.sort(); }; $scope.trialDataJson = function() { return TrialData.toJson(); }; } ]);
Fix blank lines and whitespaces
from i3pystatus import IntervalModule class Pianobar(IntervalModule): """ Shows the title and artist name of the current music In pianobar config file must be setted the fifo and event_command options (see man pianobar for more information) Mouse events: - Left click play/pauses - Right click plays next song - Scroll up/down changes volume """ settings = ( ("format"), ("songfile", "File generated by pianobar eventcmd"), ("ctlfile", "Pianobar fifo file"), ("color", "The color of the text"), ) format = "{songtitle} -- {songartist}" required = ("format", "songfile", "ctlfile") color = "#FFFFFF" def run(self): with open(self.songfile, "r") as f: contents = f.readlines() sn = contents[0].strip() sa = contents[1].strip() self.output = { "full_text": self.format.format(songtitle=sn, songartist=sa), "color": self.color } def on_leftclick(self): open(self.ctlfile, "w").write("p") def on_rightclick(self): open(self.ctlfile, "w").write("n") def on_upscroll(self): open(self.ctlfile, "w").write(")") def on_downscroll(self): open(self.ctlfile, "w").write("(")
from i3pystatus import IntervalModule class Pianobar(IntervalModule): """ Shows the title and artist name of the current music In pianobar config file must be setted the fifo and event_command options (see man pianobar for more information) Mouse events: - Left click play/pauses - Right click plays next song - Scroll up/down changes volume """ settings = ( ("format"), ("songfile", "File generated by pianobar eventcmd"), ("ctlfile", "Pianobar fifo file"), ("color", "The color of the text"), ) format = "{songtitle} -- {songartist}" required = ("format", "songfile", "ctlfile") color = "#FFFFFF" def run(self): with open(self.songfile, "r") as f: contents = f.readlines() sn = contents[0].strip() sa = contents[1].strip() self.output = { "full_text": self.format.format(songtitle=sn, songartist=sa), "color": self.color } def on_leftclick(self): open(self.ctlfile,"w").write("p") def on_rightclick(self): open(self.ctlfile,"w").write("n") def on_upscroll(self): open(self.ctlfile,"w").write(")") def on_downscroll(self): open(self.ctlfile,"w").write("(")
Mark audio driver as unconfigured
<?php namespace Mpociot\BotMan\Drivers; use Mpociot\BotMan\BotMan; use Mpociot\BotMan\Message; class TelegramAudioDriver extends TelegramDriver { const DRIVER_NAME = 'TelegramAudio'; /** * Determine if the request is for this driver. * * @return bool */ public function matchesRequest() { return ! is_null($this->event->get('from')) && ! is_null($this->event->get('audio')); } /** * Retrieve the chat message. * * @return array */ public function getMessages() { $message = new Message(BotMan::AUDIO_PATTERN, $this->event->get('from')['id'], $this->event->get('chat')['id'], $this->event); $message->setAudio($this->getAudio()); return [$message]; } /** * Retrieve a image from an incoming message. * @return array A download for the image file. */ private function getAudio() { $audio = $this->event->get('audio'); $response = $this->http->get('https://api.telegram.org/bot'.$this->config->get('telegram_token').'/getFile', [ 'file_id' => $audio['file_id'], ]); $path = json_decode($response->getContent()); return ['https://api.telegram.org/file/bot'.$this->config->get('telegram_token').'/'.$path->result->file_path]; } /** * @return bool */ public function isConfigured() { return false; } }
<?php namespace Mpociot\BotMan\Drivers; use Mpociot\BotMan\BotMan; use Mpociot\BotMan\Message; class TelegramAudioDriver extends TelegramDriver { const DRIVER_NAME = 'TelegramAudio'; /** * Determine if the request is for this driver. * * @return bool */ public function matchesRequest() { return ! is_null($this->event->get('from')) && ! is_null($this->event->get('audio')); } /** * Retrieve the chat message. * * @return array */ public function getMessages() { $message = new Message(BotMan::AUDIO_PATTERN, $this->event->get('from')['id'], $this->event->get('chat')['id'], $this->event); $message->setAudio($this->getAudio()); return [$message]; } /** * Retrieve a image from an incoming message. * @return array A download for the image file. */ private function getAudio() { $audio = $this->event->get('audio'); $response = $this->http->get('https://api.telegram.org/bot'.$this->config->get('telegram_token').'/getFile', [ 'file_id' => $audio['file_id'], ]); $path = json_decode($response->getContent()); return ['https://api.telegram.org/file/bot'.$this->config->get('telegram_token').'/'.$path->result->file_path]; } }
Downgrade script already running to info
#!/usr/bin/env python '''Checks processes''' #=============================================================================== # Import modules #=============================================================================== # Standard Library import os import subprocess import logging # Third party modules # Application modules #=============================================================================== # Check script is running #=============================================================================== def is_running(script_name): '''Checks list of processes for script name and filters out lines with the PID and parent PID. Returns a TRUE if other script with the same name is found running.''' try: logger = logging.getLogger('root') cmd1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE) cmd2 = subprocess.Popen(['grep', '-v', 'grep'], stdin=cmd1.stdout, stdout=subprocess.PIPE) cmd3 = subprocess.Popen(['grep', '-v', str(os.getpid())], stdin=cmd2.stdout, stdout=subprocess.PIPE) cmd4 = subprocess.Popen(['grep', '-v', str(os.getppid())], stdin=cmd3.stdout, stdout=subprocess.PIPE) cmd5 = subprocess.Popen(['grep', script_name], stdin=cmd4.stdout, stdout=subprocess.PIPE) other_script_found = cmd5.communicate()[0] if other_script_found: logger.info('Script already runnning. Exiting...') logger.info(other_script_found) return True return False except Exception, e: logger.error('System check failed ({error_v}). Exiting...'.format( error_v=e)) return True
#!/usr/bin/env python '''Checks processes''' #=============================================================================== # Import modules #=============================================================================== # Standard Library import os import subprocess import logging # Third party modules # Application modules #=============================================================================== # Check script is running #=============================================================================== def is_running(script_name): '''Checks list of processes for script name and filters out lines with the PID and parent PID. Returns a TRUE if other script with the same name is found running.''' try: logger = logging.getLogger('root') cmd1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE) cmd2 = subprocess.Popen(['grep', '-v', 'grep'], stdin=cmd1.stdout, stdout=subprocess.PIPE) cmd3 = subprocess.Popen(['grep', '-v', str(os.getpid())], stdin=cmd2.stdout, stdout=subprocess.PIPE) cmd4 = subprocess.Popen(['grep', '-v', str(os.getppid())], stdin=cmd3.stdout, stdout=subprocess.PIPE) cmd5 = subprocess.Popen(['grep', script_name], stdin=cmd4.stdout, stdout=subprocess.PIPE) other_script_found = cmd5.communicate()[0] if other_script_found: logger.error('Script already runnning. Exiting...') logger.error(other_script_found) return True return False except Exception, e: logger.error('System check failed ({error_v}). Exiting...'.format( error_v=e)) return True
Use Content-Type text/plain for robots.txt
<?php namespace Psr7Middlewares\Middleware; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; /** * Middleware to block robots search engine. */ class Robots { const HEADER = 'X-Robots-Tag'; private $allow = false; /** * Set whether search engines are allowed or not. * * @param bool $allow */ public function __construct($allow = false) { $this->allow = $allow; } /** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { if ($request->getUri()->getPath() === '/robots.txt') { $response = $response->withHeader('Content-Type', 'text/plain'); if ($this->allow) { $response->getBody()->write("User-Agent: *\nAllow: /"); return $response; } $response->getBody()->write("User-Agent: *\nDisallow: /"); return $response; } $response = $next($request, $response); if ($this->allow) { return $response->withHeader(self::HEADER, 'index, follow'); } return $response->withHeader(self::HEADER, 'noindex, nofollow, noarchive'); } }
<?php namespace Psr7Middlewares\Middleware; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; /** * Middleware to block robots search engine. */ class Robots { const HEADER = 'X-Robots-Tag'; private $allow = false; /** * Set whether search engines are allowed or not. * * @param bool $allow */ public function __construct($allow = false) { $this->allow = $allow; } /** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { if ($request->getUri()->getPath() === '/robots.txt') { if ($this->allow) { $response->getBody()->write("User-Agent: *\nAllow: /"); return $response; } $response->getBody()->write("User-Agent: *\nDisallow: /"); return $response; } $response = $next($request, $response); if ($this->allow) { return $response->withHeader(self::HEADER, 'index, follow'); } return $response->withHeader(self::HEADER, 'noindex, nofollow, noarchive'); } }
Copy the template name list from the fragment so we don't mutate it
from django import template from django.template.loaders import select_template register = template.Library() class PlaceholderNode(template.Node): def __init__(self, name, **kwargs): self.name = name self.kwargs = kwargs def render(self, context): name = self.name.resolve(context) kwargs = { name: value.resolve(context) for name, value in self.kwargs.items() } kwargs['fragment'] = fragment = context['page'].fragment[name] template_names = fragment.template_names[:] if 'template' in kwargs: template_names.insert(0, kwargs.pop('template')) tmpl = select_template(template_names) with context.push(**kwargs): return tmpl.render(context) @register.tag def placeholder(parser, token): bits = token.contents.split() try: name = bits.pop(0) except IndexError: raise template.TemplateSyntaxError( 'Placeholder requires one positional argument' ) try: name = template.Variable(name).resolve({}) except template.VariableDoesNotExist: raise template.TemplateSyntaxError( 'Placeholder name must be a literal.' ) kwargs = template.token_kwargs(bits, parser) if bits: raise template.TemplateSyntaxError( 'Placeholder accepts only one positional argument.' ) return PlaceholderNode(name, **kwargs)
from django import template from django.template.loaders import select_template register = template.Library() class PlaceholderNode(template.Node): def __init__(self, name, **kwargs): self.name = name self.kwargs = kwargs def render(self, context): name = self.name.resolve(context) kwargs = { name: value.resolve(context) for name, value in self.kwargs.items() } fragment = context['page'].fragment[name] kwargs['fragment'] = fragment template_names = fragment.template_names if 'template' in kwargs: template_names.insert(0, kwargs.pop('template')) tmpl = select_template(template_names) with context.push(**kwargs): return tmpl.render(context) @register.tag def placeholder(parser, token): bits = token.contents.split() try: name = bits.pop(0) except IndexError: raise template.TemplateSyntaxError( 'Placeholder requires one positional argument' ) try: name = template.Variable(name).resolve({}) except template.VariableDoesNotExist: raise template.TemplateSyntaxError( 'Placeholder name must be a literal.' ) kwargs = template.token_kwargs(bits, parser) if bits: raise template.TemplateSyntaxError( 'Placeholder accepts only one positional argument.' ) return PlaceholderNode(name, **kwargs)
Use sendFile method instead of deprecated sendfile method.
module.exports = function ClickJackingConstructor(opts) { opts = opts || {}; opts.deny = typeof opts.deny != "undefined" ? opts.deny : false; opts.sameOrigin = opts.sameOrigin || false; opts.allowFrom = opts.allowFrom || false; opts.jsUrl = opts.jsUrl || "clickjacking_protection.js"; return function clickJacking(req, res, next) { // self-awareness if (req._esecurity_clickjacking) return next(); req._esecurity_clickjacking = true; if (opts.jsUrl && opts.jsUrl.charAt(0) !== "/") opts.jsUrl = "/" + opts.jsUrl; if (opts.jsUrl && opts.jsUrl === req.url) { var sendFileOpts = { root: __dirname, maxAge: opts.maxAge }; // res.sendfile is deprecated if (res.sendFile) { return res.sendFile("utils/clickjackingProtection.js", sendFileOpts); } return res.sendfile("utils/clickjackingProtection.js", sendFileOpts); } var frameOptions = "DENY"; if (opts.deny) frameOptions = "DENY"; else if (opts.sameOrigin) frameOptions = "SAMEORIGIN"; else if (opts.allowFrom) frameOptions = "ALLOW-FROM " + opts.allowFrom; res.set("X-Frame-Options", frameOptions); return next(); }; };
module.exports = function ClickJackingConstructor(opts) { opts = opts || {}; opts.deny = typeof opts.deny != "undefined" ? opts.deny : false; opts.sameOrigin = opts.sameOrigin || false; opts.allowFrom = opts.allowFrom || false; opts.jsUrl = opts.jsUrl || "clickjacking_protection.js"; return function clickJacking(req, res, next) { // self-awareness if (req._esecurity_clickjacking) return next(); req._esecurity_clickjacking = true; if (opts.jsUrl && opts.jsUrl.charAt(0) !== "/") opts.jsUrl = "/" + opts.jsUrl; if (opts.jsUrl && opts.jsUrl === req.url) return res.sendfile("utils/clickjackingProtection.js", { root: __dirname, maxAge: opts.maxAge }); var frameOptions = "DENY"; if (opts.deny) frameOptions = "DENY"; else if (opts.sameOrigin) frameOptions = "SAMEORIGIN"; else if (opts.allowFrom) frameOptions = "ALLOW-FROM " + opts.allowFrom; res.set("X-Frame-Options", frameOptions); return next(); }; };
Increase timeout for mocha tests. Travis machine speed can be flaky sometimes. This ensures we don't fail due to a timeout.
module.exports = function( grunt ) { grunt.initConfig({ pkg: grunt.file.readJSON( "package.json" ), jshint: { options: { esnext: true, indent: 2, expr: true, camelcase: true, curly: true, eqeqeq: true, newcap: true, unused: true, trailing: true, browser: true, node: true }, files: [ "lib/node-vtt.js" ] }, bump: { options: { files: [ "package.json" ], updateConfigs: [], commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], createTag: true, tagName: "v%VERSION%", tagMessage: "Version %VERSION%", push: true, pushTo: "[email protected]:mozilla/node-vtt.git", } }, mochaTest: { test: { options: { reporter: "spec", timeout: 50000 }, src: [ "tests/**/*.js" ] } } }); grunt.loadNpmTasks( "grunt-contrib-jshint" ); grunt.loadNpmTasks( "grunt-bump" ); grunt.loadNpmTasks( "grunt-mocha-test" ); grunt.registerTask( "default", [ "jshint", "mochaTest" ] ); }
module.exports = function( grunt ) { grunt.initConfig({ pkg: grunt.file.readJSON( "package.json" ), jshint: { options: { esnext: true, indent: 2, expr: true, camelcase: true, curly: true, eqeqeq: true, newcap: true, unused: true, trailing: true, browser: true, node: true }, files: [ "lib/node-vtt.js" ] }, bump: { options: { files: [ "package.json" ], updateConfigs: [], commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], createTag: true, tagName: "v%VERSION%", tagMessage: "Version %VERSION%", push: true, pushTo: "[email protected]:mozilla/node-vtt.git", } }, mochaTest: { test: { options: { reporter: "spec", }, src: [ "tests/**/*.js" ] } } }); grunt.loadNpmTasks( "grunt-contrib-jshint" ); grunt.loadNpmTasks( "grunt-bump" ); grunt.loadNpmTasks( "grunt-mocha-test" ); grunt.registerTask( "default", [ "jshint", "mochaTest" ] ); }
Replace hashbang with /usr/bin/env python3 for better portability
#!/usr/bin/env python3 import argparse if __name__ == '__main__': # Boilerplate to allow running as script directly. Avoids error below: # SystemError: Parent module '' not loaded, cannot perform relative import # See http://stackoverflow.com/questions/2943847/ if __package__ is None: import sys import os abspath = os.path.abspath(__file__) parent_dir = os.path.dirname(os.path.dirname(abspath)) sys.path.insert(0, parent_dir) from whoarder.clippings import Clippings del sys, os parser = argparse.ArgumentParser(description="whoarder converts Kindle \ 'My Clippings.txt' files to more pleasant HTML.") parser.add_argument('source', help='Path to the source file, stored by Kindle in \ /Media/Kindle/documents/My Clippings.txt.') parser.add_argument('destination', help='Target HTML file. If omitted, a .html bearing \ the same name as the input .txt file will be used.', nargs='?', default=None) args = parser.parse_args() clippings = Clippings(args.source, args.destination) clippings.export_clippings() print('Successfully wrote ' + clippings.dest + "\n")
#!/usr/bin/python3 import argparse if __name__ == '__main__': # Boilerplate to allow running as script directly. Avoids error below: # SystemError: Parent module '' not loaded, cannot perform relative import # See http://stackoverflow.com/questions/2943847/ if __package__ is None: import sys import os abspath = os.path.abspath(__file__) parent_dir = os.path.dirname(os.path.dirname(abspath)) sys.path.insert(0, parent_dir) from whoarder.clippings import Clippings del sys, os parser = argparse.ArgumentParser(description="whoarder converts Kindle \ 'My Clippings.txt' files to more pleasant HTML.") parser.add_argument('source', help='Path to the source file, stored by Kindle in \ /Media/Kindle/documents/My Clippings.txt.') parser.add_argument('destination', help='Target HTML file. If omitted, a .html bearing \ the same name as the input .txt file will be used.', nargs='?', default=None) args = parser.parse_args() clippings = Clippings(args.source, args.destination) clippings.export_clippings() print('Successfully wrote ' + clippings.dest + "\n")
Include course number in course search results
/** Course search utility for admin **/ !function(app, $) { $(document).ready(function() { if($('.courses-search-query').length) { var target = $('.courses-search-query'); $.ajax({ url: target.data('autocompleteurl'), dataType: "json", success: function(courses) { target.omniselect({ source: courses, resultsClass: 'typeahead dropdown-menu course-result', activeClass: 'active', itemLabel: function(course) { return course.courseno + " " + course.name; }, itemId: function(course) { return course.id; }, renderItem: function(label) { return '<li><a href="#">' + label + '</a></li>'; }, filter: function(item, query) { var regex = new RegExp(query, 'i'); return item.name.match(regex) || item.courseno.match(regex); } }).on('omniselect:select', function(event, id) { var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", "/current_course/change"); var field = document.createElement("input"); field.setAttribute("type", "hidden"); field.setAttribute("name", "course_id"); field.setAttribute("value", id); form.appendChild(field); document.body.appendChild(form); form.submit(); return false; }); } }); } }); }(Gradecraft, jQuery);
/** Course search utility for admin **/ !function(app, $) { $(document).ready(function() { if($('.courses-search-query').length) { var target = $('.courses-search-query'); $.ajax({ url: target.data('autocompleteurl'), dataType: "json", success: function(courses) { target.omniselect({ source: courses, resultsClass: 'typeahead dropdown-menu course-result', activeClass: 'active', itemLabel: function(course) { return course.name; }, itemId: function(course) { return course.id; }, renderItem: function(label) { return '<li><a href="#">' + label + '</a></li>'; }, filter: function(item, query) { var regex = new RegExp(query, 'i'); return item.name.match(regex) || item.courseno.match(regex); } }).on('omniselect:select', function(event, id) { var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", "/current_course/change"); var field = document.createElement("input"); field.setAttribute("type", "hidden"); field.setAttribute("name", "course_id"); field.setAttribute("value", id); form.appendChild(field); document.body.appendChild(form); form.submit(); return false; }); } }); } }); }(Gradecraft, jQuery);
Sort by greatest CP when the name is the same
import Long from 'long'; import _ from 'lodash'; export default { recent(items) { return _.reverse( _.sortBy(items, (v) => { const ms = v && v.creation_time_ms; return ms && new Long(ms.low, ms.high, ms.unsigned).toString(); }) ); }, iv(items) { return _.reverse( _.sortBy(items, (v) => { let i = 0; let sum = 0; _.forEach(['individual_attack', 'individual_defense', 'individual_stamina'], (key) => { if (typeof v[key] !== 'undefined') { sum += v[key]; i++; } }); return sum / i; }) ); }, id(items) { return _.sortBy( _.sortBy(items, (v) => -v.cp), (v) => v.pokemon_id ); }, cp(items) { return _.sortBy(items, (v) => -v.cp); }, name(items) { return _.sortBy( _.sortBy(items, (v) => -v.cp), (v) => { if (typeof v.nickname !== "undefined" && v.nickname !== "") { return v.nickname; } else { return v.meta.name; } } ); }, };
import Long from 'long'; import _ from 'lodash'; export default { recent(items) { return _.reverse( _.sortBy(items, (v) => { const ms = v && v.creation_time_ms; return ms && new Long(ms.low, ms.high, ms.unsigned).toString(); }) ); }, iv(items) { return _.reverse( _.sortBy(items, (v) => { let i = 0; let sum = 0; _.forEach(['individual_attack', 'individual_defense', 'individual_stamina'], (key) => { if (typeof v[key] !== 'undefined') { sum += v[key]; i++; } }); return sum / i; }) ); }, id(items) { return _.sortBy( _.sortBy(items, (v) => -v.cp), (v) => v.pokemon_id ); }, cp(items) { return _.sortBy(items, (v) => -v.cp); }, name(items) { return _.sortBy(items, (v) => { if (typeof v.nickname !== "undefined" && v.nickname !== "") { return v.nickname; } else { return v.meta.name; } }); }, };
Allow customizing a template extension in requirejs config
define(["handlebars"], function(Handlebars) { var buildMap = {}, templateExtension = ".hbs"; return { // http://requirejs.org/docs/plugins.html#apiload load: function (name, parentRequire, onload, config) { // Get the template extension. var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension); if (config.isBuild) { // Use node.js file system module to load the template. // Sorry, no Rhino support. var fs = nodeRequire("fs"); var fsPath = config.dirBaseUrl + "/" + name + ext; buildMap[name] = fs.readFileSync(fsPath).toString(); onload(); } else { // In browsers use the text-plugin to the load template. This way we // don't have to deal with ajax stuff parentRequire(["text!" + name + ext], function(raw) { // Just return the compiled template onload(Handlebars.compile(raw)); }); } }, // http://requirejs.org/docs/plugins.html#apiwrite write: function (pluginName, name, write) { var compiled = Handlebars.precompile(buildMap[name]); // Write out precompiled version of the template function as AMD // definition. write( "define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" + "return Handlebars.template(" + compiled.toString() + ");\n" + "});\n" ); } }; });
define(["handlebars"], function(Handlebars) { var buildMap = {}; return { // http://requirejs.org/docs/plugins.html#apiload load: function (name, parentRequire, onload, config) { if (config.isBuild) { // Use node.js file system module to load the template. // Sorry, no Rhino support. var fs = nodeRequire("fs"); var fsPath = config.dirBaseUrl + "/" + name + ".hbs"; buildMap[name] = fs.readFileSync(fsPath).toString(); onload(); } else { // In browsers use the text-plugin to the load template. This way we // don't have to deal with ajax stuff parentRequire(["text!" + name + ".hbs"], function(raw) { // Just return the compiled template onload(Handlebars.compile(raw)); }); } }, // http://requirejs.org/docs/plugins.html#apiwrite write: function (pluginName, name, write) { var compiled = Handlebars.precompile(buildMap[name]); // Write out precompiled version of the template function as AMD // definition. write( "define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" + "return Handlebars.template(" + compiled.toString() + ");\n" + "});\n" ); } }; });
Add duration property in transition
import Vue from 'vue' const transitionsKeys = [ 'name', 'mode', 'css', 'type', 'duration', 'enterClass', 'leaveClass', 'enterActiveClass', 'enterActiveClass', 'leaveActiveClass', 'enterToClass', 'leaveToClass' ] const listenersKeys = [ 'beforeEnter', 'enter', 'afterEnter', 'enterCancelled', 'beforeLeave', 'leave', 'afterLeave', 'leaveCancelled' ] export default { name: 'nuxt-child', functional: true, render (h, { parent, data }) { data.nuxtChild = true const transitions = parent.$nuxt.nuxt.transitions const defaultTransition = parent.$nuxt.nuxt.defaultTransition let depth = 0 while (parent) { if (parent.$vnode && parent.$vnode.data.nuxtChild) { depth++ } parent = parent.$parent } data.nuxtChildDepth = depth const transition = transitions[depth] || defaultTransition let transitionProps = {} transitionsKeys.forEach((key) => { if (typeof transition[key] !== 'undefined') { transitionProps[key] = transition[key] } }) let listeners = {} listenersKeys.forEach((key) => { if (typeof transition[key] === 'function') { listeners[key] = transition[key] } }) return h('transition', { props: transitionProps, on: listeners }, [ h('router-view', data) ]) } }
import Vue from 'vue' const transitionsKeys = [ 'name', 'mode', 'css', 'type', 'enterClass', 'leaveClass', 'enterActiveClass', 'enterActiveClass', 'leaveActiveClass', 'enterToClass', 'leaveToClass' ] const listenersKeys = [ 'beforeEnter', 'enter', 'afterEnter', 'enterCancelled', 'beforeLeave', 'leave', 'afterLeave', 'leaveCancelled' ] export default { name: 'nuxt-child', functional: true, render (h, { parent, data }) { data.nuxtChild = true const transitions = parent.$nuxt.nuxt.transitions const defaultTransition = parent.$nuxt.nuxt.defaultTransition let depth = 0 while (parent) { if (parent.$vnode && parent.$vnode.data.nuxtChild) { depth++ } parent = parent.$parent } data.nuxtChildDepth = depth const transition = transitions[depth] || defaultTransition let transitionProps = {} transitionsKeys.forEach((key) => { if (typeof transition[key] !== 'undefined') { transitionProps[key] = transition[key] } }) let listeners = {} listenersKeys.forEach((key) => { if (typeof transition[key] === 'function') { listeners[key] = transition[key] } }) return h('transition', { props: transitionProps, on: listeners }, [ h('router-view', data) ]) } }
Update barcode resource to new resource specification
"""Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: A dictionary for the resource page. """ # Retrieve parameters parameter_options = valid_options() barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"]) image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image = Image.open(image_path.format(barcode_length)) return {"type": "image", "data": image} def subtitle(request, resource): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: Text for subtitle (str). """ barcode_length = retrieve_query_parameter(request, "barcode_length") paper_size = retrieve_query_parameter(request, "paper_size") return "{} digits - {}".format(barcode_length, paper_size) def valid_options(): """Provide dictionary of all valid parameters. This excludes the header text parameter. Returns: All valid options (dict). """ return { "barcode_length": ["12", "13"], "paper_size": ["a4", "letter"], }
"""Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource_image(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: A list of Pillow image objects. """ # Retrieve parameters parameter_options = valid_options() barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"]) image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image = Image.open(image_path.format(barcode_length)) return image def subtitle(request, resource): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: Text for subtitle (str). """ barcode_length = retrieve_query_parameter(request, "barcode_length") paper_size = retrieve_query_parameter(request, "paper_size") return "{} digits - {}".format(barcode_length, paper_size) def valid_options(): """Provide dictionary of all valid parameters. This excludes the header text parameter. Returns: All valid options (dict). """ return { "barcode_length": ["12", "13"], "paper_size": ["a4", "letter"], }
Make query slightly more complex
import assert from "assert"; import { introspectStarwars } from './introspectStarwars'; import { initTemplateStringTransformer } from '../src/index'; import fs from 'fs'; import path from 'path'; // Uncomment the below to generate a new schema JSON // describe("graphql", () => { // it("can introspect star wars", async () => { // const result = await introspectStarwars(); // // fs.writeFileSync(path.join(__dirname, "starwars.json"), // JSON.stringify(result, null, 2)); // // assert.ok(result.data); // assert.ok(result.data.__schema); // }); // }); describe("runtime query transformer", () => { it("can be initialized with an introspected query", async () => { const result = await introspectStarwars(); const transformer = initTemplateStringTransformer(result.data); }); it("can compile a Relay.QL query", () => { Relay.QL` query HeroNameQuery { hero { name } } `; }); it("can transform a simple query", async () => { const result = await introspectStarwars(); const transformer = initTemplateStringTransformer(result.data); const transformed = transformer(` query HeroNameAndFriendsQuery { hero { id name friends { name } } } `); const expected = Relay.QL` query HeroNameAndFriendsQuery { hero { id name friends { name } } } `; assert.deepEqual(transformed, expected); }); });
import assert from "assert"; import { introspectStarwars } from './introspectStarwars'; import { initTemplateStringTransformer } from '../src/index'; import fs from 'fs'; import path from 'path'; // Uncomment the below to generate a new schema JSON // describe("graphql", () => { // it("can introspect star wars", async () => { // const result = await introspectStarwars(); // // fs.writeFileSync(path.join(__dirname, "starwars.json"), // JSON.stringify(result, null, 2)); // // assert.ok(result.data); // assert.ok(result.data.__schema); // }); // }); describe("runtime query transformer", () => { it("can be initialized with an introspected query", async () => { const result = await introspectStarwars(); const transformer = initTemplateStringTransformer(result.data); }); it("can compile a Relay.QL query", () => { Relay.QL` query HeroNameQuery { hero { name } } `; }); it("can transform a simple query", async () => { const result = await introspectStarwars(); const transformer = initTemplateStringTransformer(result.data); const transformed = transformer(` query HeroNameQuery { hero { name } } `); const expected = Relay.QL` query HeroNameQuery { hero { name } } `; assert.deepEqual(transformed, expected); }); });
Fix delete action should return a json object
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Project; use App\ProjectLabel; class LabelsController extends Controller { /** * Dsiplay a listing of the project labels * * @param Project $project * @return Response */ public function index(Project $project) { $project->load('labels'); return response()->json($project); } /** * Store a newly created resource in storage. * * @param Request $request * @param Project $project * @return Response */ public function store(Request $request, Project $project) { $label = new ProjectLabel($request->all()); $project->labels()->save($label); return response()->json($label); } /** * Update the specified resource in storage. * * @param Request $request * @param Project $project * @param ProjectLabel $label * @return Response */ public function update(Request $request, Project $project, ProjectLabel $label) { $label->update($request->all()); return response()->json($label); } /** * Remove the specified resource from storage. * * @param Project $project * @param ProjectLabel $label * @return Response */ public function destroy(Project $project, ProjectLabel $label) { $label->delete(); return $label; } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Project; use App\ProjectLabel; class LabelsController extends Controller { /** * Dsiplay a listing of the project labels * * @param Project $project * @return Response */ public function index(Project $project) { $project->load('labels'); return response()->json($project); } /** * Store a newly created resource in storage. * * @param Request $request * @param Project $project * @return Response */ public function store(Request $request, Project $project) { $label = new ProjectLabel($request->all()); $project->labels()->save($label); return response()->json($label); } /** * Update the specified resource in storage. * * @param Request $request * @param Project $project * @param ProjectLabel $label * @return Response */ public function update(Request $request, Project $project, ProjectLabel $label) { $label->update($request->all()); return response()->json($label);http://localhost:8000 } /** * Remove the specified resource from storage. * * @param Project $project * @param ProjectLabel $label * @return Response */ public function destroy(Project $project, ProjectLabel $label) { $label->delete(); } }
Change hdu[0] to hdu for optional indexing
""" Some very beta tools for IRIS """ import sunpy.io import sunpy.time import sunpy.map __all__ = ['SJI_to_cube'] def SJI_to_cube(filename, start=0, stop=None, hdu=0): """ Read a SJI file and return a MapCube ..warning:: This function is a very early beta and is not stable. Further work is on going to improve SunPy IRIS support. Parameters ---------- filename: string File to read start: Temporal axis index to create MapCube from stop: Temporal index to stop MapCube at hdu: Choose hdu index Returns ------- iris_cube: sunpy.map.MapCube A map cube of the SJI sequence """ hdus = sunpy.io.read_file(filename) #Get the time delta time_range = sunpy.time.TimeRange(hdus[hdu][1]['STARTOBS'], hdus[hdu][1]['ENDOBS']) splits = time_range.split(hdus[hdu][0].shape[0]) if not stop: stop = len(splits) headers = [hdus[hdu][1]]*(stop-start) datas = hdus[hdu][0][start:stop] #Make the cube: iris_cube = sunpy.map.Map(zip(datas,headers),cube=True) #Set the date/time for i,m in enumerate(iris_cube): m.meta['DATE-OBS'] = splits[i].center().isoformat() return iris_cube
""" Some very beta tools for IRIS """ import sunpy.io import sunpy.time import sunpy.map __all__ = ['SJI_to_cube'] def SJI_to_cube(filename, start=0, stop=None): """ Read a SJI file and return a MapCube ..warning:: This function is a very early beta and is not stable. Further work is on going to improve SunPy IRIS support. Parameters ---------- filename: string File to read start: Temporal axis index to create MapCube from stop: Temporal index to stop MapCube at Returns ------- iris_cube: sunpy.map.MapCube A map cube of the SJI sequence """ hdus = sunpy.io.read_file(filename) #Get the time delta time_range = sunpy.time.TimeRange(hdus[0][1]['STARTOBS'], hdus[0][1]['ENDOBS']) splits = time_range.split(hdus[0][0].shape[0]) if not stop: stop = len(splits) headers = [hdus[0][1]]*(stop-start) datas = hdus[0][0][start:stop] #Make the cube: iris_cube = sunpy.map.Map(zip(datas,headers),cube=True) #Set the date/time for i,m in enumerate(iris_cube): m.meta['DATE-OBS'] = splits[i].center().isoformat() return iris_cube
Reduce anonymous function creation during iteration for edge cases
'use strict' var values = require('../sources/values') var once = require('../sources/once') function getAbortCb(read, abort, cb) { return function(err) { read(err || abort, cb) } } function getChunkErrorCb(err, cb) { return function() { cb(err) } } //convert a stream of arrays or streams into just a stream. module.exports = function flatten () { return function (read) { var _read return function (abort, cb) { if (abort) { //abort the current stream, and then stream of streams. _read ? _read(abort, getAbortCb(read, abort, cb)) : read(abort, cb) } else if(_read) nextChunk() else nextStream() function nextChunk () { _read(null, function (err, data) { if (err) { if (err === true) nextStream() else read(true, getChunkErrorCb(err, cb)) } else cb(null, data) }) } function nextStream () { _read = null read(null, function (end, stream) { if(end) return cb(end) if(stream && 'object' === typeof stream) stream = values(stream) else if ('function' !== typeof stream) stream = once(stream) _read = stream nextChunk() }) } } } }
'use strict' var values = require('../sources/values') var once = require('../sources/once') //convert a stream of arrays or streams into just a stream. module.exports = function flatten () { return function (read) { var _read return function (abort, cb) { if (abort) { //abort the current stream, and then stream of streams. _read ? _read(abort, function(err) { read(err || abort, cb) }) : read(abort, cb) } else if(_read) nextChunk() else nextStream() function nextChunk () { _read(null, function (err, data) { if (err) { if (err === true) nextStream() else read(true, function(abortErr) { // TODO: what do we do with the abortErr? cb(err) }) } else cb(null, data) }) } function nextStream () { _read = null read(null, function (end, stream) { if(end) return cb(end) if(stream && 'object' === typeof stream) stream = values(stream) else if ('function' !== typeof stream) stream = once(stream) _read = stream nextChunk() }) } } } }
Store resolved path in path property (don't use separate resolvedPath property)
var ThemingContext = require('./ThemingContext'); var lessParser = require('./less-parser'); var logger = require('raptor-logging').logger(module); module.exports = function create(config) { return { properties: { path: 'string' }, // we don't actually produce JavaScript or CSS contentType: 'none', init: function(optimizerContext, callback) { if (!lessParser.exists()) { return callback(new Error('Unable to handle themed Less dependency for path "' + this.path + '". The "less" module was not found. This module should be installed as a top-level application module.')); } this.path = this.requireResolvePath(this.path); callback(); }, onAddToPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.path); } }, onAddToAsyncPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.path); } }, read: function(optimizerContext, callback) { return null; }, calculateKey: function() { // use the absolute path to the imported resource as the key return this.path; } }; };
var ThemingContext = require('./ThemingContext'); var lessParser = require('./less-parser'); var logger = require('raptor-logging').logger(module); module.exports = function create(config) { return { properties: { path: 'string' }, // we don't actually produce JavaScript or CSS contentType: 'none', init: function(optimizerContext, callback) { if (!lessParser.exists()) { return callback(new Error('Unable to handle themed Less dependency for path "' + this.path + '". The "less" module was not found. This module should be installed as a top-level application module.')); } this.resolvedPath = this.requireResolvePath(this.path); callback(); }, onAddToPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.resolvedPath); } }, onAddToAsyncPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.resolvedPath); } }, read: function(optimizerContext, callback) { return null; }, calculateKey: function() { // use the absolute path to the imported resource as the key return this.resolvedPath; } }; };
Use angular.isArray() for better IE8 support
/** * Created by Zack Boman on 1/31/14. * http://www.zackboman.com or [email protected] */ 'use strict'; (function(){ var mod = angular.module('routeStyles', ['ngRoute']); mod.directive('head', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'E', link: function(scope, elem){ var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >'; elem.append($compile(html)(scope)); scope.routeStyles = {}; $rootScope.$on('$routeChangeStart', function (e, next) { if(next && next.$$route && next.$$route.css){ if(!angular.isArray(next.$$route.css)){ next.$$route.css = [next.$$route.css]; } angular.forEach(next.$$route.css, function(sheet){ scope.routeStyles[sheet] = sheet; }); } }); $rootScope.$on('$routeChangeSuccess', function(e, current, previous) { if (previous && previous.$$route && previous.$$route.css) { if (!angular.isArray(previous.$$route.css)) { previous.$$route.css = [previous.$$route.css]; } angular.forEach(previous.$$route.css, function (sheet) { scope.routeStyles[sheet] = undefined; }); } }); } }; } ]); })();
/** * Created by Zack Boman on 1/31/14. * http://www.zackboman.com or [email protected] */ 'use strict'; (function(){ var mod = angular.module('routeStyles', ['ngRoute']); mod.directive('head', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'E', link: function(scope, elem){ var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >'; elem.append($compile(html)(scope)); scope.routeStyles = {}; $rootScope.$on('$routeChangeStart', function (e, next) { if(next && next.$$route && next.$$route.css){ if(!Array.isArray(next.$$route.css)){ next.$$route.css = [next.$$route.css]; } angular.forEach(next.$$route.css, function(sheet){ scope.routeStyles[sheet] = sheet; }); } }); $rootScope.$on('$routeChangeSuccess', function(e, current, previous) { if (previous && previous.$$route && previous.$$route.css) { if (!Array.isArray(previous.$$route.css)) { previous.$$route.css = [previous.$$route.css]; } angular.forEach(previous.$$route.css, function (sheet) { scope.routeStyles[sheet] = undefined; }); } }); } }; } ]); })();
Update the last poll time
package org.linuxguy.MarketBot; import com.gc.android.market.api.MarketSession; import com.gc.android.market.api.model.Market; import java.util.concurrent.TimeUnit; public class GooglePlayWatcher extends Watcher<Comment> implements MarketSession.Callback<Market.CommentsResponse> { private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(5); private String mUsername; private String mPassword; private String mAppId; public GooglePlayWatcher(String username, String password, String appId) { mUsername = username; mPassword = password; mAppId = appId; } @Override public void run() { MarketSession session = new MarketSession(); session.login(mUsername, mPassword); while (true) { Market.CommentsRequest commentsRequest = Market.CommentsRequest.newBuilder() .setAppId(mAppId) .setStartIndex(0) .setEntriesCount(5) .build(); session.append(commentsRequest, this); session.flush(); try { Thread.sleep(POLL_INTERVAL_MS); } catch (InterruptedException e) { break; } } } @Override public void onResult(Market.ResponseContext responseContext, Market.CommentsResponse response) { for (Market.Comment c : response.getCommentsList()) { if (c.getCreationTime() > mLastPollTime) { notifyListeners(Comment.from(c)); } } mLastPollTime = System.currentTimeMillis(); } }
package org.linuxguy.MarketBot; import com.gc.android.market.api.MarketSession; import com.gc.android.market.api.model.Market; import java.util.concurrent.TimeUnit; public class GooglePlayWatcher extends Watcher<Comment> implements MarketSession.Callback<Market.CommentsResponse> { private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(5); private String mUsername; private String mPassword; private String mAppId; public GooglePlayWatcher(String username, String password, String appId) { mUsername = username; mPassword = password; mAppId = appId; } @Override public void run() { MarketSession session = new MarketSession(); session.login(mUsername, mPassword); while (true) { Market.CommentsRequest commentsRequest = Market.CommentsRequest.newBuilder() .setAppId(mAppId) .setStartIndex(0) .setEntriesCount(5) .build(); session.append(commentsRequest, this); session.flush(); try { Thread.sleep(POLL_INTERVAL_MS); } catch (InterruptedException e) { break; } } } @Override public void onResult(Market.ResponseContext responseContext, Market.CommentsResponse response) { for (Market.Comment c : response.getCommentsList()) { if (c.getCreationTime() > mLastPollTime) { notifyListeners(Comment.from(c)); } } } }
Update compiler_error; fixed typo line 30
#!/usr/bin/python # Copyright 2017 Joshua Charles Campbell # # This file is part of UnnaturalCode. # # UnnaturalCode 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. # # UnnaturalCode 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 UnnaturalCode. If not, see <http://www.gnu.org/licenses/>. from six import integer_types class CompileError(object): def __init__(self, filename=None, line=None, column=None, functionname=None, text=None, errorname=None): assert line is not None assert isinstance(line, integer_types) self.filename = filename self.line = line self.functionname = functionname self.text = text self.errorname = errorname if column is not None: assert isintance(column, integer_types) self.column = column """ Compile result should be a list of CompileError objects, or if compile was successful, None (no list at all). """
#!/usr/bin/python # Copyright 2017 Joshua Charles Campbell # # This file is part of UnnaturalCode. # # UnnaturalCode 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. # # UnnaturalCode 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 UnnaturalCode. If not, see <http://www.gnu.org/licenses/>. from six import integer_types class CompileError(object): def __init__(self, filename=None, line=None, column=None, functionname=None, text=None, errorname=None): assert line is not None assert isintance(line, integer_types) self.filename = filename self.line = line self.functionname = functionname self.text = text self.errorname = errorname if column is not None: assert isintance(column, integer_types) self.column = column """ Compile result should be a list of CompileError objects, or if compile was successful, None (no list at all). """
Update to latest Pylons ver
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='kai', version='0.1', description='', author='Ben Bangert', author_email='[email protected]', install_requires=[ "Pylons>=0.9.7", "CouchDB>=0.4", "python-openid>=2.2.1", "pytz>=2008i", "Babel>=0.9.4", "tw.forms==0.9.3", "docutils>=0.5", "PyXML>=0.8.4", "cssutils>=0.9.6a0", "Pygments>=1.0", ], setup_requires=["PasteScript>=1.6.3"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'kai': ['i18n/*/LC_MESSAGES/*.mo']}, message_extractors = {'kai': [ ('**.py', 'python', None), ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}), ('public/**', 'ignore', None)]}, zip_safe=False, paster_plugins=['PasteScript', 'Pylons'], entry_points=""" [paste.app_factory] main = kai.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller """, )
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='kai', version='0.1', description='', author='Ben Bangert', author_email='[email protected]', install_requires=[ "Pylons>=0.9.7rc4", "CouchDB>=0.4", "python-openid>=2.2.1", "pytz>=2008i", "Babel>=0.9.4", "tw.forms==0.9.3", "docutils>=0.5", "PyXML>=0.8.4", "cssutils>=0.9.6a0", "Pygments>=1.0", ], setup_requires=["PasteScript>=1.6.3"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'kai': ['i18n/*/LC_MESSAGES/*.mo']}, message_extractors = {'kai': [ ('**.py', 'python', None), ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}), ('public/**', 'ignore', None)]}, zip_safe=False, paster_plugins=['PasteScript', 'Pylons'], entry_points=""" [paste.app_factory] main = kai.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller """, )
Add hr to sponsors list
<div id="sponsors" class="container"> <hr> <h2>Sponsors</h2> <div class="sponsors-list"> <div> <a href="https://www.digitalocean.com/?refcode=7922b1dff899"> <img src="{{ asset('images/digitalocean.png') }}"> </a> </div> <div> <a href="https://ottomatik.io/?refcode=bPeKyjQV"> <img src="{{ asset('images/ottomatik.png') }}"> </a> </div> <div> <a href="https://forge.laravel.com/"> <img src="{{ asset('images/forge.png') }}"> </a> </div> <div> <a href="https://envoyer.io/"> <img src="{{ asset('images/envoyer.png') }}"> </a> </div> <div> <a href="https://cartalyst.com/?utm_source=laravelio&utm_medium=banner&utm_campaign=laravelio"> <img src="{{ asset('images/cartalyst.png') }}"> </a> </div> <div> <a href="https://bugsnag.com/?r=xUVct0"> <img src="{{ asset('images/bugsnag.png') }}"> </a> </div> </div> </div>
<div id="sponsors" class="container"> <h2>Sponsors</h2> <div class="sponsors-list"> <div> <a href="https://www.digitalocean.com/?refcode=7922b1dff899"> <img src="{{ asset('images/digitalocean.png') }}"> </a> </div> <div> <a href="https://ottomatik.io/?refcode=bPeKyjQV"> <img src="{{ asset('images/ottomatik.png') }}"> </a> </div> <div> <a href="https://forge.laravel.com/"> <img src="{{ asset('images/forge.png') }}"> </a> </div> <div> <a href="https://envoyer.io/"> <img src="{{ asset('images/envoyer.png') }}"> </a> </div> <div> <a href="https://cartalyst.com/?utm_source=laravelio&utm_medium=banner&utm_campaign=laravelio"> <img src="{{ asset('images/cartalyst.png') }}"> </a> </div> <div> <a href="https://bugsnag.com/?r=xUVct0"> <img src="{{ asset('images/bugsnag.png') }}"> </a> </div> </div> </div>
Add regex support call to the command line
''' The management of salt command line utilities are stored in here ''' # Import python libs import optparse import os import sys # Import salt components import salt.client class SaltCMD(object): ''' The execution of a salt command happens here ''' def __init__(self): ''' Cretae a SaltCMD object ''' self.opts = self.__parse() def __parse(self): ''' Parse the command line ''' parser = optparse.OptionParser() parser.add_option('-t', '--timeout', default=5, type=int, dest='timeout', help='Set the return timeout for batch jobs') parser.add_option('-E', '--pcre', default=False, dest='pcre', action='store_true' help='Instead of using shell globs to evaluate the target'\ + ' servers, use pcre regular expressions') options, args = parser.parse_args() opts = {} opts['timeout'] = options.timeout opts['pcre'] = options.pcre opts['tgt'] = args[0] opts['fun'] = args[1] opts['arg'] = args[2:] return opts def run(self): ''' Execute the salt command line ''' local = salt.client.LocalClient() print local.cmd(self.opts['tgt'], self.opts['fun'], self.opts['arg'], self.opts['timeout'])
''' The management of salt command line utilities are stored in here ''' # Import python libs import optparse import os import sys # Import salt components import salt.client class SaltCMD(object): ''' The execution of a salt command happens here ''' def __init__(self): ''' Cretae a SaltCMD object ''' self.opts = self.__parse() def __parse(self): ''' Parse the command line ''' parser = optparse.OptionParser() parser.add_option('-t', '--timeout', default=5, type=int, dest='timeout', help='Set the return timeout for batch jobs') options, args = parser.parse_args() opts = {} opts['timeout'] = options.timeout opts['tgt'] = args[0] opts['fun'] = args[1] opts['arg'] = args[2:] return opts def run(self): ''' Execute the salt command line ''' local = salt.client.LocalClient() print local.cmd(self.opts['tgt'], self.opts['fun'], self.opts['arg'], self.opts['timeout'])
Change function defs to variable defs in block scope. Function definitions in blocks cause chrome to throw syntax error in strict mode.
var isES5 = (function(){ "use strict"; return this === void 0; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, keys: Object.keys, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5 }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function ObjectKeys(o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; } var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) { o[key] = desc.value; return o; } var ObjectFreeze = function ObjectFreeze(obj) { return obj; } var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } } var ArrayIsArray = function ArrayIsArray(obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } } module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, defineProperty: ObjectDefineProperty, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5 }; }
var isES5 = (function(){ "use strict"; return this === void 0; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, keys: Object.keys, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5 }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; function ObjectKeys(o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; } function ObjectDefineProperty(o, key, desc) { o[key] = desc.value; return o; } function ObjectFreeze(obj) { return obj; } function ObjectGetPrototypeOf(obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } } function ArrayIsArray(obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } } module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, defineProperty: ObjectDefineProperty, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5 }; }
Bump to version 0.4.1 since 0.4 was mis-packaged.
from setuptools import setup, find_packages setup(name='corker', version='0.4.1', description='Another WSGI Framework', classifiers=["Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], license='BSD', author='Joshua D. Boyd', author_email='[email protected]', url='https://github.com/jd-boyd/corker', packages=find_packages(), package_data={'': ['README.md', 'LICENSE.txt']}, install_requires=['webob', 'routes'], tests_require=['nose', 'webtest'], )
from setuptools import setup, find_packages setup(name='corker', version='0.4', description='Another WSGI Framework', classifiers=["Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], license='BSD', author='Joshua D. Boyd', author_email='[email protected]', url='https://github.com/jd-boyd/corker', packages=find_packages(), package_data={'': ['README.md', 'LICENSE.txt']}, install_requires=['webob', 'routes'], tests_require=['nose', 'webtest'], )
Remove insane double ternary operator Ternary operators are fine, but putting one inside another is hard to read and confusing.
package io.generators.core; import javax.annotation.Nonnull; import java.util.Collection; import java.util.List; import java.util.Random; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.copyOf; /** * Generates randomly selected element from collection/array * * @param <T> type of the collection's elements * @author Tomas Klubal */ public class RandomFromCollectionGenerator<T> implements Generator<T> { private final List<T> items; private final Random random = new Random(); /** * Creates generator that selects values from <code>items</code> passed in * * @param items to select from * @throws NullPointerException when collection passed in is null */ public RandomFromCollectionGenerator(@Nonnull Collection<T> items) { this.items = copyOf(checkNotNull(items, "Collection for generation can't be null")); } /** * Creates generator that selects values from <code>items</code> passed in * * @param items to select from * @throws NullPointerException when array passed in is null */ @SafeVarargs public RandomFromCollectionGenerator(T... items) { this.items = copyOf(checkNotNull(items, "Collection for generation can't be null")); } @Override public T next() { int maximumIndex = items.size() - 1; if (maximumIndex > 0) { return items.get(random.nextInt(maximumIndex)); } else if (maximumIndex == 0) { return items.get(0); } else { return null; } } }
package io.generators.core; import javax.annotation.Nonnull; import java.util.Collection; import java.util.List; import java.util.Random; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.copyOf; /** * Generates randomly selected element from collection/array * * @param <T> type of the collection's elements * * @author Tomas Klubal */ public class RandomFromCollectionGenerator<T> implements Generator<T> { private final List<T> items; private final Random random = new Random(); /** * Creates generator that selects values from <code>items</code> passed in * * @param items to select from * @throws NullPointerException when collection passed in is null */ public RandomFromCollectionGenerator(@Nonnull Collection<T> items) { this.items = copyOf(checkNotNull(items, "Collection for generation can't be null")); } /** * Creates generator that selects values from <code>items</code> passed in * * @param items to select from * @throws NullPointerException when array passed in is null */ @SafeVarargs public RandomFromCollectionGenerator(T... items) { this.items = copyOf(checkNotNull(items, "Collection for generation can't be null")); } @Override public T next() { int maximumIndex = items.size() - 1; return maximumIndex > 0 ? items.get(random.nextInt(maximumIndex)) : maximumIndex == 0 ? items.get(0) : null; } }
Set stream scenario be in sync with stream scenario from services
package io.scalecube.gateway.benchmarks; import io.scalecube.services.api.ServiceMessage; import java.util.concurrent.Callable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; public class BenchmarksServiceImpl implements BenchmarksService { @Override public Mono<ServiceMessage> one(ServiceMessage message) { Callable<ServiceMessage> callable = () -> { long value = System.currentTimeMillis(); return ServiceMessage.from(message) .header(SERVICE_RECV_TIME, value) .header(SERVICE_SEND_TIME, value) .data("hello") .build(); }; return Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()); } @Override public Mono<ServiceMessage> failure(ServiceMessage message) { return Mono.defer(() -> Mono.error(new RuntimeException("General failure"))); } @Override public Flux<ServiceMessage> infiniteStream(ServiceMessage message) { Callable<ServiceMessage> callable = () -> ServiceMessage.from(message) .header(SERVICE_SEND_TIME, System.currentTimeMillis()) .build(); return Mono.fromCallable(callable) .subscribeOn(Schedulers.parallel()) .repeat() .onBackpressureDrop(); } }
package io.scalecube.gateway.benchmarks; import io.scalecube.services.api.ServiceMessage; import java.util.concurrent.Callable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; public class BenchmarksServiceImpl implements BenchmarksService { @Override public Mono<ServiceMessage> one(ServiceMessage message) { Callable<ServiceMessage> callable = () -> { long value = System.currentTimeMillis(); return ServiceMessage.from(message) .header(SERVICE_RECV_TIME, value) .header(SERVICE_SEND_TIME, value) .data("hello") .build(); }; return Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()); } @Override public Mono<ServiceMessage> failure(ServiceMessage message) { return Mono.defer(() -> Mono.error(new RuntimeException("General failure"))); } @Override public Flux<ServiceMessage> infiniteStream(ServiceMessage message) { return Flux.defer( () -> { Callable<ServiceMessage> callable = () -> ServiceMessage.builder() .qualifier(message.qualifier()) .header(SERVICE_SEND_TIME, Long.toString(System.currentTimeMillis())) .build(); return Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()).repeat(); }); } }
Migrate org notif tests to pytest
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import pytest from udata.models import MembershipRequest, Member from udata.core.user.factories import UserFactory from udata.core.organization.factories import OrganizationFactory from udata.core.organization.notifications import ( membership_request_notifications ) from udata.tests.helpers import assert_equal_dates @pytest.mark.usefixtures('clean_db') class OrganizationNotificationsTest: def test_pending_membership_requests(self): admin = UserFactory() editor = UserFactory() applicant = UserFactory() request = MembershipRequest(user=applicant, comment='test') members = [ Member(user=editor, role='editor'), Member(user=admin, role='admin') ] org = OrganizationFactory(members=members, requests=[request]) assert len(membership_request_notifications(applicant)) is 0 assert len(membership_request_notifications(editor)) is 0 notifications = membership_request_notifications(admin) assert len(notifications) is 1 dt, details = notifications[0] assert_equal_dates(dt, request.created) assert details['id'] == request.id assert details['organization'] == org.id assert details['user']['id'] == applicant.id assert details['user']['fullname'] == applicant.fullname assert details['user']['avatar'] == str(applicant.avatar)
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from udata.models import MembershipRequest, Member from udata.core.user.factories import UserFactory from udata.core.organization.factories import OrganizationFactory from udata.core.organization.notifications import ( membership_request_notifications ) from .. import TestCase, DBTestMixin class OrganizationNotificationsTest(TestCase, DBTestMixin): def test_pending_membership_requests(self): admin = UserFactory() editor = UserFactory() applicant = UserFactory() request = MembershipRequest(user=applicant, comment='test') members = [ Member(user=editor, role='editor'), Member(user=admin, role='admin') ] org = OrganizationFactory(members=members, requests=[request]) self.assertEqual(len(membership_request_notifications(applicant)), 0) self.assertEqual(len(membership_request_notifications(editor)), 0) notifications = membership_request_notifications(admin) self.assertEqual(len(notifications), 1) dt, details = notifications[0] self.assertEqualDates(dt, request.created) self.assertEqual(details['id'], request.id) self.assertEqual(details['organization'], org.id) self.assertEqual(details['user']['id'], applicant.id) self.assertEqual(details['user']['fullname'], applicant.fullname) self.assertEqual(details['user']['avatar'], str(applicant.avatar))
Adjust phrasing of PyPI long_description
#!/usr/bin/env python """setup.py for get_user_headers""" __author__ = "Stephan Sokolow (deitarion/SSokolow)" __license__ = "MIT" import sys if __name__ == '__main__' and 'flake8' not in sys.modules: # FIXME: Why does this segfault flake8 under PyPy? from setuptools import setup setup( name="get_user_headers", version="0.1.1", description="Helper for retrieving identifying headers from the user's" "default browser", long_description="""A self-contained module with no extra dependencies which allows your script to retrieve headers like User-Agent from the user's preferred browser to ensure that requests from your (hopefully well-behaved) script don't stick out like sore thumbs for overzealous site admins to block without cause.""", author="Stephan Sokolow", author_email="http://www.ssokolow.com/ContactMe", # No spam harvesting url="https://github.com/ssokolow/get_user_headers", license="MIT", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords="http web bot spider automation", py_modules=['get_user_headers'], zip_safe=True )
#!/usr/bin/env python """setup.py for get_user_headers""" __author__ = "Stephan Sokolow (deitarion/SSokolow)" __license__ = "MIT" import sys if __name__ == '__main__' and 'flake8' not in sys.modules: # FIXME: Why does this segfault flake8 under PyPy? from setuptools import setup setup( name="get_user_headers", version="0.1.1", description="Helper for retrieving identifying headers from the user's" "default browser", long_description="""A self-contained script which allows your script to retrieve headers like User-Agent from the user's preferred browser to ensure that requests from your (hopefully well-behaved) script don't stick out like sore thumbs for overzealous site admins to block without cause.""", author="Stephan Sokolow", author_email="http://www.ssokolow.com/ContactMe", # No spam harvesting url="https://github.com/ssokolow/get_user_headers", license="MIT", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords="http web bot spider automation", py_modules=['get_user_headers'], zip_safe=True )
Fix library folders not refreshing
import React, { Component } from 'react'; import Icon from 'react-fontawesome'; import classnames from 'classnames'; import AppActions from '../../actions/AppActions'; /* |-------------------------------------------------------------------------- | LibraryFolders |-------------------------------------------------------------------------- */ export default class LibraryFolders extends Component { static propTypes = { folders: React.PropTypes.array, refreshingLibrary: React.PropTypes.bool } constructor(props) { super(props); } render() { const self = this; const foldersListClasses = classnames('musicfolders-list', { empty: this.props.folders.length === 0 }); // TODO (y.solovyov): move to separate method that returns items const removeButtonClasses = classnames('delete-libray-folder', { disabled: self.props.refreshingLibrary }); return ( <ul className={ foldersListClasses }> { this.props.folders.map((folder, i) => { return( <li key={ i }> <Icon name='close' className={ removeButtonClasses } onClick={ self.removeFolder.bind(self, i) } /> { folder } </li> ); }) } </ul> ); } removeFolder(index) { if (!this.props.refreshingLibrary) { AppActions.library.removeFolder(index); } } }
import React, { PureComponent } from 'react'; import Icon from 'react-fontawesome'; import classnames from 'classnames'; import AppActions from '../../actions/AppActions'; /* |-------------------------------------------------------------------------- | LibraryFolders |-------------------------------------------------------------------------- */ export default class LibraryFolders extends PureComponent { static propTypes = { folders: React.PropTypes.array, refreshingLibrary: React.PropTypes.bool } constructor(props) { super(props); } render() { const self = this; const foldersListClasses = classnames('musicfolders-list', { empty: this.props.folders.length === 0 }); // TODO (y.solovyov): move to separate method that returns items const removeButtonClasses = classnames('delete-libray-folder', { disabled: self.props.refreshingLibrary }); return ( <ul className={ foldersListClasses }> { this.props.folders.map((folder, i) => { return( <li key={ i }> <Icon name='close' className={ removeButtonClasses } onClick={ self.removeFolder.bind(self, i) } /> { folder } </li> ); }) } </ul> ); } removeFolder(index) { if (!this.props.refreshingLibrary) { AppActions.library.removeFolder(index); } } }
Make sure that Lexer.lex() returns str instead of bytes
# -*- encoding: utf-8 import pygments import pygments.lexers class Lexer: def __init__(self, app): self.app = app def lex(self, code, lex): """Return tokenified code. Return a list of tuples (scope, word) where word is the word to be printed and scope the scope name representing the context. :param str code: Code to tokenify. :param lex: Lexer to use. :return: """ if lex is None: if not type(code) is str: # if not suitable lexer is found, return decoded code code = code.decode("utf-8") return (("global", code),) words = pygments.lex(code, lex) scopes = [] for word in words: token = word[0] scope = "global" if token in pygments.token.Keyword: scope = "keyword" elif token == pygments.token.Comment: scope = "comment" elif token in pygments.token.Literal.String: scope = "string" elif token in pygments.token.Literal.Number: scope = "constant.numeric" elif token == pygments.token.Name.Function: scope = "entity.name.function" elif token == pygments.token.Name.Class: scope = "entity.name.class" elif token == pygments.token.Operator: scope = "keyword" elif token == pygments.token.Name.Builtin.Pseudo: scope = "constant.language" scopes.append((scope, word[1])) return scopes
# -*- encoding: utf-8 import pygments import pygments.lexers class Lexer: def __init__(self, app): self.app = app def lex(self, code, lex): """Return tokenified code. Return a list of tuples (scope, word) where word is the word to be printed and scope the scope name representing the context. :param str code: Code to tokenify. :param lex: Lexer to use. :return: """ if lex is None: return (("global", code),) words = pygments.lex(code, lex) scopes = [] for word in words: token = word[0] scope = "global" if token in pygments.token.Keyword: scope = "keyword" elif token == pygments.token.Comment: scope = "comment" elif token in pygments.token.Literal.String: scope = "string" elif token in pygments.token.Literal.Number: scope = "constant.numeric" elif token == pygments.token.Name.Function: scope = "entity.name.function" elif token == pygments.token.Name.Class: scope = "entity.name.class" elif token == pygments.token.Operator: scope = "keyword" elif token == pygments.token.Name.Builtin.Pseudo: scope = "constant.language" scopes.append((scope, word[1])) return scopes