text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Check PIN deactivated status when checking for card operationality
/**************************************************************************** * Copyright (C) 2017-2018 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH (info@ecsec.de) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.gui.android.eac.types; /** * * @author Tobias Wich */ public enum PinStatus { RC3, RC2, CAN, BLOCKED, DEACTIVATED; public boolean isBlocked() { return BLOCKED == this; } public boolean isOperational() { return ! isBlocked() && DEACTIVATED != this; } public boolean needsCan() { return CAN == this; } }
/**************************************************************************** * Copyright (C) 2017-2018 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH (info@ecsec.de) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.gui.android.eac.types; /** * * @author Tobias Wich */ public enum PinStatus { RC3, RC2, CAN, BLOCKED, DEACTIVATED; public boolean isBlocked() { return BLOCKED == this; } public boolean isOperational() { return ! isBlocked(); } public boolean needsCan() { return CAN == this; } }
Fix error message so they display something useful
import { bindable } from 'aurelia-framework'; export class UiErrorMessageCustomElement { @bindable errorSource; errorSourceChanged() { if (this.errorSource) { this.error = {}; this.error.status = this.errorSource.status; this.error.statusText = this.errorSource.statusText; if ('bodyUsed' in this.errorSource && this.errorSource.bodyUsed === false) { this.errorSource.json().then(response => { if (response.message) { this.error.message = response.message; } }) } else { if (this.errorSource.body && this.errorSource.body.message) { this.error.message = this.errorSource.body.message; } } } else { this.error = null; } } }
import { bindable } from 'aurelia-framework'; export class UiErrorMessageCustomElement { @bindable errorSource; errorSourceChanged() { if (this.errorSource) { this.error = {}; this.error.status = this.errorSource.status; this.error.statusText = this.errorSource.statusText; if (this.errorSource.bodyUsed && this.errorSource.bodyUsed === false) { this.errorSource.json().then(response => { if (response.message) { this.error.message = response.message; } }) } else { if (this.errorSource.body && this.errorSource.body.message) { this.error.message = this.errorSource.body.message; } } } else { this.error = null; } } }
Remove empty object-ids from table-wrap.
import { extractCaptionTitle, wrapCaptionTitle, expandCaption, expandTitle, expandObjectId, removeEmptyElements, removeChild, addLabel } from './r2tHelpers' export default class ConvertElementCitation { import(dom) { let tableWrap = dom.findAll('table-wrap') tableWrap.forEach(tableWrap => { removeChild(tableWrap, 'label') expandObjectId(tableWrap, 0) extractCaptionTitle(tableWrap, 1) expandTitle(tableWrap, 1) expandCaption(tableWrap, 2) }) } export(dom, {doc}) { let tableWrap = dom.findAll('table-wrap') tableWrap.forEach(tableWrap => { let tableWrapNode = doc.get(tableWrap.id) let label = tableWrapNode.state.label addLabel(tableWrap, label, 1) wrapCaptionTitle(tableWrap) removeEmptyElements(tableWrap, 'object-id') }) } }
import { extractCaptionTitle, wrapCaptionTitle, expandCaption, expandTitle, expandObjectId, removeChild, addLabel } from './r2tHelpers' export default class ConvertElementCitation { import(dom) { let tableWrap = dom.findAll('table-wrap') tableWrap.forEach(tableWrap => { removeChild(tableWrap, 'label') expandObjectId(tableWrap, 0) extractCaptionTitle(tableWrap, 1) expandTitle(tableWrap, 1) expandCaption(tableWrap, 2) }) } export(dom, {doc}) { let tableWrap = dom.findAll('table-wrap') tableWrap.forEach(tableWrap => { let tableWrapNode = doc.get(tableWrap.id) let label = tableWrapNode.state.label addLabel(tableWrap, label, 1) wrapCaptionTitle(tableWrap) }) } }
Update docs router location type to `hash` for netlify
'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { // here you can enable a production-specific feature } return ENV; };
'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { // here you can enable a production-specific feature } return ENV; };
Add redirect to locale after edit
import React, { PropTypes } from 'react'; import { push } from 'react-router-redux'; import { connect } from 'react-redux'; import LocalePairsEditable from './../components/LocalePairsEditable' import Button from './../components/Button' const EditLocalePage = ({pairs, onSubmit}) => { return ( <div> <LocalePairsEditable pairs={pairs} onSubmit={onSubmit}/> </div> ); }; EditLocalePage.propTypes = { pairs: PropTypes.object.isRequired, onSubmit: PropTypes.func.isRequired }; const mapStateToProps = (state) => { return { pairs: {'my key': 'my pair'} }; }; const mapDispatchToProps = (dispatch, ownProps) => { return { onSubmit: (pairs) => { console.log(pairs); dispatch(push(`/projects/${ownProps.params.projectId}/locales/${ownProps.params.localeId}`)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(EditLocalePage);
import React, { PropTypes } from 'react'; import { push } from 'react-router-redux'; import { connect } from 'react-redux'; import LocalePairsEditable from './../components/LocalePairsEditable' import Button from './../components/Button' const EditLocalePage = ({pairs, onSubmit}) => { return ( <div> <LocalePairsEditable pairs={pairs} onSubmit={onSubmit}/> </div> ); }; EditLocalePage.propTypes = { pairs: PropTypes.object.isRequired, onSubmit: PropTypes.func.isRequired }; const mapStateToProps = (state) => { return { pairs: {'my key': 'my pair'} }; }; const mapDispatchToProps = (dispatch, ownProps) => { return { onSubmit: (pairs) => { console.log(pairs) } }; }; export default connect(mapStateToProps, mapDispatchToProps)(EditLocalePage);
Modify toLower() to pass returned result test
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); };
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { return ""; };
Add repo url as prop
import React, { Component } from 'react'; import { List, ListItem, } from 'react-native-elements'; export default class RepoList extends Component { constructor(props) { super(props); } render() { const { navigate } = this.props.navigation; return ( <List> { this.props.list.map((item, i) => ( <ListItem key={i} title={item.name} url={item.url} onPress={() => navigate('RepoView', { reponame: item.name })} /> )) } </List> ); } }
import React, { Component } from 'react'; import { List, ListItem, } from 'react-native-elements'; export default class RepoList extends Component { constructor(props) { super(props); } render() { const { navigate } = this.props.navigation; return ( <List> { this.props.list.map((item, i) => ( <ListItem key={i} title={item.name} onPress={() => navigate('RepoView', { reponame: item.name, url: item.url })} /> )) } </List> ); } }
Add name to remote config.
var _ = require('lodash'); var wd = require('wd'); var TestCase = require('./testCase'); var Driver = require('../driver'); var WDTestCase = TestCase.extend({ constructor: function () { TestCase.apply(this, arguments); }, // timeout for raw wd methods (ms) // raw methods are the _ ones. timeout: 10000, run: function (remote, desired, done) { var browser = this.createBrowser(remote, desired, done); this.doRun(browser, remote, desired); }, createBrowser: function (remote, desired, done) { desired = _.defaults({name: this.name}, desired); var browser = new Driver(remote, desired, done); return browser; }, doRun: function (browser, remote, desired) { console.log('please define steps'); } }); module.exports = WDTestCase;
var wd = require('wd'); var TestCase = require('./testCase'); var Driver = require('../driver'); var WDTestCase = TestCase.extend({ constructor: function () { TestCase.apply(this, arguments); }, // timeout for raw wd methods (ms) // raw methods are the _ ones. timeout: 10000, run: function (remote, desired, done) { var browser = this.createBrowser(remote, desired, done); this.doRun(browser, remote, desired); }, createBrowser: function (remote, desired, done) { var browser = new Driver(remote, desired, done); return browser; }, doRun: function (browser, remote, desired) { console.log('please define steps'); } }); module.exports = WDTestCase;
Allow dev env for remote
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Component\Debug\Debug; use Symfony\Component\HttpFoundation\Request; /* * Sylius front controller. * Dev environment. */ // if (!in_array(@$_SERVER['REMOTE_ADDR'], array( // '127.0.0.1', // '172.33.33.1', // '::1', // '10.0.0.1' // ))) { // header('HTTP/1.0 403 Forbidden'); // exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); // } require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; // Initialize kernel and run the application. $kernel = new AppKernel('dev', true); $request = Request::createFromGlobals(); Request::enableHttpMethodParameterOverride(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Component\Debug\Debug; use Symfony\Component\HttpFoundation\Request; /* * Sylius front controller. * Dev environment. */ if (!in_array(@$_SERVER['REMOTE_ADDR'], array( '127.0.0.1', '172.33.33.1', '::1', '10.0.0.1' ))) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; // Initialize kernel and run the application. $kernel = new AppKernel('dev', true); $request = Request::createFromGlobals(); Request::enableHttpMethodParameterOverride(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Hide login button for logged in users.
@extends('layouts.app') @section('content') @include('includes.sideNav') <section class="home"> <div class="home--logo"> @include('includes.trio-logo') </div> <div> <p class="center-block text-center home--info"> Trios is a simple exercise to test your English skills.<br> You should put in a single word that fits all three sentences.<br> Have fun! </p> <a href="{{ url('/solve') }}" class="btn btn-big btn-success btn--home text-uppercase">Play</a> @if(!Auth::check()) <a href="{{ url('/login') }}" class="btn btn-big btn--home btn--login text-uppercase">Login</a> @endif </div> </section> @endsection
@extends('layouts.app') @section('content') @include('includes.sideNav') <section class="home"> <div class="home--logo"> @include('includes.trio-logo') </div> <div> <p class="center-block text-center home--info"> Trios is a simple exercise to test your English skills.<br> You should put in a single word that fits all three sentences.<br> Have fun! </p> <a href="{{ url('/solve') }}" class="btn btn-big btn-success btn--home text-uppercase">Play</a> <a href="{{ url('/login') }}" class="btn btn-big btn--home btn--login text-uppercase">Login</a> </div> </section> @endsection
Add circuit breaker middle to revserse proxy
package server import ( "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/roundrobin" "github.com/vulcand/oxy/stream" "github.com/vulcand/oxy/cbreaker" "net/http" "net/url" ) type ReverseProxy struct { stream *stream.Streamer } func NewReverseProxy(backends []string) *ReverseProxy { fwd, _ := forward.New() cb, _ := cbreaker.New(fwd, `NetworkErrorRatio() > 0.5`) lb, _ := roundrobin.New(cb) for _, backend := range backends { target, _ := url.Parse(backend) lb.UpsertServer(target) } stream, _ := stream.New(lb, stream.Retry(`(IsNetworkError() || ResponseCode() >= 500) && Attempts() < 2`)) return &ReverseProxy{stream: stream} } func (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { rp.stream.ServeHTTP(w, r) }
package server import ( "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/roundrobin" "github.com/vulcand/oxy/stream" "net/http" "net/url" ) type ReverseProxy struct { stream *stream.Streamer } func NewReverseProxy(backends []string) *ReverseProxy { fwd, _ := forward.New() lb, _ := roundrobin.New(fwd) for _, backend := range backends { target, _ := url.Parse(backend) lb.UpsertServer(target) } stream, _ := stream.New(lb, stream.Retry(`(IsNetworkError() || ResponseCode() >= 500) && Attempts() < 2`)) return &ReverseProxy{stream: stream} } func (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { rp.stream.ServeHTTP(w, r) }
Add the function to get the value of object, dict, list, or tuple.
# encoding: utf-8 ### Attribute Wrapper class AttrWrapper(object): attrs = [] def __setattr__(self, name, value): if name not in self.attrs: raise AttributeError("'%s' is not supported" % name) object.__setattr__(self, name, value) def __repr__(self): attrs = [] template = "%s=%s" for name in self.attrs: try: attrs.append(template % (name, getattr(self, name))) except AttributeError: pass return "%s(%s)" % (self.__class__.__name__, ", ".join(attrs)) def val(obj, name, default=None): if hasattr(obj, name): return obj.name elif name in obj: return obj[name] elif isinstance(obj, (list, tuple)) and isinstance(name, int): try: return obj[name] except Exception: return default else: return default
# encoding: utf-8 ### Attribute Wrapper class AttrWrapper(object): attrs = [] def __setattr__(self, name, value): if name not in self.attrs: raise AttributeError("'%s' is not supported" % name) object.__setattr__(self, name, value) def __repr__(self): attrs = [] template = "%s=%s" for name in self.attrs: try: attrs.append(template % (name, getattr(self, name))) except AttributeError: pass return "%s(%s)" % (self.__class__.__name__, ", ".join(attrs))
Add typing to java. It's not right yet though :)
from typing import Callable, Dict from genes.apt import commands as apt from genes.brew import commands as brew from genes.debconf import commands as debconf from genes.debian.traits import is_debian from genes.mac.traits import is_osx from genes.ubuntu.traits import is_ubuntu def main(config: Callable[[], Dict]): if is_debian() or is_ubuntu(): if config.is_oracle(): # FIXME: debian needs ppa software apt.add_ppa('webupd8team/java') apt.update() debconf.set_selections(config.version + '-installer', 'shared/accepted-oracle-license-v1-1', 'select', 'true') apt.install(config.version + '-installer') else: apt.update() apt.install(config.version) elif is_osx(): brew.update() brew.cask_install('java') else: # FIXME: print failure, handle windows pass
from genes.apt import commands as apt from genes.brew import commands as brew from genes.debconf import commands as debconf from genes.debian.traits import is_debian from genes.mac.traits import is_osx from genes.ubuntu.traits import is_ubuntu def main(config): if is_debian() or is_ubuntu(): if config.is_oracle(): # FIXME: debian needs ppa software apt.add_ppa('webupd8team/java') apt.update() debconf.set_selections(config.version + '-installer', 'shared/accepted-oracle-license-v1-1', 'select', 'true') apt.install(config.version + '-installer') else: apt.update() apt.install(config.version) elif is_osx(): brew.update() brew.cask_install('java') else: # FIXME: print failure, handle windows pass
Correct an issue with epoch timestamps in Conduit Summary: Fixes T11375. Some validation code was mishandling raw epoch timestamps. For numeric values larger than 29999999 (e.g., 2999-12-25, christmas 2999), assume the value is a timestamp. Test Plan: Used `maniphest.search` to query for `modifiedStart`, got a better result set and saw the `dateModified` constraint in the query. Reviewers: chad Reviewed By: chad Maniphest Tasks: T11375 Differential Revision: https://secure.phabricator.com/D16326
<?php final class PhabricatorSearchDateField extends PhabricatorSearchField { protected function newControl() { return new AphrontFormTextControl(); } protected function getValueFromRequest(AphrontRequest $request, $key) { return $request->getStr($key); } public function getValueForQuery($value) { return $this->parseDateTime($value); } protected function validateControlValue($value) { if (!strlen($value)) { return; } $epoch = $this->parseDateTime($value); if ($epoch) { return; } $this->addError( pht('Invalid'), pht('Date value for "%s" can not be parsed.', $this->getLabel())); } protected function parseDateTime($value) { if (!strlen($value)) { return null; } // If this appears to be an epoch timestamp, just return it unmodified. // This assumes values like "2016" or "20160101" are "Ymd". if (is_int($value) || ctype_digit($value)) { if ((int)$value > 30000000) { return (int)$value; } } return PhabricatorTime::parseLocalTime($value, $this->getViewer()); } protected function newConduitParameterType() { return new ConduitEpochParameterType(); } }
<?php final class PhabricatorSearchDateField extends PhabricatorSearchField { protected function newControl() { return new AphrontFormTextControl(); } protected function getValueFromRequest(AphrontRequest $request, $key) { return $request->getStr($key); } public function getValueForQuery($value) { return $this->parseDateTime($value); } protected function validateControlValue($value) { if (!strlen($value)) { return; } $epoch = $this->parseDateTime($value); if ($epoch) { return; } $this->addError( pht('Invalid'), pht('Date value for "%s" can not be parsed.', $this->getLabel())); } protected function parseDateTime($value) { if (!strlen($value)) { return null; } return PhabricatorTime::parseLocalTime($value, $this->getViewer()); } protected function newConduitParameterType() { return new ConduitEpochParameterType(); } }
Add some const in Http helper
<?php /** * Class RebillyHttpStatusCode * Helper class pre-defined Http response code */ class RebillyHttpStatusCode { /** * Http response code */ const STATUS_OK = 200; const STATUS_CREATED = 201; const STATUS_ACCEPTED = 202; const STATUS_NO_CONTENT = 204; const REDIRECT_SEE_OTHER = 303; const ERROR_BAD_REQUEST = 400; const ERROR_UNAUTHORIZED = 401; const ERROR_REQUEST_FAILED = 402; const ERROR_FORBIDDEN = 403; const ERROR_NOT_FOUND = 404; const ERROR_INVALID_REQUEST = 405; const ERROR_REQUEST_TIMEOUT = 408; const ERROR_PRECONDITION_FAILED = 412; const ERROR_UNPROCESSABLE_ENTITY = 422; const ERROR_INTERNAL_500 = 500; const ERROR_INTERNAL_502 = 502; const ERROR_INTERNAL_503 = 503; const ERROR_INTERNAL_504 = 504; }
<?php /** * Class RebillyHttpStatusCode * Helper class pre-defined Http response code */ class RebillyHttpStatusCode { /** * Http response code */ const STATUS_OK = 200; const STATUS_CREATED = 201; const STATUS_NO_CONTENT = 204; const ERROR_BAD_REQUEST = 400; const ERROR_UNAUTHORIZED = 401; const ERROR_REQUEST_FAILED = 402; const ERROR_FORBIDDEN = 403; const ERROR_NOT_FOUND = 404; const ERROR_INVALID_REQUEST = 405; const ERROR_REQUEST_TIMEOUT = 408; const ERROR_PRECONDITION_FAILED = 412; const ERROR_UNPROCESSABLE_ENTITY = 422; const ERROR_INTERNAL_500 = 500; const ERROR_INTERNAL_502 = 502; const ERROR_INTERNAL_503 = 503; const ERROR_INTERNAL_504 = 504; }
Add trailing space to command to stay consistent
<?php namespace Robo\Task\Development; use Robo\Task\Base\Exec; /** * Runs PHP server and stops it when task finishes. * * ``` php * <?php * // run server in /public directory * $this->taskServer(8000) * ->dir('public') * ->run(); * * // run with IP 0.0.0.0 * $this->taskServer(8000) * ->host('0.0.0.0') * ->run(); * * // execute server in background * $this->taskServer(8000) * ->background() * ->run(); * ?> * ``` */ class PhpServer extends Exec { protected $port; protected $host = '127.0.0.1'; protected $command = 'php -S %s:%d '; public function __construct($port) { $this->port = $port; if (strtolower(PHP_OS) === 'linux') { $this->command = 'exec php -S %s:%d '; } } public function host($host) { $this->host = $host; return $this; } public function dir($path) { $this->command .= "-t $path"; return $this; } public function getCommand() { return sprintf($this->command . $this->arguments, $this->host, $this->port); } }
<?php namespace Robo\Task\Development; use Robo\Task\Base\Exec; /** * Runs PHP server and stops it when task finishes. * * ``` php * <?php * // run server in /public directory * $this->taskServer(8000) * ->dir('public') * ->run(); * * // run with IP 0.0.0.0 * $this->taskServer(8000) * ->host('0.0.0.0') * ->run(); * * // execute server in background * $this->taskServer(8000) * ->background() * ->run(); * ?> * ``` */ class PhpServer extends Exec { protected $port; protected $host = '127.0.0.1'; protected $command = 'php -S %s:%d '; public function __construct($port) { $this->port = $port; if (strtolower(PHP_OS) === 'linux') { $this->command = 'exec php -S %s:%d'; } } public function host($host) { $this->host = $host; return $this; } public function dir($path) { $this->command .= "-t $path"; return $this; } public function getCommand() { return sprintf($this->command . $this->arguments, $this->host, $this->port); } }
Set labelInValues for site ff
<?php class CM_FormField_Site extends CM_FormField_Set_Select { /** * @param int $userInput * @param CM_Response_Abstract $response * @return CM_Site_Abstract */ public function validate($userInput, CM_Response_Abstract $response) { $userInput = parent::validate($userInput, $response); return CM_Site_Abstract::factory($userInput); } public function _setup() { $valuesSet = array(); foreach (CM_Site_Abstract::getAll() as $site) { $valuesSet[$site->getType()] = $site->getName(); } $this->_params->set('values', $valuesSet); $this->_params->set('labelsInValues', true); parent::_setup(); } }
<?php class CM_FormField_Site extends CM_FormField_Set_Select { /** * @param int $userInput * @param CM_Response_Abstract $response * @return CM_Site_Abstract */ public function validate($userInput, CM_Response_Abstract $response) { $userInput = parent::validate($userInput, $response); return CM_Site_Abstract::factory($userInput); } public function _setup() { $valuesSet = array(); foreach (CM_Site_Abstract::getAll() as $site) { $valuesSet[$site->getType()] = $site->getName(); } $this->_params->set('values', $valuesSet); parent::_setup(); } }
Change word splitting method to exclude junk characters.
'use strict'; var _ = require('lodash'); var pokeapi = require('./pokeapi'); var twitter = require('./twitter'); var stream = twitter.client.stream('user', { with: 'user' }); stream.on('tweet', function(tweet) { var user = tweet.user.screen_name; // Don't talk to yourself, silly robot if (user === 'tweetdexbot') { return; } extractPokemon(tweet.text) .then(function(pokemon) { return pokeapi.getPokedexEntry(pokemon); }) .then(function(entry) { return twitter.reply(tweet.id_str, entry, user); }); }); // Extract a Pokemon name to look up from the body of a tweet. function extractPokemon(text) { return pokeapi.getPokemonList() .then(function(list) { var words = text.match(/(@?\b\S+\b)/g); var pokemon = _(words) .reject(function(word) { return _.startsWith(word, '@'); }) .map(function(word) { return word.toLowerCase(); }) .find(function(word) { return _.some(list, { 'name': word }); }); return pokemon; }); }
'use strict'; var _ = require('lodash'); var pokeapi = require('./pokeapi'); var twitter = require('./twitter'); var stream = twitter.client.stream('user', { with: 'user' }); stream.on('tweet', function(tweet) { var user = tweet.user.screen_name; // Don't talk to yourself, silly robot if (user === 'tweetdexbot') { return; } extractPokemon(tweet.text) .then(function(pokemon) { return pokeapi.getPokedexEntry(pokemon); }) .then(function(entry) { return twitter.reply(tweet.id_str, entry, user); }); }); // Extract a Pokemon name to look up from the body of a tweet. function extractPokemon(text) { return pokeapi.getPokemonList() .then(function(list) { var pokemon = _(text.split(' ')) .reject(function(word) { return _.startsWith(word, '@'); }) .map(function(word) { return word.toLowerCase(); }) .find(function(word) { return _.some(list, { 'name': word }); }); return pokemon; }); }
Fix literal pattern matching creation to correctly convert integer literals in the specification which are encoded as strings.
package org.metaborg.meta.lang.dynsem.interpreter.nodes.matching; import org.metaborg.meta.lang.dynsem.interpreter.utils.SourceSectionUtil; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.terms.util.NotImplementedException; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.source.SourceSection; public abstract class LiteralMatchPattern extends MatchPattern { public LiteralMatchPattern(SourceSection source) { super(source); } public static LiteralMatchPattern create(IStrategoAppl t, FrameDescriptor fd) { SourceSection source = SourceSectionUtil.fromStrategoTerm(t); if (Tools.hasConstructor(t, "True", 0)) { return new TrueLiteralTermMatchPattern(source); } if (Tools.hasConstructor(t, "False", 0)) { return new FalseLiteralTermMatchPattern(source); } if (Tools.hasConstructor(t, "Int", 1)) { return new IntLiteralTermMatchPattern(Integer.parseInt(Tools.stringAt(t, 0).stringValue()), source); } if (Tools.hasConstructor(t, "String", 1)) { return new StringLiteralTermMatchPattern(Tools.stringAt(t, 0).stringValue(), source); } throw new NotImplementedException("Unsupported literal: " + t); } }
package org.metaborg.meta.lang.dynsem.interpreter.nodes.matching; import org.metaborg.meta.lang.dynsem.interpreter.utils.SourceSectionUtil; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.terms.util.NotImplementedException; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.source.SourceSection; public abstract class LiteralMatchPattern extends MatchPattern { public LiteralMatchPattern(SourceSection source) { super(source); } public static LiteralMatchPattern create(IStrategoAppl t, FrameDescriptor fd) { SourceSection source = SourceSectionUtil.fromStrategoTerm(t); if(Tools.hasConstructor(t, "True",0)){ return new TrueLiteralTermMatchPattern(source); } if(Tools.hasConstructor(t, "False",0)){ return new FalseLiteralTermMatchPattern(source); } if(Tools.hasConstructor(t, "Int", 1)){ return new IntLiteralTermMatchPattern(Tools.intAt(t, 0).intValue(), source); } if(Tools.hasConstructor(t, "String", 1)){ return new StringLiteralTermMatchPattern(Tools.stringAt(t, 0).stringValue(), source); } throw new NotImplementedException("Unsupported literal: " + t); } }
Deploy smart contracts v0.0.6 to Ropsten
# -*- coding: utf-8 -*- UINT64_MAX = 2 ** 64 - 1 UINT64_MIN = 0 INT64_MAX = 2 ** 63 - 1 INT64_MIN = -(2 ** 63) UINT256_MAX = 2 ** 256 - 1 # Deployed to Ropsten revival on 2017-09-03 from commit f4f8dcbe791b7be8bc15475f79ad9cbbfe15435b ROPSTEN_REGISTRY_ADDRESS = 'ce30a13daa47c0f35631e5ed750e39c12172f325' ROPSTEN_DISCOVERY_ADDRESS = 'aecb64f87c7fa12d983e541eabb0064fc9d87c4f' DISCOVERY_REGISTRATION_GAS = 500000 MINUTE_SEC = 60 MINUTE_MS = 60 * 1000 NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6 # TODO: add this as an attribute of the transport class UDP_MAX_MESSAGE_SIZE = 1200
# -*- coding: utf-8 -*- UINT64_MAX = 2 ** 64 - 1 UINT64_MIN = 0 INT64_MAX = 2 ** 63 - 1 INT64_MIN = -(2 ** 63) UINT256_MAX = 2 ** 256 - 1 # Deployed to Ropsten revival on 2017-08-18 from commit 01554102f0a52fc5aec3f41dc46d53017108b400 ROPSTEN_REGISTRY_ADDRESS = '7205a22f083a12d1b22ee89d7e892d23b1f1438a' ROPSTEN_DISCOVERY_ADDRESS = '1ed4eab14a09ba2f334d9ed579a5ee4ae57aec45' DISCOVERY_REGISTRATION_GAS = 500000 MINUTE_SEC = 60 MINUTE_MS = 60 * 1000 NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6 # TODO: add this as an attribute of the transport class UDP_MAX_MESSAGE_SIZE = 1200
Handle HTTPS Git clone URLs
const { execSync } = require('child_process'); const { readFileSync } = require('fs'); const { resolve } = require('path'); function getGitCommit() { return execSync('git show -s --format=%h') .toString() .trim(); } function getGitHubURL() { // TODO potentially replace this with an fb.me URL (assuming it can forward the query params) const url = execSync('git remote get-url origin') .toString() .trim(); if (url.startsWith('https://')) { return url.replace('.git', ''); } else { return url .replace(':', '/') .replace('git@', 'https://') .replace('.git', ''); } } function getVersionString() { const packageVersion = JSON.parse( readFileSync(resolve(__dirname, '../package.json')) ).version; const commit = getGitCommit(); return `${packageVersion}-${commit}`; } module.exports = { getGitCommit, getGitHubURL, getVersionString };
const { execSync } = require('child_process'); const { readFileSync } = require('fs'); const { resolve } = require('path'); function getGitCommit() { return execSync('git show -s --format=%h') .toString() .trim(); } function getGitHubURL() { // TODO potentially replac this with an fb.me URL (if it can forward the query params) return execSync('git remote get-url origin') .toString() .trim() .replace(':', '/') .replace('git@', 'https://') .replace('.git', ''); } function getVersionString() { const packageVersion = JSON.parse( readFileSync(resolve(__dirname, '../package.json')) ).version; const commit = getGitCommit(); return `${packageVersion}-${commit}`; } module.exports = { getGitCommit, getGitHubURL, getVersionString };
Fix compatibility with postcss-reporter after API changes
'use strict' module.exports = function(gulp, plugins, config, name, file) { // eslint-disable-line func-names const theme = config.themes[name] const srcBase = plugins.path.join(config.projectPath, theme.dest) const stylelintConfig = require('../helper/config-loader')('stylelint.yml', plugins, config) return gulp.src(file || plugins.globby.sync(srcBase + '/**/*.css')) .pipe(plugins.if( !plugins.util.env.ci, plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }) )) .pipe(plugins.postcss([ plugins.stylelint({ config: stylelintConfig }), plugins.reporter({ clearReportedMessages: true, throwError: plugins.util.env.ci || false }) ])) .pipe(plugins.logger({ display : 'name', beforeEach: 'Theme: ' + name + ' ' + 'File: ', afterEach : ' - CSS Lint finished.' })) }
'use strict' module.exports = function(gulp, plugins, config, name, file) { // eslint-disable-line func-names const theme = config.themes[name] const srcBase = plugins.path.join(config.projectPath, theme.dest) const stylelintConfig = require('../helper/config-loader')('stylelint.yml', plugins, config) return gulp.src(file || plugins.globby.sync(srcBase + '/**/*.css')) .pipe(plugins.if( !plugins.util.env.ci, plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }) )) .pipe(plugins.postcss([ plugins.stylelint({ config: stylelintConfig }), plugins.reporter({ clearMessages: true, throwError: plugins.util.env.ci || false }) ])) .pipe(plugins.logger({ display : 'name', beforeEach: 'Theme: ' + name + ' ' + 'File: ', afterEach : ' - CSS Lint finished.' })) }
Add to one more file.
/* @flow */ var InfiniteComputer = require('./infinite_computer.js'); class ConstantInfiniteComputer extends InfiniteComputer { getTotalScrollableHeight()/* : number */ { return this.heightData * this.numberOfChildren; } getDisplayIndexStart(windowTop/* : number */)/* : number */ { return Math.floor(windowTop / this.heightData); } getDisplayIndexEnd(windowBottom/* : number */)/* : number */ { var nonZeroIndex = Math.ceil(windowBottom / this.heightData); if (nonZeroIndex > 0) { return nonZeroIndex - 1; } return nonZeroIndex; } getTopSpacerHeight(displayIndexStart/* : number */)/* : number */ { return displayIndexStart * this.heightData; } getBottomSpacerHeight(displayIndexEnd/* : number */)/* : number */ { var nonZeroIndex = displayIndexEnd + 1; return Math.max(0, (this.numberOfChildren - nonZeroIndex) * this.heightData); } } module.exports = ConstantInfiniteComputer;
var InfiniteComputer = require('./infinite_computer.js'); class ConstantInfiniteComputer extends InfiniteComputer { getTotalScrollableHeight(): number { return this.heightData * this.numberOfChildren; } getDisplayIndexStart(windowTop: number): number { return Math.floor(windowTop / this.heightData); } getDisplayIndexEnd(windowBottom: number): number { var nonZeroIndex = Math.ceil(windowBottom / this.heightData); if (nonZeroIndex > 0) { return nonZeroIndex - 1; } return nonZeroIndex; } getTopSpacerHeight(displayIndexStart: number): number { return displayIndexStart * this.heightData; } getBottomSpacerHeight(displayIndexEnd: number): number { var nonZeroIndex = displayIndexEnd + 1; return Math.max(0, (this.numberOfChildren - nonZeroIndex) * this.heightData); } } module.exports = ConstantInfiniteComputer;
Update to other app credentials
exports.register = function (plugin, options, next) { plugin.auth.strategy('github', 'bell', { provider: 'github', password: 'password', isSecure: false, clientId: '35c8883e92b62df9be91', clientSecret: 'a4ab9f45c816c1e1068e0ba6ed664a5e7c844b73' }); // Remove later plugin.route({ method: '*', path: '/auth/callback', config: { auth: 'github', handler: function (request, reply) { reply(request.auth.credentials); } } }); next(); }; exports.register.attributes = { name: 'authentication', version: require('../../package.json').version };
exports.register = function (plugin, options, next) { plugin.auth.strategy('github', 'bell', { provider: 'github', password: 'password', isSecure: false, clientId: 'bdede9fad8112d781b5d', clientSecret: '22cd018f20db6c6ce353acebf70a4c47bdd57524' }); // Remove later plugin.route({ method: '*', path: '/login', config: { auth: 'github', handler: function (request, reply) { reply(request.auth.credentials); } } }); next(); }; exports.register.attributes = { name: 'authentication', version: require('../../package.json').version };
Revert "added entity lists(libgdx arrays) for fishes and sharks" This reverts commit 80c76c829d63f67faa83ef7c2aaa8a601ce461ef.
package com.stewesho.wator; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.OrthographicCamera; public class Main extends ApplicationAdapter { SpriteBatch batch; OrthographicCamera cam; @Override public void create () { batch = new SpriteBatch(); cam = new OrthographicCamera(50, 50); } @Override public void render () { Gdx.gl.glClearColor(0.250f, 0.250f, 0.300f, 1.000f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setProjectionMatrix(cam.combined); batch.begin(); // batch.draw(map.render(), -map.getWidth()/2, -map.getHeight()/2); batch.end(); } @Override public void dispose () { batch.dispose(); // map.disposeResources(); } }
package com.stewesho.wator; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.OrthographicCamera; public class Main extends ApplicationAdapter { SpriteBatch batch; OrthographicCamera cam; WorldManager world; @Override public void create () { batch = new SpriteBatch(); cam = new OrthographicCamera(50, 50); world = new WorldManager(25, 25); } @Override public void render () { Gdx.gl.glClearColor(0.250f, 0.250f, 0.300f, 1.000f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setProjectionMatrix(cam.combined); batch.begin(); batch.draw(world.run(), -world.getMap.getWidth()/2, -world.getMap.getHeight()/2); batch.end(); } @Override public void dispose () { batch.dispose(); // map.disposeResources(); } }
:art: Make server compatible with latest Client
"use strict" let EventEmitter = require('events').EventEmitter let WS = require('ws') let Client = require('./Client') class Server extends EventEmitter{ constructor(Options){ super() this.Server = WS.createServer(Options) this.Server.on('connection', this.gotConnection.bind(this)) this.Connections = new WeakMap // this.Server.clients <--> this.Connections } gotConnection(Connection){ let ClientConnection = new Client(Connection, this) this.Connections.set(Connection, ClientConnection) this.emit('connection', ClientConnection) } onConnection(Callback){ this.on('connection', Callback) return this } Broadcast(Type, Message){ for(let Connection of this.Server.clients){ let ClientConnection = this.Connections.get(Connection) if(ClientConnection) { // Of course it's not undefined but still ClientConnection.request(Type, Message) } } } } module.exports = Server
"use strict" let EventEmitter = require('events').EventEmitter let WS = require('ws') let Client = require('./Client') class Server extends EventEmitter{ constructor(Options){ super() this.Server = WS.createServer(Options) this.Server.on('connection', this._onConnection.bind(this)) this.Connections = new WeakMap // this.Server.clients <--> this.Connections } _onConnection(Connection){ let ClientConnection = new Client(Connection, this) this.Connections.set(Connection, ClientConnection) this.emit('connection', ClientConnection) } onConnection(Callback){ this.on('connection', Callback) return this } Broadcast(Type, Message){ for(let Connection of this.Server.clients){ let ClientConnection = this.Connections.get(Connection) if(ClientConnection) { // Of course it's not undefined but still ClientConnection.Send(Type, Message) } } } } module.exports = Server
Set specific session expiration of 14d
<?php class Denkmal_FormAction_Login_Process extends CM_FormAction_Abstract { protected function _getRequiredFields() { return array('email', 'password'); } protected function _checkData(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) { } protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) { /** @var Denkmal_Site $site */ $site = $response->getSite(); try { $user = Denkmal_Model_User::authenticate($params->getString('email'), $params->getString('password')); } catch (CM_Exception_AuthFailed $e) { $response->addError($e->getMessagePublic($response->getRender()), 'password'); return; } $response->getRequest()->getSession()->setUser($user); $response->getRequest()->getSession()->setLifetime(86400 * 14); $response->addMessage($response->getRender()->getTranslation('Erfolgreich angemeldet. Bitte warten...')); $response->redirect($site->getLoginPage(), null, true); } }
<?php class Denkmal_FormAction_Login_Process extends CM_FormAction_Abstract { protected function _getRequiredFields() { return array('email', 'password'); } protected function _checkData(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) { } protected function _process(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) { /** @var Denkmal_Site $site */ $site = $response->getSite(); try { $user = Denkmal_Model_User::authenticate($params->getString('email'), $params->getString('password')); } catch (CM_Exception_AuthFailed $e) { $response->addError($e->getMessagePublic($response->getRender()), 'password'); return; } $response->getRequest()->getSession()->setUser($user); $response->addMessage($response->getRender()->getTranslation('Erfolgreich angemeldet. Bitte warten...')); $response->redirect($site->getLoginPage(), null, true); } }
Fix append contents js again
/** * Load all h2, h3, h4, h5 and h6 tags as contents. */ $('.append-contents').each(function() { let html = '<ul class="list-unstyled contents">', level = 2; for(let h of $('h2, h3, h4, h5, h6').not('.append-contents')) { let newLevel = parseInt(h.tagName.charAt(1)); if (newLevel > level) { html += `<ul>`; } else if (newLevel < level) { html += `</li></ul>`; } else { html += `</li>`; } level = newLevel; html = `${html}<li><a href="#${h.innerHTML.replace(/ /g,'')}">${h.innerHTML}</a>`; h.setAttribute('id', h.innerHTML.replace(/ /g,'')); } while (level > 2) { html += `</ul>`; level -= 1; } $(this).after(html) });
/** * Load all h2, h3, h4, h5 and h6 tags as contents. */ $('.append-contents').each(function() { let html = '<ul class="list-unstyled contents">', level = 2; for(let h of $('h2, h3, h4, h5, h6').not('.append-contents')) { let newLevel = parseInt(h.tagName.charAt(1)); if (newLevel > level) { html += `<ul>`; } else if (newLevel < level) { html += `</li></ul>`; } else { html += `</li>`; } level = newLevel; html = `${html}<li><a href="${h.getAttribute('id')}" id="${h.innerHTML.trim()}">${h.innerHTML}</a>`; h.setAttribute('id', this.innerHTML.trim()); } while (level > 2) { html += `</ul>`; level -= 1; } $(this).after(html) });
Add eo to installed packages.
from setuptools import setup from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) setup( cmdclass = { 'install' : install }, name = 'hydra', version = '0.1', author = 'tatsy', author_email = 'tatsy.mail@gmail.com', url = 'https://github.com/tatsy/hydra.git', description = 'Python HDR image processing library.', license = 'MIT', classifiers = [ 'Development Status :: 1 - Planning', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ], packages = [ 'hydra', 'hydra.core', 'hydra.eo', 'hydra.filters', 'hydra.gen', 'hydra.io', 'hydra.tonemap' ] )
from setuptools import setup from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) setup( cmdclass = { 'install' : install }, name = 'hydra', version = '0.1', author = 'tatsy', author_email = 'tatsy.mail@gmail.com', url = 'https://github.com/tatsy/hydra.git', description = 'Python HDR image processing library.', license = 'MIT', classifiers = [ 'Development Status :: 1 - Planning', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ], packages = [ 'hydra', 'hydra.core', 'hydra.gen', 'hydra.io', 'hydra.filters', 'hydra.tonemap' ] )
Add shipping address request to example facade
<?php use Aquatic\AuthorizeNet\Contract\Address; use Aquatic\AuthorizeNet\CIM\CreateCustomerProfile; use Aquatic\AuthorizeNet\CIM\CreateCustomerShippingAddress; // Facade for AuthorizeNet requests class AuthorizeNet { public static function createCustomerProfile(string $customer_id, string $email, string $description = null) { return (new CreateCustomerProfile($customer_id, $email, $description)) ->setCredentials(getenv('AUTHORIZENET_ID'), getenv('AUTHORIZENET_KEY')) ->sendRequest() ->parseResponse() ->getResponse(); } public static function yerACustomerProfileHarry(string $customer_id, string $email) { return (new \My\CreateAProfile($customer_id, $email))->getResponse(); } public static function createCustomerShippingAddress(int $customer_id, Address $address) { return (new CreateCustomerShippingAddress($customer_id, $address)) ->setCredentials(getenv('AUTHORIZENET_ID'), getenv('AUTHORIZENET_KEY')) ->sendRequest() ->parseResponse(); } }
<?php use Aquatic\AuthorizeNet\CIM\CreateCustomerProfile; // Facade for AuthorizeNet requests class AuthorizeNet { public static function createCustomerProfile(string $customer_id, string $email, string $description = null) { return (new CreateCustomerProfile($customer_id, $email, $description)) ->setCredentials(getenv('AUTHORIZENET_ID'), getenv('AUTHORIZENET_KEY')) ->sendRequest() ->parseResponse() ->getResponse(); } public static function yerACustomerProfileHarry(string $customer_id, string $email) { return (new \My\CreateAProfile($customer_id, $email))->getResponse(); } } // Call from your application to receive parsed response // AuthorizeNet::createCustomerProfile(123, 'herp@derpingt.on', 'guest'); // Call from your application to receive your custom parsed response // AuthorizeNet::yerACustomerProfileHarry(321, 'harry@hogwar.ts');
Fix typo in return during exception while loading page
import selenium.webdriver as webdriver import bs4 as bs import pyisbn import re def paytm(isbn): if len(isbn) == 10: p_link = 'https://paytm.com/shop/search/?q='+pyisbn.Isbn10(isbn).convert(code='978')+'&sort_price=1' else: p_link = 'https://paytm.com/shop/search/?q='+isbn+'&sort_price=1' # print p_link driver = webdriver.PhantomJS('phantomjs',service_args=['--ssl-protocol=any']) # driver = webdriver.Firefox() try: driver.get(p_link) content = driver.page_source except: content = '' return {'price':'NA','url':p_link} # print content driver.quit() soup = bs.BeautifulSoup(content) p_class = soup.findAll('span',class_="border-radius ng-binding") # print p_class if not p_class: return {'price':'NA','url':p_link} else: p_class = p_class[0] try: p_price = re.findall(r'>Rs (.*?)</span>',str(p_class))[0] return {'price':p_price,'url':p_link} except Exception, e: return {'price':'NA','url':p_link}
import selenium.webdriver as webdriver import bs4 as bs import pyisbn import re def paytm(isbn): if len(isbn) == 10: p_link = 'https://paytm.com/shop/search/?q='+pyisbn.Isbn10(isbn).convert(code='978')+'&sort_price=1' else: p_link = 'https://paytm.com/shop/search/?q='+isbn+'&sort_price=1' # print p_link driver = webdriver.PhantomJS('phantomjs',service_args=['--ssl-protocol=any']) # driver = webdriver.Firefox() try: driver.get(p_link) content = driver.page_source except: content = '' return {'price':'NA','url':p_link}eturn # print content driver.quit() soup = bs.BeautifulSoup(content) p_class = soup.findAll('span',class_="border-radius ng-binding") # print p_class # print p_class if not p_class: return {'price':'NA','url':p_link} else: p_class = p_class[0] try: p_price = re.findall(r'>Rs (.*?)</span>',str(p_class))[0] return {'price':p_price,'url':p_link} except Exception, e: return {'price':'NA','url':p_link}
Add official OSI name in the license metadata (thanks @ecederstrand)
import os from setuptools import setup # type: ignore VERSION = '4.4.1' setup( name='conllu', packages=["conllu"], python_requires=">=3.6", package_data={ "": ["py.typed"] }, version=VERSION, license='MIT License', description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="emil@emilstenstrom.se", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Operating System :: OS Independent", ], )
import os from setuptools import setup # type: ignore VERSION = '4.4.1' setup( name='conllu', packages=["conllu"], python_requires=">=3.6", package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="emil@emilstenstrom.se", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Operating System :: OS Independent", ], )
DOC: Update content type for description PyPI rejects uploads that fail to render.
#!/usr/bin/env python from os.path import exists from setuptools import setup setup(name='cachey', version='0.2.0', description='Caching mindful of computation/storage costs', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering", ], url='http://github.com/dask/cachey/', maintainer='Matthew Rocklin', maintainer_email='mrocklin@gmail.com', license='BSD', keywords='', packages=['cachey'], python_requires='>=3.6', install_requires=list(open('requirements.txt').read().strip().split('\n')), long_description=(open('README.md').read() if exists('README.md') else ''), long_description_content_type='text/markdown', zip_safe=False)
#!/usr/bin/env python from os.path import exists from setuptools import setup setup(name='cachey', version='0.2.0', description='Caching mindful of computation/storage costs', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering", ], url='http://github.com/dask/cachey/', maintainer='Matthew Rocklin', maintainer_email='mrocklin@gmail.com', license='BSD', keywords='', packages=['cachey'], python_requires='>=3.6', install_requires=list(open('requirements.txt').read().strip().split('\n')), long_description=(open('README.md').read() if exists('README.md') else ''), zip_safe=False)
Add colorama for coloring on windows Add the module colorama that makes ANSI escape character sequences work under MS Windows. The coloring is used to give a better overview about the testresults
#!/usr/bin/env python2 import os import sys import argparse import logging import datetime import colorama from src.application.Logger import Logger from src.application.ValidationController import ValidationController from src.application.TestController import TestController def main(argv): colorama.init() logger = Logger() parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="Start with a Testfile", nargs=1) parser.add_argument("-v", "--validate", help="Validates Testfile", nargs=1, ) args = parser.parse_args() if args.input: validator = ValidationController(os.getcwd() + "/" + args.input[0]) if validator.logic(): tester = TestController(os.getcwd() + "/" + args.input[0]) tester.logic() elif args.validate: validator = ValidationController(os.getcwd() + "/" + args.validate[0]) validator.logic() if __name__ == "__main__": main(sys.argv[1:])
#!/usr/bin/env python2 import os import sys import argparse import logging import datetime from src.application.Logger import Logger from src.application.ValidationController import ValidationController from src.application.TestController import TestController def main(argv): logger = Logger() parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="Start with a Testfile", nargs=1) parser.add_argument("-v", "--validate", help="Validates Testfile", nargs=1, ) args = parser.parse_args() if args.input: validator = ValidationController(os.getcwd() + "/" + args.input[0]) if validator.logic(): tester = TestController(os.getcwd() + "/" + args.input[0]) tester.logic() elif args.validate: validator = ValidationController(os.getcwd() + "/" + args.validate[0]) validator.logic() if __name__ == "__main__": main(sys.argv[1:])
Make ender slime spawn rate more sane
package net.silentchaos512.gems.entity; import java.util.List; import com.google.common.collect.Lists; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Biomes; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.silentchaos512.lib.registry.SRegistry; public class ModEntities { public static List<Class> nodePacketClasses = Lists.newArrayList(); public static void init(SRegistry reg) { reg.registerEntity(EntityChaosProjectile.class, "ChaosProjectile", 64, 4, true); reg.registerEntity(EntityChaosProjectileHoming.class, "ChaosProjectileHoming", 64, 4, true); reg.registerEntity(EntityChaosProjectileSweep.class, "ChaosProjectileSweep", 64, 4, true); reg.registerEntity(EntityThrownTomahawk.class, "ThrownTomahawk"); reg.registerEntity(EntityEnderSlime.class, "EnderSlime", 64, 4, false, 0x003333, 0xAA00AA); EntityRegistry.addSpawn(EntityEnderSlime.class, 10, 1, 4, EnumCreatureType.MONSTER, Biomes.SKY); } }
package net.silentchaos512.gems.entity; import java.util.List; import com.google.common.collect.Lists; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Biomes; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.silentchaos512.lib.registry.SRegistry; public class ModEntities { public static List<Class> nodePacketClasses = Lists.newArrayList(); public static void init(SRegistry reg) { reg.registerEntity(EntityChaosProjectile.class, "ChaosProjectile", 64, 4, true); reg.registerEntity(EntityChaosProjectileHoming.class, "ChaosProjectileHoming", 64, 4, true); reg.registerEntity(EntityChaosProjectileSweep.class, "ChaosProjectileSweep", 64, 4, true); reg.registerEntity(EntityThrownTomahawk.class, "ThrownTomahawk"); reg.registerEntity(EntityEnderSlime.class, "EnderSlime", 64, 4, false, 0x003333, 0xAA00AA); EntityRegistry.addSpawn(EntityEnderSlime.class, 50, 1, 4, EnumCreatureType.MONSTER, Biomes.SKY); } }
Return the scale in the order it was created.
package edu.virginia.psyc.r01.persistence; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.commons.collections.map.HashedMap; import org.mindtrails.domain.questionnaire.LinkedQuestionnaireData; import org.mindtrails.domain.questionnaire.MeasureField; import javax.persistence.Entity; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.Map; import java.util.TreeMap; /** * Created by samportnow on 7/21/14. */ @Entity @Table(name="CC") @EqualsAndHashCode(callSuper = true) @Data public class CC extends LinkedQuestionnaireData { @MeasureField(desc="While reading the brief stories in the training program, how much did you relate to the situations presented?") @NotNull private Integer related; @MeasureField(desc="While reading the brief stories in the training program, how much did you feel like it could be you behaving that way in those stories?") @NotNull private Integer compare; @Override public Map<Integer, String> getScale(String scale) { Map<Integer, String> tmpScale = new TreeMap<>(); tmpScale.put(1, "Not at all"); tmpScale.put(2, "Slightly"); tmpScale.put(3, "Somewhat"); tmpScale.put(4, "Mostly"); tmpScale.put(5, "Very much"); return Collections.unmodifiableMap(tmpScale); } }
package edu.virginia.psyc.r01.persistence; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.commons.collections.map.HashedMap; import org.mindtrails.domain.questionnaire.LinkedQuestionnaireData; import org.mindtrails.domain.questionnaire.MeasureField; import javax.persistence.Entity; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.Map; /** * Created by samportnow on 7/21/14. */ @Entity @Table(name="CC") @EqualsAndHashCode(callSuper = true) @Data public class CC extends LinkedQuestionnaireData { @MeasureField(desc="While reading the brief stories in the training program, how much did you relate to the situations presented?") @NotNull private Integer related; @MeasureField(desc="While reading the brief stories in the training program, how much did you feel like it could be you behaving that way in those stories?") @NotNull private Integer compare; @Override public Map<Integer, String> getScale(String scale) { Map<Integer, String> tmpScale = new HashedMap(); tmpScale.put(1, "Not at all"); tmpScale.put(2, "Slightly"); tmpScale.put(3, "Somewhat"); tmpScale.put(4, "Mostly"); tmpScale.put(5, "Very much"); return Collections.unmodifiableMap(tmpScale); } }
Add todo comment about using quicktest library.
<?php use Mimic\Functional as F; /** * Unit Test for every Mimic library function. * * @since 0.1.0 * * @todo Need to use QuickTest library. */ class EveryFuncTest extends PHPUnit_Framework_TestCase { public function dataProvider_Passthrough() { return array( array(true), array(false) ); } /** * @dataProvider dataProvider_Passthrough * @covers ::Mimic\Functional\every */ public function testPassthrough($passthrough) { $self = $this; $data = array(1, 1, 1, 1); $callback = function($element, $index, $collection) use ($data, $self, $passthrough) { $self->assertTrue((is_string($index) || is_numeric($index)), 'index is not correct type'); $self->assertTrue(array_key_exists($index, $data), 'index does not exist in given data'); $self->assertEquals($data[$index], $element, 'existing array does not match given element'); $self->assertEquals($data, $collection, 'given collection does not match data'); return $passthrough; }; $this->assertEquals($passthrough, F\every($data, $callback)); } }
<?php use Mimic\Functional as F; /** * Unit Test for every Mimic library function. * * @since 0.1.0 */ class EveryFuncTest extends PHPUnit_Framework_TestCase { public function dataProvider_Passthrough() { return array( array(true), array(false) ); } /** * @dataProvider dataProvider_Passthrough * @covers ::Mimic\Functional\every */ public function testPassthrough($passthrough) { $self = $this; $data = array(1, 1, 1, 1); $callback = function($element, $index, $collection) use ($data, $self, $passthrough) { $self->assertTrue((is_string($index) || is_numeric($index)), 'index is not correct type'); $self->assertTrue(array_key_exists($index, $data), 'index does not exist in given data'); $self->assertEquals($data[$index], $element, 'existing array does not match given element'); $self->assertEquals($data, $collection, 'given collection does not match data'); return $passthrough; }; $this->assertEquals($passthrough, F\every($data, $callback)); } }
Make get shuttles api route more secure by encapsulating array in data key This is better as per this article: https://www.owasp.org/index.php/AJAX_Security_Cheat_Sheet#Always_return_JSON_with_an_Object_on_the_outside
const express = require('express'); const router = express.Router(); const cms = require('../cms.js'); const mongoose = require('mongoose'); const Shuttle = require("../schema/shuttle.js"); const helperLib = require("../helper.js").helpers; const helper = new helperLib(); module.exports = router; router.get('/', function(req, res) { //checks if user is logged in if (!req.session || !req.session.cas_user) { res.redirect("/login"); return; } var rcs_id = req.session.cas_user.toLowerCase(); //if the user is an admin if (helper.isAdmin(rcs_id)) { //query the database and return all information on all shuttles var query = Shuttle.find({}).lean(); query.exec(function(err, docs) { res.send({"data":docs}); }); } else { var query = Shuttle.find({}).lean(); // Ensure non-admin users cannot see other riders, nor the waitlist for a shuttle. query.select('-riders'); query.select('-waitlist'); query.exec(function(err, docs) { res.send(docs); }); } });
const express = require('express'); const router = express.Router(); const cms = require('../cms.js'); const mongoose = require('mongoose'); const Shuttle = require("../schema/shuttle.js"); const helperLib = require("../helper.js").helpers; const helper = new helperLib(); module.exports = router; router.get('/', function(req, res) { //checks if user is logged in if (!req.session || !req.session.cas_user) { res.redirect("/login"); return; } var rcs_id = req.session.cas_user.toLowerCase(); //if the user is an admin if (helper.isAdmin(rcs_id)) { //query the database and return all information on all shuttles var query = Shuttle.find({}).lean(); query.exec(function(err, docs) { res.send(docs); }); } else { var query = Shuttle.find({}).lean(); // Ensure non-admin users cannot see other riders, nor the waitlist for a shuttle. query.select('-riders'); query.select('-waitlist'); query.exec(function(err, docs) { res.send(docs); }); } });
Add image form field to template
{!! Form::errors($errors) !!} @if (isset($model)) {!! Form::model($model, ['route' => ['admin.news.update', $model->id], 'method' => 'PUT']) !!} @else {!! Form::open(['url' => 'admin/news']) !!} @endif {!! Form::smartText('title', trans('app.title')) !!} {!! Form::smartSelectRelation('newsCat', trans('app.category'), $modelClass) !!} {!! Form::smartSelectRelation('creator', trans('app.author'), $modelClass, user()->id) !!} {!! Form::smartTextarea('summary', trans('news::summary'), true) !!} {!! Form::smartTextarea('text', trans('app.text'), true) !!} {!! Form::smartImageFile() !!} {!! Form::smartDateTime('published_at', trans('news::publish_at')) !!} {!! Form::smartCheckbox('published', trans('app.published'), true) !!} {!! Form::smartCheckbox('internal', trans('app.internal')) !!} {!! Form::smartCheckbox('enable_comments', trans('app.enable_comments'), true) !!} {!! Form::actions() !!} {!! Form::close() !!}
{!! Form::errors($errors) !!} @if (isset($model)) {!! Form::model($model, ['route' => ['admin.news.update', $model->id], 'method' => 'PUT']) !!} @else {!! Form::open(['url' => 'admin/news']) !!} @endif {!! Form::smartText('title', trans('app.title')) !!} {!! Form::smartSelectRelation('newsCat', trans('app.category'), $modelClass) !!} {!! Form::smartSelectRelation('creator', trans('app.author'), $modelClass, user()->id) !!} {!! Form::smartTextarea('summary', trans('news::summary'), true) !!} {!! Form::smartTextarea('text', trans('app.text'), true) !!} {!! Form::smartDateTime('published_at', trans('news::publish_at')) !!} {!! Form::smartCheckbox('published', trans('app.published'), true) !!} {!! Form::smartCheckbox('internal', trans('app.internal')) !!} {!! Form::smartCheckbox('enable_comments', trans('app.enable_comments'), true) !!} {!! Form::actions() !!} {!! Form::close() !!}
Rename one test, use default dx and dz, fix naming of test class.
import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestAnalyticalHelmholtz(unittest.TestCase): def setUp(self): pass def test_cleanExecution(self): nx = 100 nz = 200 systemConfig = { 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main()
import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestMiniZephyr(unittest.TestCase): def setUp(self): pass def test_forwardModelling(self): nx = 100 nz = 200 systemConfig = { 'dx': 1., # m 'dz': 1., # m 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main()
Order posts by the creation date
from django.views.generic import ListView, DetailView from .models import Post class PostListView(ListView): context_object_name = 'posts' model = Post template_name = 'hermes/post_list.html' def get_queryset(self): return self.model.objects.order_by('-created_on') class CategoryPostListView(PostListView): def get_queryset(self): category_slug = self.kwargs.get('slug', '') return self.model.objects.in_category(category_slug) class ArchivePostListView(PostListView): def get_queryset(self): year = self.kwargs.get('year', None) month = self.kwargs.get('month', None) day = self.kwargs.get('day', None) return self.model.objects.created_on(year=year, month=month, day=day) class PostDetail(DetailView): context_object_name = 'post' model = Post template_name = "hermes/post_detail.html"
from django.views.generic import ListView, DetailView from .models import Post class PostListView(ListView): context_object_name = 'posts' model = Post template_name = 'hermes/post_list.html' class CategoryPostListView(PostListView): def get_queryset(self): category_slug = self.kwargs.get('slug', '') return self.model.objects.in_category(category_slug) class ArchivePostListView(PostListView): def get_queryset(self): year = self.kwargs.get('year', None) month = self.kwargs.get('month', None) day = self.kwargs.get('day', None) return self.model.objects.created_on(year=year, month=month, day=day) class PostDetail(DetailView): context_object_name = 'post' model = Post template_name = "hermes/post_detail.html"
Stop claiming support for 2.6 I don't even have a Python 2.6 interpreter.
from setuptools import setup setup( name="ftfy", version='3.3.0', maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', license="MIT", url='http://github.com/LuminosoInsight/python-ftfy', platforms=["any"], description="Fixes some problems with Unicode text after the fact", packages=['ftfy', 'ftfy.bad_codecs'], package_data={'ftfy': ['char_classes.dat']}, classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Filters", "Development Status :: 5 - Production/Stable" ], entry_points={ 'console_scripts': [ 'ftfy = ftfy.cli:main' ] } )
from setuptools import setup setup( name="ftfy", version='3.3.0', maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', license="MIT", url='http://github.com/LuminosoInsight/python-ftfy', platforms=["any"], description="Fixes some problems with Unicode text after the fact", packages=['ftfy', 'ftfy.bad_codecs'], package_data={'ftfy': ['char_classes.dat']}, classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Filters", "Development Status :: 5 - Production/Stable" ], entry_points={ 'console_scripts': [ 'ftfy = ftfy.cli:main' ] } )
Remove redis cache stats url.
# -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings urlpatterns = patterns('', url(r'^api/', include('greenmine.urls.api', namespace='api')), url(r'^', include('greenmine.urls.main', namespace='web')), #url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')), ) urlpatterns += staticfiles_urlpatterns() if settings.DEBUG: from django.views.static import serve _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] urlpatterns += patterns('', (r'^%s(?P<path>.*)$' % _media_url, serve, {'document_root': settings.MEDIA_ROOT}) )
# -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings urlpatterns = patterns('', url(r'^api/', include('greenmine.urls.api', namespace='api')), url(r'^', include('greenmine.urls.main', namespace='web')), url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')), ) urlpatterns += staticfiles_urlpatterns() if settings.DEBUG: from django.views.static import serve _media_url = settings.MEDIA_URL if _media_url.startswith('/'): _media_url = _media_url[1:] urlpatterns += patterns('', (r'^%s(?P<path>.*)$' % _media_url, serve, {'document_root': settings.MEDIA_ROOT}) )
Print better output on acceptance test assertion failure
package helper import ( "encoding/json" "testing" ) // Asserts that the request did not return an error. // Optionally perform some checks only if the request did not fail func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) { if err != nil { response_json, _ := json.MarshalIndent(response, "", " ") errorPayload, _ := json.MarshalIndent(err, "", " ") t.Fatalf("Failed to perform request, because %s. Response:\n%s", errorPayload, response_json) } else { if check_fn != nil { check_fn() } } } // Asserts that the request _did_ return an error. // Optionally perform some checks only if the request failed func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) { if err == nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json) } else { if check_fn != nil { check_fn() } } }
package helper import ( "encoding/json" "testing" ) // Asserts that the request did not return an error. // Optionally perform some checks only if the request did not fail func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) { if err != nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Failed to perform request, because %#v. Response:\n%s", err, response_json) } else { if check_fn != nil { check_fn() } } } // Asserts that the request _did_ return an error. // Optionally perform some checks only if the request failed func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) { if err == nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json) } else { if check_fn != nil { check_fn() } } }
Change column names of result
<?php namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; /** * TraitTypeRepository * * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom * repository methods below. */ class TraitTypeRepository extends EntityRepository { public function getNumber(){ $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt'); return $query->getSingleScalarResult(); } /** * @param $trait_type_id * @return array type, format, trait_type_id and ontology_url of specific trait */ public function getInfo($trait_type_id){ $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('t.id AS traitTypeId', 't.type', 't.ontologyUrl', 'IDENTITY(t.traitFormat) AS trait_format_id', 't.description', 't.unit') ->from('AppBundle\Entity\TraitType', 't') ->where('t.id = :trait_type_id') ->setParameter('trait_type_id', $trait_type_id); $query = $qb->getQuery(); return $query->getSingleResult(); } }
<?php namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; /** * TraitTypeRepository * * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom * repository methods below. */ class TraitTypeRepository extends EntityRepository { public function getNumber(){ $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt'); return $query->getSingleScalarResult(); } /** * @param $trait_type_id * @return array type, format, trait_type_id and ontology_url of specific trait */ public function getInfo($trait_type_id){ $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('t.id AS trait_type_id', 't.type', 't.ontologyUrl', 'IDENTITY(t.traitFormat) AS trait_format_id', 't.description', 't.unit') ->from('AppBundle\Entity\TraitType', 't') ->where('t.id = :trait_type_id') ->setParameter('trait_type_id', $trait_type_id); $query = $qb->getQuery(); return $query->getSingleResult(); } }
Make InputManager mouseup and mousemove global events. This fixes when you move camera then move mouse over a dialog it all goes wrong.
'use strict'; function _InputManager() { EventEmitter.call(this); var self = this; function addElCapture(name, outname) { if (!outname) { outname = name; } $(function() { renderer.domElement.addEventListener(name, function(e) { self._handleEvent(outname, e); }, false ); }); } function addCapture(name, outname) { if (!outname) { outname = name; } document.addEventListener(name, function(e) { self._handleEvent(outname, e); }, false ); } addElCapture('mousedown'); addCapture('mouseup'); addCapture('mousemove'); addCapture('keydown'); addCapture('keyup'); addElCapture('touchstart'); addElCapture('touchend'); addElCapture('touchmove'); addElCapture('mousewheel'); addElCapture('DOMMouseScroll', 'mousewheel'); document.addEventListener('contextmenu', function(e) { e.preventDefault(); }); } _InputManager.prototype = new EventEmitter(); _InputManager.prototype._handleEvent = function(name, e) { this.emit(name, e); }; var InputManager = new _InputManager();
'use strict'; function _InputManager() { EventEmitter.call(this); var self = this; function addElCapture(name, outname) { if (!outname) { outname = name; } $(function() { renderer.domElement.addEventListener(name, function(e) { self._handleEvent(outname, e); }, false ); }); } function addCapture(name, outname) { if (!outname) { outname = name; } document.addEventListener(name, function(e) { self._handleEvent(outname, e); }, false ); } addElCapture('mousedown'); addElCapture('mouseup'); addElCapture('mousemove'); addCapture('keydown'); addCapture('keyup'); addElCapture('touchstart'); addElCapture('touchend'); addElCapture('touchmove'); addElCapture('mousewheel'); addElCapture('DOMMouseScroll', 'mousewheel'); document.addEventListener('contextmenu', function(e) { e.preventDefault(); }); } _InputManager.prototype = new EventEmitter(); _InputManager.prototype._handleEvent = function(name, e) { this.emit(name, e); }; var InputManager = new _InputManager();
Fix bug with data frames
# get_weather_data.py import pandas as pd import constants as const import utils def main(): engine = utils.get_db_engine() today = utils.get_current_time() resp = utils.get_uri_content(uri=const.DARK_SKY_URI, content_type='json') for key in resp.keys(): if isinstance(resp.get(key), dict) and 'data' in resp.get(key): for n, i in enumerate(resp.get(key)['data']): resp.get(key)['data'][n]['currentTime'] = today resp['currently']['lat'] = resp['latitude'] resp['currently']['lng'] = resp['longitude'] current_df = pd.DataFrame([resp['currently']]) daily_df = pd.DataFrame(resp['daily']['data']) hourly_df = pd.DataFrame(resp['hourly']['data']) minutely_df = pd.DataFrame(resp['minutely']['data']) tables = ['current_weather', 'daily_weather', 'hourly_weather', 'minutely_weather'] data_to_import = [current_df, daily_df, hourly_df, minutely_df] for data, table in zip(data_to_import, tables): data.to_sql(table, con=engine, if_exists='append', index=False) if __name__ == '__main__': main()
# get_weather_data.py import pandas as pd import constants as const import utils def main(): engine = utils.get_db_engine() today = utils.get_current_time() resp = utils.get_uri_content(uri=const.DARK_SKY_URI, content_type='json') for key in resp.keys(): if isinstance(resp.get(key), dict) and 'data' in resp.get(key): for n, i in enumerate(resp.get(key)['data']): resp.get(key)['data'][n]['currentTime'] = today resp['currently']['lat'] = resp['latitude'] resp['currently']['lng'] = resp['longitude'] daily_df = pd.DataFrame(resp['daily']['data']) tables = ['current_weather', 'daily_weather', 'hourly_weather', 'minutely_weather'] for table in tables: daily_df.to_sql(table, con=engine, if_exists='append', index=False) if __name__ == '__main__': main()
Introduce test to verify resolving multiple promises
'use strict'; const Promise = require('promise'); const chai = require('chai'); const expect = chai.expect; const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); describe('ES2015 Promises', () => { it('should provide a greeting', () => { // When const promise = generateGreeting('Sean'); // Then return expect(promise).to.eventually.equal('Hello Sean!'); }); it('should provide multiple greetings', () => { // Given const promise1 = generateGreeting('Sean'); const promise2 = generateGreeting('Beth'); // When const promises = Promise.all([promise1, promise2]); // Then® const expectedGreetings = ['Hello Sean!', 'Hello Beth!']; return expect(promises).to.eventually.deep.equal(expectedGreetings); }); it('should use promise.resolve', () => { // Given const message = 'Say Hello!'; // When const promise = Promise.resolve(message); // Then return expect(promise).to.eventually.equal(message); }); it('should use promise.reject', () => { // Given const errorMessage = 'Help! Error!'; // When const promise = Promise.reject(new Error(errorMessage)); // Then return expect(promise).to.eventually.rejectedWith(errorMessage); }); const generateGreeting = (name) => { return new Promise((resolve) => { setTimeout(() => { resolve(`Hello ${name}!`); }, 1500); }); }; });
'use strict'; const Promise = require('promise'); const chai = require('chai'); const expect = chai.expect; const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); describe('ES2015 Promises', () => { it('should provide a greeting', () => { // When const promise = generateGreeting('Sean'); // Then return expect(promise).to.eventually.equal('Hello Sean!'); }); it('should use promise.resolve', () => { // Given const message = 'Say Hello!'; // When const promise = Promise.resolve(message); // Then return expect(promise).to.eventually.equal(message); }); it('should use promise.reject', () => { // Given const errorMessage = 'Help! Error!'; // When const promise = Promise.reject(new Error(errorMessage)); // Then return expect(promise).to.eventually.rejectedWith(errorMessage); }); const generateGreeting = (name) => { return new Promise((resolve) => { setTimeout(() => { resolve(`Hello ${name}!`); }, 1500); }); }; });
Add num_tries to the feed update. If there are more than 10 tries, the requests must stop
import json import requests from time import sleep from django.http import HttpResponse from .models import NewsFeed HACKER_NEWS_API_URL = 'http://api.ihackernews.com/page' def get_news(request=None): feed = NewsFeed.objects.latest() return json.dumps(feed.json) # View for updating the feed def update_feed(request): feed = NewsFeed() feed = get_feed(feed) return HttpResponse(feed.created) # Will document this soon. def get_feed(feed, num_tries=10): r = requests.get(HACKER_NEWS_API_URL) if r.status_code == 200: feed.json = r.text feed.save() elif num_tries > 0: num_tries = num_tries - 1 print "Trying again..." sleep(10) get_feed(feed, num_tries) return feed def update_feed_internal(): feed = NewsFeed() feed = get_feed(feed) return feed.created
import json import requests from time import sleep from django.http import HttpResponse from .models import NewsFeed HACKER_NEWS_API_URL = 'http://api.ihackernews.com/page' def get_news(request=None): feed = NewsFeed.objects.latest() return json.dumps(feed.json) # View for updating the feed def update_feed(request): feed = NewsFeed() feed = get_feed(feed) return HttpResponse(feed.created) # Will document this soon. def get_feed(feed): r = requests.get(HACKER_NEWS_API_URL) if r.status_code == 200: feed.json = r.text feed.save() else: print "Trying again..." sleep(10) get_feed(feed) return feed def update_feed_internal(): feed = NewsFeed() feed = get_feed(feed) return feed.created
Add orientation change to window service
"use strict"; var withObservable = require("../common/withObservable"); var debounceUpdateListener = require("../common/debounceUpdateListener"); var windowService = withObservable.call({ "viewportSize": { x: 0, y: 0 }, updateViewportSize: function () { this.viewportSize.x = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); this.viewportSize.y = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); return this.viewportSize; }, getViewportSize: function () { return this.viewportSize; } }); window.addEventListener("resize", debounceUpdateListener({ "timeout": 500, "debounce": 250, start: function () { windowService.notify("start", windowService.updateViewportSize()); }, update: function () { windowService.notify("update", windowService.updateViewportSize()); }, end: function () { windowService.notify("end", windowService.updateViewportSize()); } })); window.addEventListener("orientationchange", function () { var vpSize = windowService.updateViewportSize(); windowService.notify("start", vpSize); windowService.notify("end", vpSize); }); windowService.updateViewportSize(); module.exports = windowService;
"use strict"; var withObservable = require("../common/withObservable"); var debounceUpdateListener = require("../common/debounceUpdateListener"); var windowService = withObservable.call({ "viewportSize": { x: 0, y: 0 }, updateViewportSize: function () { this.viewportSize.x = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); this.viewportSize.y = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); return this.viewportSize; }, getViewportSize: function () { return this.viewportSize; } }); window.addEventListener("resize", debounceUpdateListener({ "timeout": 500, "debounce": 250, start: function () { windowService.notify("start", windowService.updateViewportSize()); }, update: function () { windowService.notify("update", windowService.updateViewportSize()); }, end: function () { windowService.notify("end", windowService.updateViewportSize()); } })); windowService.updateViewportSize(); module.exports = windowService;
Icon: Remove unused var in story
/** * Icon Story: Basic Usage */ import React from 'react'; import { select } from '@storybook/addon-knobs'; import Icon from '../Icon'; import icons from '../icons'; import css from './style.css'; export default () => { const size = select('Size', { small: 'Small', medium: 'Medium', large: 'Large' }, 'large'); const status = select('Status', { warn: 'Warning', error: 'Error', success: 'Success', none: 'None' }, 'none'); const list = Object.keys(icons).map((icon, i) => ( <li className={css.iconGridItem} key={i}> <div className={css.iconGridItemInner}> <Icon size={size} icon={icon} status={status !== 'none' ? status : undefined} /> </div> <p>{icon}</p> </li> )); return ( <div style={{ padding: '15px' }}> <ul className={css.iconGrid}> { list } </ul> </div> ); };
/** * Icon Story: Basic Usage */ import React from 'react'; import { select, color } from '@storybook/addon-knobs'; import Icon from '../Icon'; import icons from '../icons'; import css from './style.css'; export default () => { const size = select('Size', { small: 'Small', medium: 'Medium', large: 'Large' }, 'large'); const status = select('Status', { warn: 'Warning', error: 'Error', success: 'Success', none: 'None' }, 'none'); const list = Object.keys(icons).map((icon, i) => ( <li className={css.iconGridItem} key={i}> <div className={css.iconGridItemInner}> <Icon size={size} icon={icon} status={status !== 'none' ? status : undefined} /> </div> <p>{icon}</p> </li> )); return ( <div style={{ padding: '15px' }}> <ul className={css.iconGrid}> { list } </ul> </div> ); };
Fix test to not create a new directory in the project.
# Copyright (c) 2015, Matt Layman try: from unittest import mock except ImportError: import mock import tempfile from tap.plugins import pytest from tap.tests import TestCase from tap.tracker import Tracker class TestPytestPlugin(TestCase): def setUp(self): """The pytest plugin uses module scope so a fresh tracker must be installed each time.""" pytest.tracker = Tracker() def test_includes_options(self): group = mock.Mock() parser = mock.Mock() parser.getgroup.return_value = group pytest.pytest_addoption(parser) self.assertEqual(group.addoption.call_count, 1) def test_tracker_outdir_set(self): outdir = tempfile.mkdtemp() config = mock.Mock() config.option.tap_outdir = outdir pytest.pytest_configure(config) self.assertEqual(pytest.tracker.outdir, outdir)
# Copyright (c) 2015, Matt Layman try: from unittest import mock except ImportError: import mock from tap.plugins import pytest from tap.tests import TestCase from tap.tracker import Tracker class TestPytestPlugin(TestCase): def setUp(self): """The pytest plugin uses module scope so a fresh tracker must be installed each time.""" pytest.tracker = Tracker() def test_includes_options(self): group = mock.Mock() parser = mock.Mock() parser.getgroup.return_value = group pytest.pytest_addoption(parser) self.assertEqual(group.addoption.call_count, 1) def test_tracker_outdir_set(self): config = mock.Mock() config.option.tap_outdir = 'fakeout' pytest.pytest_configure(config) self.assertEqual(pytest.tracker.outdir, 'fakeout')
Fix typo in variable name s7conn vs. s7con
import s7 class Alarm: ALARM_DB = 12 def __init__(self, s7conn): self._s7conn = s7conn def arm(self): # Toggle bit self._s7conn.writeBit(self.ALARM_DB, 0, 1, 1) self._s7conn.writeBit(self.ALARM_DB, 0, 1, 0) def disarm(self): # Toggle bit self._s7conn.writeBit(self.ALARM_DB, 0, 2, 1) self._s7conn.writeBit(self.ALARM_DB, 0, 2, 0) def isArmed(self): return False def isAlarmTriggered(self): return False
import s7 class Alarm: ALARM_DB = 12 def __init__(self, s7conn): self._s7conn = s7conn def arm(self): # Toggle bit self._s7con.writeBit(self.ALARM_DB, 0, 1, 1) self._s7con.writeBit(self.ALARM_DB, 0, 1, 0) def disarm(self): # Toggle bit self._s7con.writeBit(self.ALARM_DB, 0, 2, 1) self._s7con.writeBit(self.ALARM_DB, 0, 2, 0) def isArmed(self): return False def isAlarmTriggered(self): return False
Use logging directly in main
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logging.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logging.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logging.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logging.info("END: destalinate_job") if __name__ == "__main__": sched.start()
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
Add alias -h to --help
import click import os plugin_folder = os.path.join(os.path.dirname(__file__), 'commands') CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) class BlackBelt(click.MultiCommand): def list_commands(self, ctx): rv = [] for filename in os.listdir(plugin_folder): if filename.endswith('.py') and filename != '__init__.py': rv.append(filename[:-3]) rv.sort() return rv def get_command(self, ctx, name): ns = {} fn = os.path.join(plugin_folder, name + '.py') with open(fn) as f: code = compile(f.read(), fn, 'exec') eval(code, ns, ns) return ns['cli'] cli = BlackBelt(context_settings=CONTEXT_SETTINGS, help='Black Belt: automate project The Apiary Way. Please provide a command.') # backward compatibility def main(): cli() if __name__ == '__main__': cli()
import click import os plugin_folder = os.path.join(os.path.dirname(__file__), 'commands') class BlackBelt(click.MultiCommand): def list_commands(self, ctx): rv = [] for filename in os.listdir(plugin_folder): if filename.endswith('.py') and filename != '__init__.py': rv.append(filename[:-3]) rv.sort() return rv def get_command(self, ctx, name): ns = {} fn = os.path.join(plugin_folder, name + '.py') with open(fn) as f: code = compile(f.read(), fn, 'exec') eval(code, ns, ns) return ns['cli'] cli = BlackBelt(help='Black Belt: automate project The Apiary Way. Please provide a command.') # backward compatibility def main(): cli() if __name__ == '__main__': cli()
Change zero back-off next interval default.
package watchdog import ( "time" ) // BackOff is the interface to a back-off interval generator. type BackOff interface { // Mark the next call to NextInterval as the "first" retry in a sequence. // If the generated intervals are dependent on the number of consecutive // (unsuccessful) retries, previous retries should be forgotten here. Reset() // Generate the next back-off interval. NextInterval() time.Duration } // // type zeroBackOff struct{} func (b *zeroBackOff) Reset() {} func (b *zeroBackOff) NextInterval() time.Duration { return 0 * time.Second } // A back-off interval generator which always returns a zero interval. func NewZeroBackOff() BackOff { return &zeroBackOff{} } // // type constantBackOff struct { interval time.Duration } func (b *constantBackOff) Reset() {} func (b *constantBackOff) NextInterval() time.Duration { return b.interval } // A back-off interval generator which always returns the same interval. func NewConstantBackOff(interval time.Duration) BackOff { return &constantBackOff{ interval: interval, } }
package watchdog import ( "time" ) // BackOff is the interface to a back-off interval generator. type BackOff interface { // Mark the next call to NextInterval as the "first" retry in a sequence. // If the generated intervals are dependent on the number of consecutive // (unsuccessful) retries, previous retries should be forgotten here. Reset() // Generate the next back-off interval. NextInterval() time.Duration } // // type zeroBackOff struct{} func (b *zeroBackOff) Reset() {} func (b *zeroBackOff) NextInterval() time.Duration { return 0 * time.Millisecond } // A back-off interval generator which always returns a zero interval. func NewZeroBackOff() BackOff { return &zeroBackOff{} } // // type constantBackOff struct { interval time.Duration } func (b *constantBackOff) Reset() {} func (b *constantBackOff) NextInterval() time.Duration { return b.interval } // A back-off interval generator which always returns the same interval. func NewConstantBackOff(interval time.Duration) BackOff { return &constantBackOff{ interval: interval, } }
Add defaults, change init to extend
'use strict'; var Handlebars = require('handlebars'); var _ = require('lodash'); module.exports = { defaults: { ext: ".hbs" }, /** * Extend the Handlebars instance. * Register any custom helpers and partials set in the config. */ extend: function(ext){ ext = ext || {} _.each(ext.helpers || {}, function(helper, name){ Handlebars.registerHelper(name, helper); }); _.each(ext.partials || {}, function(partial, name){ Handlebars.registerPartial(name, partial); }); }, /** * Register component view templates as partials. * Called every time the component file tree changes. */ registerViews: function(views) { views.forEach(function(view){ Handlebars.registerPartial(view.handle, view.content); if (view.alias) { Handlebars.registerPartial(view.alias, view.content); } }); }, /** * Render the component view contents. */ render: function(str, context, meta) { var template = Handlebars.compile(str); return template(context); } };
'use strict'; var Handlebars = require('handlebars'); var _ = require('lodash'); module.exports = { /** * Initialise the Handlebars instance. * Register any custom helpers and partials set in the config. */ init: function(config){ var extras = config.extend || {}; _.each(extras.helpers || {}, function(helper, name){ Handlebars.registerHelper(name, helper); }); _.each(extras.partials || {}, function(partial, name){ Handlebars.registerPartial(name, partial); }); }, /** * Register component view templates as partials. * Called every time the component file tree changes. */ registerViews: function(views) { views.forEach(function(view){ Handlebars.registerPartial(view.handle, view.content); if (view.alias) { Handlebars.registerPartial(view.alias, view.content); } }); }, /** * Render the component view contents. */ render: function(str, context, meta) { var template = Handlebars.compile(str); return template(context); } };
Enforce requirement on python >= 3.4
from setuptools import setup from rohrpost import __version__ def read(filepath): with open(filepath, "r", encoding="utf-8") as f: return f.read() setup( name="rohrpost", version=__version__, description="rohrpost WebSocket protocol for ASGI", long_description=read("README.rst"), url="https://github.com/axsemantics/rohrpost", author="Tobias Kunze", author_email="tobias.kunze@ax-semantics.com", license="MIT", python_requires=">=3.4", classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], packages=["rohrpost"], )
from setuptools import setup from rohrpost import __version__ def read(filepath): with open(filepath, "r", encoding="utf-8") as f: return f.read() setup( name="rohrpost", version=__version__, description="rohrpost WebSocket protocol for ASGI", long_description=read("README.rst"), url="https://github.com/axsemantics/rohrpost", author="Tobias Kunze", author_email="tobias.kunze@ax-semantics.com", license="MIT", classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], packages=["rohrpost"], )
Fix sympy profile to work with sympy 0.7. Sympy 0.7 no longer supports x,y,z = symbols('xyz'). symbols ('xyz') is now a single symbol 'xyz'. Change the sympy profile to symbols(x,y,z).
c = get_config() app = c.InteractiveShellApp # This can be used at any point in a config file to load a sub config # and merge it into the current one. load_subconfig('ipython_config.py', profile='default') lines = """ from __future__ import division from sympy import * x, y, z = symbols('x,y,z') k, m, n = symbols('k,m,n', integer=True) f, g, h = map(Function, 'fgh') """ # You have to make sure that attributes that are containers already # exist before using them. Simple assigning a new list will override # all previous values. if hasattr(app, 'exec_lines'): app.exec_lines.append(lines) else: app.exec_lines = [lines] # Load the sympy_printing extension to enable nice printing of sympy expr's. if hasattr(app, 'extensions'): app.extensions.append('sympyprinting') else: app.extensions = ['sympyprinting']
c = get_config() app = c.InteractiveShellApp # This can be used at any point in a config file to load a sub config # and merge it into the current one. load_subconfig('ipython_config.py', profile='default') lines = """ from __future__ import division from sympy import * x, y, z = symbols('xyz') k, m, n = symbols('kmn', integer=True) f, g, h = map(Function, 'fgh') """ # You have to make sure that attributes that are containers already # exist before using them. Simple assigning a new list will override # all previous values. if hasattr(app, 'exec_lines'): app.exec_lines.append(lines) else: app.exec_lines = [lines] # Load the sympy_printing extension to enable nice printing of sympy expr's. if hasattr(app, 'extensions'): app.extensions.append('sympyprinting') else: app.extensions = ['sympyprinting']
Improve test coverage once again...
from tinydb.utils import LRUCache def test_lru_cache(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["b"] = 2 cache["c"] = 3 _ = cache["a"] # move to front in lru queue cache["d"] = 4 # move oldest item out of lru queue assert cache.lru == ["c", "a", "d"] def test_lru_cache_set_multiple(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["a"] = 2 cache["a"] = 3 cache["a"] = 4 assert cache.lru == ["a"] def test_lru_cache_get(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["b"] = 1 cache["c"] = 1 cache.get("a") cache["d"] = 4 assert cache.lru == ["c", "a", "d"] def test_lru_cache_delete(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["b"] = 2 del cache["a"] assert cache.lru == ["b"] def test_lru_cache_clear(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["b"] = 2 cache.clear() assert cache.lru == [] def test_lru_cache_unlimited(): cache = LRUCache() for i in xrange(100): cache[i] = i assert len(cache.lru) == 100
from tinydb.utils import LRUCache def test_lru_cache(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["b"] = 2 cache["c"] = 3 _ = cache["a"] # move to front in lru queue cache["d"] = 4 # move oldest item out of lru queue assert cache.lru == ["c", "a", "d"] def test_lru_cache_set_multiple(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["a"] = 2 cache["a"] = 3 cache["a"] = 4 assert cache.lru == ["a"] def test_lru_cache_delete(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["b"] = 2 del cache["a"] assert cache.lru == ["b"] def test_lru_cache_clear(): cache = LRUCache(capacity=3) cache["a"] = 1 cache["b"] = 2 cache.clear() assert cache.lru == []
Fix an error in application template causing the cluster to hang on exit
const cluster = require('cluster'), stopSignals = [ 'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM' ], production = process.env.NODE_ENV == 'production'; let stopping = false; cluster.on('disconnect', function(worker) { if (production) { if (!stopping) { cluster.fork(); } } else { process.exit(1); } }); if (cluster.isMaster) { const workerCount = process.env.NODE_CLUSTER_WORKERS || 4; console.log(`Starting ${workerCount} workers...`); for (let i = 0; i < workerCount; i++) { cluster.fork(); } if (production) { stopSignals.forEach(function (signal) { process.on(signal, function () { console.log(`Got ${signal}, stopping workers...`); stopping = true; cluster.disconnect(function () { console.log('All workers stopped, exiting.'); process.exit(0); }); }); }); } } else { require('./app.js'); }
const cluster = require('cluster'), stopSignals = [ 'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM' ], production = process.env.NODE_ENV == 'production'; let stopping = false; cluster.on('disconnect', function(worker) { if (production) { if (!stopping) { cluster.fork(); } } else { process.exit(1); } }); if (cluster.isMaster) { const workerCount = process.env.NODE_CLUSTER_WORKERS || 4; console.log(`Starting ${workerCount} workers...`); for (let i = 0; i < workerCount; i++) { cluster.fork(); } if (production) { stopSignals.forEach(function (signal) { process.on(signal, function () { console.log(`Got ${signal}, stopping workers...`); stopping = true; cluster.disconnect(); }); }); } } else { require('./app.js'); }
Save initial scope cookie if public and private
var $ = require('jquery-browserify'); var _ = require('underscore'); var Backbone = require('backbone'); var templates = require('../../dist/templates'); var auth = require('../config'); var cookie = require('../cookie'); // Set scope auth.scope = cookie.get('scope') || 'repo'; module.exports = Backbone.View.extend({ id: 'start', initialize: function () { this.persistScope(auth.scope); }, events: { 'click a[href="#scopes"]': 'toggleScope', 'change .toggle-hide select': 'setScope' }, template: templates.start, render: function() { this.$el.html(_.template(this.template, auth, { variable: 'auth' })); return this; }, toggleScope: function(e) { e.preventDefault(); this.$('.toggle-hide').toggleClass('show'); }, setScope: function(e) { var scope = $(e.currentTarget).val(); this.persistScope(scope); this.render(); router.app.nav.render(); }, persistScope: function(scope) { var expire = new Date((new Date()).setYear((new Date()).getFullYear() + 20)); auth.scope = scope; cookie.set('scope', scope, expire); } });
var $ = require('jquery-browserify'); var _ = require('underscore'); var Backbone = require('backbone'); var templates = require('../../dist/templates'); var auth = require('../config'); var cookie = require('../cookie'); // Set scope auth.scope = cookie.get('scope') || 'repo'; module.exports = Backbone.View.extend({ id: 'start', events: { 'click a[href="#scopes"]': 'toggleScope', 'change .toggle-hide select': 'setScope' }, template: templates.start, render: function() { this.$el.html(_.template(this.template, auth, { variable: 'auth' })); return this; }, toggleScope: function(e) { e.preventDefault(); this.$('.toggle-hide').toggleClass('show'); }, setScope: function(e) { var scope = $(e.currentTarget).val(), expire = new Date((new Date()).setYear((new Date()).getFullYear() + 20)); auth.scope = scope; cookie.set('scope', scope, expire); this.render(); router.app.nav.render(); } });
Add form for looking up transactions by number
<? require 'scat.php'; head("transactions"); $type= $_REQUEST['type']; if ($type) { $criteria= "type = '".$db->real_escape_string($type)."'"; } else { $criteria= '1=1'; } ?> <form method="get" action="txn.php"> <select name="type"> <option value="customer">Invoice <option value="vendor">Purchase Order <option value="internal">Internal </select> <input id="focus" type="text" name="number" value=""> <input type="submit" value="Look Up"> </form> <br> <? $q= "SELECT txn.type AS meta, CONCAT(txn.id, '|', type, '|', txn.number) AS Number\$txn, txn.created AS Created\$date, SUM(ordered) AS Ordered, SUM(shipped) AS Shipped, SUM(allocated) AS Allocated FROM txn LEFT JOIN txn_line ON (txn.id = txn_line.txn) WHERE $criteria GROUP BY txn.id ORDER BY created DESC LIMIT 200"; dump_table($db->query($q)); dump_query($q);
<? require 'scat.php'; head("transactions"); $type= $_REQUEST['type']; if ($type) { $criteria= "type = '".$db->real_escape_string($type)."'"; } else { $criteria= '1=1'; } /* $q= $_GET['q']; ?> <form method="get" action="<?=$_SERVER['PHP_SELF']?>"> <input id="focus" type="text" name="q" value="<?=htmlspecialchars($q)?>"> <input type="submit" value="Search"> </form> <br> <? */ $q= "SELECT txn.type AS meta, CONCAT(txn.id, '|', type, '|', txn.number) AS Number\$txn, txn.created AS Created\$date, SUM(ordered) AS Ordered, SUM(shipped) AS Shipped, SUM(allocated) AS Allocated FROM txn LEFT JOIN txn_line ON (txn.id = txn_line.txn) WHERE $criteria GROUP BY txn.id ORDER BY created DESC LIMIT 200"; dump_table($db->query($q)); dump_query($q);
Set protractor page timeout to 30s
var exec = require("sync-exec"); exports.config = { suites: { core: "../src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/*Spec.js", mercator: "../src/mercator/tests/acceptance/*Spec.js" }, baseUrl: "http://localhost:9090", getPageTimeout: 30000, directConnect: true, capabilities: { "browserName": "chrome" }, beforeLaunch: function() { exec("bin/supervisord"); exec("bin/supervisorctl restart adhocracy_test:test_zeo test_backend_with_ws adhocracy_test:test_autobahn adhocracy_test:test_frontend"); }, afterLaunch: function() { exec("bin/supervisorctl stop adhocracy_test:test_zeo test_backend_with_ws adhocracy_test:test_autobahn adhocracy_test:test_frontend"); exec("rm -rf var/test_zeodata/Data.fs* var/test_zeodata/blobs"); }, jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, isVerbose: true, includeStackTrace: true } }
var exec = require("sync-exec"); exports.config = { suites: { core: "../src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/*Spec.js", mercator: "../src/mercator/tests/acceptance/*Spec.js" }, baseUrl: "http://localhost:9090", directConnect: true, capabilities: { "browserName": "chrome" }, beforeLaunch: function() { exec("bin/supervisord"); exec("bin/supervisorctl restart adhocracy_test:test_zeo test_backend_with_ws adhocracy_test:test_autobahn adhocracy_test:test_frontend"); }, afterLaunch: function() { exec("bin/supervisorctl stop adhocracy_test:test_zeo test_backend_with_ws adhocracy_test:test_autobahn adhocracy_test:test_frontend"); exec("rm -rf var/test_zeodata/Data.fs* var/test_zeodata/blobs"); }, jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, isVerbose: true, includeStackTrace: true } }
Add oidc for /api (swagger-ui)
package org.synyx.urlaubsverwaltung.api; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.synyx.urlaubsverwaltung.security.SecurityConfigurationProperties; import static org.springframework.security.config.http.SessionCreationPolicy.NEVER; @Configuration @Order(1) public class RestApiSecurityConfig extends WebSecurityConfigurerAdapter { private final boolean isOauth2Enabled; public RestApiSecurityConfig(SecurityConfigurationProperties properties) { isOauth2Enabled = "oidc".equalsIgnoreCase(properties.getAuth().name()); } @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") .sessionManagement() .sessionCreationPolicy(NEVER) .and() .authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().authenticated(); if (isOauth2Enabled) { http.oauth2Login(); } else { http.httpBasic(); } } }
package org.synyx.urlaubsverwaltung.api; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import static org.springframework.security.config.http.SessionCreationPolicy.NEVER; @Configuration @Order(1) public class RestApiSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") .sessionManagement() .sessionCreationPolicy(NEVER) .and() .httpBasic() .and() .authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().authenticated(); } }
TASK: Adjust test assertions to PHPUnit 8
<?php namespace Neos\Flow\Tests\Unit\Http\Helper; use GuzzleHttp\Psr7\ServerRequest; use Neos\Flow\Http\Helper\RequestInformationHelper; use Neos\Flow\Tests\UnitTestCase; /** * Tests for the RequestInformationHelper */ class RequestInformationHelperTest extends UnitTestCase { /** * @test */ public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials() { $request = ServerRequest::fromGlobals() ->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword') ->withAddedHeader('Authorization', 'Bearer SomeToken'); $renderedHeaders = RequestInformationHelper::renderRequestHeaders($request); self::assertStringNotContainsString('SomePassword', $renderedHeaders); self::assertStringNotContainsString('SomeToken', $renderedHeaders); } }
<?php namespace Neos\Flow\Tests\Unit\Http\Helper; use GuzzleHttp\Psr7\ServerRequest; use Neos\Flow\Http\Helper\RequestInformationHelper; use Neos\Flow\Tests\UnitTestCase; /** * Tests for the RequestInformationHelper */ class RequestInformationHelperTest extends UnitTestCase { /** * @test */ public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials() { $request = ServerRequest::fromGlobals() ->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword') ->withAddedHeader('Authorization', 'Bearer SomeToken'); $renderedHeaders = RequestInformationHelper::renderRequestHeaders($request); self::assertStringContainsString('SomePassword', $renderedHeaders); self::assertStringContainsString('SomeToken', $renderedHeaders); } }
Use prefixes in SPARQL query
import Joi from 'joi' import { graph } from 'helpers/sparql' export default [ { path: '/pipelines', query: ` PREFIX mu: <http://mu.semte.ch/vocabularies/core/> PREFIX pwo: <http://purl.org/spar/pwo/> CONSTRUCT { ?pipeline ?p ?o . ?step ?x ?y } FROM <${graph}> WHERE { ?pipeline mu:uuid ?uuid . ?pipeline ?p ?o . ?pipeline pwo:hasStep ?step . ?step ?x ?y }`, config: { validate: { query: { 'uuid': Joi.string().required() } } } } ]
import Joi from 'joi' import { graph } from 'helpers/sparql' export default [ { path: '/pipelines', query: ` PREFIX core: <http://mu.semte.ch/vocabularies/core/> CONSTRUCT { ?pipeline ?p ?o . ?step ?x ?y } FROM <${graph}> WHERE { ?pipeline core:uuid ?uuid . ?pipeline ?p ?o . ?pipeline <http://purl.org/spar/pwo/hasStep> ?step . ?step ?x ?y }`, config: { validate: { query: { 'uuid': Joi.string().required() } } } } ]
Fix nested model should be a value object.
/** * Created by dungvn3000 on 3/14/14. * The model automatic update mapping field when set associations table. */ Ext.define('sunerp.model.BaseModel', { extend: 'Ext.data.Model', set: function (fieldName, newValue) { var me = this; me.callParent(arguments); if (newValue != null && Ext.isObject(newValue)) { Ext.each(me.associations.keys, function (table) { if (fieldName == table) { for (var key in newValue) { me.set(table + "." + key, newValue[key]); } me.set(key + 'Id', newValue.id); } }); } } });
/** * Created by dungvn3000 on 3/14/14. * The model automatic update mapping field when set associations table. */ Ext.define('sunerp.model.BaseModel', { extend: 'Ext.data.Model', set: function (fieldName, newValue) { var me = this; Ext.each(me.associations.keys, function (key) { if (fieldName == key) { Ext.each(newValue.fields.keys, function (field) { me.set(key + "." + field, newValue.get(field)) }); me.set(key + 'Id', newValue.get('id')); } }); me.callParent(arguments); } });
[FIX] Fix useless import following the removal of rml purchase reports bzr revid: openerp-sle@openerp-sle.home-20140214150700-2zuukk4ahs4q1zhs
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import purchase_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import order import request_quotation import purchase_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Reduce cordova demo on windows It can later be investigated how to improve windows support for cordova plug-ins, but for now include only the two that acually work. Change-Id: I1839ab1604d8191d5ed67e76d7e2f3398a1d8bbb
const {Button, Page, NavigationView, ScrollView, device, ui} = require('tabris'); const ToastPage = require('./ToastPage'); const SharingPage = require('./SharingPage'); const MotionPage = require('./MotionPage'); const NetworkPage = require('./NetworkPage'); const MediaPage = require('./MediaPage'); const CameraPage = require('./CameraPage'); const ActionSheetPage = require('./ActionSheetPage'); const BarcodeScannerPage = require('./BarcodeScannerPage'); let navigationView = new NavigationView({left: 0, top: 0, right: 0, bottom: 0}) .appendTo(ui.contentView); let mainPage = new Page({ title: 'Cordova Examples' }).appendTo(navigationView); let contentContainer = new ScrollView({ left: 0, top: 0, right: 0, bottom: 0 }).appendTo(mainPage); ( device.platform === 'windows' ? [ MotionPage, NetworkPage ] : [ SharingPage, ToastPage, MotionPage, NetworkPage, CameraPage, BarcodeScannerPage, MediaPage, ActionSheetPage ] ).forEach(Page => { let page = new Page(); addPageSelector(page); }); function addPageSelector(page) { new Button({ left: 16, top: 'prev() 8', right: 16, text: page.title }).on('select', () => page.appendTo(navigationView)) .appendTo(contentContainer); }
const {Button, Page, NavigationView, ScrollView, ui} = require('tabris'); const ToastPage = require('./ToastPage'); const SharingPage = require('./SharingPage'); const MotionPage = require('./MotionPage'); const NetworkPage = require('./NetworkPage'); const MediaPage = require('./MediaPage'); const CameraPage = require('./CameraPage'); const ActionSheetPage = require('./ActionSheetPage'); const BarcodeScannerPage = require('./BarcodeScannerPage'); let navigationView = new NavigationView({left: 0, top: 0, right: 0, bottom: 0}) .appendTo(ui.contentView); let mainPage = new Page({ title: 'Cordova Examples' }).appendTo(navigationView); let contentContainer = new ScrollView({ left: 0, top: 0, right: 0, bottom: 0 }).appendTo(mainPage); [ SharingPage, ToastPage, MotionPage, NetworkPage, CameraPage, BarcodeScannerPage, MediaPage, ActionSheetPage ].forEach(Page => { let page = new Page(); addPageSelector(page); }); function addPageSelector(page) { new Button({ left: 16, top: 'prev() 8', right: 16, text: page.title }).on('select', () => page.appendTo(navigationView)) .appendTo(contentContainer); }
Fix : Render du flag
package tropicalescape; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import tropicalescape.physics.Hitbox; public class Flag extends GameObject { static final int DESC_HEIGHT_SHIFT = 15; static final String IMG_FILE = "res/flag.png"; String m_desc; static Image m_img; static { try { m_img = new Image(IMG_FILE); } catch (SlickException e) { e.printStackTrace(); } } Flag(String desc, float x, float y) { super(new Hitbox()); m_desc = desc; getPosition().x = x; getPosition().y = y; } @Override public void render(Graphics g) { Vector2f pos = getPosition(); m_img.draw(pos.x, pos.y); if (getPosition().y - DESC_HEIGHT_SHIFT < 0) { g.drawString(m_desc, pos.x, m_img.getHeight()); } else { g.drawString(m_desc, pos.x, pos.y - DESC_HEIGHT_SHIFT); } } @Override public void update(int delta) { } }
package tropicalescape; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import tropicalescape.physics.Hitbox; public class Flag extends GameObject { static final int DESC_HEIGHT_SHIFT = 15; static final String IMG_FILE = "res/flag.png"; String m_desc; static Image m_img; static { try { m_img = new Image(IMG_FILE); } catch (SlickException e) { e.printStackTrace(); } } Flag(String desc, float x, float y) { super(new Hitbox()); m_desc = desc; getPosition().x = x; getPosition().y = y; } @Override public void render(Graphics g) { m_img.draw(); if (getPosition().y - DESC_HEIGHT_SHIFT < 0) { g.drawString(m_desc, 0, m_img.getHeight()); } else { g.drawString(m_desc, 0, -DESC_HEIGHT_SHIFT); } } @Override public void update(int delta) { } }
Add full path to example import path
package sqlcond_test import ( "database/sql" "fmt" "time" "github.com/WatchBeam/sqlcond" _ "github.com/go-sql-driver/mysql" ) func mustExec(db *sql.DB, query string) { if _, err := db.Exec(query); err != nil { panic(err) } } func getDatabase() *sql.DB { db, err := sql.Open("mysql", "root@/sqlcond") if err != nil { panic(err) } mustExec(db, "DROP TABLE IF EXISTS tt;") mustExec(db, "CREATE TABLE `tt` (`id` INT NOT NULL);") return db } func ExampleSQLCond() { db := getDatabase() defer db.Close() go func() { time.Sleep(time.Second) mustExec(db, "INSERT INTO `tt` VALUES (1);") }() cond := sqlcond.New(db, sqlcond.Exists("tt", "id = ?", 1)) defer cond.Close() select { case err := <-cond.Errors: fmt.Println("An error occurred: " + err.Error()) case <-cond.C: fmt.Println("Row with ID 1 appeared") case <-time.After(time.Second * 5): fmt.Println("Timeout") } // Output: Row with ID 1 appeared }
package sqlcond_test import ( "database/sql" "fmt" "sqlcond" "time" _ "github.com/go-sql-driver/mysql" ) func mustExec(db *sql.DB, query string) { if _, err := db.Exec(query); err != nil { panic(err) } } func getDatabase() *sql.DB { db, err := sql.Open("mysql", "root@/sqlcond") if err != nil { panic(err) } mustExec(db, "DROP TABLE IF EXISTS tt;") mustExec(db, "CREATE TABLE `tt` (`id` INT NOT NULL);") return db } func ExampleSQLCond() { db := getDatabase() defer db.Close() go func() { time.Sleep(time.Second) mustExec(db, "INSERT INTO `tt` VALUES (1);") }() cond := sqlcond.New(db, sqlcond.Exists("tt", "id = ?", 1)) defer cond.Close() select { case err := <-cond.Errors: fmt.Println("An error occurred: " + err.Error()) case <-cond.C: fmt.Println("Row with ID 1 appeared") case <-time.After(time.Second * 5): fmt.Println("Timeout") } // Output: Row with ID 1 appeared }
Update array data for the second example
export default function move (array, moveIndex, toIndex) { /* #move - Moves an array item from one position in an array to another. Note: This is a pure function so a new array will be returned, instead of altering the array argument. Arguments: 1. array (String) : Array in which to move an item. (required) 2. moveIndex (Object) : The index of the item to move. (required) 3. toIndex (Object) : The index to move item at moveIndex to. (required) */ let itemRemovedArray = [ ...array.slice(0, moveIndex), ...array.slice(moveIndex + 1, array.length) ] return [ ...itemRemovedArray.slice(0, toIndex), array[moveIndex], ...itemRemovedArray.slice(toIndex, itemRemovedArray.length) ] } // Examples // -------- move(['a', 'b','c'], 2, 0) // -> ['c', 'a', 'b'] move([{name: 'Fred'}, {name: 'Barney'}, {name: 'Wilma'}, {name: 'Betty'}], 2, 1) // -> [{name: 'Fred', name: 'Wilman', name: 'Barney', name: 'Betty'}]
export default function move (array, moveIndex, toIndex) { /* #move - Moves an array item from one position in an array to another. Note: This is a pure function so a new array will be returned, instead of altering the array argument. Arguments: 1. array (String) : Array in which to move an item. (required) 2. moveIndex (Object) : The index of the item to move. (required) 3. toIndex (Object) : The index to move item at moveIndex to. (required) */ let itemRemovedArray = [ ...array.slice(0, moveIndex), ...array.slice(moveIndex + 1, array.length) ] return [ ...itemRemovedArray.slice(0, toIndex), array[moveIndex], ...itemRemovedArray.slice(toIndex, itemRemovedArray.length) ] } // Examples // -------- move(['a', 'b','c'], 2, 0) // -> ['c', 'a', 'b'] move([{name: 'Fred', name: 'Barney', name: 'Wilma', name: 'Betty'}], 2, 1) // -> [{name: 'Fred', name: 'Wilman', name: 'Barney', name: 'Betty'}]
Fix error when empty string
$(document).ready(function() { $("#search-lots").autocomplete({ minLength: 2, source: "/lots/search-ajax/", focus: function( event, ui ) { $("#search-lots").val( ui.item.name ); return false; }, select: function( event, ui ) { window.location.href = "/revenue/receipt/add/" + ui.item.name; return false; } }).autocomplete("instance")._renderItem = function(ul, item) { return $( "<li>" ) .append( "<div>" + item.name + " <small>" + item.address + "</small><br>" + item.owner__name + "</div>" ) .appendTo( ul ); }; }); function parse_decimal(str) { try { return new BigNumber(str.replace(/[^0-9\.]+/g,"")); } catch (e) { return new BigNumber('0.00'); } }
$(document).ready(function() { $("#search-lots").autocomplete({ minLength: 2, source: "/lots/search-ajax/", focus: function( event, ui ) { $("#search-lots").val( ui.item.name ); return false; }, select: function( event, ui ) { window.location.href = "/revenue/receipt/add/" + ui.item.name; return false; } }).autocomplete("instance")._renderItem = function(ul, item) { return $( "<li>" ) .append( "<div>" + item.name + " <small>" + item.address + "</small><br>" + item.owner__name + "</div>" ) .appendTo( ul ); }; }); function parse_decimal(str) { return str !== '' ? new BigNumber(str.replace(/[^0-9\.]+/g,"")) : new BigNumber('0.00'); }
Fix event parameter. Send 500 when file not found
const fs = require('fs') const path = require('path') const mime = require('mime-types') const { getElapsedTime } = require('../dates') module.exports = (req, res, next, {config, eventEmitter, log, bidCookieDetails}) => { const { startTime, upstream } = req const opts = upstream.upstream.options const file = path.join(opts.path, opts.file) const emitServingEvent = (err) => { const duration = getElapsedTime(startTime) if (err) { eventEmitter.emit('servingFileError', err, upstream, duration) } else { eventEmitter.emit('servingFile', upstream, duration) } } res.setHeader('content-type', mime.lookup(opts.file)) if (typeof opts.download === 'boolean' && opts.download) { res.setHeader('content-disposition', 'attachment; filename=' + opts.file) fs.readFile(file, opts.encoding, (err, data) => { emitServingEvent(err) res.send(err ? 500 : data) }) } else { emitServingEvent() fs.createReadStream(file).pipe(res) } }
const fs = require('fs') const path = require('path') const mime = require('mime-types') const { getElapsedTime } = require('../dates') module.exports = (req, res, next, {config, eventEmitter, log, bidCookieDetails}) => { const opts = req.upstream.upstream.options const file = path.join(opts.path, opts.file) res.setHeader('content-type', mime.lookup(opts.file)) if (typeof opts.download === 'boolean' && opts.download) { res.setHeader('content-disposition', 'attachment; filename=' + opts.file) fs.readFile(file, opts.encoding, (err, data) => { const duration = getElapsedTime(req.startTime) if (err) { eventEmitter.emit('servingFileError', err, req.upstreamm, duration) } else { eventEmitter.emit('servingFile', req.upstreamm, duration) } res.send(data) }) } else { fs.createReadStream(file).pipe(res) } }
Switch from subject to user.
exports = module.exports = function(authenticate) { return function verify(req, token, cb) { authenticate(token, function(err, tkn, ctx) { if (err) { return cb(err); } // TODO: Check confirmation methods, etc var info = {}; if (tkn.client) { info.client = tkn.client; } if (tkn.scope) { info.scope = tkn.scope; } if (!tkn.user) { return cb(null, false); } return cb(null, tkn.user, info); }); }; }; exports['@require'] = [ 'http://i.bixbyjs.org/security/authentication/token/authenticate' ];
exports = module.exports = function(authenticate) { return function verify(req, token, cb) { authenticate(token, function(err, tkn, ctx) { if (err) { return cb(err); } // TODO: Check confirmation methods, etc var info = {}; if (tkn.client) { info.client = tkn.client; } if (tkn.scope) { info.scope = tkn.scope; } if (!tkn.subject) { return cb(null, false); } return cb(null, tkn.subject, info); }); }; }; exports['@require'] = [ 'http://i.bixbyjs.org/security/authentication/token/authenticate' ];
Drop non-existent filter classes and log an error
<?php namespace Kibo\Phast\Filters\HTML\Composite; use Kibo\Phast\Environment\Package; use Kibo\Phast\Logging\LoggingTrait; use Kibo\Phast\ValueObjects\URL; class Factory { use LoggingTrait; public function make(array $config) { $composite = new Filter(URL::fromString($config['documents']['baseUrl']), $config['outputServerSideStats']); foreach (array_keys($config['documents']['filters']) as $class) { $package = Package::fromPackageClass($class); if ($package->hasFactory()) { $filter = $package->getFactory()->make($config); } elseif (!class_exists($class)) { $this->logger(__METHOD__, __LINE__) ->error("Skipping non-existent filter class: $class"); } else { $filter = new $class(); } $composite->addHTMLFilter($filter); } return $composite; } }
<?php namespace Kibo\Phast\Filters\HTML\Composite; use Kibo\Phast\Environment\Package; use Kibo\Phast\ValueObjects\URL; class Factory { public function make(array $config) { $composite = new Filter(URL::fromString($config['documents']['baseUrl']), $config['outputServerSideStats']); foreach (array_keys($config['documents']['filters']) as $class) { $package = Package::fromPackageClass($class); if ($package->hasFactory()) { $filter = $package->getFactory()->make($config); } else { $filter = new $class(); } $composite->addHTMLFilter($filter); } return $composite; } }
Fix issue where some how NUL (0 byte) is returned from getch on windows. The "fix" is to basically ignore the zero byte.
package gopass import ( "os" ) // getPasswd returns the input read from terminal. // If masked is true, typing will be matched by asterisks on the screen. // Otherwise, typing will echo nothing. func getPasswd(masked bool) []byte { var pass, bs, mask []byte if masked { bs = []byte("\b \b") mask = []byte("*") } for { if v := getch(); v == 127 || v == 8 { if l := len(pass); l > 0 { pass = pass[:l-1] os.Stdout.Write(bs) } } else if v == 13 || v == 10 { break } else if v != 0 { pass = append(pass, v) os.Stdout.Write(mask) } } println() return pass } // GetPasswd returns the password read from the terminal without echoing input. // The returned byte array does not include end-of-line characters. func GetPasswd() []byte { return getPasswd(false) } // GetPasswdMasked returns the password read from the terminal, echoing asterisks. // The returned byte array does not include end-of-line characters. func GetPasswdMasked() []byte { return getPasswd(true) }
package gopass import ( "os" ) // getPasswd returns the input read from terminal. // If masked is true, typing will be matched by asterisks on the screen. // Otherwise, typing will echo nothing. func getPasswd(masked bool) []byte { var pass, bs, mask []byte if masked { bs = []byte("\b \b") mask = []byte("*") } for { if v := getch(); v == 127 || v == 8 { if l := len(pass); l > 0 { pass = pass[:l-1] os.Stdout.Write(bs) } } else if v == 13 || v == 10 { break } else { pass = append(pass, v) os.Stdout.Write(mask) } } println() return pass } // GetPasswd returns the password read from the terminal without echoing input. // The returned byte array does not include end-of-line characters. func GetPasswd() []byte { return getPasswd(false) } // GetPasswdMasked returns the password read from the terminal, echoing asterisks. // The returned byte array does not include end-of-line characters. func GetPasswdMasked() []byte { return getPasswd(true) }
Fix asset import in ember-cli < 2.7
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-nouislider', included: function(app) { this._super.included(app); if (!process.env.EMBER_CLI_FASTBOOT) { // In nested addons, app.bowerDirectory might not be available var bowerDirectory = app.bowerDirectory || 'bower_components'; // In ember-cli < 2.7, this.import is not available, so fall back to use app.import var importShim = typeof this.import !== 'undefined' ? this : app; importShim.import({ development: bowerDirectory + '/nouislider/distribute/nouislider.js', production: bowerDirectory + '/nouislider/distribute/nouislider.min.js' }); importShim.import(bowerDirectory + '/nouislider/distribute/nouislider.min.css'); importShim.import('vendor/nouislider/shim.js', { exports: { 'noUiSlider': ['default'] } }); } } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-nouislider', included: function(app) { this._super.included(app); if (!process.env.EMBER_CLI_FASTBOOT) { var bowerDirectory = app.bowerDirectory || 'bower_components'; this.import({ development: bowerDirectory + '/nouislider/distribute/nouislider.js', production: bowerDirectory + '/nouislider/distribute/nouislider.min.js' }); this.import(bowerDirectory + '/nouislider/distribute/nouislider.min.css'); this.import('vendor/nouislider/shim.js', { exports: { 'noUiSlider': ['default'] } }); } } };
Add simple proprety and rule tests
// jshint ignore: start jest.autoMockOff(); const lib = require('../lib'), Value = lib.Value, Property = lib.Property, Rule = lib.Rule, render = lib.render; describe('build function', () => { it('renders Values', () => { expect( render(Value(2, 'px')) ).toBe('2px'); expect( render(Value('none')) ).toBe('none'); expect( render(Value('rgb', [ Value(0), Value(1), Value(2) ])) ).toBe('rgb(0, 1, 2)') // Shorthand function expect( render(Value('rgba', [1, 2, 3, 0.4])) ).toBe('rgba(1, 2, 3, 0.4)') }); it('renders Properties', () => { expect( render(Property('foo', Value('bar'))) ).toBe('foo: bar'); }); it('renders Rules', () => { expect(render(Rule('.foo', [ Property('bar', Value('baz')) ]), {indent:false})).toBe('.foo {bar: baz}') }); });
// jshint ignore: start jest.autoMockOff(); const lib = require('../lib'), Value = lib.Value, Property = lib.Property, Rule = lib.Rule, render = lib.render; describe('build function', () => { it('renders Values', () => { expect( render(Value(2, 'px')) ).toBe('2px'); expect( render(Value('none')) ).toBe('none'); expect( render(Value('rgb', [ Value(0), Value(1), Value(2) ])) ).toBe('rgb(0, 1, 2)') // Shorthand function expect( render(Value('rgba', [1, 2, 3, 0.4])) ).toBe('rgba(1, 2, 3, 0.4)') }); it('renders Properties', () => { }); it('renders Rules', () => { }); });
Add test to the update method on the DAL
var should = require('should'), queixinhas_db = require('../lib/db/db'); // Change the default BD configs queixinhas_db.db_name = 'queixinhas_tests'; describe('MongoDB accesser', function(){ it('should save, load, modify and remove a document in the database', function(done){ var value = Date.now(); queixinhas_db.save('test', {value: value}, function(error, id){ queixinhas_db.load('test', id, function(error, docs){ docs[0].value.should.equal(value); var new_value = Date.now(); queixinhas_db.update('test', id, {value: new_value}, function(error, doc){ doc.value.should.equal(new_value); queixinhas_db.remove('test', id, function(error, docs){ queixinhas_db.load('test', id, function(error, docs){ docs.length.should.equal(0); done(); }); }); }); }); }); }); });
var should = require('should'), queixinhas_db = require('../lib/db/db'); // Change the default BD configs queixinhas_db.db_name = 'queixinhas_tests'; describe('MongoDB accesser', function(){ it('should save, load and remove a document in the database', function(done){ var value = Date.now(); queixinhas_db.save('test', {value: value}, function(error, id){ queixinhas_db.load('test', id, function(error, docs){ docs[0].value.should.equal(value); queixinhas_db.remove('test', id, function(error, docs){ queixinhas_db.load('test', id, function(error, docs){ docs.length.should.equal(0); done(); }) }); }); }); }); });
Make it work more or less with HTML4
import {NAMESPACE, PREFIX} from './constants'; const ast = require('parametric-svg-ast'); const arrayFrom = require('array-from'); const startsWith = require('starts-with'); const ELEMENT_NODE = 1; const getChildren = ({children, childNodes}) => (children ? arrayFrom(children) : arrayFrom(childNodes).filter(({nodeType}) => nodeType === ELEMENT_NODE) ); const nodeBelongsToNamespace = ({namespace, prefix = null}, node) => ( (node.namespaceURI ? node.namespaceURI === namespace : (prefix !== null && startsWith(node.name, `${prefix}:`)) ) ); const getLocalName = (node) => (node.namespaceURI ? node.localName : node.name.replace(new RegExp(`^.*?:`), '') ); const crawl = (parentAddress) => (attributes, element, indexInParent) => { const address = parentAddress.concat(indexInParent); const currentAttributes = arrayFrom(element.attributes) .filter((node) => nodeBelongsToNamespace({ namespace: NAMESPACE, prefix: PREFIX, }, node)) .map((attribute) => ({ address, name: getLocalName(attribute), dependencies: [], // Proof of concept relation: () => Number(attribute.value), // Proof of concept })); return getChildren(element).reduce( crawl(address), attributes.concat(currentAttributes) ); }; export default (root) => { const attributes = getChildren(root).reduce(crawl([]), []); return ast({attributes, defaults: []}); };
import {NAMESPACE, PREFIX} from './constants'; const ast = require('parametric-svg-ast'); const arrayFrom = require('array-from'); const startsWith = require('starts-with'); const ELEMENT_NODE = 1; const getChildren = ({children, childNodes}) => (children ? arrayFrom(children) : arrayFrom(childNodes).filter(({nodeType}) => nodeType === ELEMENT_NODE) ); const nodeBelongsToNamespace = ({namespace, prefix = null}, node) => ( ('namespaceURI' in node ? node.namespaceURI === namespace : (prefix !== null && startsWith(node.name, `${prefix}:`)) ) ); const getLocalName = (node) => ('namespaceURI' in node ? node.localName : node.name.replace(new RegExp(`^.*?:`), '') ); const crawl = (parentAddress) => (attributes, element, indexInParent) => { const address = parentAddress.concat(indexInParent); const currentAttributes = arrayFrom(element.attributes) .filter((node) => nodeBelongsToNamespace({ namespace: NAMESPACE, prefix: PREFIX, }, node)) .map((attribute) => ({ address, name: getLocalName(attribute), dependencies: [], // Proof of concept relation: () => Number(attribute.value), // Proof of concept })); return getChildren(element).reduce( crawl(address), attributes.concat(currentAttributes) ); }; export default (root) => { const attributes = getChildren(root).reduce(crawl([]), []); return ast({attributes, defaults: []}); };
Fix test on Python 2.6
from __future__ import print_function, division, absolute_import, unicode_literals from fontTools.misc.py23 import * import unittest import fontTools.encodings.codecs # Not to be confused with "import codecs" class ExtendedCodecsTest(unittest.TestCase): def test_decode(self): self.assertEqual(b'x\xfe\xfdy'.decode(encoding="x-mac-japanese-ttx"), unichr(0x78)+unichr(0x2122)+unichr(0x00A9)+unichr(0x79)) def test_encode(self): self.assertEqual(b'x\xfe\xfdy', (unichr(0x78)+unichr(0x2122)+unichr(0x00A9)+unichr(0x79)).encode("x-mac-japanese-ttx")) if __name__ == '__main__': unittest.main()
from __future__ import print_function, division, absolute_import, unicode_literals from fontTools.misc.py23 import * import unittest import fontTools.encodings.codecs # Not to be confused with "import codecs" class ExtendedCodecsTest(unittest.TestCase): def test_decode(self): self.assertEqual(b'x\xfe\xfdy'.decode(encoding="x-mac-japanese-ttx"), unichr(0x78)+unichr(0x2122)+unichr(0x00A9)+unichr(0x79)) def test_encode(self): self.assertEqual(b'x\xfe\xfdy', (unichr(0x78)+unichr(0x2122)+unichr(0x00A9)+unichr(0x79)).encode(encoding="x-mac-japanese-ttx")) if __name__ == '__main__': unittest.main()
Add absolute URL generation without consideration of subdomains or params in domains
<?php namespace Tightenco\Ziggy; use Illuminate\Routing\Router; class BladeRouteGenerator { private $router; public $routes; public function __construct(Router $router) { $this->router = $router; } public function generate() { $json = (string) $this->nameKeyedRoutes(); $appUrl = rtrim(config('app.url'), '/') . '/'; return <<<EOT <script type="text/javascript"> var namedRoutes = JSON.parse('$json'), baseUrl = '$appUrl'; function route (name, params, absolute = true) { return (absolute ? baseUrl : '') + namedRoutes[name].uri.replace( /\{([^}]+)\}/, function (tag) { return params[tag.replace(/\{|\}/gi, '')]; } ); } </script> EOT; } public function nameKeyedRoutes() { return collect($this->router->getRoutes()->getRoutesByName()) ->map(function ($route) { return collect($route)->only(['uri', 'methods']); }); } }
<?php namespace Tightenco\Ziggy; use Illuminate\Routing\Router; class BladeRouteGenerator { private $router; public $routes; public function __construct(Router $router) { $this->router = $router; } public function generate() { $json = (string) $this->nameKeyedRoutes(); return <<<EOT <script type="text/javascript"> var namedRoutes = JSON.parse('$json'); function route (name, params) { return namedRoutes[name].uri.replace( /\{([^}]+)\}/, function (tag) { return params[tag.replace(/\{|\}/gi, '')]; } ); } </script> EOT; } public function nameKeyedRoutes() { return collect($this->router->getRoutes()->getRoutesByName()) ->map(function ($route) { return collect($route)->only(['uri', 'methods']); }); } }
Change icon_url to use adorable.io
var _ = require('lodash'); var logger = require('winston'); var request = require('superagent'); function SlackGateway(incomingURL, channelMapping) { this.incomingURL = incomingURL; this.invertedMapping = _.invert(channelMapping); } SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) { var payload = { username: author, icon_url: 'http://api.adorable.io/avatars/48/' + author + '.png', channel: this.invertedMapping[ircChannel], text: message }; request .post(this.incomingURL) .send(payload) .set('Accept', 'application/json') .end(function(err, res) { if (err) return logger.error('Couldn\'t post message to Slack', err); logger.debug('Posted message to Slack', res.body, res.statusCode); }); }; module.exports = SlackGateway;
var _ = require('lodash'); var logger = require('winston'); var request = require('superagent'); function SlackGateway(incomingURL, channelMapping) { this.incomingURL = incomingURL; this.invertedMapping = _.invert(channelMapping); } SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) { var payload = { username: author, icon_url: 'https://github.com/identicons/' + author + '.png', channel: this.invertedMapping[ircChannel], text: message }; request .post(this.incomingURL) .send(payload) .set('Accept', 'application/json') .end(function(err, res) { if (err) return logger.error('Couldn\'t post message to Slack', err); logger.debug('Posted message to Slack', res.body, res.statusCode); }); }; module.exports = SlackGateway;
Add description to FieldtypeDatetime's 'format' argument.
<?php namespace ProcessWire\GraphQL\Field\Traits; use Youshido\GraphQL\Config\Field\FieldConfig; use Youshido\GraphQL\Execution\ResolveInfo; use Youshido\GraphQL\Field\InputField; use Youshido\GraphQL\Type\Scalar\StringType; use ProcessWire\GraphQL\Utils; use ProcessWire\NullPage; use ProcessWire\FieldtypeDatetime; trait DatetimeResolverTrait { public function build(FieldConfig $config) { $config->addArgument(new InputField([ 'name' => 'format', 'type' => new StringType(), 'description' => 'PHP date formatting string. Refer to https://devdocs.io/php/function.date', ])); } public function resolve($value, array $args, ResolveInfo $info) { $fieldName = $this->getName(); if (isset($args['format'])) { $format = $args['format']; $rawValue = $value->$fieldName; if (Utils::fields()->get($fieldName) instanceof FieldtypeDatetime) { $rawValue = $value->getUnformatted($fieldName); } return date($format, $rawValue); } return $value->$fieldName; } }
<?php namespace ProcessWire\GraphQL\Field\Traits; use Youshido\GraphQL\Config\Field\FieldConfig; use Youshido\GraphQL\Execution\ResolveInfo; use Youshido\GraphQL\Field\InputField; use Youshido\GraphQL\Type\Scalar\StringType; use ProcessWire\GraphQL\Utils; use ProcessWire\NullPage; use ProcessWire\FieldtypeDatetime; trait DatetimeResolverTrait { public function build(FieldConfig $config) { $config->addArgument(new InputField([ 'name' => 'format', 'type' => new StringType(), ])); } public function resolve($value, array $args, ResolveInfo $info) { $fieldName = $this->getName(); if (isset($args['format'])) { $format = $args['format']; $rawValue = $value->$fieldName; if (Utils::fields()->get($fieldName) instanceof FieldtypeDatetime) { $rawValue = $value->getUnformatted($fieldName); } return date($format, $rawValue); } return $value->$fieldName; } }
Move code to correct semantics in spec
describe("Implement queue with two stacks", function() { const Queue = new QueueTwoStacks(); Queue.enqueue(1); Queue.enqueue(2); Queue.enqueue(3); describe("enqueue()", function() { it("appends an element to tail", function() { Queue.enqueue(4); const expected = [1,2,3,4]; expect(Queue.inStack).toEqual(expected); }) it("appends an element correctly after dequeing", function() { Queue.dequeue(); Queue.enqueue(5); const expected = [2,3,4,5]; expect(Queue.inStack).toEqual(expected); }) }); describe("dequeue()", function () { it("removes an element from head", function () { Queue.dequeue(); const expected = [3,4,5]; expect(Queue.inStack).toEqual(expected); }); it("throws an error when queue is empty", function() { Queue.dequeue(); Queue.dequeue(); Queue.dequeue(); expect(function() { Queue.dequeue(); }).toThrow(); }) }); })
describe("Implement queue with two stacks", function() { const Queue = new QueueTwoStacks(); Queue.enqueue(1); Queue.enqueue(2); Queue.enqueue(3); describe("enqueue()", function() { it("appends an element to tail", function() { Queue.enqueue(4); const expected = [1,2,3,4]; expect(Queue.inStack).toEqual(expected); }) it("appends an element correctly after dequeing", function() { Queue.dequeue(); Queue.enqueue(5); const expected = [2,3,4,5]; expect(Queue.inStack).toEqual(expected); }) }) describe("dequeue()", function () { it("removes an element from head", function () { Queue.dequeue(); const expected = [3,4,5]; expect(Queue.inStack).toEqual(expected); }) }) describe("when queue is empty", function() { it("throws an error", function() { Queue.dequeue(); Queue.dequeue(); Queue.dequeue(); expect(function() { Queue.dequeue(); }).toThrow(); }) }) })
Add docblock to test function
<?php namespace MarkWilson\Test; require_once __DIR__ . '/../VerbalExpression.php'; use MarkWilson\VerbalExpression; /** * Class VerbalExpressionOutputTest * * @package MarkWilson\Test * @author Mark Wilson <mark@rippleffect.com> */ class VerbalExpressionOutputTest extends \PHPUnit_Framework_TestCase { /** * Test equivalent test from original repo * * @return void */ public function testEquivalentFromJehna() { $verbalExpression = new VerbalExpression(); $verbalExpression->startOfLine() ->then('http') ->maybe('s') ->then('://') ->maybe('www.') ->anythingBut(' ') ->endOfLine(); $this->assertEquals($verbalExpression->compile(), '^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$'); $this->assertEquals(1, preg_match($verbalExpression->toString(), 'https://www.google.com')); } }
<?php namespace MarkWilson\Test; require_once __DIR__ . '/../VerbalExpression.php'; use MarkWilson\VerbalExpression; /** * Class VerbalExpressionOutputTest * * @package MarkWilson\Test * @author Mark Wilson <mark@rippleffect.com> */ class VerbalExpressionOutputTest extends \PHPUnit_Framework_TestCase { public function testEquivalentFromJehna() { $verbalExpression = new VerbalExpression(); $verbalExpression->startOfLine() ->then('http') ->maybe('s') ->then('://') ->maybe('www.') ->anythingBut(' ') ->endOfLine(); $this->assertEquals($verbalExpression->compile(), '^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$'); $this->assertEquals(1, preg_match($verbalExpression->toString(), 'https://www.google.com')); } }
Fix endpoints to reflect their correct per-region values.
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.cloud.pubsublite; public final class Endpoints { public static String dataEndpoint(CloudRegion region) { return region.value() + "-pubsublite.googleapis.com"; } public static String adminEndpoint(CloudRegion region) { return region.value() + "-pubsublite.googleapis.com"; } public static String cursorEndpoint(CloudRegion region) { return region.value() + "-pubsublite.googleapis.com"; } private Endpoints() {} }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.cloud.pubsublite; public final class Endpoints { public static String dataEndpoint(CloudRegion region) { return region + "-pubsublite.googleapis.com/v1/data"; } public static String adminEndpoint(CloudRegion region) { return region + "-pubsublite.googleapis.com/v1/admin"; } public static String cursorEndpoint(CloudRegion region) { return region + "-pubsublite.googleapis.com/v1/cursor"; } private Endpoints() {} }
Fix CSS problem when Flexx is enbedded in page-app
""" Layout widgets """ from . import Widget class Layout(Widget): """ Abstract class for widgets that organize their child widgets. Panel widgets are layouts that do not take the natural size of their content into account, making them more efficient and suited for high-level layout. Other layouts, like HBox, are more suited for laying out content where the natural size is important. """ CSS = """ body { margin: 0; padding: 0; /*overflow: hidden;*/ } .flx-Layout { /* sizing of widgets/layouts inside layout is defined per layout */ width: 100%; height: 100%; margin: 0px; padding: 0px; border-spacing: 0px; border: 0px; } """
""" Layout widgets """ from . import Widget class Layout(Widget): """ Abstract class for widgets that organize their child widgets. Panel widgets are layouts that do not take the natural size of their content into account, making them more efficient and suited for high-level layout. Other layouts, like HBox, are more suited for laying out content where the natural size is important. """ CSS = """ body { margin: 0; padding: 0; overflow: hidden; } .flx-Layout { /* sizing of widgets/layouts inside layout is defined per layout */ width: 100%; height: 100%; margin: 0px; padding: 0px; border-spacing: 0px; border: 0px; } """
Check framework has the studios lot before showing start page
# -*- coding: utf-8 -*- from __future__ import unicode_literals from app import data_api_client from flask import abort, render_template from ...helpers.buyers_helpers import get_framework_and_lot from ...main import main @main.route('/buyers/frameworks/<framework_slug>/requirements/user-research-studios', methods=['GET']) def studios_start_page(framework_slug): # Check framework is live and has the user-research-studios lot get_framework_and_lot(framework_slug, 'user-research-studios', data_api_client, status='live') return render_template( "buyers/studios_start_page.html" ), 200 @main.route('/buyers/frameworks/<framework_slug>/requirements/<lot_slug>', methods=['GET']) def info_page_for_starting_a_brief(framework_slug, lot_slug): framework, lot = get_framework_and_lot(framework_slug, lot_slug, data_api_client, status='live', must_allow_brief=True) return render_template( "buyers/start_brief_info.html", framework=framework, lot=lot ), 200
# -*- coding: utf-8 -*- from __future__ import unicode_literals from app import data_api_client from flask import abort, render_template from ...helpers.buyers_helpers import get_framework_and_lot from ...main import main @main.route('/buyers/frameworks/<framework_slug>/requirements/user-research-studios', methods=['GET']) def studios_start_page(framework_slug): framework = data_api_client.get_framework(framework_slug)['frameworks'] if framework['status'] != 'live': abort(404) return render_template( "buyers/studios_start_page.html" ), 200 @main.route('/buyers/frameworks/<framework_slug>/requirements/<lot_slug>', methods=['GET']) def info_page_for_starting_a_brief(framework_slug, lot_slug): framework, lot = get_framework_and_lot(framework_slug, lot_slug, data_api_client, status='live', must_allow_brief=True) return render_template( "buyers/start_brief_info.html", framework=framework, lot=lot ), 200
Add missing properties to flash message
<?php namespace Knp\RadBundle\Flash; class Message { private $template; private $parameters; private $pluralization; public function __construct($template, array $parameters = array(), $pluralization = null) { $this->template = $template; $this->parameters = $parameters; $this->pluralization = $pluralization; } public function getTemplate() { return $this->template; } public function getParameters() { return $this->parameters; } public function getPluralization() { return $this->pluralization; } public function __toString() { return strtr($this->template, $this->parameters); } }
<?php namespace Knp\RadBundle\Flash; class Message { private $template; public function __construct($template, array $parameters = array(), $pluralization = null) { $this->template = $template; $this->parameters = $parameters; $this->pluralization = $pluralization; } public function getTemplate() { return $this->template; } public function getParameters() { return $this->parameters; } public function getPluralization() { return $this->pluralization; } public function __toString() { return strtr($this->template, $this->parameters); } }
Add of getPrompt function to redisplay the prompt when search field is empty. git-svn-id: 36dcc065b18e9ace584b1c777eaeefb1d96b1ee8@290117 13f79535-47bb-0310-9956-ffa450edef68
/* * Copyright 2002-2004 The Apache Software Foundation or its licensors, * as applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * getBlank script - when included in a html file and called from a form text field, will set the value of this field to "" * if the text value is still the standard value. * getPrompt script - when included in a html file and called from a form text field, will set the value of this field to the prompt * if the text value is empty. * * Typical usage: * <script type="text/javascript" language="JavaScript" src="getBlank.js"></script> * <input type="text" id="query" value="Search the site:" onFocus="getBlank (this, 'Search the site:');" onBlur="getPrompt (this, 'Search the site:');"/> */ <!-- function getBlank (form, stdValue){ if (form.value == stdValue){ form.value = ''; } return true; } function getPrompt (form, stdValue){ if (form.value == ''){ form.value = stdValue; } return true; } //-->
/* * Copyright 2002-2004 The Apache Software Foundation or its licensors, * as applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This script, when included in a html file and called from a form text field, will set the value of this field to "" * if the text value is still the standard value. * * Typical usage: * <script type="text/javascript" language="JavaScript" src="getBlank.js"></script> * <input type="text" id="query" value="Search the site:" onFocus="getBlank (this, 'Search the site:');"/> */ <!-- function getBlank (form, stdValue){ if (form.value == stdValue){ form.value = ''; } return true; } //-->
Fix chat with us on intercom text wrapping fbshipit-source-id: 498ec09
import StyleConstants from './StyleConstants'; export default { input: { borderColor: StyleConstants.colorBorder, borderWidth: 1, borderRadius: 5, borderStyle: 'solid', paddingTop: 8, paddingRight: 8, paddingBottom: 8, paddingLeft: 8, }, hoverBox: { // gray border and box shadow backgroundColor: 'white', borderColor: StyleConstants.colorBorder, borderStyle: 'solid', borderWidth: 1, boxShadow: `0 5px 10px rgba(0, 0, 0, 0.2)`, color: StyleConstants.colorText, minWidth: 180, }, errorMessage: { color: StyleConstants.colorError, fontSize: 13, fontWeight: 'bold', marginBottom: 20, textAlign: 'center', }, };
import StyleConstants from './StyleConstants'; export default { input: { borderColor: StyleConstants.colorBorder, borderWidth: 1, borderRadius: 5, borderStyle: 'solid', paddingTop: 8, paddingRight: 8, paddingBottom: 8, paddingLeft: 8, }, hoverBox: { // gray border and box shadow backgroundColor: 'white', borderColor: StyleConstants.colorBorder, borderStyle: 'solid', borderWidth: 1, boxShadow: `0 5px 10px rgba(0, 0, 0, 0.2)`, color: StyleConstants.colorText, minWidth: 170, }, errorMessage: { color: StyleConstants.colorError, fontSize: 13, fontWeight: 'bold', marginBottom: 20, textAlign: 'center', }, };
Remove IDs for all candidates, not just Zac
import json from django.core.management.base import BaseCommand from django.db import transaction from people.models import Person from candidates.views.version_data import get_change_metadata from popolo.models import Identifier class Command(BaseCommand): def handle(self, *args, **options): schemes = ("yournextmp-candidate", "popit-person") # We can't use the GFK any more because we just deleted it, but the # content is still there identifiers = Identifier.objects.filter(scheme__in=schemes).values_list( "object_id", flat=True ) for person in Person.objects.filter(pk__in=identifiers): with transaction.atomic(): meta_data = get_change_metadata( None, "Removing legacy identifiers" ) meta_data["username"] = "CandidateBot" person.record_version(meta_data) person.save()
import json from django.core.management.base import BaseCommand from django.db import transaction from people.models import Person from candidates.views.version_data import get_change_metadata from popolo.models import Identifier class Command(BaseCommand): def handle(self, *args, **options): schemes = ("yournextmp-candidate", "popit-person") # We can't use the GFK any more because we just deleted it, but the # content is still there identifiers = Identifier.objects.filter(scheme__in=schemes).values_list( "object_id", flat=True ) for person in Person.objects.filter(pk__in=identifiers).filter(pk=502): with transaction.atomic(): meta_data = get_change_metadata( None, "Removing legacy identifiers" ) meta_data["username"] = "CandidateBot" person.record_version(meta_data) person.save()
Remove useless cloning of cached node
/** * Module dependencies. */ var crypto = require('crypto'); var MemoryCache = module.exports = function() { this._cache = {}; }; /** * Set cache item with given `key` to `value`. * * @param {String} key * @param {Object} value * @api private */ MemoryCache.prototype.set = function(key, value) { this._cache[key] = value.clone(); }; /** * Get cache item with given `key`. * * @param {String} key * @return {Object} * @api private */ MemoryCache.prototype.get = function(key) { return this._cache[key]; }; /** * Check if cache has given `key`. * * @param {String} key * @return {Boolean} * @api private */ MemoryCache.prototype.has = function(key) { return key in this._cache; }; /** * Generate key for the source `str` with `options`. * * @param {String} str * @param {Object} options * @return {String} * @api private */ MemoryCache.prototype.key = function(str, options) { var hash = crypto.createHash('sha1'); hash.update(str + options.prefix); return hash.digest('hex'); };
/** * Module dependencies. */ var crypto = require('crypto'); var MemoryCache = module.exports = function() { this._cache = {}; }; /** * Set cache item with given `key` to `value`. * * @param {String} key * @param {Object} value * @api private */ MemoryCache.prototype.set = function(key, value) { this._cache[key] = value.clone(); }; /** * Get cache item with given `key`. * * @param {String} key * @return {Object} * @api private */ MemoryCache.prototype.get = function(key) { return this._cache[key].clone(); }; /** * Check if cache has given `key`. * * @param {String} key * @return {Boolean} * @api private */ MemoryCache.prototype.has = function(key) { return key in this._cache; }; /** * Generate key for the source `str` with `options`. * * @param {String} str * @param {Object} options * @return {String} * @api private */ MemoryCache.prototype.key = function(str, options) { var hash = crypto.createHash('sha1'); hash.update(str + options.prefix); return hash.digest('hex'); };
Add cover test : core factories
from django.test import TestCase from .. import factories class CoreFactoriesTest(TestCase): """ Ensure factories work as expected. Here we just call each one to ensure they do not trigger any random error without verifying any other expectation. """ def test_path_factory(self): factories.PathFactory() def test_topology_mixin_factory(self): factories.TopologyFactory() def test_path_aggregation_factory(self): factories.PathAggregationFactory() def test_source_management_factory(self): factories.PathSourceFactory() def test_challenge_management_factory(self): factories.StakeFactory() def test_usage_management_factory(self): factories.UsageFactory() def test_network_management_factory(self): factories.NetworkFactory() def test_path_management_factory(self): factories.TrailFactory() def test_path_in_bounds_existing_factory(self): factories.PathFactory.create() factories.PathInBoundsExistingGeomFactory() def test_path_in_bounds_not_existing_factory(self): with self.assertRaises(IndexError): factories.PathInBoundsExistingGeomFactory()
from django.test import TestCase from .. import factories class CoreFactoriesTest(TestCase): """ Ensure factories work as expected. Here we just call each one to ensure they do not trigger any random error without verifying any other expectation. """ def test_path_factory(self): factories.PathFactory() def test_topology_mixin_factory(self): factories.TopologyFactory() def test_path_aggregation_factory(self): factories.PathAggregationFactory() def test_source_management_factory(self): factories.PathSourceFactory() def test_challenge_management_factory(self): factories.StakeFactory() def test_usage_management_factory(self): factories.UsageFactory() def test_network_management_factory(self): factories.NetworkFactory() def test_path_management_factory(self): factories.TrailFactory()
Fix project description for pypi
from setuptools import setup, find_packages requirements = [ 'GitPython == 1.0.1', 'docker-py >= 1.7.0', 'requests ==2.7.0' ] setup_requirements = [ 'flake8' ] description = """ Tool for releasing docker images. It is useful when your docker image files are under continuous development and you want to have a convenient way to release (publish) them. This utility supports: - tagging git repository when a docker image gets released - tagging docker image with a git hash commit - incrementing docker image version (tag) - updating 'latest' tag in the docker hub """ setup( name='docker-release', version='0.3-SNAPSHOT', description=description, author='Grzegorz Kokosinski', author_email='g.kokosinski a) gmail.com', keywords='docker image release', url='https://github.com/kokosing/docker-release', packages=find_packages(), package_dir={'docker_release': 'docker_release'}, install_requires=requirements, setup_requires=setup_requirements, entry_points={'console_scripts': ['docker-release = docker_release.main:main']} )
from setuptools import setup, find_packages requirements = [ 'GitPython == 1.0.1', 'docker-py >= 1.7.0', 'requests ==2.7.0' ] setup_requirements = [ 'flake8' ] setup( name='docker-release', version='0.3-SNAPSHOT', description='Tool for releasing docker images.', author='Grzegorz Kokosinski', author_email='g.kokosinski a) gmail.com', keywords='docker image release', url='https://github.com/kokosing/docker_release', packages=find_packages(), package_dir={'docker_release': 'docker_release'}, install_requires=requirements, setup_requires=setup_requirements, entry_points={'console_scripts': ['docker-release = docker_release.main:main']} )
Enable to use env variable. Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php return [ /* |---------------------------------------------------------------------- | Default Driver |---------------------------------------------------------------------- | | Set default driver for Orchestra\Memory. | */ 'driver' => env('MEMORY_DRIVER', 'fluent.default'), /* |---------------------------------------------------------------------- | Cache configuration |---------------------------------------------------------------------- */ 'cache' => [], /* |---------------------------------------------------------------------- | Eloquent configuration |---------------------------------------------------------------------- */ 'eloquent' => [ 'default' => [ 'model' => '\Orchestra\Memory\Model', 'cache' => false, ], ], /* |---------------------------------------------------------------------- | Fluent configuration |---------------------------------------------------------------------- */ 'fluent' => [ 'default' => [ 'table' => 'orchestra_options', 'cache' => false, ], ], /* |---------------------------------------------------------------------- | Runtime configuration |---------------------------------------------------------------------- */ 'runtime' => [], ];
<?php return [ /* |---------------------------------------------------------------------- | Default Driver |---------------------------------------------------------------------- | | Set default driver for Orchestra\Memory. | */ 'driver' => 'fluent.default', /* |---------------------------------------------------------------------- | Cache configuration |---------------------------------------------------------------------- */ 'cache' => [], /* |---------------------------------------------------------------------- | Eloquent configuration |---------------------------------------------------------------------- */ 'eloquent' => [ 'default' => [ 'model' => '\Orchestra\Memory\Model', 'cache' => false, ], ], /* |---------------------------------------------------------------------- | Fluent configuration |---------------------------------------------------------------------- */ 'fluent' => [ 'default' => [ 'table' => 'orchestra_options', 'cache' => false, ], ], /* |---------------------------------------------------------------------- | Runtime configuration |---------------------------------------------------------------------- */ 'runtime' => [], ];
Enable HTTP Cache on Prod
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. /* $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader); $loader->unregister(); $apcLoader->register(true); */ require_once __DIR__.'/../app/AppKernel.php'; require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', true); $kernel->loadClassCache(); $kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. /* $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader); $loader->unregister(); $apcLoader->register(true); */ require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);