text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add option for multiple inner expectations | <?php
namespace Matthias\Codesniffer\Sequence\Expectation;
use Matthias\Codesniffer\Sequence\Exception\ExpectationNotMatched;
use Matthias\Codesniffer\Sequence\SequenceInterface;
class Quantity implements ExpectationInterface
{
const ANY = null;
/**
* @var $innerExpectation ExpectationInterface[]
*/
private $innerExpectations;
private $minimum;
private $maximum;
public function __construct($innerExpectation, $minimum, $maximum)
{
// TODO this should be refactored, probably introduce an "iterator" expectation
$this->innerExpectations = is_array($innerExpectation) ? $innerExpectation : array($innerExpectation);
$this->minimum = $minimum;
$this->maximum = $maximum;
}
public function match(SequenceInterface $sequence)
{
$occurrences = 0;
while (!$sequence->endOfSequence()) {
try {
foreach ($this->innerExpectations as $innerExpectation) {
$innerExpectation->match($sequence);
$sequence->next();
}
$occurrences++;
} catch (ExpectationNotMatched $exception) {
break;
}
}
$this->matchOccurrences($occurrences);
}
private function matchOccurrences($occurrences)
{
if ($this->minimum !== null && $occurrences < $this->minimum) {
throw new ExpectationNotMatched();
}
if ($this->maximum !== null && $occurrences > $this->maximum) {
throw new ExpectationNotMatched();
}
}
}
| <?php
namespace Matthias\Codesniffer\Sequence\Expectation;
use Matthias\Codesniffer\Sequence\Exception\ExpectationNotMatched;
use Matthias\Codesniffer\Sequence\SequenceInterface;
class Quantity implements ExpectationInterface
{
const ANY = null;
private $innerExpectation;
private $minimum;
private $maximum;
public function __construct(ExpectationInterface $innerExpectation, $minimum, $maximum)
{
$this->innerExpectation = $innerExpectation;
$this->minimum = $minimum;
$this->maximum = $maximum;
}
public function match(SequenceInterface $sequence)
{
$occurrences = 0;
while (!$sequence->endOfSequence()) {
try {
$this->innerExpectation->match($sequence);
$occurrences++;
$sequence->next();
} catch (ExpectationNotMatched $exception) {
break;
}
}
$this->matchOccurrences($occurrences);
}
private function matchOccurrences($occurrences)
{
if ($this->minimum !== null && $occurrences < $this->minimum) {
throw new ExpectationNotMatched();
}
if ($this->maximum !== null && $occurrences > $this->maximum) {
throw new ExpectationNotMatched();
}
}
}
|
fix(suspension/actionButton): Reorder action button in toolbar
related to CAM-1403 | ngDefine('cockpit.plugin.base.views', ['require'], function(module, require) {
var Controller = [ '$scope', '$dialog',
function($scope, $dialog) {
$scope.openDialog = function () {
var dialog = $dialog.dialog({
resolve: {
processData: function() { return $scope.processData; },
processInstance: function() { return $scope.processInstance; }
},
controller: 'UpdateProcessInstanceSuspensionStateController',
templateUrl: require.toUrl('./update-suspension-state-dialog.html')
});
dialog.open().then(function(result) {
// dialog closed. YEA!
if (result.status === 'SUCCESS') {
$scope.processInstance.suspended = result.suspended;
$scope.processData.set('filter', angular.extend({}, $scope.filter));
}
});
};
}];
var Configuration = function PluginConfiguration(ViewsProvider) {
ViewsProvider.registerDefaultView('cockpit.processInstance.action', {
id: 'update-suspension-state-action',
label: 'Update Suspension State',
url: 'plugin://base/static/app/views/processInstance/update-suspension-state-action.html',
controller: Controller,
priority: 5
});
};
Configuration.$inject = ['ViewsProvider'];
module.config(Configuration);
});
| ngDefine('cockpit.plugin.base.views', ['require'], function(module, require) {
var Controller = [ '$scope', '$dialog',
function($scope, $dialog) {
$scope.openDialog = function () {
var dialog = $dialog.dialog({
resolve: {
processData: function() { return $scope.processData; },
processInstance: function() { return $scope.processInstance; }
},
controller: 'UpdateProcessInstanceSuspensionStateController',
templateUrl: require.toUrl('./update-suspension-state-dialog.html')
});
dialog.open().then(function(result) {
// dialog closed. YEA!
if (result.status === 'SUCCESS') {
$scope.processInstance.suspended = result.suspended;
$scope.processData.set('filter', angular.extend({}, $scope.filter));
}
});
};
}];
var Configuration = function PluginConfiguration(ViewsProvider) {
ViewsProvider.registerDefaultView('cockpit.processInstance.action', {
id: 'update-suspension-state-action',
label: 'Update Suspension State',
url: 'plugin://base/static/app/views/processInstance/update-suspension-state-action.html',
controller: Controller,
priority: 50
});
};
Configuration.$inject = ['ViewsProvider'];
module.config(Configuration);
});
|
Fix bug where client didn't use proper host name | import React, { Component } from 'react';
import SocketIOClient from 'socket.io-client';
import logo from '../assets/logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.socket = SocketIOClient(location.origin);
this.keyPressEvent = this.keyPressEvent.bind(this);
}
keyPressEvent() {
/**test to send out Object--not yet working
var name = 'Alex';
var nsheid = 300;
var permit = 'Student';
var data = {
Name: name,
NSHE: nsheid,
Permit: permit
};
**/
this.socket.emit('hello', 'Hello from application');
this.socket.on('message', (message)=>{
console.log('Received the following messge from server: ' + message);
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<button
onClick={this.keyPressEvent}>
Send Message
</button>
</div>
);
}
/* //Performing an API Request
//www.raywenderlich.com/126063/react-native-tutorial
*/
}
export default App;
| import React, { Component } from 'react';
import SocketIOClient from 'socket.io-client';
import logo from '../assets/logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.socket = SocketIOClient('http://localhost:3000');
this.keyPressEvent = this.keyPressEvent.bind(this);
}
keyPressEvent() {
/**test to send out Object--not yet working
var name = 'Alex';
var nsheid = 300;
var permit = 'Student';
var data = {
Name: name,
NSHE: nsheid,
Permit: permit
};
**/
this.socket.emit('hello', 'Hello from application');
this.socket.on('message', (message)=>{
console.log('Received the following messge from server: ' + message);
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<button
onClick={this.keyPressEvent}>
Send Message
</button>
</div>
);
}
/* //Performing an API Request
//www.raywenderlich.com/126063/react-native-tutorial
*/
}
export default App;
|
Add migrations folder to build. | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-oidc-provider',
version='0.0.4',
packages=[
'oidc_provider', 'oidc_provider/lib', 'oidc_provider/lib/endpoints',
'oidc_provider/lib/utils', 'oidc_provider/tests', 'oidc_provider/migrations',
],
include_package_data=True,
license='MIT License',
description='OpenID Connect Provider implementation for Django.',
long_description=README,
url='http://github.com/juanifioren/django-oidc-provider',
author='Juan Ignacio Fiorentino',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=[
'pyjwt==1.1.0',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-oidc-provider',
version='0.0.4',
packages=[
'oidc_provider', 'oidc_provider/lib', 'oidc_provider/lib/endpoints',
'oidc_provider/lib/utils', 'oidc_provider/tests',
],
include_package_data=True,
license='MIT License',
description='OpenID Connect Provider implementation for Django.',
long_description=README,
url='http://github.com/juanifioren/django-oidc-provider',
author='Juan Ignacio Fiorentino',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=[
'pyjwt==1.1.0',
],
)
|
Switch from fetch to beacon | document
.querySelectorAll('pre')
.forEach(node => {
node.title = 'Copy to clipboard';
node.classList.add('copy');
node.onclick = function (event) {
navigator.clipboard.writeText(event.target.innerText);
};
});
(function () {
const themes = [ 'light', 'dark', 'markdown' ];
let theme = localStorage.getItem('theme') ||
(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light');
const updateTheme = function () {
document.body.className = theme;
if (theme === 'markdown') {
document.querySelectorAll('img').forEach(node => { node.dataset.src = node.src; node.src = ''; });
}
else {
document.querySelectorAll('img').forEach(node => { node.src = node.dataset.src || node.src; });
}
};
updateTheme();
const themeSwitch = document.getElementById('theme-switch');
themeSwitch.style.display = null;
themeSwitch.onclick = function () {
theme = themes[(themes.indexOf(theme) + 1) % themes.length];
localStorage.setItem('theme', theme);
updateTheme();
};
}());
(function () {
if (navigator.doNotTrack === '1' || localStorage.getItem('dnt')) return;
const payload = {
location: document.location.pathname,
referrer: document.referrer
};
navigator.sendBeacon(
'https://log.lusmo.re/api/log',
JSON.stringify(payload)
);
}()); | document
.querySelectorAll('pre')
.forEach(node => {
node.title = 'Copy to clipboard';
node.classList.add('copy');
node.onclick = function (event) {
navigator.clipboard.writeText(event.target.innerText);
};
});
(function () {
const themes = [ 'light', 'dark', 'markdown' ];
let theme = localStorage.getItem('theme') ||
(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light');
const updateTheme = function () {
document.body.className = theme;
if (theme === 'markdown') {
document.querySelectorAll('img').forEach(node => { node.dataset.src = node.src; node.src = ''; });
}
else {
document.querySelectorAll('img').forEach(node => { node.src = node.dataset.src || node.src; });
}
};
updateTheme();
const themeSwitch = document.getElementById('theme-switch');
themeSwitch.style.display = null;
themeSwitch.onclick = function () {
theme = themes[(themes.indexOf(theme) + 1) % themes.length];
localStorage.setItem('theme', theme);
updateTheme();
};
}());
(function () {
if (navigator.doNotTrack === '1' || localStorage.getItem('dnt')) return;
const payload = {
location: document.location.pathname,
referrer: document.referrer
};
fetch(
'https://log.lusmo.re/api/log',
{
method: 'POST',
body: JSON.stringify(payload)
}
);
}()); |
Update cookie-based login process event
エラーログによると、クッキーベースのログインをしたとき、
ログイン履歴を保存するためのフック関数において
https://github.com/fetus-hina/stat.ink/blob/ec679de7b6402be34edbff51a4b54b8cd6046a87/config/web/user.php#L38
の identity プロパティが見つからない時があるらしい。
この identity は \yii\web\User によって提供される getIdentity() の呼び出しになるはずなので
見つからないはずがないのだが、記録されているものは仕方がない。
なので、getter を明示的に呼び出すようにしてみた。
もしなぜか identity が null だったりすると例外を飛ばす | <?php
declare(strict_types=1);
use app\components\web\User;
use app\models\LoginMethod;
use app\models\User as UserModel;
use app\models\UserLoginHistory;
use yii\web\ServerErrorHttpException;
use yii\web\UserEvent;
return (function (): array {
$authKeyFile = dirname(__DIR__) . '/authkey-secret.php';
$authKeySecret = @file_exists($authKeyFile)
? require($authKeyFile)
: null;
return [
'class' => User::class,
'identityFixedKey' => $authKeySecret,
'identityClass' => UserModel::class,
'identityCookie' => [
'name' => '_identity',
'httpOnly' => true,
'secure' => (bool)preg_match(
'/(?:^|\.)stat\.ink$/i',
$_SERVER['HTTP_HOST'] ?? ''
),
],
'enableAutoLogin' => $authKeySecret !== null,
'loginUrl' => ['user/login'],
'on afterLogin' => function (UserEvent $event): void {
if (!$event->cookieBased) {
// 通常ログインはこのフックでは記録しない。
// 適切な箇所で UserLoginHistory::login() を呼び出すこと。
return;
}
$identity = Yii::$app->user->getIdentity();
if (!$identity) {
// なんでやねん
throw new ServerErrorHttpException('Internal error while auto-login process');
}
UserLoginHistory::login($identity, LoginMethod::METHOD_COOKIE);
UserModel::onLogin($identity, LoginMethod::METHOD_COOKIE);
},
];
})();
| <?php
declare(strict_types=1);
use app\components\web\User;
use app\models\LoginMethod;
use app\models\User as UserModel;
use app\models\UserLoginHistory;
use yii\web\UserEvent;
return (function (): array {
$authKeyFile = dirname(__DIR__) . '/authkey-secret.php';
$authKeySecret = @file_exists($authKeyFile)
? require($authKeyFile)
: null;
return [
'class' => User::class,
'identityFixedKey' => $authKeySecret,
'identityClass' => UserModel::class,
'identityCookie' => [
'name' => '_identity',
'httpOnly' => true,
'secure' => (bool)preg_match(
'/(?:^|\.)stat\.ink$/i',
$_SERVER['HTTP_HOST'] ?? ''
),
],
'enableAutoLogin' => $authKeySecret !== null,
'loginUrl' => ['user/login'],
'on afterLogin' => function (UserEvent $event): void {
if (!$event->cookieBased) {
// 通常ログインはこのフックでは記録しない。
// 適切な箇所で UserLoginHistory::login() を呼び出すこと。
return;
}
UserLoginHistory::login(
Yii::$app->user->identity,
LoginMethod::METHOD_COOKIE
);
UserModel::onLogin(
Yii::$app->user->identity,
LoginMethod::METHOD_COOKIE
);
},
];
})();
|
Use correct command in docblock type hint | <?php declare(strict_types=1);
namespace ApiClients\Client\Github\CommandBus\Handler\Repository;
use ApiClients\Client\AppVeyor\AsyncClient;
use ApiClients\Client\AppVeyor\Resource\ProjectInterface;
use ApiClients\Client\Github\CommandBus\Command\Repository\AppVeyorCommand;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
final class AppVeyorHandler
{
/**
* @var AsyncClient
*/
private $appveyor;
/**
* @param AsyncClient $appveyor
*/
public function __construct(AsyncClient $appveyor)
{
$this->appveyor = $appveyor;
}
/**
* @param AppVeyorCommand $command
* @return PromiseInterface
*/
public function handle(AppVeyorCommand $command): PromiseInterface
{
return new Promise(function ($resolve, $reject) use ($command) {
$repo = false;
$this->appveyor->projects()->filter(function (ProjectInterface $project) use ($command) {
return $project->repositoryType() === 'github' &&
$project->repositoryName() === $command->getRepository();
})->take(1)->subscribe(function ($repository) use (&$repo) {
$repo = $repository;
}, function ($error) use ($reject) {
$reject($error);
}, function () use (&$repo, $resolve) {
$resolve($repo);
});
});
}
}
| <?php declare(strict_types=1);
namespace ApiClients\Client\Github\CommandBus\Handler\Repository;
use ApiClients\Client\AppVeyor\AsyncClient;
use ApiClients\Client\AppVeyor\Resource\ProjectInterface;
use ApiClients\Client\Github\CommandBus\Command\Repository\AppVeyorCommand;
use ApiClients\Client\Github\CommandBus\Command\Repository\TravisCommand;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
final class AppVeyorHandler
{
/**
* @var AsyncClient
*/
private $appveyor;
/**
* @param AsyncClient $appveyor
*/
public function __construct(AsyncClient $appveyor)
{
$this->appveyor = $appveyor;
}
/**
* @param TravisCommand $command
* @return PromiseInterface
*/
public function handle(AppVeyorCommand $command): PromiseInterface
{
return new Promise(function ($resolve, $reject) use ($command) {
$repo = false;
$this->appveyor->projects()->filter(function (ProjectInterface $project) use ($command) {
return $project->repositoryType() === 'github' &&
$project->repositoryName() === $command->getRepository();
})->take(1)->subscribe(function ($repository) use (&$repo) {
$repo = $repository;
}, function ($error) use ($reject) {
$reject($error);
}, function () use (&$repo, $resolve) {
$resolve($repo);
});
});
}
}
|
Add support for Select placeholder option customization without `option.value: ''`
Fixes #72 | import React from 'react'
//
import { buildHandler } from './util'
import FormInput from '../formInput'
export default function FormInputSelect ({
options,
field,
showErrors,
errorBefore,
onChange,
onBlur,
isForm,
noTouch,
errorProps,
placeholder,
...rest
}) {
return (
<FormInput
field={field}
showErrors={showErrors}
errorBefore={errorBefore}
isForm={isForm}
errorProps={errorProps}
>
{({ setValue, getValue, setTouched }) => {
const resolvedOptions = options.find(d => d.value === '')
? options
: [
{
label: placeholder || 'Select One...',
value: '',
disabled: true,
},
...options,
]
const selectedIndex = resolvedOptions.findIndex(
d => d.value === getValue()
)
const nullIndex = resolvedOptions.findIndex(d => d.value === '')
return (
<select
{...rest}
onChange={buildHandler(onChange, e => {
const val = resolvedOptions[e.target.value].value
setValue(val, noTouch)
})}
onBlur={buildHandler(onBlur, () => setTouched())}
value={selectedIndex > -1 ? selectedIndex : nullIndex}
>
{resolvedOptions.map((option, i) => {
return (
<option key={option.value} value={i} disabled={option.disabled}>
{option.label}
</option>
)
})}
</select>
)
}}
</FormInput>
)
}
| import React from 'react'
//
import { buildHandler } from './util'
import FormInput from '../formInput'
export default function FormInputSelect ({
options,
field,
showErrors,
errorBefore,
onChange,
onBlur,
isForm,
noTouch,
errorProps,
...rest
}) {
return (
<FormInput
field={field}
showErrors={showErrors}
errorBefore={errorBefore}
isForm={isForm}
errorProps={errorProps}
>
{({ setValue, getValue, setTouched }) => {
const resolvedOptions = options.find(d => d.value === '')
? options
: [
{
label: 'Select One...',
value: '',
disabled: true,
},
...options,
]
const selectedIndex = resolvedOptions.findIndex(
d => d.value === getValue()
)
const nullIndex = resolvedOptions.findIndex(d => d.value === '')
return (
<select
{...rest}
onChange={buildHandler(onChange, e => {
const val = resolvedOptions[e.target.value].value
setValue(val, noTouch)
})}
onBlur={buildHandler(onBlur, () => setTouched())}
value={selectedIndex > -1 ? selectedIndex : nullIndex}
>
{resolvedOptions.map((option, i) => {
return (
<option key={i} value={i} disabled={option.disabled}>
{option.label}
</option>
)
})}
</select>
)
}}
</FormInput>
)
}
|
Remove emitter from cache if disposed | package org.adridadou.ethereum.propeller.event;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* Created by davidroon on 19.08.16.
* This code is released under Apache 2 license
*/
public class AbstractHandler<T> implements ObservableOnSubscribe<T> {
public final Observable<T> observable;
private final Set<ObservableEmitter<? super T>> emitters = ConcurrentHashMap.newKeySet();
public AbstractHandler() {
observable = Observable.create(this);
}
@Override
public void subscribe(ObservableEmitter<T> observableEmitter) throws Exception {
emitters.add(observableEmitter);
removeDisposed();
}
public void on(final T param) {
newElement(param);
}
public void newElement(final T param) {
removeDisposed();
emitters.forEach(emitter -> {
try {
if (emitter.isDisposed()) {
emitter.onComplete();
emitters.remove(emitter);
} else {
emitter.onNext(param);
}
} catch (Throwable ex) {
emitter.onError(ex);
}
});
}
private void removeDisposed() {
Set<ObservableEmitter<? super T>> disposed = emitters.stream()
.filter(ObservableEmitter::isDisposed)
.collect(Collectors.toSet());
emitters.removeAll(disposed);
}
}
| package org.adridadou.ethereum.propeller.event;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* Created by davidroon on 19.08.16.
* This code is released under Apache 2 license
*/
public class AbstractHandler<T> implements ObservableOnSubscribe<T> {
public final Observable<T> observable;
private final Set<ObservableEmitter<? super T>> emitters = ConcurrentHashMap.newKeySet();
public AbstractHandler() {
observable = Observable.create(this);
}
@Override
public void subscribe(ObservableEmitter<T> observableEmitter) throws Exception {
emitters.add(observableEmitter);
removeDisposed();
}
public void on(final T param) {
newElement(param);
}
public void newElement(final T param) {
removeDisposed();
emitters.forEach(emitter -> {
try {
if (emitter.isDisposed()) {
emitter.onComplete();
} else {
emitter.onNext(param);
}
} catch (Throwable ex) {
emitter.onError(ex);
}
});
}
private void removeDisposed() {
Set<ObservableEmitter<? super T>> disposed = emitters.stream()
.filter(ObservableEmitter::isDisposed)
.collect(Collectors.toSet());
emitters.removeAll(disposed);
}
}
|
Use correct environment markers syntax in the extras_require section.
See https://github.com/pypa/setuptools/issues/1087 | from setuptools import find_packages, setup
from channels import __version__
setup(
name='channels',
version=__version__,
url='http://github.com/django/channels',
author='Django Software Foundation',
author_email='[email protected]',
description="Brings event-driven capabilities to Django with a channel system. Django 1.8 and up only.",
license='BSD',
packages=find_packages(exclude=['tests']),
include_package_data=True,
install_requires=[
'Django>=1.8',
'asgiref~=1.1',
'daphne~=1.3',
],
extras_require={
'tests': [
'coverage',
'flake8>=2.0,<3.0',
'isort',
],
'tests:python_version < "3.0"': ['mock'],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import find_packages, setup
from channels import __version__
setup(
name='channels',
version=__version__,
url='http://github.com/django/channels',
author='Django Software Foundation',
author_email='[email protected]',
description="Brings event-driven capabilities to Django with a channel system. Django 1.8 and up only.",
license='BSD',
packages=find_packages(exclude=['tests']),
include_package_data=True,
install_requires=[
'Django>=1.8',
'asgiref~=1.1',
'daphne~=1.3',
],
extras_require={
'tests': [
'coverage',
'mock ; python_version < "3.0"',
'flake8>=2.0,<3.0',
'isort',
],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
],
)
|
CL011: Fix checkboxes inform and involved | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
Override to add inform and involved field
"""
data = super(TextCommentForm, self).get_comment_create_data()
data.update({'inform': self.cleaned_data["inform"],
'involved': self.cleaned_data["involved"]})
return data
| from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
Override to add inform field
"""
data = super(TextCommentForm, self).get_comment_create_data()
data.update({'inform': True})
return data
|
Remove unused left over parameter | #!/usr/bin/env python3
import json
import sys
import time
from urllib.request import urlopen
STATS_URL = "http://localhost:18001/stats"
MAXIMUM_TIME_SECONDS = 2 * 60
SLEEPING_INTERVAL_SECONDS = 1
STATUS_CODE_OK = 200
def is_initialised():
try:
response = urlopen(STATS_URL)
if (response.getcode() == STATUS_CODE_OK):
encoding = response.info().get_content_charset('utf-8')
content = response.read().decode(encoding)
return json.loads(content)['initialised']
else:
return False
except Exception as e:
return False
def wait_until_cluster_initialised():
start = time.time()
elapsed = 0.0
while elapsed < MAXIMUM_TIME_SECONDS:
if is_initialised():
print("Cluster initialised!")
break
elapsed = time.time() - start
print("Cluster not initialised... keep waiting... elapsed time: {0:.2f} seconds.".format(elapsed))
time.sleep(SLEEPING_INTERVAL_SECONDS)
elapsed = time.time() - start
else:
sys.exit("Cluster not initialised after {} seconds. I give up!".format(MAXIMUM_TIME_SECONDS))
if __name__ == "__main__":
wait_until_cluster_initialised()
| #!/usr/bin/env python3
import json
import sys
import time
from urllib.request import urlopen
STATS_URL = "http://localhost:18001/stats"
MAXIMUM_TIME_SECONDS = 2 * 60
SLEEPING_INTERVAL_SECONDS = 1
STATUS_CODE_OK = 200
def is_initialised():
try:
response = urlopen(STATS_URL)
if (response.getcode() == STATUS_CODE_OK):
encoding = response.info().get_content_charset('utf-8')
content = response.read().decode(encoding)
return json.loads(content)['initialised']
else:
return False
except Exception as e:
return False
def wait_until_cluster_initialised():
start = time.time()
elapsed = 0.0
while elapsed < MAXIMUM_TIME_SECONDS:
if is_initialised():
print("Cluster initialised!")
break
elapsed = time.time() - start
print("Cluster not initialised... keep waiting... elapsed time: {1:.2f} seconds.".format(
SLEEPING_INTERVAL_SECONDS, elapsed))
time.sleep(SLEEPING_INTERVAL_SECONDS)
elapsed = time.time() - start
else:
sys.exit("Cluster not initialised after {} seconds. I give up!".format(MAXIMUM_TIME_SECONDS))
if __name__ == "__main__":
wait_until_cluster_initialised() |
Refactor migrations after generating to ensure custom user model compatibility. | #!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)
# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings
# Now, imports from Django will work properly without raising errors related to
# missing or badly-configured settings.
from django.core import management
from refactor_migrations import refactor
def generate_migrations(initial):
management.call_command('syncdb', interactive=False)
if initial:
management.call_command('schemamigration', 'djoauth2', initial=True)
else:
management.call_command('schemamigration', 'djoauth2', auto=True)
refactor('./djoauth2/migrations/')
def test_migrations():
management.call_command('syncdb', interactive=False)
management.call_command('migrate', 'djoauth2')
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--initial-migration',
action='store_true',
default=False,
dest='initial')
parser.add_argument('--test-migrations',
action='store_true',
default=False,
dest='test_migrations')
args = parser.parse_args()
if args.test_migrations:
test_migrations()
else:
generate_migrations(args.initial)
| #!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)
# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings
# Now, imports from Django will work properly without raising errors related to
# missing or badly-configured settings.
from django.core import management
def generate_migrations(initial):
management.call_command('syncdb', interactive=False)
if initial:
management.call_command('schemamigration', 'djoauth2', initial=True)
else:
management.call_command('schemamigration', 'djoauth2', auto=True)
def test_migrations():
management.call_command('syncdb', interactive=False)
management.call_command('migrate', 'djoauth2')
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--initial-migration',
action='store_true',
default=False,
dest='initial')
parser.add_argument('--test-migrations',
action='store_true',
default=False,
dest='test_migrations')
args = parser.parse_args()
if args.test_migrations:
test_migrations()
else:
generate_migrations(args.initial)
|
Return str instead of dict. | import json
from flask import abort
from flask import Flask
from flask_caching import Cache
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Parser</title>' +
'</head>' +
'<body>' +
'<p><a href="ki">Campus Solna (KI)</a></p>' +
'<p><a href="uu">Campus Uppsala (BMC)</a></p>' +
'</body>' +
'</html>')
return content
@app.route('/api/restaurants')
@cache.cached(timeout=3600)
def api_list_restaurants():
return json.dumps(main.list_restaurants())
@app.route('/api/restaurant/<name>')
@cache.cached(timeout=3600)
def api_get_restaurant(name):
data = main.get_restaurant(name)
if not data:
abort(404)
return json.dumps(data)
@app.route('/ki')
@cache.cached(timeout=3600)
def make_menu_ki():
return main.gen_ki_menu()
@app.route('/uu')
@cache.cached(timeout=3600)
def make_menu_uu():
return main.gen_uu_menu()
| from flask import abort
from flask import Flask
from flask_caching import Cache
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Parser</title>' +
'</head>' +
'<body>' +
'<p><a href="ki">Campus Solna (KI)</a></p>' +
'<p><a href="uu">Campus Uppsala (BMC)</a></p>' +
'</body>' +
'</html>')
return content
@app.route('/api/restaurants')
@cache.cached(timeout=3600)
def api_list_restaurants():
return main.list_restaurants()
@app.route('/api/restaurant/<name>')
@cache.cached(timeout=3600)
def api_get_restaurant(name):
data = main.get_restaurant(name)
if not data:
abort(404)
return data
@app.route('/ki')
@cache.cached(timeout=3600)
def make_menu_ki():
return main.gen_ki_menu()
@app.route('/uu')
@cache.cached(timeout=3600)
def make_menu_uu():
return main.gen_uu_menu()
|
Allow a function to be called whenever a candidate blob is found during
image
processing | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config, each_blob=None):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:param each_blob: function, taking a SimpleCV.Blob as an argument, that is called for every candidate blob
:return: Mask with candidates
"""
hsv_image = img.toHSV()
segmented = Image(cv2.inRange(hsv_image.getNumpy(),
numpy.array([config.min_hue, config.min_sat, config.min_val]),
numpy.array([config.max_hue, config.max_sat, config.max_val])))
segmented = segmented.dilate(2)
blobs = segmented.findBlobs()
if blobs:
for b in blobs:
if b.radius() > 10:
rect_width = b.minRectWidth()
rect_height = b.minRectHeight()
aspect_ratio = rect_width / rect_height
square_error = abs(obj.aspect_ratio - aspect_ratio) / abs(aspect_ratio)
if square_error < 0.1:
if not each_blob: # default to just outlining
# minRectX and minRectY actually give the center point, not the minX and minY, so we shift by 1/2
segmented.drawRectangle(b.minRectX()-rect_width/2, b.minRectY()-rect_height/2, rect_width,
rect_height, color=Color.GREEN, width=6)
else:
each_blob(b)
# Give the result mask
return segmented.applyLayers() | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:return: Mask with candidates surrounded in a green rectangle
"""
hsv_image = img.toHSV()
segmented = Image(cv2.inRange(hsv_image.getNumpy(),
numpy.array([config.min_hue, config.min_sat, config.min_val]),
numpy.array([config.max_hue, config.max_sat, config.max_val])))
segmented = segmented.dilate(2)
blobs = segmented.findBlobs()
if blobs:
for b in blobs:
if b.radius() > 10:
rect_width = b.minRectWidth()
rect_height = b.minRectHeight()
aspect_ratio = rect_width / rect_height
square_error = abs(obj.aspect_ratio - aspect_ratio) / abs(aspect_ratio)
if square_error < 0.1:
# minRectX and minRectY actually give the center point, not the minX and minY, so we shift by 1/2
segmented.drawRectangle(b.minRectX()-rect_width/2, b.minRectY()-rect_height/2, rect_width,
rect_height, color=Color.GREEN, width=6)
# Give the result mask
return segmented.applyLayers() |
Add missing dependency on h5py. | from setuptools import setup
setup(name='keras_tf_multigpu',
version='0.1',
description='Multi-GPU data-parallel training in Keras/TensorFlow',
url='https://github.com/rossumai/keras-multi-gpu',
author='Bohumir Zamecnik',
author_email='[email protected]',
license='MIT',
packages=['keras_tf_multigpu'],
zip_safe=False,
install_requires=[
'h5py',
'Keras>=2.0.8',
'numpy',
'tensorflow-gpu>=1.3',
],
setup_requires=['setuptools-markdown'],
long_description_markdown_filename='README.md',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Operating System :: POSIX :: Linux',
])
| from setuptools import setup
setup(name='keras_tf_multigpu',
version='0.1',
description='Multi-GPU data-parallel training in Keras/TensorFlow',
url='https://github.com/rossumai/keras-multi-gpu',
author='Bohumir Zamecnik',
author_email='[email protected]',
license='MIT',
packages=['keras_tf_multigpu'],
zip_safe=False,
install_requires=[
'Keras>=2.0.8',
'numpy',
'tensorflow-gpu>=1.3',
],
setup_requires=['setuptools-markdown'],
long_description_markdown_filename='README.md',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Operating System :: POSIX :: Linux',
])
|
BUG: Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing. | """Delete all documents every second forever"""
__author__ = 'tunnell'
import sys
import time
import json
import pymongo
if __name__ == "__main__":
c = pymongo.MongoClient()
db = c.data
collection = db.test
# Key to sort by so we can use an index for quick query
sort_key = [("_id", pymongo.ASCENDING),
("triggertime", pymongo.ASCENDING)]
# Index for quick query
collection.create_index(sort_key, dropDups=True)
# Loop until Ctrl-C or error
while (1):
# This try-except catches Ctrl-C and error
try:
# Non-sense query that is in index
query = {"triggertime": {'$gt': 0}}
# Perform query
cursor = collection.find(query,
fields=['triggertime']).sort(sort_key)
# Are we using index for quick queries? Not always true if there
# are no documents in the collection...
print('Using index:', cursor.explain()['indexOnly'])
# Stats on how the delete worked. Write concern is on.
print(json.dumps(collection.remove(query),
indent=4,
sort_keys=True))
# Wait a second so we don't query the DB too much
time.sleep(1)
except pymongo.errors.OperationFailure as e:
print('MongoDB error:', e)
except KeyboardInterrupt:
print("Ctrl-C caught so exiting.")
sys.exit(0)
| """Delete all documents every second forever"""
__author__ = 'tunnell'
import sys
import time
import json
import pymongo
if __name__ == "__main__":
c = pymongo.MongoClient()
db = c.data
collection = db.test
# Key to sort by so we can use an index for quick query
sort_key = [("_id", pymongo.ASCENDING),
("triggertime", pymongo.ASCENDING)]
# Index for quick query
collection.create_index(sort_key, dropDups=True)
# Loop until Ctrl-C or error
while (1):
# This try-except catches Ctrl-C and error
try:
# Non-sense query that is in index
query = {"triggertime": {'$gt': 0}}
# Perform query
cursor = collection.find(query,
fields=['triggertime']).sort(sort_key)
# Are we using index for quick queries? Not always true if there
# are no documents in the collection...
print('Using index:', cursor.explain()['indexOnly'])
# Stats on how the delete worked. Write concern (w=1) is on.
print(json.dumps(collection.remove(query),
indent=4,
sort_keys=True,
w=1))
# Wait a second so we don't query the DB too much
time.sleep(1)
except pymongo.errors.OperationFailure as e:
print('MongoDB error:', e)
except KeyboardInterrupt:
print("Ctrl-C caught so exiting.")
sys.exit(0)
|
Simplify implementation of removeObject method. | <?php
namespace SimpleAcl\Object;
use SimpleAcl\Object;
/**
* Implement common function for Role and Resources.
*
*/
abstract class ObjectAggregate
{
/**
* @var Object[]
*/
protected $objects = array();
/**
* @param Object $object
*/
protected function addObject(Object $object)
{
$this->objects[$object->getName()] = $object;
}
protected function removeObjects()
{
$this->objects = array();
}
/**
* @param string $objectName
*/
protected function removeObject($objectName)
{
unset($this->objects[$objectName]);
}
/**
* @param array $objects
*/
protected function setObjects($objects)
{
/** @var Object $object */
foreach ($objects as $object) {
$this->addObject($object);
}
}
/**
* @return array|Object[]
*/
protected function getObjects()
{
return $this->objects;
}
/**
* @param string $objectName
* @return null|Object
*/
protected function getObject($objectName)
{
if ( isset($this->objects[$objectName]) ) {
return $this->objects[$objectName];
}
return null;
}
}
| <?php
namespace SimpleAcl\Object;
use SimpleAcl\Object;
/**
* Implement common function for Role and Resources.
*
*/
abstract class ObjectAggregate
{
/**
* @var Object[]
*/
protected $objects = array();
/**
* @param Object $object
*/
protected function addObject(Object $object)
{
$this->objects[$object->getName()] = $object;
}
protected function removeObjects()
{
$this->objects = array();
}
/**
* @param string $objectName
*/
protected function removeObject($objectName)
{
foreach ( $this->objects as $objectIndex => $object ) {
if ( $object->getName() == $objectName ) {
unset($this->objects[$objectIndex]);
return;
}
}
}
/**
* @param array $objects
*/
protected function setObjects($objects)
{
/** @var Object $object */
foreach ($objects as $object) {
$this->addObject($object);
}
}
/**
* @return array|Object[]
*/
protected function getObjects()
{
return $this->objects;
}
/**
* @param string $objectName
* @return null|Object
*/
protected function getObject($objectName)
{
if ( isset($this->objects[$objectName]) ) {
return $this->objects[$objectName];
}
return null;
}
}
|
Fix count check of clusters in $grid | <?php
#
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#
# If we are in compare_hosts, views and decompose_graph context we shouldn't attempt
# any connections to the gmetad
if ( in_array($context, $SKIP_GMETAD_CONTEXTS) ) {
} else {
if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) )
{
print "<H4>There was an error collecting ganglia data ".
"(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error</H4>\n";
exit;
}
# If we have no child data sources, assume something is wrong.
if (!count($grid) and !count($cluster))
{
print "<H4>Ganglia cannot find a data source. Is gmond running?</H4>";
exit;
}
# If we only have one cluster source, suppress MetaCluster output.
if (count($grid) < 2 and $context=="meta")
{
# Lets look for one cluster (the other is our grid).
foreach($grid as $source)
if (isset($source['CLUSTER']) and $source['CLUSTER'])
{
$standalone = 1;
$context = "cluster";
# Need to refresh data with new context.
Gmetad($conf['ganglia_ip'], $conf['ganglia_port']);
$clustername = $source['NAME'];
}
}
}
?>
| <?php
#
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#
# If we are in compare_hosts, views and decompose_graph context we shouldn't attempt
# any connections to the gmetad
if ( in_array($context, $SKIP_GMETAD_CONTEXTS) ) {
} else {
if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) )
{
print "<H4>There was an error collecting ganglia data ".
"(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error</H4>\n";
exit;
}
# If we have no child data sources, assume something is wrong.
if (!count($grid) and !count($cluster))
{
print "<H4>Ganglia cannot find a data source. Is gmond running?</H4>";
exit;
}
# If we only have one cluster source, suppress MetaCluster output.
if (count($grid) <= 2 and $context=="meta")
{
# Lets look for one cluster (the other is our grid).
foreach($grid as $source)
if (isset($source['CLUSTER']) and $source['CLUSTER'])
{
$standalone = 1;
$context = "cluster";
# Need to refresh data with new context.
Gmetad($conf['ganglia_ip'], $conf['ganglia_port']);
$clustername = $source['NAME'];
}
}
}
?>
|
news: Fix click behavior of like button | function likebutton(el, url) {
var dropdown;
var button;
init();
function init() {
button = el.querySelector('.button');
el.removeAttribute('onmousedown');
el.onmousedown = function(evt) {
toggle();
evt.stopPropagation();
};
dropdown = document.createElement('div');
dropdown.className = 'dropdown';
dropdown.style.top = button.offsetHeight + 5 + "px";
add('facebook', '<iframe src="//www.facebook.com/plugins/like.php?href='+encodeURIComponent(url)+'&height=20&colorscheme=light&layout=button_count&action=like&show_faces=false&send=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:21px;" allowTransparency="true"></iframe>');
window.setTimeout(function() {
document.addEventListener('mousedown', function(evt) {
hide();
}, false);
}, 0);
toggle();
}
function add(name, html) {
var item;
var item_button;
item = document.createElement('div');
item.className = 'item';
item.innerHTML = html;
dropdown.appendChild(item);
}
function toggle() {
if (dropdown.parentNode === el)
el.removeChild(dropdown);
else
el.appendChild(dropdown);
}
function hide() {
if (dropdown.parentNode == el)
el.removeChild(dropdown);
}
}
| function likebutton(el, url) {
var dropdown;
var button;
init();
function init() {
button = el.querySelector('.button');
el.removeAttribute('onmousedown');
el.onmousedown = function(evt) {
toggle();
evt.stopPropagation();
};
dropdown = document.createElement('div');
dropdown.className = 'dropdown';
dropdown.style.top = button.offsetHeight + 5 + "px";
add('facebook', '<iframe src="//www.facebook.com/plugins/like.php?href='+encodeURIComponent(url)+'&height=20&colorscheme=light&layout=button_count&action=like&show_faces=false&send=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:21px;" allowTransparency="true"></iframe>');
document.addEventListener('mousedown', function(evt) {
hide();
}, false);
toggle();
}
function add(name, html) {
var item;
var item_button;
item = document.createElement('div');
item.className = 'item';
item.innerHTML = html;
dropdown.appendChild(item);
}
function toggle() {
if (dropdown.parentNode == el)
el.removeChild(dropdown);
else
el.appendChild(dropdown);
}
function hide() {
if (dropdown.parentNode == el)
el.removeChild(dropdown);
}
}
|
Add different function to manage recursivity | <?php
require 'vendor/autoload.php';
function checkFirstAvailable($name, $field)
{
if (Member::where($field, $name)->count() == 0)
return $name;
$c = 0;
while (1 < 2) {
$c = $c + 1;
if (Member::where($field, $name . $c)->count() == 0)
return $name . $c;
}
}
Bootstrap::boot();
$a = Csv::csv2array('example.csv');
foreach ($a as $k => $member) {
if (Member::where('email', $member[2])->count() == 0 AND Member::where('identification', $member[3])->count() == 0) {
$invite = sha1($member[0] . " " . $member[1] . ", " . date('c'));
if (! Member::where('invite_code', $invite)->count()) {
$m = new Member;
$m->invite_code = $invite;
$m->login = checkFirstAvailable(substr($member[2], 0, strpos($member[2], "@")), 'login')
$m->identification = $member[3];
$m->name = checkFirstAvailable(ucwords(strtolower($member[0])) . " " . ucwords(strtolower($member[1])), 'name');
$m->save();
} else {
print_r($member);
echo $invite;
}
} else
$invite = "";
$a[$k][4] = $invite;
}
echo Csv::array2csv($a);
| <?php
require 'vendor/autoload.php';
Bootstrap::boot();
$a = Csv::csv2array('example.csv');
foreach ($a as $k => $member) {
if (Member::where('email', $member[2])->count() == 0 AND Member::where('identification', $member[3])->count() == 0) {
$invite = sha1($member[0] . " " . $member[1] . ", " . date('c'));
if (! Member::where('invite_code', $invite)->count()) {
$m = new Member;
$m->invite_code = $invite;
$login = substr($member[2], 0, strpos($member[2], "@"));
if (Member::where('login', $login)->count() == 0)
$m->login = $login;
elseif (Member::where('login', $login . '1')->count() == 0)
$m->login = $login . '1';
elseif (Member::where('login', $login . '2')->count() == 0)
$m->login = $login . '2';
$m->identification = $member[3];
$m->name = ucwords(strtolower($member[0])) . " " . ucwords(strtolower($member[1]));
$m->save();
} else {
print_r($member);
echo $invite;
}
} else
$invite = "";
$a[$k][4] = $invite;
}
echo Csv::array2csv($a);
|
Fix issue with state being saved with last value | import React, { Component } from 'react';
import PikadayWrapper from '../../lib-components/PikadayWrapper/PikadayWrapper';
export default class PantryItem extends Component {
constructor(props) {
super(props);
this.state = {
expiration: this.props.item.expiration,
name: this.props.item.name
};
}
onSelectDate(newDate) {
this.setState({ expiration: newDate }, () => {
this.props.onItemChange(this.getItem());
});
}
onNameChange(newName) {
this.setState({ name: newName }, () => {
this.props.onItemChange(this.getItem());
});
}
getItem() {
return {
name: this.state.name,
expiration: this.state.expiration
};
}
render() {
return (
<div>
<div className="pantry-item__form-group">
<label className="pantry-item__form-label">
Product name
<input type="text" className="pantry-item__form-input" defaultValue={this.state.name} onChange={evt => this.onNameChange(evt.target.value)} />
</label>
</div>
<div className="pantry-item__form-group">
<label className="pantry-item__form-label">
Expiry date
<PikadayWrapper onSelect={(date) => this.onSelectDate(date)}
defaultValue={this.state.expiration}
className="pantry-item__form-input pantry-item__form-input--datepicker" />
</label>
</div>
</div>
);
}
} | import React, { Component } from 'react';
import PikadayWrapper from '../../lib-components/PikadayWrapper/PikadayWrapper';
export default class PantryItem extends Component {
constructor(props) {
super(props);
this.state = {
expiration: this.props.item.expiration,
name: this.props.item.name
};
}
onSelectDate(newDate) {
this.setState({ expiration: newDate });
this.props.onItemChange(this.getItem());
}
onNameChange(newName) {
this.setState({ name: newName });
this.props.onItemChange(this.getItem());
}
getItem() {
return {
name: this.state.name,
expiration: this.state.expiration
};
}
render() {
return (
<div>
<div className="pantry-item__form-group">
<label className="pantry-item__form-label">
Product name
<input type="text" className="pantry-item__form-input" defaultValue={this.state.name} onChange={evt => this.onNameChange(evt.target.value) } />
</label>
</div>
<div className="pantry-item__form-group">
<label className="pantry-item__form-label">
Expiry date
<PikadayWrapper onSelect={(date) => this.onSelectDate(date)}
defaultValue={this.state.expiration}
className="pantry-item__form-input pantry-item__form-input--datepicker" />
</label>
</div>
</div>
);
}
} |
[FEATURE] Use static instantiation with max depth check | <?php
namespace FOS\ElasticaBundle\Serializer;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;
class Callback
{
protected $serializer;
protected $groups;
protected $version;
public function setSerializer($serializer)
{
$this->serializer = $serializer;
if (!method_exists($this->serializer, 'serialize')) {
throw new \RuntimeException('The serializer must have a "serialize" method.');
}
}
public function setGroups(array $groups)
{
$this->groups = $groups;
if ($this->groups) {
if (!$this->serializer instanceof SerializerInterface) {
throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
}
}
}
public function setVersion($version)
{
$this->version = $version;
if ($this->version) {
if (!$this->serializer instanceof SerializerInterface) {
throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
}
}
}
public function serialize($object)
{
$context = $this->serializer instanceof SerializerInterface ? SerializationContext::create()->enableMaxDepthChecks() : array();
if ($this->groups) {
$context->setGroups($this->groups);
}
if ($this->version) {
$context->setVersion($this->version);
}
return $this->serializer->serialize($object, 'json', $context);
}
}
| <?php
namespace FOS\ElasticaBundle\Serializer;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;
class Callback
{
protected $serializer;
protected $groups;
protected $version;
public function setSerializer($serializer)
{
$this->serializer = $serializer;
if (!method_exists($this->serializer, 'serialize')) {
throw new \RuntimeException('The serializer must have a "serialize" method.');
}
}
public function setGroups(array $groups)
{
$this->groups = $groups;
if ($this->groups) {
if (!$this->serializer instanceof SerializerInterface) {
throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
}
}
}
public function setVersion($version)
{
$this->version = $version;
if ($this->version) {
if (!$this->serializer instanceof SerializerInterface) {
throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
}
}
}
public function serialize($object)
{
$context = $this->serializer instanceof SerializerInterface ? new SerializationContext() : array();
if ($this->groups) {
$context->setGroups($this->groups);
}
if ($this->version) {
$context->setVersion($this->version);
}
return $this->serializer->serialize($object, 'json', $context);
}
}
|
Rename parameter in interface to be more generic. | <?php
/**
* Interface that collections must implement.
*
* PHP Version 5.3
*
* @copyright (c) 2006-2014 brian ridley
* @author brian ridley <[email protected]>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ptlis\ConNeg\Collection;
use Countable;
use IteratorAggregate;
use Traversable;
/**
* Interface that collections must implement.
*/
interface CollectionInterface extends Countable, IteratorAggregate
{
/**
* Set the internal store to the provided values.
*
* @param array $list
*
* @return CollectionInterface
*/
public function setList(array $list);
/**
* Return count of elements.
*
* @link http://php.net/manual/en/countable.count.php
*
* @return int
*/
public function count();
/**
* Retrieve an external iterator.
*
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return Traversable
*/
public function getIterator();
/**
* Returns a new sorted collection.
*
* @return CollectionInterface with elements in ascending order
*/
public function getAscending();
/**
* Returns a new sorted collection.
*
* @return CollectionInterface with elements in descending order
*/
public function getDescending();
}
| <?php
/**
* Interface that collections must implement.
*
* PHP Version 5.3
*
* @copyright (c) 2006-2014 brian ridley
* @author brian ridley <[email protected]>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ptlis\ConNeg\Collection;
use Countable;
use IteratorAggregate;
use Traversable;
/**
* Interface that collections must implement.
*/
interface CollectionInterface extends Countable, IteratorAggregate
{
/**
* Set the internal store to the provided values.
*
* @param array $typePairList
*
* @return CollectionInterface
*/
public function setList(array $typePairList);
/**
* Return count of elements.
*
* @link http://php.net/manual/en/countable.count.php
*
* @return int
*/
public function count();
/**
* Retrieve an external iterator.
*
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return Traversable
*/
public function getIterator();
/**
* Returns a new sorted collection.
*
* @return CollectionInterface with elements in ascending order
*/
public function getAscending();
/**
* Returns a new sorted collection.
*
* @return CollectionInterface with elements in descending order
*/
public function getDescending();
}
|
Add use-strict to fix old versions of node. | 'use strict';
var fs = require('fs');
var path = require('path');
function getComponentFiles(filename) {
var ext = path.extname(filename);
if (ext === '.js') {
return null;
}
var nameNoExt = path.basename(filename, ext);
var isEntry = 'index' === nameNoExt;
var fileMatch = '('+nameNoExt.replace(/\./g, '\\.') + '\\.' + (isEntry ? '|' : '') + ')';
var styleMatch = new RegExp('^'+fileMatch+'style\\.\\w+$');
var componentMatch = new RegExp('^'+fileMatch+'component\\.\\w+$');
var splitComponentMatch = new RegExp('^'+fileMatch+'component-browser\\.\\w+$');
var dirname = path.dirname(filename);
var foundFiles = {
styles: [],
file: null,
browserFile: null
};
var dirFiles = fs.readdirSync(dirname);
dirFiles.sort();
for (let i=dirFiles.length - 1; i>=0; i--) {
let file = dirFiles[i];
if (styleMatch.test(file)) {
foundFiles.styles.push(file);
} else if (splitComponentMatch.test(file)) {
foundFiles.browserFile = file;
} else if (componentMatch.test(file)) {
foundFiles.file = file;
}
}
return foundFiles;
}
module.exports = getComponentFiles;
| var fs = require('fs');
var path = require('path');
function getComponentFiles(filename) {
var ext = path.extname(filename);
if (ext === '.js') {
return null;
}
var nameNoExt = path.basename(filename, ext);
var isEntry = 'index' === nameNoExt;
var fileMatch = '('+nameNoExt.replace(/\./g, '\\.') + '\\.' + (isEntry ? '|' : '') + ')';
var styleMatch = new RegExp('^'+fileMatch+'style\\.\\w+$');
var componentMatch = new RegExp('^'+fileMatch+'component\\.\\w+$');
var splitComponentMatch = new RegExp('^'+fileMatch+'component-browser\\.\\w+$');
var dirname = path.dirname(filename);
var foundFiles = {
styles: [],
file: null,
browserFile: null
};
var dirFiles = fs.readdirSync(dirname);
dirFiles.sort();
for (let i=dirFiles.length - 1; i>=0; i--) {
let file = dirFiles[i];
if (styleMatch.test(file)) {
foundFiles.styles.push(file);
} else if (splitComponentMatch.test(file)) {
foundFiles.browserFile = file;
} else if (componentMatch.test(file)) {
foundFiles.file = file;
}
}
return foundFiles;
}
module.exports = getComponentFiles;
|
Change function to take ConcreteIntegers | package org.aac.average.java.impl;
import org.aac.average.java.impl.function.Function;
import org.aac.average.java.impl.function.FunctionParameter;
import org.aac.average.java.impl.datatypes.ConcreteInteger;
public class Average {
public static void main(String[] args) {
Function<ConcreteInteger> averageTwoIntegers;
averageTwoIntegers = new Function<>().addParameter(new FunctionParameter<ConcreteInteger>("a"))
.addParameter(new FunctionParameter<ConcreteInteger>("b"));
ConcreteInteger firstNumber = new ConcreteInteger.Builder()
.addDigit(ConcreteInteger.Digit.TWO)
.build();
ConcreteInteger secondNumber = new ConcreteInteger.Builder()
.addDigit(ConcreteInteger.Digit.ONE)
.addDigit(ConcreteInteger.Digit.EIGHT)
.build();
}
}
| package org.aac.average.java.impl;
import org.aac.average.java.impl.function.Function;
import org.aac.average.java.impl.function.FunctionParameter;
import org.aac.average.java.impl.datatypes.ConcreteInteger;
public class Average {
public static void main(String[] args) {
Function<Integer> average;
average = new Function<>().addParameter(new FunctionParameter<Integer>("a"))
.addParameter(new FunctionParameter<Integer>("b"));
ConcreteInteger firstNumber = new ConcreteInteger.Builder()
.addDigit(ConcreteInteger.Digit.TWO)
.build();
ConcreteInteger secondNumber = new ConcreteInteger.Builder()
.addDigit(ConcreteInteger.Digit.ONE)
.addDigit(ConcreteInteger.Digit.EIGHT)
.build();
}
}
|
Add missing fields in the create game resource. | @extends('layouts.app')
@section('content')
<form class="ui form" action="{{ route('games.store') }}" method="POST">
{{ csrf_field() }}
<div class="field">
<label>
Name: <input name="name" type="text">
</label>
</div>
<div class="field">
<label>
Description: <textarea name="description" rows="2"></textarea>
</label>
</div>
<div class="field">
<label>
Photo: <input name="photo" type="text">
</label>
</div>
<div class="field">
<label>
URL: <input name="url" type="text">
</label>
</div>
<div class="field">
<label>
Developer:
<select name="developer_id">
@foreach($developers as $developer)
<option value="{{ $developer->id }}">
{{ $developer->nickname or $developer->name }}
</option>
@endforeach
</select>
</label>
</div>
<button class="ui primary button" type="submit">Save</button>
</form>
@endsection
| @extends('layouts.app')
@section('content')
<form class="ui form" action="{{ route('games.store') }}" method="POST">
{{ csrf_field() }}
<div class="field">
<label>
Name: <input name="name" type="text">
</label>
</div>
<div class="field">
<label>
Description: <textarea name="description" rows="2"></textarea>
</label>
</div>
<div class="field">
<label>
Developer:
<select name="developer_id">
@foreach($developers as $developer)
<option value="{{ $developer->id }}">
{{ $developer->nickname or $developer->name }}
</option>
@endforeach
</select>
</label>
</div>
<button class="ui primary button" type="submit">Save</button>
</form>
@endsection
|
Add null as error argument for callback
Refs: #13
PR-URL: https://github.com/metarhia/metasync/pull/152
Reviewed-By: Timur Shemsedinov <[email protected]> | 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
if (!timer) {
timer = setTimeout(() => {
timer = null;
if (wait) throttled();
}, timeout);
if (args) fn(...args);
else fn();
wait = false;
} else {
wait = true;
}
};
};
api.metasync.debounce = (
timeout,
fn,
args = []
) => {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), timeout);
};
};
api.metasync.timeout = (
// Set timeout for function execution
timeout, // time interval
asyncFunction, // async function to be executed
// done - callback function
done // callback function on done
) => {
let finished = false;
done = api.metasync.cb(done);
const timer = setTimeout(() => {
if (!finished) {
finished = true;
done(null);
}
}, timeout);
asyncFunction((err, data) => {
if (!finished) {
clearTimeout(timer);
finished = true;
done(err, data);
}
});
};
};
| 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
if (!timer) {
timer = setTimeout(() => {
timer = null;
if (wait) throttled();
}, timeout);
if (args) fn(...args);
else fn();
wait = false;
} else {
wait = true;
}
};
};
api.metasync.debounce = (
timeout,
fn,
args = []
) => {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), timeout);
};
};
api.metasync.timeout = (
// Set timeout for function execution
timeout, // time interval
asyncFunction, // async function to be executed
// done - callback function
done // callback function on done
) => {
let finished = false;
done = api.metasync.cb(done);
const timer = setTimeout(() => {
if (!finished) {
finished = true;
done();
}
}, timeout);
asyncFunction(() => {
if (!finished) {
clearTimeout(timer);
finished = true;
done();
}
});
};
};
|
Fix roles for Courses API | (function () {
'use strict';
// Courses controller
angular
.module('courses')
.controller('CoursesController', CoursesController);
CoursesController.$inject = ['$scope', '$state', '$window', 'Authentication', 'courseResolve', 'DepartmentsService'];
function CoursesController ($scope, $state, $window, Authentication, course, DepartmentsService) {
var vm = this;
vm.authentication = Authentication;
vm.departments = DepartmentsService.query();
vm.course = course;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
// Remove existing Course
function remove() {
if ($window.confirm('Are you sure you want to delete?')) {
vm.course.$remove($state.go('admin.courses.list'));
}
}
// Save Course
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.courseForm');
return false;
}
if (vm.authentication.user.roles.indexOf('admin') < 0 && vm.authentication.user.department !== undefined) {
vm.course.department = vm.authentication.user.department;
}
// TODO: move create/update logic to service
if (vm.course._id) {
vm.course.$update(successCallback, errorCallback);
} else {
vm.course.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('admin.courses.list');
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
}
}());
| (function () {
'use strict';
// Courses controller
angular
.module('courses')
.controller('CoursesController', CoursesController);
CoursesController.$inject = ['$scope', '$state', '$window', 'Authentication', 'courseResolve', 'DepartmentsService'];
function CoursesController ($scope, $state, $window, Authentication, course, DepartmentsService) {
var vm = this;
vm.authentication = Authentication;
vm.departments = DepartmentsService.query();
vm.course = course;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
// Remove existing Course
function remove() {
if ($window.confirm('Are you sure you want to delete?')) {
vm.course.$remove($state.go('admin.courses.list'));
}
}
// Save Course
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.courseForm');
return false;
}
// TODO: move create/update logic to service
if (vm.course._id) {
vm.course.$update(successCallback, errorCallback);
} else {
vm.course.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('admin.courses.list');
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
}
}());
|
Remove public keyword from interface declarations | package org.commcare.android.tasks.templates;
/**
* @author ctsims
*/
public interface CommCareTaskConnector<R> {
/**
* IMPORTANT: Any implementing class of CommCareTaskConnector should be
* implemented such that it will only automatically manage the dialog of a
* connected task IF the task id is non-negative. If the user does NOT
* want to implement a dialog, or is implementing the dialog in a
* different way, they should be able to use a negative task id in order
* to avoid this.
*/
<A, B, C> void connectTask(CommCareTask<A,B,C,R> task);
/**
* Should call showProgressDialog() for a task if its id is non-negative,
* and if there is no dialog already showing
*/
void startBlockingForTask(int id);
/**
* Should call dismissProgressDialog() for a task if its id is
* non-negative, and if shouldDismissDialog is true (this flag should be
* controlled by the task transition)
*/
void stopBlockingForTask(int id);
void taskCancelled(int id);
R getReceiver();
/**
* Should be called at the beginning of onPostExecute or onCancelled for
* any CommCareTask, indicating that we are starting a potential transition
* from one task to another (if the end of the first task triggers the
* start of another)
*/
void startTaskTransition();
/**
* Should be called at the end of onPreExecute or onCancelled for any
* CommCareTask, indicating that we are ending a potential transition from
* one task to another
*/
void stopTaskTransition();
}
| package org.commcare.android.tasks.templates;
/**
* @author ctsims
*/
public interface CommCareTaskConnector<R> {
/**
* IMPORTANT: Any implementing class of CommCareTaskConnector should be
* implemented such that it will only automatically manage the dialog of a
* connected task IF the task id is non-negative. If the user does NOT
* want to implement a dialog, or is implementing the dialog in a
* different way, they should be able to use a negative task id in order
* to avoid this.
*/
public <A, B, C> void connectTask(CommCareTask<A,B,C,R> task);
/**
* Should call showProgressDialog() for a task if its id is non-negative,
* and if there is no dialog already showing
*/
public void startBlockingForTask(int id);
/**
* Should call dismissProgressDialog() for a task if its id is
* non-negative, and if shouldDismissDialog is true (this flag should be
* controlled by the task transition)
*/
public void stopBlockingForTask(int id);
public void taskCancelled(int id);
public R getReceiver();
/**
* Should be called at the beginning of onPostExecute or onCancelled for
* any CommCareTask, indicating that we are starting a potential transition
* from one task to another (if the end of the first task triggers the
* start of another)
*/
public void startTaskTransition();
/**
* Should be called at the end of onPreExecute or onCancelled for any
* CommCareTask, indicating that we are ending a potential transition from
* one task to another
*/
public void stopTaskTransition();
}
|
Replace undefined with null as default for index for BufferGeometry | import * as THREE from 'three';
import PropTypes from 'prop-types';
import GeometryDescriptorBase from './GeometryDescriptorBase';
import propTypeInstanceOf from '../../utils/propTypeInstanceOf';
class BufferGeometryDescriptor extends GeometryDescriptorBase {
constructor(react3RendererInstance) {
super(react3RendererInstance);
[
'vertices',
'colors',
'faceVertexUvs',
'faces',
'dynamic',
].forEach((propName) => {
this.removeProp(propName);
});
[
'position',
'normal',
'color',
'uv',
].forEach((attributeName) => {
this.hasProp(attributeName, {
type: PropTypes.oneOfType([
propTypeInstanceOf(THREE.BufferAttribute),
propTypeInstanceOf(THREE.InterleavedBufferAttribute),
]),
update(threeObject, attributeValue) {
if (attributeValue) {
threeObject.addAttribute(attributeName, attributeValue);
} else {
threeObject.removeAttribute(attributeName);
}
},
updateInitial: true,
default: undefined,
});
});
this.hasProp('index', {
type: PropTypes.oneOfType([
propTypeInstanceOf(THREE.BufferAttribute),
propTypeInstanceOf(THREE.InterleavedBufferAttribute),
]),
update(threeObject, attributeValue) {
threeObject.setIndex(attributeValue);
},
updateInitial: true,
default: null,
});
}
construct() {
return new THREE.BufferGeometry();
}
}
module.exports = BufferGeometryDescriptor;
| import * as THREE from 'three';
import PropTypes from 'prop-types';
import GeometryDescriptorBase from './GeometryDescriptorBase';
import propTypeInstanceOf from '../../utils/propTypeInstanceOf';
class BufferGeometryDescriptor extends GeometryDescriptorBase {
constructor(react3RendererInstance) {
super(react3RendererInstance);
[
'vertices',
'colors',
'faceVertexUvs',
'faces',
'dynamic',
].forEach((propName) => {
this.removeProp(propName);
});
[
'position',
'normal',
'color',
'uv',
].forEach((attributeName) => {
this.hasProp(attributeName, {
type: PropTypes.oneOfType([
propTypeInstanceOf(THREE.BufferAttribute),
propTypeInstanceOf(THREE.InterleavedBufferAttribute),
]),
update(threeObject, attributeValue) {
if (attributeValue) {
threeObject.addAttribute(attributeName, attributeValue);
} else {
threeObject.removeAttribute(attributeName);
}
},
updateInitial: true,
default: undefined,
});
});
this.hasProp('index', {
type: PropTypes.oneOfType([
propTypeInstanceOf(THREE.BufferAttribute),
propTypeInstanceOf(THREE.InterleavedBufferAttribute),
]),
update(threeObject, attributeValue) {
threeObject.setIndex(attributeValue);
},
updateInitial: true,
default: undefined,
});
}
construct() {
return new THREE.BufferGeometry();
}
}
module.exports = BufferGeometryDescriptor;
|
Move string above the imports so it becomes a docstring | """ Super simple IMS mock.
Just listens on localhost:8080 for the appropriate url, returns a test role and
a dummy JSON response.
"""
from __future__ import print_function, absolute_import, unicode_literals, division
from datetime import datetime, timedelta
from textwrap import dedent
from bottle import Bottle
import pytz
def expiration_10s_from_now():
n = datetime.now(tz=pytz.utc) + timedelta(seconds=10)
return n.strftime("%Y-%m-%dT%H:%M:%SZ")
class MockIms(Bottle):
PATH = '/latest/meta-data/iam/security-credentials/'
json_response = dedent("""
{"Code": "Success",
"AccessKeyId": "ASIAI",
"SecretAccessKey": "XXYYZZ",
"Token": "0123456789abcdefghijklmnopqrstuvwxyzAB",
"Expiration": "%s",
"Type": "AWS-HMAC"}
""")
def __init__(self):
super(MockIms, self).__init__()
self.route(self.PATH, callback=self.get_roles)
self.route(self.PATH + '<role>', callback=self.get_credentials)
def get_roles(self):
return 'test_role'
def get_credentials(self, role):
return self.json_response % expiration_10s_from_now() if role == 'test_role' else ''
if __name__ == "__main__":
MockIms().run()
| from __future__ import print_function, absolute_import, unicode_literals, division
from datetime import datetime, timedelta
from textwrap import dedent
from bottle import Bottle
import pytz
""" Super simple IMS mock.
Just listens on localhost:8080 for the appropriate url, returns a test role and
a dummy JSON response.
"""
def expiration_10s_from_now():
n = datetime.now(tz=pytz.utc) + timedelta(seconds=10)
return n.strftime("%Y-%m-%dT%H:%M:%SZ")
class MockIms(Bottle):
PATH = '/latest/meta-data/iam/security-credentials/'
json_response = dedent("""
{"Code": "Success",
"AccessKeyId": "ASIAI",
"SecretAccessKey": "XXYYZZ",
"Token": "0123456789abcdefghijklmnopqrstuvwxyzAB",
"Expiration": "%s",
"Type": "AWS-HMAC"}
""")
def __init__(self):
super(MockIms, self).__init__()
self.route(self.PATH, callback=self.get_roles)
self.route(self.PATH + '<role>', callback=self.get_credentials)
def get_roles(self):
return 'test_role'
def get_credentials(self, role):
return self.json_response % expiration_10s_from_now() if role == 'test_role' else ''
if __name__ == "__main__":
MockIms().run()
|
Remove unused code from line graph view | define([
'extensions/views/graph/graph'
],
function (Graph) {
var LineGraph = Graph.extend({
components: function () {
var labelOptions, yAxisOptions;
if (this.isOneHundredPercent()) {
labelOptions = {
showValues: true,
showValuesPercentage: true,
isLineGraph: true,
showOriginalValues: true,
showSummary: false
};
yAxisOptions = {
tickFormat: function () {
return function (d) {
return d * 100 + '%';
};
}
};
}
return {
axis: { view: this.sharedComponents.xaxis },
yaxis: {
view: this.sharedComponents.yaxis,
options: yAxisOptions
},
linelabel: {
view: this.sharedComponents.linelabel,
options: labelOptions
},
line: {
view: this.sharedComponents.line,
options: {
interactive: function (e) {
return e.slice % 3 !== 2;
}
}
},
callout: {
view: this.sharedComponents.callout,
options: {
showPercentage: this.isOneHundredPercent()
}
},
hover: { view: this.sharedComponents.hover }
};
}
});
return LineGraph;
});
| define([
'extensions/views/graph/graph',
'extensions/views/graph/linelabel'
],
function (Graph, LineLabel) {
var LineGraph = Graph.extend({
components: function () {
var labelComponent, labelOptions, yAxisOptions;
if (this.isOneHundredPercent()) {
labelComponent = LineLabel;
labelOptions = {
showValues: true,
showValuesPercentage: true,
isLineGraph: true,
showOriginalValues: true,
showSummary: false
};
yAxisOptions = {
tickFormat: function () {
return function (d) {
return d * 100 + '%';
};
}
};
} else {
labelComponent = this.sharedComponents.linelabel;
}
labelComponent = this.sharedComponents.linelabel;
return {
axis: { view: this.sharedComponents.xaxis },
yaxis: {
view: this.sharedComponents.yaxis,
options: yAxisOptions
},
linelabel: {
view: labelComponent,
options: labelOptions
},
line: {
view: this.sharedComponents.line,
options: {
interactive: function (e) {
return e.slice % 3 !== 2;
}
}
},
callout: {
view: this.sharedComponents.callout,
options: {
showPercentage: this.isOneHundredPercent()
}
},
hover: { view: this.sharedComponents.hover }
};
}
});
return LineGraph;
});
|
Add comment to explain the length of the scripts taken into account in DuplicateScripts | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, self).__init__()
self.total_duplicate = 0
self.list_duplicate = []
def finalize(self):
"""Output the duplicate scripts detected."""
if self.total_duplicate > 0:
print("%d duplicate scripts found" % self.total_duplicate)
for duplicate in self.list_duplicate:
print duplicate
def analyze(self, scratch):
"""Run and return the results from the DuplicateChecks plugin.
Only takes into account scripts with more than 3 blocks"""
scripts_set = set()
for script in self.iter_scripts(scratch):
blocks_list = []
for name, _, _ in self.iter_blocks(script.blocks):
blocks_list.append(name)
blocks_tuple = tuple(blocks_list)
if blocks_tuple in scripts_set:
if len(blocks_list)>3:
self.total_duplicate += 1
self.list_duplicate.append(blocks_list)
else:
scripts_set.add(blocks_tuple)
| """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, self).__init__()
self.total_duplicate = 0
self.list_duplicate = []
def finalize(self):
"""Output the duplicate scripts detected."""
if self.total_duplicate > 0:
print("%d duplicate scripts found" % self.total_duplicate)
for duplicate in self.list_duplicate:
print duplicate
def analyze(self, scratch):
"""Run and return the results from the DuplicateChecks plugin."""
scripts_set = set()
for script in self.iter_scripts(scratch):
blocks_list = []
for name, _, _ in self.iter_blocks(script.blocks):
blocks_list.append(name)
blocks_tuple = tuple(blocks_list)
if blocks_tuple in scripts_set:
if len(blocks_list)>3:
self.total_duplicate += 1
self.list_duplicate.append(blocks_list)
else:
scripts_set.add(blocks_tuple)
|
Fix case converter for receiving multiple arguments | <?php
namespace Omelet\Util;
use Camel\Format;
final class CaseSensor
{
private static $formatters = [];
public static function LowerSnake()
{
return new self(Format\SnakeCase::class);
}
public static function UpperSnake()
{
return new self(Format\ScreamingSnakeCase::class);
}
public static function LowerCamel()
{
return new self(Format\CamelCase::class);
}
public static function UpperCamel()
{
return new self(Format\StudlyCaps::class);
}
private static function getFormatter($class)
{
if (! isset(self::$formatters[$class])) {
$f = new $class();
self::$formatters[$class] = $f;
}
else {
$f = self::$formatters[$class];
}
return $f;
}
/**
* @Format\FormatInterface
*/
private $formatter;
private function __construct($formatterClass)
{
$this->formatter = self::getFormatter($formatterClass);
}
public function convert(...$inputs)
{
$tokens = [];
foreach ($inputs as $input) {
$tokens[] = $this->getSplitter($input)->split($input);
}
return $this->formatter->join(call_user_func_array('array_merge', $tokens));
}
private function getSplitter($input)
{
if (strpos($input, '_') !== false) {
return self::getFormatter(Format\SnakeCase::class);
}
else {
return self::getFormatter(Format\CamelCase::class);
}
}
}
| <?php
namespace Omelet\Util;
use Camel\Format;
final class CaseSensor
{
private static $formatters = [];
public static function LowerSnake()
{
return new self(self::getFormatter(Format\SnakeCase::class));
}
public static function UpperSnake()
{
return new self(self::getFormatter(Format\ScreamingSnakeCase::class));
}
public static function LowerCamel()
{
return new self(self::getFormatter(Format\CamelCase::class));
}
public static function UpperCamel()
{
return new self(self::getFormatter(Format\StudlyCaps::class));
}
private static function getFormatter($class)
{
if (! isset(self::$formatters[$class])) {
$f = new $class();
self::$formatters[$class] = $f;
}
else {
$f = self::$formatters[$class];
}
return $f;
}
/**
* @Format\FormatInterface
*/
private $formatter;
private function __construct(Format\FormatInterface $formatter)
{
$this->formatter = $formatter;
}
public function convert($input)
{
$tokens = $this->getSplitter($input)->split($input);
return $this->formatter->join($tokens);
}
private function getSplitter($input)
{
if (strpos($input, '_') !== false) {
return self::getFormatter(Format\SnakeCase::class);
}
else {
return self::getFormatter(Format\CamelCase::class);
}
}
}
|
Add get_config as GPIO action | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read', 'get_config')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key,
request_action=self._perform_gpio_action)
def _perform_gpio_action(self, instruction):
result = {'error': 1, 'response': "An error occurred"}
if instruction['action'] not in ALLOWED_ACTIONS:
result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS))
return result
try:
pin = instruction['pin']
except KeyError:
try:
result['response'] = getattr(self.pins, instruction['action'])()
result['error'] = 0
except Exception as e:
result['response'] = e.message
else:
try:
result['response'] = getattr(self.pins, instruction['action'])(int(pin))
result['error'] = 0
except ValueError:
result['response'] = "'pin' value must be an integer"
except Exception as e:
result['response'] = e.message
return result
def stop(self):
self.pins.cleanup()
super(GPIOService, self).stop()
| from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key,
request_action=self._perform_gpio_action)
def _perform_gpio_action(self, instruction):
result = {'error': 1, 'pin': instruction['pin'], 'response': "An error occurred"}
if instruction['action'] not in ALLOWED_ACTIONS:
result['response'] = "'action' must be one of: {0}".format(', '.join(ALLOWED_ACTIONS))
return result
try:
result['response'] = getattr(self.pins, instruction['action'])(int(instruction['pin']))
result['error'] = 0
except ValueError:
result['response'] = "'pin' value must be an integer"
except Exception as e:
result['response'] = e.message
return result
def stop(self):
self.pins.cleanup()
super(GPIOService, self).stop()
|
Fix demo for <SplitView> to match prop changes of <ColumnView> | import React from 'react';
import SplitView from '@ichef/gypcrete/src/SplitView';
import SplitViewColumn from '@ichef/gypcrete/src/SplitViewColumn';
import DebugBox from 'utils/DebugBox';
import ColoredBox from 'utils/ColoredBox';
import DemoColumnView from './DemoColumnView';
function InsideColumnView() {
return (
<DebugBox width="40rem" height="24rem">
<DemoColumnView bodyPadding={{ bottom: 0 }}>
<SplitView>
<SplitViewColumn>
<ColoredBox
width="100%"
height="30rem"
color="rgb(255, 235, 235)">
Narrow Column
</ColoredBox>
</SplitViewColumn>
<SplitViewColumn wide>
<ColoredBox
width="100%"
height="30rem"
color="rgb(235, 245, 255)">
Narrow Column
</ColoredBox>
</SplitViewColumn>
</SplitView>
</DemoColumnView>
</DebugBox>
);
}
export default InsideColumnView;
| import React from 'react';
import SplitView from '@ichef/gypcrete/src/SplitView';
import SplitViewColumn from '@ichef/gypcrete/src/SplitViewColumn';
import DebugBox from 'utils/DebugBox';
import ColoredBox from 'utils/ColoredBox';
import DemoColumnView from './DemoColumnView';
function InsideColumnView() {
return (
<DebugBox width="40rem" height="24rem">
<DemoColumnView bottomPadding="0">
<SplitView>
<SplitViewColumn>
<ColoredBox
width="100%"
height="30rem"
color="rgb(255, 235, 235)">
Narrow Column
</ColoredBox>
</SplitViewColumn>
<SplitViewColumn wide>
<ColoredBox
width="100%"
height="30rem"
color="rgb(235, 245, 255)">
Narrow Column
</ColoredBox>
</SplitViewColumn>
</SplitView>
</DemoColumnView>
</DebugBox>
);
}
export default InsideColumnView;
|
Add RFS to `sendgrid` test | import sendgrid
import os
from flask import request, Flask
app = Flask(__name__)
@app.route("/sendgrid")
def send():
sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
data = {
"content": [
{
"type": "text/html",
"value": "<html>{}</html>".format(request.args["html_content"])
}
],
"from": {
"email": "[email protected]",
"name": "Sam Smith"
},
"headers": {},
"mail_settings": {
"footer": {
"enable": True,
"html": "<html>{}</html>".format(request.args["html_footer"]),
"text": "Thanks,/n The SendGrid Team"
},
},
"reply_to": {
"email": "[email protected]",
"name": "Sam Smith"
},
"send_at": 1409348513,
"subject": "Hello, World!",
"template_id": "[YOUR TEMPLATE ID GOES HERE]",
"tracking_settings": {
"subscription_tracking": {
"enable": True,
"html": "<html>{}</html>".format(request.args["html_tracking"]),
"substitution_tag": "<%click here%>",
"text": "If you would like to unsubscribe and stop receiving these emails <% click here %>."
}
}
}
response = sg.client.mail.send.post(request_body=data)
| # This tests that the developer doesn't pass tainted user data into the mail.send.post() method in the SendGrid library.
import sendgrid
import os
sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
data = {
"content": [
{
"type": "text/html",
"value": "<html><p>Hello, world!</p><img src=[CID GOES HERE]></img></html>"
}
],
"from": {
"email": "[email protected]",
"name": "Sam Smith"
},
"headers": {},
"mail_settings": {
"footer": {
"enable": True,
"html": "<p>Thanks</br>The SendGrid Team</p>",
"text": "Thanks,/n The SendGrid Team"
},
},
"reply_to": {
"email": "[email protected]",
"name": "Sam Smith"
},
"send_at": 1409348513,
"subject": "Hello, World!",
"template_id": "[YOUR TEMPLATE ID GOES HERE]",
"tracking_settings": {
"subscription_tracking": {
"enable": True,
"html": "If you would like to unsubscribe and stop receiving these emails <% clickhere %>.",
"substitution_tag": "<%click here%>",
"text": "If you would like to unsubscribe and stop receiving these emails <% click here %>."
}
}
}
response = sg.client.mail.send.post(request_body=data)
|
Add handling of online/offline event | import React from 'react';
import {Link} from 'react-router';
export default class Header extends React.Component {
constructor() {
super();
this.state = {online: navigator.onLine};
}
componentDidMoun() {
window.addEventListener('online', this.updateOnlineState.bind(this));
window.addEventListener('offline', this.updateOnlineState.bind(this));
}
updateOnlineState() {
this.setState({online: navigator.onLine});
}
render() {
var offline = false;
if (!this.state.online) offline = (<span className="offline">offline</span>);
return (
<div className="header">
<div className="container">
<Link to="builds" className="brand">
Frigg CI
{offline}
</Link>
<div className="navigation">
<Link to="builds" className="button">Builds</Link>
<StaffButton href="/stats/" text="Stats" {...this.props.user} />
<StaffButton href="/admin/" text="Admin" {...this.props.user} />
<LogInOutButton {...this.props.user} />
</div>
</div>
</div>
);
}
}
export class LogInOutButton extends React.Component {
render() {
if (this.props.is_anonymous === false) {
return (
<a href="/auth/logout/" className="button">Logout</a>
);
} else {
return (
<a href="/auth/login/" className="button">Login</a>
);
}
}
}
export class StaffButton extends React.Component {
render() {
if (this.props.is_staff === false) return false;
return (
<a href={this.props.href} className="button">{this.props.text}</a>
);
}
}
| import React from 'react';
import {Link} from 'react-router';
export default class Header extends React.Component {
render() {
var offline = false;
if (!navigator.onLine) offline = (<span className="offline">offline</span>);
return (
<div className="header">
<div className="container">
<Link to="builds" className="brand">
Frigg CI
{offline}
</Link>
<div className="navigation">
<Link to="builds" className="button">Builds</Link>
<StaffButton href="/stats/" text="Stats" {...this.props.user} />
<StaffButton href="/admin/" text="Admin" {...this.props.user} />
<LogInOutButton {...this.props.user} />
</div>
</div>
</div>
);
}
}
export class LogInOutButton extends React.Component {
render() {
if (this.props.is_anonymous === false) {
return (
<a href="/auth/logout/" className="button">Logout</a>
);
} else {
return (
<a href="/auth/login/" className="button">Login</a>
);
}
}
}
export class StaffButton extends React.Component {
render() {
if (this.props.is_staff === false) return false;
return (
<a href={this.props.href} className="button">{this.props.text}</a>
);
}
}
|
Throw Exception if is empty | <?php
namespace marmelab\NgAdminGeneratorBundle\Generator;
use Doctrine\ORM\EntityManagerInterface;
use marmelab\NgAdminGeneratorBundle\Transformer\TransformerInterface;
class ConfigurationGenerator
{
private $em;
private $twig;
/** @var TransformerInterface[] */
private $transformers = [];
public function __construct(array $transformers = [], EntityManagerInterface $em, \Twig_Environment $twig)
{
$this->transformers = $transformers;
$this->em = $em;
$this->twig = $twig;
}
public function generateConfiguration(array $objectDefinitions)
{
if (empty($objectDefinitions)) {
throw new \RuntimeException("No entity available for generation.");
}
$transformedData = [];
foreach ($this->transformers as $transformer) {
$inputData = count($transformedData) ? $transformedData: $objectDefinitions;
$transformedData = [];
foreach ($inputData as $input) {
$transformedData[] = $transformer->transform($input);
}
}
$dataWithKeys = [];
foreach ($transformedData as $data) {
$dataWithKeys[$data['name']] = $data;
}
return $this->twig->render('marmelabNgAdminGeneratorBundle:Configuration:config.js.twig', [
'entities' => $dataWithKeys
]);
}
}
| <?php
namespace marmelab\NgAdminGeneratorBundle\Generator;
use Doctrine\ORM\EntityManagerInterface;
use marmelab\NgAdminGeneratorBundle\Transformer\TransformerInterface;
class ConfigurationGenerator
{
private $em;
private $twig;
/** @var TransformerInterface[] */
private $transformers = [];
public function __construct(array $transformers = [], EntityManagerInterface $em, \Twig_Environment $twig)
{
$this->transformers = $transformers;
$this->em = $em;
$this->twig = $twig;
}
public function generateConfiguration(array $objectDefinitions)
{
$transformedData = [];
foreach ($this->transformers as $transformer) {
$inputData = count($transformedData) ? $transformedData: $objectDefinitions;
if (empty($inputData)) {
throw new \RuntimeException("No entity available for generation.");
}
$transformedData = [];
foreach ($inputData as $input) {
$transformedData[] = $transformer->transform($input);
}
}
$dataWithKeys = [];
foreach ($transformedData as $data) {
$dataWithKeys[$data['name']] = $data;
}
return $this->twig->render('marmelabNgAdminGeneratorBundle:Configuration:config.js.twig', [
'entities' => $dataWithKeys
]);
}
}
|
Update Core dependency to v27 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.7.0",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >= 27.0, < 28.0",
],
extras_require = {
"dev": [
"autopep8 == 1.4.0",
"flake8 >= 3.5.0, < 3.6.0",
"flake8-print",
"pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.7.0",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >= 26.0, < 27.0",
],
extras_require = {
"dev": [
"autopep8 == 1.4.0",
"flake8 >= 3.5.0, < 3.6.0",
"flake8-print",
"pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
|
Fix missing serialized name annotation | package co.phoenixlab.discord.api.entities;
import com.google.gson.annotations.SerializedName;
public class ReadyMessage {
@SerializedName("v")
private int version;
private User user;
@SerializedName("session_id")
private String sessionId;
@SerializedName("read_state")
private ReadState[] readState;
@SerializedName("private_channels")
private PrivateChannel[] privateChannels;
@SerializedName("heartbeat_interval")
private long heartbeatInterval;
@SerializedName("guilds")
private Server[] servers;
public ReadyMessage() {
}
public int getVersion() {
return version;
}
public User getUser() {
return user;
}
public String getSessionId() {
return sessionId;
}
public ReadState[] getReadState() {
return readState;
}
public PrivateChannel[] getPrivateChannels() {
return privateChannels;
}
public long getHeartbeatInterval() {
return heartbeatInterval;
}
public Server[] getServers() {
return servers;
}
class ReadState {
@SerializedName("mention_count")
private int mentionCount;
@SerializedName("last_message_id")
private String lastMessageId;
private String id;
public int getMentionCount() {
return mentionCount;
}
public String getLastMessageId() {
return lastMessageId;
}
public String getId() {
return id;
}
}
}
| package co.phoenixlab.discord.api.entities;
import com.google.gson.annotations.SerializedName;
public class ReadyMessage {
@SerializedName("v")
private int version;
private User user;
private String sessionId;
@SerializedName("read_state")
private ReadState[] readState;
@SerializedName("private_channels")
private PrivateChannel[] privateChannels;
@SerializedName("heartbeat_interval")
private long heartbeatInterval;
@SerializedName("guilds")
private Server[] servers;
public ReadyMessage() {
}
public int getVersion() {
return version;
}
public User getUser() {
return user;
}
public String getSessionId() {
return sessionId;
}
public ReadState[] getReadState() {
return readState;
}
public PrivateChannel[] getPrivateChannels() {
return privateChannels;
}
public long getHeartbeatInterval() {
return heartbeatInterval;
}
public Server[] getServers() {
return servers;
}
class ReadState {
@SerializedName("mention_count")
private int mentionCount;
@SerializedName("last_message_id")
private String lastMessageId;
private String id;
public int getMentionCount() {
return mentionCount;
}
public String getLastMessageId() {
return lastMessageId;
}
public String getId() {
return id;
}
}
}
|
Fix js error when using node < 4.x | var is = require('is');
var Immutable = require('immutable');
var Promise = require('../../utils/promise');
var editHTMLElement = require('./editHTMLElement');
/**
Return language for a code blocks from a list of class names
@param {Array<String>}
@return {String}
*/
function getLanguageForClass(classNames) {
return Immutable.List(classNames)
.map(function(cl) {
// Markdown
if (cl.search('lang-') === 0) {
return cl.slice('lang-'.length);
}
// Asciidoc
if (cl.search('language-') === 0) {
return cl.slice('language-'.length);
}
return null;
})
.find(function(cl) {
return Boolean(cl);
});
}
/**
Highlight all code elements
@param {Function(lang, body) -> String} highlight
@param {HTMLDom} $
@return {Promise}
*/
function highlightCode(highlight, $) {
return editHTMLElement($, 'code', function($code) {
var classNames = ($code.attr('class') || '').split(' ');
var lang = getLanguageForClass(classNames);
var source = $code.text();
return Promise(highlight(lang, source))
.then(function(r) {
if (is.string(r.html)) {
$code.html(r.html);
} else {
$code.text(r.text);
}
});
});
}
module.exports = highlightCode;
| var is = require('is');
var Promise = require('../../utils/promise');
var editHTMLElement = require('./editHTMLElement');
/**
Return language for a code blocks from a list of class names
@param {Array<String>}
@return {String}
*/
function getLanguageForClass(classNames) {
return classNames
.map(function(cl) {
// Markdown
if (cl.search('lang-') === 0) {
return cl.slice('lang-'.length);
}
// Asciidoc
if (cl.search('language-') === 0) {
return cl.slice('language-'.length);
}
return null;
})
.find(function(cl) {
return Boolean(cl);
});
}
/**
Highlight all code elements
@param {Function(lang, body) -> String} highlight
@param {HTMLDom} $
@return {Promise}
*/
function highlightCode(highlight, $) {
return editHTMLElement($, 'code', function($code) {
var classNames = ($code.attr('class') || '').split(' ');
var lang = getLanguageForClass(classNames);
var source = $code.text();
return Promise(highlight(lang, source))
.then(function(r) {
if (is.string(r.html)) {
$code.html(r.html);
} else {
$code.text(r.text);
}
});
});
}
module.exports = highlightCode;
|
Test Head Behavior: Apply new HLM | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from humanoid_league_msgs.msg import BallInImage, BallRelative, BallInImageArray
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
def run():
pub_ball = rospy.Publisher("ball_in_image", BallsInImage, queue_size=1)
pub_hmg = rospy.Publisher("head_motor_goals", JointTrajectory, queue_size=1)
hmg = JointTrajectory()
goal = JointTrajectoryPoint()
goal.positions = [0, 0]
goal.velocities = [0, 0]
hmg.points = [goal]
counter = 320
direction = 1
rospy.loginfo("Create Test")
rospy.init_node("bitbots_testHeadBehaviour")
pub_hmg.publish(hmg)
rate = rospy.Rate(4)
rospy.logdebug("Laeuft...")
while not rospy.is_shutdown():
# Ball in Image
ball = BallInImage()
ball.center.x = counter
if(counter > 340 or counter < 300):
direction *= -1
counter += direction
else:
counter += direction
ball.center.y = 200
ball.diameter = 10
ball.confidence = 1
balls = BallInImageArray()
balls.candidates.append(ball)
pub_ball.publish(balls)
rospy.loginfo("Published ball: %s" % counter)
rate.sleep()
if __name__ == "__main__":
run()
| #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from humanoid_league_msgs.msg import BallInImage, BallRelative, BallsInImage
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
def run():
pub_ball = rospy.Publisher("ball_in_image", BallsInImage, queue_size=1)
pub_hmg = rospy.Publisher("head_motor_goals", JointTrajectory, queue_size=1)
hmg = JointTrajectory()
goal = JointTrajectoryPoint()
goal.positions = [0, 0]
goal.velocities = [0, 0]
hmg.points = [goal]
counter = 320
direction = 1
rospy.loginfo("Create Test")
rospy.init_node("bitbots_testHeadBehaviour")
pub_hmg.publish(hmg)
rate = rospy.Rate(4)
rospy.logdebug("Laeuft...")
while not rospy.is_shutdown():
# Ball in Image
ball = BallInImage()
ball.center.x = counter
if(counter > 340 or counter < 300):
direction *= -1
counter += direction
else:
counter += direction
ball.center.y = 200
ball.diameter = 10
ball.confidence = 1
balls = BallsInImage()
balls.candidates.append(ball)
pub_ball.publish(balls)
rospy.loginfo("Published ball: %s" % counter)
rate.sleep()
if __name__ == "__main__":
run()
|
Use build() result for test | !function (assert, path) {
'use strict';
require('vows').describe('Integration test').addBatch({
'When minifying a CSS file': {
topic: function () {
var callback = this.callback,
topic;
require('publishjs')({
cache: false,
log: false,
processors: {
cssmin: require('../index')
}
}).build(function (pipe, callback) {
pipe.from(path.resolve(path.dirname(module.filename), 'integration-test-files'))
.cssmin()
.run(callback);
}, callback);
},
'should returns a minified copy': function (topic) {
assert.equal(Object.getOwnPropertyNames(topic).length, 1);
assert.equal(topic['default.css'].toString(), 'html,body{font-family:Arial}');
}
}
}).export(module);
}(
require('assert'),
require('path')
); | !function (assert, path) {
'use strict';
require('vows').describe('Integration test').addBatch({
'When minifying a CSS file': {
topic: function () {
var callback = this.callback,
topic;
require('publishjs')({
cache: false,
log: false,
processors: {
cssmin: require('../index')
}
}).build(function (pipe) {
pipe.from(path.resolve(path.dirname(module.filename), 'integration-test-files'))
.cssmin()
.run(callback);
}, callback);
},
'should returns a minified copy': function (topic) {
assert.equal(Object.getOwnPropertyNames(topic).length, 1);
assert.equal(topic['default.css'].buffer.toString(), 'html,body{font-family:Arial}');
}
}
}).export(module);
}(
require('assert'),
require('path')
); |
Install requires pycryptodome, not pycrypto
PyCrypto version on PyPi is 2.6, but sjcl requires 2.7.
PyCrypto is not maintained. PyCryptodome is a drop in replacement.
A fresh install of sjcl with PyCrypto in Python 3.6.1 on macOS results
in error on:
File "/Users/jthetzel/.local/src/py_test/venv/lib/python3.6/
site-packages/sjcl/sjcl.py", line 76, in check_mode_ccm
"You need a version >= 2.7a1 (or a special branch)."
Exception: Pycrypto does not seem to support MODE_CCM.
You need a version >= 2.7a1 (or a special branch).
A fresh install of sjcl with PyCryptodome has no error. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('pandoc -o README.rst README.md')
os.system('python setup.py sdist upload')
sys.exit()
README = open('README.md').read()
HISTORY = open('CHANGES.txt').read().replace('.. :changelog:', '')
setup(
name='sjcl',
version='0.1.5',
description="""
Decrypt and encrypt messages compatible to the "Stanford Javascript Crypto
Library (SJCL)" message format.
This module was created while programming and testing the encrypted
blog platform on cryptedblog.com which is based on sjcl.
""",
long_description=README + '\n\n' + HISTORY,
author='Ulf Bartel',
author_email='[email protected]',
url='https://github.com/berlincode/sjcl',
packages=[
'sjcl',
],
package_dir={'sjcl': 'sjcl'},
include_package_data=True,
install_requires=['pycryptodome'], # TODO add version >=
license="new-style BSD",
zip_safe=False,
keywords='SJCL, AES, encryption, pycrypto, Javascript',
entry_points={
},
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
],
test_suite='tests',
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('pandoc -o README.rst README.md')
os.system('python setup.py sdist upload')
sys.exit()
README = open('README.md').read()
HISTORY = open('CHANGES.txt').read().replace('.. :changelog:', '')
setup(
name='sjcl',
version='0.1.5',
description="""
Decrypt and encrypt messages compatible to the "Stanford Javascript Crypto
Library (SJCL)" message format.
This module was created while programming and testing the encrypted
blog platform on cryptedblog.com which is based on sjcl.
""",
long_description=README + '\n\n' + HISTORY,
author='Ulf Bartel',
author_email='[email protected]',
url='https://github.com/berlincode/sjcl',
packages=[
'sjcl',
],
package_dir={'sjcl': 'sjcl'},
include_package_data=True,
install_requires=['pycrypto'], # TODO add version >=
license="new-style BSD",
zip_safe=False,
keywords='SJCL, AES, encryption, pycrypto, Javascript',
entry_points={
},
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
],
test_suite='tests',
)
|
Return invalid if payment method is not supported yet | from mhvdb2.models import Payment, Entity
import re
from datetime import datetime
from peewee import DoesNotExist
def validate(amount, email, method, type, notes, reference):
errors = []
if not amount or not amount.isdigit() or int(amount) <= 0:
errors.append("Sorry, you need to provide a valid amount.")
if not re.match("[^@\s]+@[^@\s]+", email):
errors.append("Sorry, you need to provide a valid email address.")
else: # Valid email, so check that they're a member
try:
Entity.get(Entity.email == email)
except DoesNotExist:
errors.append("Sorry, you need to provide a valid member's email address.")
if not type or not type.isdigit() or int(type) > 2:
errors.append("Sorry, you need to provide a valid payment type.")
if not method or not method.isdigit() or int(method) > 0:
errors.append("Sorry, you need to provide a valid payment method.")
if not reference:
errors.append("Sorry, you need to provide a reference.")
return errors
def create(amount, email, method, type, notes, reference):
# Create payment
payment = Payment()
payment.time = datetime.now()
payment.entity = Entity.get(Entity.email == email)
payment.amount = amount
payment.source = method
payment.is_donation = type != 0
payment.notes = notes
if method == 0: # Bank transfer
payment.bank_reference = reference
payment.pending = True
payment.save()
| from mhvdb2.models import Payment, Entity
import re
from datetime import datetime
from peewee import DoesNotExist
def validate(amount, email, method, type, notes, reference):
errors = []
if not amount or not amount.isdigit() or int(amount) <= 0:
errors.append("Sorry, you need to provide a valid amount.")
if not re.match("[^@\s]+@[^@\s]+", email):
errors.append("Sorry, you need to provide a valid email address.")
else: # Valid email, so check that they're a member
try:
Entity.get(Entity.email == email)
except DoesNotExist:
errors.append("Sorry, you need to provide a valid member's email address.")
if not type or not type.isdigit() or int(type) > 2:
errors.append("Sorry, you need to provide a valid payment type.")
if not method or not method.isdigit() or int(method) > 2:
errors.append("Sorry, you need to provide a valid payment method.")
if not reference:
errors.append("Sorry, you need to provide a reference.")
return errors
def create(amount, email, method, type, notes, reference):
# Create payment
payment = Payment()
payment.time = datetime.now()
payment.entity = Entity.get(Entity.email == email)
payment.amount = amount
payment.source = method
payment.is_donation = type != 0
payment.notes = notes
if method == 0: # Bank transfer
payment.bank_reference = reference
payment.pending = True
payment.save()
|
Use Launchpad page as URL | from setuptools import setup, find_packages
from setuptools.command.install import install as Install
import re
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("axiom/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
class InstallAndRegenerate(Install):
def run(self):
"""
Runs the usual install logic, then regenerates the plugin cache.
"""
Install.run(self)
from twisted import plugin
list(plugin.getPlugins(plugin.IPlugin, "axiom.plugins"))
setup(
name="Axiom",
version=version,
description="An in-process object-relational database",
url="https://launchpad.net/divmod.org",
maintainer="Divmod, Inc.",
maintainer_email="[email protected]",
install_requires=["twisted", "epsilon"],
packages=find_packages() + ['twisted.plugins'],
scripts=['bin/axiomatic'],
license="MIT",
platforms=["any"],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Framework :: Twisted",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 2 :: Only",
"Topic :: Database"])
| from setuptools import setup, find_packages
from setuptools.command.install import install as Install
import re
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("axiom/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
class InstallAndRegenerate(Install):
def run(self):
"""
Runs the usual install logic, then regenerates the plugin cache.
"""
Install.run(self)
from twisted import plugin
list(plugin.getPlugins(plugin.IPlugin, "axiom.plugins"))
setup(
name="Axiom",
version=version,
description="An in-process object-relational database",
url="http://divmod.org/trac/wiki/DivmodAxiom",
maintainer="Divmod, Inc.",
maintainer_email="[email protected]",
install_requires=["twisted", "epsilon"],
packages=find_packages() + ['twisted.plugins'],
scripts=['bin/axiomatic'],
license="MIT",
platforms=["any"],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Framework :: Twisted",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 2 :: Only",
"Topic :: Database"])
|
Add web middleware to route | <?php
namespace Gregoriohc\Preview;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
class PreviewServiceProvider extends LaravelServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->handleConfigs();
if (!$this->app->routesAreCached() && $this->isEnabled()) {
Route::group(['middleware' => ['web']], function () {
Route::get('_preview/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
});
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [];
}
private function handleConfigs()
{
$configPath = __DIR__.'/../config/preview.php';
$this->publishes([$configPath => config_path('preview.php')]);
$this->mergeConfigFrom($configPath, 'preview');
}
public static function isEnabled()
{
return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
}
}
| <?php
namespace Gregoriohc\Preview;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
class PreviewServiceProvider extends LaravelServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->handleConfigs();
if (!$this->app->routesAreCached() && $this->isEnabled()) {
Route::get('_preview/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [];
}
private function handleConfigs()
{
$configPath = __DIR__.'/../config/preview.php';
$this->publishes([$configPath => config_path('preview.php')]);
$this->mergeConfigFrom($configPath, 'preview');
}
public static function isEnabled()
{
return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
}
}
|
Use importlib to take place of im module
The imp module is deprecated[1] since version 3.4, use importlib to
instead
1: https://docs.python.org/3/library/imp.html#imp.reload
Change-Id: Ic126bc8e0936e5d7a2c7a910b54b7348026fedcb | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import importlib
from oslo_config import cfg
from watcher.api import config as api_config
from watcher.tests.api import base
class TestRoot(base.FunctionalTest):
def test_config_enable_webhooks_auth(self):
acl_public_routes = ['/']
cfg.CONF.set_override('enable_webhooks_auth', True, 'api')
importlib.reload(api_config)
self.assertEqual(acl_public_routes,
api_config.app['acl_public_routes'])
def test_config_disable_webhooks_auth(self):
acl_public_routes = ['/', '/v1/webhooks/.*']
cfg.CONF.set_override('enable_webhooks_auth', False, 'api')
importlib.reload(api_config)
self.assertEqual(acl_public_routes,
api_config.app['acl_public_routes'])
| # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import imp
from oslo_config import cfg
from watcher.api import config as api_config
from watcher.tests.api import base
class TestRoot(base.FunctionalTest):
def test_config_enable_webhooks_auth(self):
acl_public_routes = ['/']
cfg.CONF.set_override('enable_webhooks_auth', True, 'api')
imp.reload(api_config)
self.assertEqual(acl_public_routes,
api_config.app['acl_public_routes'])
def test_config_disable_webhooks_auth(self):
acl_public_routes = ['/', '/v1/webhooks/.*']
cfg.CONF.set_override('enable_webhooks_auth', False, 'api')
imp.reload(api_config)
self.assertEqual(acl_public_routes,
api_config.app['acl_public_routes'])
|
Move Nut extension command from TableHelper to Table | <?php
namespace Bolt\Nut;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Nut command to list all installed extensions
*/
class Extensions extends BaseCommand
{
/**
* @see \Symfony\Component\Console\Command\Command::configure()
*/
protected function configure()
{
$this
->setName('extensions')
->setDescription('Lists all installed extensions')
;
}
/**
* @see \Symfony\Component\Console\Command\Command::execute()
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (count($this->app['extend.manager']->getMessages())) {
foreach ($this->app['extend.manager']->getMessages() as $message) {
$output->writeln(sprintf('<error>%s</error>', $message));
}
return;
}
$installed = $this->app['extend.manager']->showPackage('installed');
$rows = [];
foreach ($installed as $ext) {
/** @var \Composer\Package\CompletePackageInterface $package */
$package = $ext['package'];
$rows[] = [$package->getPrettyName(), $package->getPrettyVersion(), $package->getType(), $package->getDescription()];
}
$table = new Table($output);
$table
->setHeaders(['Name', 'Version', 'Type', 'Description'])
->setRows($rows)
->render()
;
}
}
| <?php
namespace Bolt\Nut;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Nut command to list all installed extensions
*/
class Extensions extends BaseCommand
{
/**
* @see \Symfony\Component\Console\Command\Command::configure()
*/
protected function configure()
{
$this
->setName('extensions')
->setDescription('Lists all installed extensions')
;
}
/**
* @see \Symfony\Component\Console\Command\Command::execute()
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (count($this->app['extend.manager']->getMessages())) {
foreach ($this->app['extend.manager']->getMessages() as $message) {
$output->writeln(sprintf('<error>%s</error>', $message));
}
return;
}
$installed = $this->app['extend.manager']->showPackage('installed');
$rows = [];
foreach ($installed as $ext) {
/** @var \Composer\Package\CompletePackageInterface $package */
$package = $ext['package'];
$rows[] = [$package->getPrettyName(), $package->getPrettyVersion(), $package->getType(), $package->getDescription()];
}
$table = $this->getHelper('table');
$table
->setHeaders(['Name', 'Version', 'Type', 'Description'])
->setRows($rows);
$table->render($output);
}
}
|
Correct cloud type checker in TUI for localhost
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com> | from conjureup import events, utils
from conjureup.app_config import app
from . import common
class CredentialsController(common.BaseCredentialsController):
def render(self):
if app.provider.cloud_type == 'lxd':
# no credentials required for localhost
self.finish()
elif not self.credentials:
utils.warning("You attempted to do an install against a cloud "
"that requires credentials that could not be "
"found. If you wish to supply those "
"credentials please run "
"`juju add-credential "
"{}`.".format(app.provider.cloud))
events.Shutdown.set(1)
elif not app.provider.credential:
utils.warning("You attempted to install against a cloud with "
"multiple credentials and no default credentials "
"set. Please set a default credential with:\n"
"\n"
" juju set-default-credential {} <credential>")
events.Shutdown.set(1)
else:
self.finish()
_controller_class = CredentialsController
| from conjureup import events, utils
from conjureup.app_config import app
from . import common
class CredentialsController(common.BaseCredentialsController):
def render(self):
if app.provider.cloud_type == 'localhost':
# no credentials required for localhost
self.finish()
elif not self.credentials:
utils.warning("You attempted to do an install against a cloud "
"that requires credentials that could not be "
"found. If you wish to supply those "
"credentials please run "
"`juju add-credential "
"{}`.".format(app.provider.cloud))
events.Shutdown.set(1)
elif not app.provider.credential:
utils.warning("You attempted to install against a cloud with "
"multiple credentials and no default credentials "
"set. Please set a default credential with:\n"
"\n"
" juju set-default-credential {} <credential>")
events.Shutdown.set(1)
else:
self.finish()
_controller_class = CredentialsController
|
Change validators to allow additional arguments to be given to the functions they are wrapping | import json
from functools import wraps
from twisted.web import http
from jsonschema import Draft4Validator
from vumi_http_retry.workers.api.utils import response
def validate(*validators):
def validator(fn):
@wraps(fn)
def wrapper(api, req, *a, **kw):
errors = []
for v in validators:
errors.extend(v(req, *a, **kw) or [])
if not errors:
return fn(api, req, *a, **kw)
else:
return response(req, {'errors': errors}, code=http.BAD_REQUEST)
return wrapper
return validator
def has_header(name):
def validator(req, *a, **kw):
if not req.requestHeaders.hasHeader(name):
return [{
'type': 'header_missing',
'message': "Header '%s' is missing" % (name,)
}]
else:
return []
return validator
def body_schema(schema):
json_validator = Draft4Validator(schema)
def validator(req, body, *a, **kw):
return [{
'type': 'invalid_body',
'message': e.message
} for e in json_validator.iter_errors(body)]
return validator
| import json
from functools import wraps
from twisted.web import http
from jsonschema import Draft4Validator
from vumi_http_retry.workers.api.utils import response
def validate(*validators):
def validator(fn):
@wraps(fn)
def wrapper(api, req, *a, **kw):
errors = []
for v in validators:
errors.extend(v(req, *a, **kw) or [])
if not errors:
return fn(api, req, *a, **kw)
else:
return response(req, {'errors': errors}, code=http.BAD_REQUEST)
return wrapper
return validator
def has_header(name):
def validator(req):
if not req.requestHeaders.hasHeader(name):
return [{
'type': 'header_missing',
'message': "Header '%s' is missing" % (name,)
}]
else:
return []
return validator
def body_schema(schema):
json_validator = Draft4Validator(schema)
def validator(req, body):
return [{
'type': 'invalid_body',
'message': e.message
} for e in json_validator.iter_errors(body)]
return validator
|
Allow specifying fields for model_details | from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
if not fields:
_fields = instance._meta.fields
else:
_fields = [instance._meta.get_field_by_name(f)[0] for f in fields.split(',')]
for f in _fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
| from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
for f in instance._meta.fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
|
Improve thread safety with additional checks and a synchronized map. | package io.collap.bryg.environment;
import io.collap.bryg.Template;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class StandardEnvironment implements Environment {
private Map<String, Template> templateMap = Collections.synchronizedMap (new HashMap<String, Template> ());
private ClassLoader templateClassLoader;
public StandardEnvironment (ClassLoader templateClassLoader) {
this.templateClassLoader = templateClassLoader;
}
@Override
public Template getTemplate (String name) {
Template template = templateMap.get (name);
if (template == null) {
template = loadTemplate (name);
}
return template;
}
/**
* Also adds the loaded template to the cache.
*/
private synchronized Template loadTemplate (String name) {
Template template = templateMap.get (name);
/* There could be a case where getTemplate is called with the same name two or more times,
which would result in the following scenario:
1. The first call reaches loadTemplate and calls it. loadTemplate is then locked on this object.
2. The second call reaches loadTemplate and calls it.
3. The first call finishes.
4. The second call can now enter loadTemplate and *loads the template again*.
The check ensures that the template is not loaded again. */
if (template == null) {
try {
System.out.println ();
System.out.println ("Template: " + name);
long start = System.nanoTime ();
Class<? extends Template> cl = (Class<? extends Template>) templateClassLoader.loadClass (name);
template = cl.newInstance ();
templateMap.put (name, template);
System.out.println ("Loading took " + ((System.nanoTime () - start) / 1.0e9) + "s.");
System.out.println ();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace ();
}
}
return template;
}
}
| package io.collap.bryg.environment;
import io.collap.bryg.Template;
import java.util.HashMap;
import java.util.Map;
public class StandardEnvironment implements Environment {
private Map<String, Template> templateMap = new HashMap<> ();
private ClassLoader templateClassLoader;
public StandardEnvironment (ClassLoader templateClassLoader) {
this.templateClassLoader = templateClassLoader;
}
@Override
public Template getTemplate (String name) {
Template template = templateMap.get (name);
if (template == null) {
template = loadTemplate (name);
}
return template;
}
/**
* Also adds the loaded template to the cache.
*/
private synchronized Template loadTemplate (String name) {
Template template = null;
try {
System.out.println ();
System.out.println ("Template: " + name);
long start = System.nanoTime ();
Class<? extends Template> cl = (Class<? extends Template>) templateClassLoader.loadClass (name);
template = cl.newInstance ();
templateMap.put (name, template);
System.out.println ("Loading took " + ((System.nanoTime () - start) / 1.0e9) + "s.");
System.out.println ();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace ();
}
return template;
}
}
|
Correct the hostname option (smtpServer) | <?php
namespace duncan3dc\SwiftMailer;
class Mailer extends Email
{
public function __construct(array $options = null)
{
if (!is_array($options)) {
$options = [];
}
if (empty($options["smtpServer"])) {
$hostname = "localhost";
} else {
$hostname = $options["smtpServer"];
}
if ($hostname === "localhost") {
$port = isset($options["local-port"]) ? $options["local-port"] : 25;
} else {
$port = isset($options["port"]) ? $options["port"] : 465;
}
$server = new Server($hostname, $port);
if (!empty($options["username"]) || !empty($options["password"])) {
$server->setCredentials($options["username"], $options["password"]);
}
if (!empty($options["fromAddress"])) {
$server->setFromAddress($options["fromAddress"], $options["fromName"]);
}
if (!empty($options["encryption"])) {
$server->setEncryptionMethod($options["encryption"]);
}
if (!empty($options["returnPath"])) {
$server->setReturnPath($options["returnPath"]);
}
parent::__construct($server);
}
}
| <?php
namespace duncan3dc\SwiftMailer;
class Mailer extends Email
{
public function __construct(array $options = null)
{
if (!is_array($options)) {
$options = [];
}
if (empty($options["hostname"])) {
$hostname = "localhost";
} else {
$hostname = $options["hostname"];
}
if ($hostname === "localhost") {
$port = isset($options["local-port"]) ? $options["local-port"] : 25;
} else {
$port = isset($options["port"]) ? $options["port"] : 465;
}
$server = new Server($hostname, $port);
if (!empty($options["username"]) || !empty($options["password"])) {
$server->setCredentials($options["username"], $options["password"]);
}
if (!empty($options["fromAddress"])) {
$server->setFromAddress($options["fromAddress"], $options["fromName"]);
}
if (!empty($options["encryption"])) {
$server->setEncryptionMethod($options["encryption"]);
}
if (!empty($options["returnPath"])) {
$server->setReturnPath($options["returnPath"]);
}
parent::__construct($server);
}
}
|
Fix setting up legacy Contenttype object
$this->app['storage']->getContenttype($contentType) can return object or array. | <?php
namespace Bolt\Storage;
use Bolt\Storage\Mapping\ContentType;
use Silex\Application;
/**
* Legacy bridge for Content object backward compatibility.
*
* @author Ross Riley <[email protected]>
*/
class ContentLegacyService
{
use Entity\ContentRelationTrait;
use Entity\ContentRouteTrait;
use Entity\ContentSearchTrait;
use Entity\ContentTaxonomyTrait;
use Entity\ContentValuesTrait;
protected $app;
/**
* Constructor.
*
* @param Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Initialise.
*
* @param Entity\Entity $entity
*/
public function initialize(Entity\Entity $entity)
{
$this->setupContenttype($entity);
$this->setupContainer($entity);
}
/**
* Set the legacy ContentType object on the Entity.
*
* @param Entity\Entity $entity
*/
public function setupContenttype(Entity\Entity $entity)
{
$contentType = $entity->getContenttype();
if (is_string($contentType)) {
$contentTypeData = $this->app['storage']->getContenttype($contentType);
if ($contentTypeData instanceof ContentType) {
$contentTypeObject = $contentTypeData;
} else {
$contentTypeObject = new ContentType($contentType, $contentTypeData);
}
$entity->contenttype = $contentTypeObject;
}
}
public function setupContainer($entity)
{
$entity->app = $this->app;
}
}
| <?php
namespace Bolt\Storage;
use Bolt\Storage\Mapping\ContentType;
use Silex\Application;
/**
* Legacy bridge for Content object backward compatibility.
*
* @author Ross Riley <[email protected]>
*/
class ContentLegacyService
{
use Entity\ContentRelationTrait;
use Entity\ContentRouteTrait;
use Entity\ContentSearchTrait;
use Entity\ContentTaxonomyTrait;
use Entity\ContentValuesTrait;
protected $app;
/**
* Constructor.
*
* @param Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Initialise.
*
* @param Entity\Entity $entity
*/
public function initialize(Entity\Entity $entity)
{
$this->setupContenttype($entity);
$this->setupContainer($entity);
}
/**
* Set the legacy ContentType object on the Entity.
*
* @param Entity\Entity $entity
*/
public function setupContenttype(Entity\Entity $entity)
{
$contentType = $entity->getContenttype();
if (is_string($contentType)) {
$entity->contenttype = new ContentType($contentType, $this->app['storage']->getContenttype($contentType));
}
}
public function setupContainer($entity)
{
$entity->app = $this->app;
}
}
|
test(karma): Set tests to run on Crome Canary on CI | // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
var configuration = {
basePath: '',
frameworks: ['jasmine', 'angular-cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-remap-istanbul'),
require('angular-cli/plugins/karma')
],
files: [
{pattern: './src/test.ts', watched: false}
],
preprocessors: {
'./src/test.ts': ['angular-cli']
},
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov',
json: './coverage/coverage.json'
},
remapOptions: {
exclude: /(util|test|polyfills).ts$/
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: ['progress', 'karma-remap-istanbul'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
// browser for travis-ci
customLaunchers: {
Chrome_travis_ci: {
base: 'ChromeCanary',
flags: ['--no-sandbox']
}
}
};
if (process.env.TRAVIS) {
configuration.browsers = ['Chrome_travis_ci'];
}
config.set(configuration);
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
var configuration = {
basePath: '',
frameworks: ['jasmine', 'angular-cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-remap-istanbul'),
require('angular-cli/plugins/karma')
],
files: [
{pattern: './src/test.ts', watched: false}
],
preprocessors: {
'./src/test.ts': ['angular-cli']
},
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov',
json: './coverage/coverage.json'
},
remapOptions: {
exclude: /(util|test|polyfills).ts$/
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: ['progress', 'karma-remap-istanbul'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
// browser for travis-ci
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
};
if (process.env.TRAVIS) {
configuration.browsers = ['Chrome_travis_ci'];
}
config.set(configuration);
};
|
Use submit button type in search posts well. | import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.props.onSubmit) {
const q = this.q.value.trim();
if (q) {
this.props.onSubmit(q);
}
}
}
render() {
const {q, pending} = this.props;
return (
<Well>
<h4>Blog Search</h4>
<form autoComplete="off" onSubmit={this.handleSubmit}>
<InputGroup>
<FormControl inputRef={ ref => {
this.q = ref;
}}
defaultValue={q} />
<InputGroup.Button>
<Button disabled={pending} type="submit">
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button>
</InputGroup>
</form>
</Well>
);
}
}
SearchPostsWell.propTypes = {
q: PropTypes.string,
pending: PropTypes.bool,
onSubmit: PropTypes.func
};
export default SearchPostsWell;
| import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.props.onSubmit) {
const q = this.q.value.trim();
if (q) {
this.props.onSubmit(q);
}
}
}
render() {
const {q, pending} = this.props;
return (
<Well>
<h4>Blog Search</h4>
<form autoComplete="off" onSubmit={this.handleSubmit}>
<InputGroup>
<FormControl inputRef={ ref => {
this.q = ref;
}}
defaultValue={q} />
<InputGroup.Button>
<Button disabled={pending}>
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button>
</InputGroup>
</form>
</Well>
);
}
}
SearchPostsWell.propTypes = {
q: PropTypes.string,
pending: PropTypes.bool,
onSubmit: PropTypes.func
};
export default SearchPostsWell; |
Add method for file renaming | const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get writeFile() {
return util.promisify(fs.writeFile)
}
static get mkdir() {
return util.promisify(fs.mkdir)
}
static get rename() {
return util.promisify(fs.rename)
}
static fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
static mkdirp(pathname = '') {
const pathParts = pathname.split('/')
return pathParts.reduce((promise, part) => promise
.then(previousPath => {
const newPath = path.join(previousPath, part)
if (FsUtils.fileExist(newPath)) {
return newPath
}
return FsUtils.mkdir(newPath)
.catch(error => {
if (error.code !== 'EEXIST') {
throw new Error('dir_create_failed')
}
})
.then(() => newPath)
}), Promise.resolve(pathname[0] === '/' ? '/' : ''))
}
}
module.exports = exports = { FsUtils }
| const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get writeFile() {
return util.promisify(fs.writeFile)
}
static get mkdir() {
return util.promisify(fs.mkdir)
}
static fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
static mkdirp(pathname = '') {
const pathParts = pathname.split('/')
return pathParts.reduce((promise, part) => promise
.then(previousPath => {
const newPath = path.join(previousPath, part)
if (FsUtils.fileExist(newPath)) {
return newPath
}
return FsUtils.mkdir(newPath)
.catch(error => {
if (error.code !== 'EEXIST') {
throw new Error('dir_create_failed')
}
})
.then(() => newPath)
}), Promise.resolve(pathname[0] === '/' ? '/' : ''))
}
}
module.exports = exports = { FsUtils }
|
Make ResaleApartmentSerializer return Decoration.name on decoration field.
It allows to show readable value at resale detailed page. | from rest_framework import serializers
from .models import ResaleApartment, ResaleApartmentImage
class ResaleApartmentImageSerializer(serializers.ModelSerializer):
class Meta:
model = ResaleApartmentImage
fields = '__all__'
class ResaleApartmentSerializer(serializers.ModelSerializer):
# images = ResaleApartmentImageSerializer(source='photos', many=True)
get_building_type_display = serializers.ReadOnlyField()
price_per_square_meter = serializers.ReadOnlyField()
neighbourhood = serializers.StringRelatedField()
decoration = serializers.ReadOnlyField(source='decoration.name')
class Meta:
model = ResaleApartment
fields = (
'total_area',
'address',
'floor',
'number_of_storeys',
# 'images',
'full_price',
'old_price',
'price_per_square_meter',
'neighbourhood',
'get_building_type_display',
'number_of_storeys',
'date_of_construction',
'celling_height',
'decoration',
'kitchen_area',
'balcony_area',
'id',
)
| from rest_framework import serializers
from .models import ResaleApartment, ResaleApartmentImage
class ResaleApartmentImageSerializer(serializers.ModelSerializer):
class Meta:
model = ResaleApartmentImage
fields = '__all__'
class ResaleApartmentSerializer(serializers.ModelSerializer):
# images = ResaleApartmentImageSerializer(source='photos', many=True)
get_building_type_display = serializers.ReadOnlyField()
price_per_square_meter = serializers.ReadOnlyField()
neighbourhood = serializers.StringRelatedField()
class Meta:
model = ResaleApartment
fields = (
'total_area',
'address',
'floor',
'number_of_storeys',
# 'images',
'full_price',
'old_price',
'price_per_square_meter',
'neighbourhood',
'get_building_type_display',
'number_of_storeys',
'date_of_construction',
'celling_height',
'decoration',
'kitchen_area',
'balcony_area',
'id',
)
|
Set JSON mode as a requirement explicitly | hqDefine('hqwebapp/js/base_ace', [
'jquery',
'ace-builds/src-min-noconflict/ace',
'ace-builds/src-min-noconflict/mode-json',
], function (
$,
ace,
jsonMode
) {
var initAceEditor = function (element, mode, options, value) {
var defaultOptions = {
showPrintMargin: false,
maxLines: 40,
minLines: 3,
fontSize: 14,
wrap: true,
useWorker: false,
readOnly: true,
};
options = $.extend(defaultOptions, options);
var editor = ace.edit(element, options);
editor.session.setMode(mode);
if (value) {
editor.getSession().setValue(value);
}
return editor;
};
var initJsonWidget = function (element) {
var $element = $(element),
editorElement = $element.after('<pre />').next()[0];
var editor = initAceEditor(editorElement, 'ace/mode/json', {
useWorker: true,
readOnly: false,
}, $element.val());
$element.hide();
editor.getSession().on('change', function () {
$element.val(editor.getSession().getValue());
});
};
$(function () {
_.each($('.jsonwidget'), initJsonWidget);
});
return {
initJsonWidget: initJsonWidget,
initAceEditor: initAceEditor,
};
});
| hqDefine('hqwebapp/js/base_ace', [
'jquery',
'ace-builds/src-min-noconflict/ace',
], function (
$,
ace
) {
if (!ace.config.get('basePath')) {
var basePath = requirejs.s.contexts._.config.paths["ace-builds/src-min-noconflict/ace"];
ace.config.set("basePath",basePath.substring(0,basePath.lastIndexOf("/")));
}
var initAceEditor = function (element, mode, options, value) {
var defaultOptions = {
showPrintMargin: false,
maxLines: 40,
minLines: 3,
fontSize: 14,
wrap: true,
useWorker: false,
readOnly: true,
};
options = $.extend(defaultOptions, options);
var editor = ace.edit(element, options);
editor.session.setMode(mode);
if (value) {
editor.getSession().setValue(value);
}
return editor;
};
var initJsonWidget = function (element) {
var $element = $(element),
editorElement = $element.after('<pre />').next()[0];
var editor = initAceEditor(editorElement, 'ace/mode/json', {
useWorker: true,
readOnly: false,
}, $element.val());
$element.hide();
editor.getSession().on('change', function () {
$element.val(editor.getSession().getValue());
});
};
$(function () {
_.each($('.jsonwidget'), initJsonWidget);
});
return {
initJsonWidget: initJsonWidget,
initAceEditor: initAceEditor,
};
});
|
Add shortcuts for levels and config | <?php declare(strict_types=1);
namespace Rector\Console;
use Jean85\PrettyVersions;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
final class Application extends SymfonyApplication
{
/**
* @var string
*/
private const NAME = 'Rector';
public function __construct()
{
parent::__construct(self::NAME, PrettyVersions::getVersion('rector/rector')->getPrettyVersion());
}
protected function getDefaultInputDefinition(): InputDefinition
{
$defaultInputDefinition = parent::getDefaultInputDefinition();
$this->removeUnusedOptions($defaultInputDefinition);
$this->addCustomOptions($defaultInputDefinition);
return $defaultInputDefinition;
}
private function removeUnusedOptions(InputDefinition $inputDefinition): void
{
$options = $inputDefinition->getOptions();
unset($options['quiet'], $options['version'], $options['no-interaction']);
$inputDefinition->setOptions($options);
}
private function addCustomOptions(InputDefinition $inputDefinition): void
{
$inputDefinition->addOption(new InputOption(
'config',
'c',
InputOption::VALUE_REQUIRED,
'Path to config file.',
getcwd() . '/rector.yml'
));
$inputDefinition->addOption(new InputOption(
'level',
'l',
InputOption::VALUE_REQUIRED,
'Finds config by shortcut name.'
));
}
}
| <?php declare(strict_types=1);
namespace Rector\Console;
use Jean85\PrettyVersions;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
final class Application extends SymfonyApplication
{
/**
* @var string
*/
private const NAME = 'Rector';
public function __construct()
{
parent::__construct(self::NAME, PrettyVersions::getVersion('rector/rector')->getPrettyVersion());
}
protected function getDefaultInputDefinition(): InputDefinition
{
$defaultInputDefinition = parent::getDefaultInputDefinition();
$this->removeUnusedOptions($defaultInputDefinition);
$this->addCustomOptions($defaultInputDefinition);
return $defaultInputDefinition;
}
private function removeUnusedOptions(InputDefinition $inputDefinition): void
{
$options = $inputDefinition->getOptions();
unset($options['quiet'], $options['version'], $options['no-interaction']);
$inputDefinition->setOptions($options);
}
private function addCustomOptions(InputDefinition $inputDefinition): void
{
$inputDefinition->addOption(new InputOption(
'config',
null,
InputOption::VALUE_REQUIRED,
'Path to config file.',
getcwd() . '/rector.yml'
));
$inputDefinition->addOption(new InputOption(
'level',
null,
InputOption::VALUE_REQUIRED,
'Finds config by shortcut name.'
));
}
}
|
Make cycle detection atomic. No 2 threads should use getInstance at the same time. The lock is shared for all scopes. This is a problem. | package toothpick;
import java.util.Stack;
import java.util.concurrent.locks.ReentrantLock;
import toothpick.config.Binding;
import static java.lang.String.format;
public abstract class Configuration {
public static volatile Configuration instance;
abstract void checkIllegalBinding(Binding binding);
abstract void checkCyclesStart(Class clazz);
abstract void checkCyclesEnd();
static {
//default mode is production
production();
}
public static void development() {
instance = new Configuration() {
private Stack<Class> cycleDetectionStack = new Stack<>();
//used to make the cycle check atomic.
private ReentrantLock reentrantLock = new ReentrantLock();
@Override
void checkIllegalBinding(Binding binding) {
}
@Override
void checkCyclesStart(Class clazz) {
if (cycleDetectionStack.contains(clazz)) {
//TODO make the message better
throw new CyclicDependencyException(format("Class %s creates a cycle", clazz.getName()));
}
cycleDetectionStack.push(clazz);
reentrantLock.lock();
}
@Override
void checkCyclesEnd() {
cycleDetectionStack.pop();
reentrantLock.unlock();
}
};
}
public static void production() {
instance = new Configuration() {
@Override
void checkIllegalBinding(Binding binding) {
//do nothing
}
@Override
void checkCyclesStart(Class clazz) {
//do nothing
}
@Override
void checkCyclesEnd() {
//do nothing
}
};
}
/**
* Allows to pass custom configurations.
*
* @param configuration the configuration to use
*/
static void setConfiguration(Configuration configuration) {
instance = configuration;
}
}
| package toothpick;
import java.util.Stack;
import toothpick.config.Binding;
import static java.lang.String.format;
public abstract class Configuration {
public static volatile Configuration instance;
abstract void checkIllegalBinding(Binding binding);
abstract void checkCyclesStart(Class clazz);
abstract void checkCyclesEnd();
static {
//default mode is production
production();
}
public static void development() {
instance = new Configuration() {
private Stack<Class> cycleDetectionStack = new Stack<>();
@Override
void checkIllegalBinding(Binding binding) {
}
@Override
void checkCyclesStart(Class clazz) {
if (cycleDetectionStack.contains(clazz)) {
//TODO make the message better
throw new CyclicDependencyException(format("Class %s creates a cycle", clazz.getName()));
}
cycleDetectionStack.push(clazz);
}
@Override
void checkCyclesEnd() {
cycleDetectionStack.pop();
}
};
}
public static void production() {
instance = new Configuration() {
@Override
void checkIllegalBinding(Binding binding) {
//do nothing
}
@Override
void checkCyclesStart(Class clazz) {
//do nothing
}
@Override
void checkCyclesEnd() {
//do nothing
}
};
}
/**
* Allows to pass custom configurations.
*
* @param configuration the configuration to use
*/
static void setConfiguration(Configuration configuration) {
instance = configuration;
}
}
|
Add support for resolving the types | <?php
namespace PHPCfg\Visitor;
use PHPCfg\Visitor;
use PHPCfg\Op;
use PHPCfg\Block;
use PHPCfg\Operand;
class CallFinder implements Visitor {
protected $calls = [];
protected $funcStack = [];
protected $func;
public function getCallsForFunction($func) {
$func = strtolower($func);
return isset($this->calls[$func]) ? $this->calls[$func] : [];
}
public function enterBlock(Block $block, Block $prior = null) {}
public function enterOp(Op $op, Block $block) {
if ($op instanceof Op\CallableOp) {
$this->funcStack[] = $this->func;
$this->func = $op;
}
if ($op instanceof Op\Expr\FuncCall) {
if ($op->name instanceof Operand\Literal) {
$this->calls[strtolower($op->name->value)][] = [
$op,
$this->func
];
}
}
}
public function leaveOp(Op $op, Block $block) {
if ($op instanceof Op\CallableOp) {
$this->func = array_pop($this->funcStack);
}
}
public function leaveBlock(Block $block, Block $prior = null) {}
public function skipBlock(Block $block, Block $prior = null) {}
} | <?php
namespace PHPCfg\Visitor;
use PHPCfg\Visitor;
use PHPCfg\Op;
use PHPCfg\Block;
use PHPCfg\Operand;
class CallFinder implements Visitor {
protected $calls = [];
protected $funcStack = [];
protected $func;
public function getCallsForFunction($func) {
return isset($this->calls[$func]) ? $this->calls[$func] : [];
}
public function enterBlock(Block $block, Block $prior = null) {}
public function enterOp(Op $op, Block $block) {
if ($op instanceof Op\CallableOp) {
$this->funcStack[] = $this->func;
$this->func = $op;
}
if ($op instanceof Op\Expr\FuncCall) {
if ($op->name instanceof Operand\Literal) {
$this->calls[$op->name->value][] = [
$op,
$this->func
];
}
}
}
public function leaveOp(Op $op, Block $block) {
if ($op instanceof Op\CallableOp) {
$this->func = array_pop($this->funcStack);
}
}
public function leaveBlock(Block $block, Block $prior = null) {}
public function skipBlock(Block $block, Block $prior = null) {}
} |
Add comment for empty catch | <?php
namespace Kevinrob\GuzzleCache\Storage;
use Doctrine\Common\Cache\Cache;
use Kevinrob\GuzzleCache\CacheEntry;
class DoctrineCacheWrapper implements CacheStorageInterface
{
/**
* @var Cache
*/
protected $cache;
/**
* @param Cache $cache
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
/**
* @inheritdoc
*/
public function fetch($key)
{
try {
$cache = unserialize($this->cache->fetch($key));
if ($cache instanceof CacheEntry) {
return $cache;
}
} catch (\Exception $ignored) {
return null;
}
return null;
}
/**
* @inheritdoc
*/
public function save($key, CacheEntry $data)
{
try {
$lifeTime = $data->getTTL();
if ($lifeTime >= 0) {
return $this->cache->save(
$key,
serialize($data),
$lifeTime
);
}
} catch (\Exception $ignored) {
// No fail if we can't save it the storage
}
return false;
}
} | <?php
namespace Kevinrob\GuzzleCache\Storage;
use Doctrine\Common\Cache\Cache;
use Kevinrob\GuzzleCache\CacheEntry;
class DoctrineCacheWrapper implements CacheStorageInterface
{
/**
* @var Cache
*/
protected $cache;
/**
* @param Cache $cache
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
/**
* @inheritdoc
*/
public function fetch($key)
{
try {
$cache = unserialize($this->cache->fetch($key));
if ($cache instanceof CacheEntry) {
return $cache;
}
} catch (\Exception $ignored) {
return null;
}
return null;
}
/**
* @inheritdoc
*/
public function save($key, CacheEntry $data)
{
try {
$lifeTime = $data->getTTL();
if ($lifeTime >= 0) {
return $this->cache->save(
$key,
serialize($data),
$lifeTime
);
}
} catch (\Exception $ignored) { }
return false;
}
} |
Fix typo and minor formatting. | # -*- coding: utf-8 -*-
import os
import pprint
import warnings
from gpn.node import Node
suffix = '.node'
suffix_default = '.node-default'
class Graph(object):
def __init__(self, path=None, nodes=None):
global suffix
global suffix_default
assert not path or not nodes, ('Cannot specify both path and nodes.')
# Get nodes.
if not nodes:
if not path:
path = os.getcwd() # Default to cwd.
def is_node(x):
return x.endswith(suffix) or x.endswith(suffix_default)
nodes = [Node(x) for x in os.listdir(path) if is_node(x)]
self.path = path
else:
self.path = '<from collection>'
# Set nodes.
def node_item(p):
assert isinstance(p, Node), '%r is not a Node.' % p
if p.name:
key = p.name
else:
key = p.get_hash()[:12] # <- TODO!!!: Implement get_hash().
warnings.warn("Node is unnamed--using "
"short hash '%s'." % key)
return (key, p)
self.nodes = dict(node_item(p) for p in nodes)
# Set edges.
self.edges = [None]
| # -*- coding: utf-8 -*-
import os
import pprint
import warnings
from gpn.node import Node
suffix = '.node'
suffix_default = '.node-default'
class Graph(object):
def __init__(self, path=None, nodes=None):
global suffix
global suffix_default
assert not path or not nodes, ('Cannot specify both path '
'and nodes.')
# Get nodes.
if not nodes:
if not path:
path = os.getcwd() # Defaule to cwd.
def is_node(x):
return x.endswith(suffix) or x.endswith(suffix_default)
nodes = [Node(x) for x in os.listdir(path) if is_node(x)]
self.path = path
else:
self.path = '<from collection>'
# Set nodes.
def node_item(p):
assert isinstance(p, Node), '%r is not a Node.' % p
if p.name:
key = p.name
else:
key = p.get_hash()[:12] # <- TODO!!!: Implement get_hash().
warnings.warn("Node is unnamed--using "
"short hash '%s'." % key)
return (key, p)
self.nodes = dict(node_item(p) for p in nodes)
# Set edges.
self.edges = [None]
|
Fix potential performance issue reported by FindBugs | package net.onrc.onos.ofcontroller.linkdiscovery.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.floodlightcontroller.routing.Link;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
import net.onrc.onos.ofcontroller.linkdiscovery.LinkInfo;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
public class LinksResource extends ServerResource {
@Get("json")
public Set<LinkWithType> retrieve() {
ILinkDiscoveryService ld = (ILinkDiscoveryService)getContext().getAttributes().
get(ILinkDiscoveryService.class.getCanonicalName());
Map<Link, LinkInfo> links = new HashMap<Link, LinkInfo>();
Set<LinkWithType> returnLinkSet = new HashSet<LinkWithType>();
if (ld != null) {
links.putAll(ld.getLinks());
for(Entry<Link, LinkInfo> e : links.entrySet()) {
Link link = e.getKey();
LinkInfo info = e.getValue();
LinkWithType lwt = new LinkWithType(link,
info.getSrcPortState(),
info.getDstPortState(),
ld.getLinkType(link, info));
returnLinkSet.add(lwt);
}
}
return returnLinkSet;
}
}
| package net.onrc.onos.ofcontroller.linkdiscovery.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.floodlightcontroller.routing.Link;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
import net.onrc.onos.ofcontroller.linkdiscovery.LinkInfo;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
public class LinksResource extends ServerResource {
@Get("json")
public Set<LinkWithType> retrieve() {
ILinkDiscoveryService ld = (ILinkDiscoveryService)getContext().getAttributes().
get(ILinkDiscoveryService.class.getCanonicalName());
Map<Link, LinkInfo> links = new HashMap<Link, LinkInfo>();
Set<LinkWithType> returnLinkSet = new HashSet<LinkWithType>();
if (ld != null) {
links.putAll(ld.getLinks());
for (Link link: links.keySet()) {
LinkInfo info = links.get(link);
LinkWithType lwt = new LinkWithType(link,
info.getSrcPortState(),
info.getDstPortState(),
ld.getLinkType(link, info));
returnLinkSet.add(lwt);
}
}
return returnLinkSet;
}
}
|
Fix to work with DataObjects | <?php
class TestimonialsExtension extends SiteTreeExtension
{
private static $has_many = [
'Testimonials' => 'Testimonial'
];
public function updateCMSFields(FieldList $fields)
{
/** @var GridFieldConfig $gridConfig */
$gridConfig = GridFieldConfig::create();
$gridConfig
->addComponent(new GridFieldButtonRow('before'))
->addComponent(new GridFieldAddNewButton('buttons-before-left'))
->addComponent(new GridFieldToolbarHeader())
->addComponent(new GridFieldSortableHeader())
->addComponent(new GridFieldOrderableRows('SortOrder'))
->addComponent($dataColumns = new GridFieldDataColumns())
->addComponent(new GridFieldEditButton())
->addComponent(new GridFieldDeleteAction())
->addComponent(new GridFieldDetailForm());
$dataColumns->setDisplayFields([
'Title' => 'Author',
'Testimonial.Summary' => 'Testimonial Preview',
]);
/** @var TabSet $rootTab */
//We need to repush Metadata to ensure it is the last tab
$rootTab = $fields->fieldByName('Root');
$fields->removeByName('Testimonials');
if ($this->owner->exists()) {
$rootTab->push(Tab::create('Testimonials'));
$GridField = GridField::create('Testimonials', 'Testimonials', $this->owner->Testimonials(), $gridConfig);
$fields->addFieldToTab('Root.Testimonials', $GridField);
}
return $fields;
}
}
| <?php
class TestimonialsExtension extends SiteTreeExtension
{
private static $has_many = [
'Testimonials' => 'Testimonial'
];
public function updateCMSFields(FieldList $fields)
{
/** @var GridFieldConfig $gridConfig */
$gridConfig = GridFieldConfig::create();
$gridConfig
->addComponent(new GridFieldButtonRow('before'))
->addComponent(new GridFieldAddNewButton('buttons-before-left'))
->addComponent(new GridFieldToolbarHeader())
->addComponent(new GridFieldSortableHeader())
->addComponent(new GridFieldOrderableRows('SortOrder'))
->addComponent($dataColumns = new GridFieldDataColumns())
->addComponent(new GridFieldEditButton())
->addComponent(new GridFieldDeleteAction())
->addComponent(new GridFieldDetailForm());
$dataColumns->setDisplayFields([
'Title' => 'Author',
'Testimonial.Summary' => 'Testimonial Preview',
]);
/** @var TabSet $rootTab */
//We need to repush Metadata to ensure it is the last tab
$rootTab = $fields->fieldByName('Root');
$fields->removeByName('Testimonials');
$rootTab->push(Tab::create('Testimonials'));
$GridField = GridField::create('Testimonials', 'Testimonials', $this->owner->Testimonials(), $gridConfig);
$fields->addFieldToTab('Root.Testimonials', $GridField);
return $fields;
}
}
|
Add provenance type as item to reset. | Application.Services.factory('toggleDragButton', [toggleDragButton]);
function toggleDragButton() {
var service = {
addToReview: {
'samples': false,
'notes': false,
'files': false,
'provenance': false
},
addToProv: {
samples: false,
notes: false,
files: false,
provenance: false
},
toggle: function (type, button) {
switch (type) {
case "samples":
service[button].samples = !service[button].samples;
break;
case "notes":
service[button].notes = !service[button].notes;
break;
case "files":
service[button].files = !service[button].files;
break;
case "provenance":
service[button].provenance = !service[button].provenance;
break;
}
},
reset: function(button) {
service[button] = {
'samples': false,
'notes': false,
'files': false,
'provenance': false
};
},
get: function (type, button) {
return service[button][type];
}
};
return service;
}
| Application.Services.factory('toggleDragButton', [toggleDragButton]);
function toggleDragButton() {
var service = {
addToReview: {
'samples': false,
'notes': false,
'files': false,
'provenance': false
},
toggle: function (type, button) {
switch (type) {
case "samples":
service[button].samples = !service[button].samples;
break;
case "notes":
service[button].notes = !service[button].notes;
break;
case "files":
service[button].files = !service[button].files;
break;
case "provenance":
service[button].provenance = !service[button].provenance;
break;
}
},
reset: function(){
service.addToReview= {
'samples': false,
'notes': false,
'files': false,
'provenance': false
};
},
get: function (type, button) {
return service[button][type];
}
};
return service;
}
|
Check if app is mounted | import React, { Component } from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import ImgurImage from './ImgurImage';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0};
}
loadImages(page = 0) {
searchGallery(undefined, undefined, page).then((result) => {
if (this.isMounted()) {
this.setState({images: result.data, page: page});
}
});
}
componentDidMount() {
this.loadImages();
}
render() {
return (
<div>
<Navbar
brand='React Imgur viewer'
fixedTop={true}>
<Nav right>
<NavItem
onClick={() => this.loadImages(this.state.page - 1)}
disabled={this.state.page <= 0}>
<i className='glyphicon glyphicon-arrow-left'></i> Previous page
</NavItem>
<NavItem onClick={() => this.loadImages(this.state.page + 1)}>
Next page <i className='glyphicon glyphicon-arrow-right'></i>
</NavItem>
</Nav>
</Navbar>
<div
className='container'
style={{paddingTop: '70px'}}>
{this.state.images.map(function(image) {
return (
<ImgurImage
image={image}
key={image.id} />
);
})}
</div>
</div>
);
}
}
| import React, { Component } from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import ImgurImage from './ImgurImage';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0};
}
loadImages(page = 0) {
searchGallery(undefined, undefined, page).then((result) => {
this.setState({images: result.data, page: page});
});
}
componentDidMount() {
this.loadImages();
}
render() {
return (
<div>
<Navbar
brand='React Imgur viewer'
fixedTop={true}>
<Nav right>
<NavItem
onClick={() => this.loadImages(this.state.page - 1)}
disabled={this.state.page <= 0}>
<i className='glyphicon glyphicon-arrow-left'></i> Previous page
</NavItem>
<NavItem onClick={() => this.loadImages(this.state.page + 1)}>
Next page <i className='glyphicon glyphicon-arrow-right'></i>
</NavItem>
</Nav>
</Navbar>
<div
className='container'
style={{paddingTop: '70px'}}>
{this.state.images.map(function(image) {
return (
<ImgurImage
image={image}
key={image.id} />
);
})}
</div>
</div>
);
}
}
|
Remove accidentally committed test code | package me.williamhester.reddit.ui.activities;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import me.williamhester.reddit.R;
import me.williamhester.reddit.models.Submission;
import me.williamhester.reddit.ui.fragments.CommentsFragment;
/** Activity that holds basic content. */
public class ContentActivity extends BaseActivity {
public static final String TYPE_EXTRA = "type";
public static final String VOTABLE_EXTRA = "votable";
public static final String PERMALINK_EXTRA = "permalink";
public static final String COMMENTS = "comments";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, createContentFragment())
.commit();
}
}
@Override
protected int getLayoutId() {
return R.layout.activity_content;
}
protected Fragment createContentFragment() {
Bundle args = getIntent().getExtras();
String type = args.getString(TYPE_EXTRA);
if (type == null) {
return null;
}
switch (type) {
case COMMENTS:
String permalink = args.getString(PERMALINK_EXTRA);
Submission s = args.getParcelable(VOTABLE_EXTRA);
return CommentsFragment.newInstance(permalink, s);
default:
return null;
}
}
}
| package me.williamhester.reddit.ui.activities;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import me.williamhester.reddit.R;
import me.williamhester.reddit.models.Submission;
import me.williamhester.reddit.ui.fragments.CommentsFragment;
/** Activity that holds basic content. */
public class ContentActivity extends BaseActivity {
public static final String TYPE_EXTRA = "type";
public static final String VOTABLE_EXTRA = "votable";
public static final String PERMALINK_EXTRA = "permalink";
public static final String COMMENTS = "comments";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, createContentFragment())
.commit();
}
SharedPreferences prefs = getSharedPreferences("default", MODE_PRIVATE);
prefs.edit().putBoolean("test", true).apply();
}
@Override
protected int getLayoutId() {
return R.layout.activity_content;
}
protected Fragment createContentFragment() {
Bundle args = getIntent().getExtras();
String type = args.getString(TYPE_EXTRA);
if (type == null) {
return null;
}
switch (type) {
case COMMENTS:
String permalink = args.getString(PERMALINK_EXTRA);
Submission s = args.getParcelable(VOTABLE_EXTRA);
return CommentsFragment.newInstance(permalink, s);
default:
return null;
}
}
}
|
doc: Use route for links to documents | @extends('layouts.app')
@section('title', 'Index')
@section('content')
<div class="row">
@if ($data['num_doc'] > 0)
<div class="row">
<div class="col-md-12">
<div class="col-md-offset-9 col-md-3">
Uploaded documents: {{$data['num_doc']}} ({{$data['num_doc_shown']}} shown)
</div>
</div>
</div>
<div class="container">
@foreach($data['docs'] as $doc)
<div class="row">
<div class="well">
<a href="{{route('doc_show', $doc->title)}}">{{$doc->title}}</a>
</div>
</div>
@endforeach
</div>
{{$data['docs']->links()}}
@else
@if (!Auth::guest())
<a class="btn btn-primary" href={{route('doc_upload')}}>Add new document</a>
@endif
<div class="container text-center">
No documents have been uploaded.
</div>
@endif
</div>
@endsection
| @extends('layouts.app')
@section('title', 'Index')
@section('content')
<div class="row">
@if ($data['num_doc'] > 0)
<div class="row">
<div class="col-md-12">
<div class="col-md-offset-9 col-md-3">
Uploaded documents: {{$data['num_doc']}} ({{$data['num_doc_shown']}} shown)
</div>
</div>
</div>
<div class="container">
@foreach($data['docs'] as $doc)
<div class="row">
<div class="well">
<a href="/doc/show/{{$doc->title}}">{{$doc->title}}</a>
</div>
</div>
@endforeach
</div>
{{$data['docs']->links()}}
@else
@if (!Auth::guest())
<a class="btn btn-primary" href={{route('doc_upload')}}>Add new document</a>
@endif
<div class="container text-center">
No documents have been uploaded.
</div>
@endif
</div>
@endsection
|
Add more information to failure message | package com.coronaide.test.ui;
import java.io.IOException;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.coronaide.core.model.Project;
import com.coronaide.core.service.IProjectService;
import com.coronaide.ui.CoronaUIApplication;
public class CreateProjectTest extends CoronaUITest {
@Inject
private IProjectService projectService;
private final String TEST_PROJECT_NAME = "test_project";
@Before
public void setup() throws Exception {
launch(CoronaUIApplication.class);
}
@Test
public void createProjectTest() {
clickOn("#menu-file").clickOn("#menu-file-new-project");
write(TEST_PROJECT_NAME);
clickOn("OK");
Collection<String> projectNames = projectService.getAll().stream()
.map(Project::getName)
.collect(Collectors.toList());
boolean found = projectNames.stream()
.filter(Predicate.isEqual(TEST_PROJECT_NAME))
.findAny()
.isPresent();
Assert.assertTrue("Expected newly created project to be found in project list (" + projectNames + ")", found);
}
@After
public void teardown() {
projectService.getAll().stream()
.filter(p -> TEST_PROJECT_NAME.equals(p.getName()))
.forEach(p -> {
try {
projectService.delete(p);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
| package com.coronaide.test.ui;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.coronaide.core.model.Project;
import com.coronaide.core.service.IProjectService;
import com.coronaide.ui.CoronaUIApplication;
public class CreateProjectTest extends CoronaUITest {
@Inject
private IProjectService projectService;
private final String TEST_PROJECT_NAME = "test_project";
@Before
public void setup() throws Exception {
launch(CoronaUIApplication.class);
}
@Test
public void createProjectTest() {
clickOn("#menu-file").clickOn("#menu-file-new-project");
write(TEST_PROJECT_NAME);
clickOn("OK");
Assert.assertTrue("Expected newly created project to be found in project list.",
projectService.getAll().stream().map(Project::getName).collect(Collectors.toList())
.contains(TEST_PROJECT_NAME));
}
@After
public void teardown() {
projectService.getAll().stream()
.filter(p -> TEST_PROJECT_NAME.equals(p.getName()))
.forEach(p -> {
try {
projectService.delete(p);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
|
Remove unused dependency and variable | var module = angular.module('ldsNavigation', ['ngRoute']);
module.directive('ldsNavigation', [function () {
return {
restrict: "E",
scope: true,
controller: ['$attrs', '$route', '$scope', function ($attrs, $route, $scope) {
var navItems = [],
routeDef,
route,
currentRoute = $route.current,
routeScope = $scope.$new(),
url,
urlParamNum,
urlParam,
urlParamFind,
urlParamReplace
for (routeDef in $route.routes) {
route = $route.routes[routeDef]
routeScope.route = route
if ((!$attrs.filter || routeScope.$eval($attrs.filter)) &&
route.navigationLabel
) {
url = "#" + routeDef
for (urlParamNum = 0; urlParamNum < route.keys.length; urlParamNum++) {
urlParam = route.keys[urlParamNum]
urlParamFind = "/:" + urlParam.name
urlParamReplace = currentRoute.params[urlParam.name]
if (urlParam.optional) {
urlParamFind += "?"
}
else if (!urlParamReplace) {
throw "'" + urlParam.name + "' is required by navigation but cannot be found in current route"
}
url = url.replace(urlParamFind, "/" + urlParamReplace)
}
navItems.push({
url: url,
label: route.navigationLabel,
selected: (currentRoute.originalPath == route.originalPath)
})
}
}
$scope.navItems = navItems
}]
}
}]) | var module = angular.module('ldsNavigation', ['ngRoute']);
module.directive('ldsNavigation', [function () {
return {
restrict: "E",
scope: true,
controller: ['$attrs', '$route', '$scope', 'lidsysFootballSchedule', function ($attrs, $route, $scope, footballSchedule) {
var navItems = [],
routeDef,
route,
currentRoute = $route.current,
routeScope = $scope.$new(),
url,
urlParamNum,
urlParam,
urlParamFind,
urlParamReplace
for (routeDef in $route.routes) {
route = $route.routes[routeDef]
routeScope.route = route
if ((!$attrs.filter || routeScope.$eval($attrs.filter)) &&
route.navigationLabel
) {
url = "#" + routeDef
for (urlParamNum = 0; urlParamNum < route.keys.length; urlParamNum++) {
urlParam = route.keys[urlParamNum]
urlParamFind = "/:" + urlParam.name
urlParamReplace = currentRoute.params[urlParam.name]
if (urlParam.optional) {
urlParamFind += "?"
}
else if (!urlParamReplace) {
throw "'" + urlParam.name + "' is required by navigation but cannot be found in current route"
}
url = url.replace(urlParamFind, "/" + urlParamReplace)
}
navItems.push({
url: url,
label: route.navigationLabel,
selected: (currentRoute.originalPath == route.originalPath)
})
}
}
$scope.navItems = navItems
}]
}
}]) |
Change the DT call, now the coding is working | import RPi.GPIO as GPIO
import time
class WeightSensor:
""" Class that get the weight from a HX711
this module is based on the HX711 datasheet
"""
def __init__(self, SCK, DT):
self.SCK = SCK
self.DT = DT
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.SCK, GPIO.OUT) # SCK command
GPIO.setup(self.DT, GPIO.IN) # Device Output
def getWeight(self):
while GPIO.input(self.DT) == 1:
pass
weight = 0
for i in range(0, 24):
weight = weight << 1
GPIO.output(self.SCK, True)
if GPIO.input(self.DT):
weight += 1
GPIO.output(self.SCK, False)
GPIO.output(self.SCK, True)
GPIO.output(self.SCK, False)
return weight
if __name__ == "__main__":
SCK_PIN = 26
DT_PIN = 20
WS = WeightSensor(SCK_PIN, DT_PIN)
try:
while True:
print (WS.getWeight())
time.sleep(0.5)
except KeyboardInterrupt:
GPIO.cleanup()
print ("lean GPIO") # Clean the GPIO
| import RPi.GPIO as GPIO
import time
class WeightSensor:
""" Class that get the weight from a HX711
this module is based on the HX711 datasheet
Not test yet
"""
def __init__(self, SCK, DT):
self.SCK = SCK
self.DT = DT
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.SCK, GPIO.OUT) # SCK command
GPIO.setup(self.DT, GPIO.IN) # Device Output
def getWeight(self):
weight = 0
GPIO.output(self.SCK, False)
while GPIO.input(self.DT):
for i in range(0, 24):
GPIO.output(self.SCK, True)
time.sleep(0.01)
weight = weight << 1
GPIO.output(self.SCK, False)
if GPIO.input(self.DT):
weight += 1
if weight > 100000000:
return 0
GPIO.output(self.SCK, True)
weight ^= 0x800000
GPIO.output(self.SCK, False)
return weight
if __name__ == "__main__":
SCK_PIN = 26
DT_PIN = 20
WS = WeightSensor(SCK_PIN, DT_PIN)
try:
while True:
print (WS.getWeight())
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
print ("lean GPIO")
|
Convert a module's call to BEST.helpers.timeline -> BEST.helpers.piecewise | BEST.module('arkady.pevzner:timeline-example', {
behaviors: {
'#ui-el' : {
size: [100, 100],
style: function(myStyle) {
return myStyle;
},
position: function(myTimeline, time) {
return BEST.helpers.piecewise(myTimeline)(time);
}
}
},
events: {
'#ui-el' : {
'famous:events:click' : function($state) {
$state.set('time', 2000, {duration: 2000});
}
}
},
states: {
time: 0,
myTimeline: [
[0, [100, 100], 'outExo'],
[500, [600, 100], 'inExpo'],
[1000, [600, 600], 'inOutBack'],
[2000, [100, 100]]
],
myStyle : {
'background-color' : 'black',
'text-align' : 'center',
'line-height' : '100px',
'color' : 'white',
'cursor' : 'pointer'
}
},
tree: 'timeline-example.html',
})
.config({
imports: {
'famous:core': ['ui-element']
}
});
| BEST.module('arkady.pevzner:timeline-example', {
behaviors: {
'#ui-el' : {
size: [100, 100],
style: function(myStyle) {
return myStyle;
},
position: function(myTimeline, time) {
return BEST.helpers.timeline(myTimeline)(time);
}
}
},
events: {
'#ui-el' : {
'famous:events:click' : function($state) {
$state.set('time', 2000, {duration: 2000});
}
}
},
states: {
time: 0,
myTimeline: [
[0, [100, 100], 'outExo'],
[500, [600, 100], 'inExpo'],
[1000, [600, 600], 'inOutBack'],
[2000, [100, 100]]
],
myStyle : {
'background-color' : 'black',
'text-align' : 'center',
'line-height' : '100px',
'color' : 'white',
'cursor' : 'pointer'
}
},
tree: 'timeline-example.html',
})
.config({
imports: {
'famous:core': ['ui-element']
}
});
|
Update last login time on newcomer auth | <?php
namespace App\Http\Controllers\All;
use App\Http\Controllers\Controller;
use App\Models\User;
use EtuUTT;
use Request;
use Config;
use View;
use Crypt;
use Redirect;
use Auth;
use Response;
class AuthController extends Controller
{
/**
* Show the authentication for newcomer page
*
* @return Response
*/
public function login()
{
return View::make('newcomer.login');
}
/**
* Authenticate the newcomer
*
* @return Response
*/
public function loginSubmit()
{
$user = User::where('login', Request::get('login'))->get()->first();
if ($user && !empty($user->password)) {
if (password_verify(Request::get('password'), $user->password)) {
$user->last_login = new \DateTime();
$user->save();
Auth::login($user, true);
if ($user->isNewcomer()) {
return Redirect::route('newcomer.home')->withSuccess('Vous êtes maintenant connecté.');
}
else {
return Redirect::route('menu')->withSuccess('Vous êtes maintenant connecté.');
}
}
}
return $this->error('Identifiant ou mot de passe incorrect. Contactez [email protected] si vous n\'arrivez pas à vous connecter.');
}
/**
* log out the newcomer
*
* @return Response
*/
public function logout()
{
Auth::logout();
return Redirect::route('index')->withSuccess('Vous êtes maintenant déconnecté.');
}
}
| <?php
namespace App\Http\Controllers\All;
use App\Http\Controllers\Controller;
use App\Models\User;
use EtuUTT;
use Request;
use Config;
use View;
use Crypt;
use Redirect;
use Auth;
use Response;
class AuthController extends Controller
{
/**
* Show the authentication for newcomer page
*
* @return Response
*/
public function login()
{
return View::make('newcomer.login');
}
/**
* Authenticate the newcomer
*
* @return Response
*/
public function loginSubmit()
{
$user = User::where('login', Request::get('login'))->get()->first();
if ($user && !empty($user->password)) {
if (password_verify(Request::get('password'), $user->password)) {
Auth::login($user, true);
if ($user->isNewcomer()) {
return Redirect::route('newcomer.home')->withSuccess('Vous êtes maintenant connecté.');
}
else {
return Redirect::route('menu')->withSuccess('Vous êtes maintenant connecté.');
}
}
}
return $this->error('Identifiant ou mot de passe incorrect. Contactez [email protected] si vous n\'arrivez pas à vous connecter.');
}
/**
* log out the newcomer
*
* @return Response
*/
public function logout()
{
Auth::logout();
return Redirect::route('index')->withSuccess('Vous êtes maintenant déconnecté.');
}
}
|
Update adapter to catch exception from loader | from collections import defaultdict
from django.template.base import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except loader.TemplateNotFound:
raise TemplateDoesNotExist(template_name)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
| from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
Rename FK in migration 70 - For some reason, Gunks' db has it named differently than ours. | """Fix Folder, EASFolderSyncStatus unique constraints
Revision ID: 2525c5245cc2
Revises: 479b3b84a73e
Create Date: 2014-07-28 18:57:24.476123
"""
# revision identifiers, used by Alembic.
revision = '2525c5245cc2'
down_revision = '479b3b84a73e'
from alembic import op
import sqlalchemy as sa
from inbox.ignition import main_engine
engine = main_engine()
Base = sa.ext.declarative.declarative_base()
Base.metadata.reflect(engine)
def upgrade():
op.drop_constraint('folder_fk1', 'folder', type_='foreignkey')
op.drop_constraint('account_id', 'folder', type_='unique')
op.create_foreign_key('folder_fk1',
'folder', 'account',
['account_id'], ['id'])
op.create_unique_constraint('account_id',
'folder',
['account_id', 'name', 'canonical_name'])
if 'easfoldersyncstatus' in Base.metadata.tables:
op.create_unique_constraint('account_id_2',
'easfoldersyncstatus',
['account_id', 'eas_folder_id'])
def downgrade():
raise Exception('Unsupported, going back will break things.')
| """Fix Folder, EASFolderSyncStatus unique constraints
Revision ID: 2525c5245cc2
Revises: 479b3b84a73e
Create Date: 2014-07-28 18:57:24.476123
"""
# revision identifiers, used by Alembic.
revision = '2525c5245cc2'
down_revision = '479b3b84a73e'
from alembic import op
import sqlalchemy as sa
from inbox.ignition import main_engine
engine = main_engine()
Base = sa.ext.declarative.declarative_base()
Base.metadata.reflect(engine)
def upgrade():
op.drop_constraint('folder_ibfk_1', 'folder', type_='foreignkey')
op.drop_constraint('account_id', 'folder', type_='unique')
op.create_foreign_key('folder_ibfk_1',
'folder', 'account',
['account_id'], ['id'])
op.create_unique_constraint('account_id',
'folder',
['account_id', 'name', 'canonical_name'])
if 'easfoldersyncstatus' in Base.metadata.tables:
op.create_unique_constraint('account_id_2',
'easfoldersyncstatus',
['account_id', 'eas_folder_id'])
def downgrade():
raise Exception('Unsupported, going back will break things.')
|
Copy README.md to dist folder | var path = require("path");
var webpack = require("webpack");
var libraryName = 'lc-form-validation';
var CopyWebpackPlugin = require('copy-webpack-plugin');
var basePath = __dirname;
var env = process.env.NODE_ENV;
var production = 'production';
var config = {
context: path.join(basePath, "src"),
resolve: {
// .js is required for react imports.
// .tsx is for our app entry point.
// .ts is optional, in case you will be importing any regular ts files.
extensions: ['', '.js', '.ts', '.tsx']
},
entry: [
'./index.ts'
],
output: {
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
loaders: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
loader: 'ts-loader'
}
]
},
plugins:[
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env)
}),
new CopyWebpackPlugin([
{from: '../package.json', to:'dist/package.json'},
{from: '../../README.md', to:'dist/README.md'}
])
]
};
if (env === production) {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
warnings: false
}
})
)
}
module.exports = config;
| var path = require("path");
var webpack = require("webpack");
var libraryName = 'lc-form-validation';
var CopyWebpackPlugin = require('copy-webpack-plugin');
var basePath = __dirname;
var env = process.env.NODE_ENV;
var production = 'production';
var config = {
context: path.join(basePath, "src"),
resolve: {
// .js is required for react imports.
// .tsx is for our app entry point.
// .ts is optional, in case you will be importing any regular ts files.
extensions: ['', '.js', '.ts', '.tsx']
},
entry: [
'./index.ts'
],
output: {
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
loaders: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
loader: 'ts-loader'
}
]
},
plugins:[
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env)
}),
new CopyWebpackPlugin([
{from: '../package.json', to:'dist/package.json'}
])
]
};
if (env === 'production') {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
warnings: false
}
})
)
}
module.exports = config;
|
Add basic unit tests for BMAttackSurrender | <?php
class BMAttackSurrenderTest extends PHPUnit_Framework_TestCase {
/**
* @var BMAttackSurrender
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = BMAttackSurrender::get_instance();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* @covers BMAttackSurrender::validate_attack
*/
public function testValidate_attack()
{
$game = new TestDummyGame;
$die1 = new BMDie;
$die1->init(6);
$die1->value = 6;
$die2 = new BMDie;
$die2->init(6);
$die2->value = 1;
// Basic error handling
$this->assertTrue($this->object->validate_attack($game, array(), array()));
$this->assertFalse($this->object->validate_attack($game, array($die1), array()));
$this->assertFalse($this->object->validate_attack($game, array(), array($die1)));
$this->assertFalse($this->object->validate_attack($game, array($die1), array($die2)));
}
}
?> | <?php
class BMAttackSurrenderTest extends PHPUnit_Framework_TestCase {
/**
* @var BMAttackSurrender
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = BMAttackSurrender::get_instance();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* @covers BMAttackSurrender::validate_attack
*/
public function testValidate_attack()
{
// $game = new TestDummyGame;
//
// $die1 = new BMDie;
// $die1->init(6);
// $die1->value = 6;
//
// $die2 = new BMDie;
// $die2->init(6);
// $die2->value = 1;
//
// // Basic error handling
// $this->assertTrue($this->object->validate_attack($game, array(), array()));
// $this->assertFalse($this->object->validate_attack($game, array($die1), array()));
// $this->assertFalse($this->object->validate_attack($game, array(), array($die1)));
// $this->assertFalse($this->object->validate_attack($game, array($die1), array($die2)));
}
}
?> |
Add images to snapshot details | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot, serializers={
Snapshot: SnapshotWithImagesSerializer(),
})
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
| from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot)
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
|
Fix another simplejson deprecation warning | import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from djangocms_table.utils import static_url
from django.http import HttpResponseRedirect
class TablePlugin(CMSPluginBase):
model = Table
form = TableForm
name = _("Table")
render_template = "cms/plugins/table.html"
text_enabled = True
fieldsets = (
(None, {
'fields': ('name',)
}),
(_('Headers'), {
'fields': (('headers_top', 'headers_left', 'headers_bottom'),)
}),
(None, {
'fields': ('table_data', 'csv_upload')
})
)
def render(self, context, instance, placeholder):
try:
data = json.loads(instance.table_data)
except:
data = "error"
context.update({
'name': instance.name,
'data': data,
'instance':instance,
})
return context
def icon_src(self, instance):
return static_url("img/table.png")
def response_change(self, request, obj):
response = super(TablePlugin, self).response_change(request, obj)
if 'csv_upload' in request.FILES.keys():
self.object_successfully_changed = False
return response
plugin_pool.register_plugin(TablePlugin)
| from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from django.utils import simplejson
from djangocms_table.utils import static_url
from django.http import HttpResponseRedirect
class TablePlugin(CMSPluginBase):
model = Table
form = TableForm
name = _("Table")
render_template = "cms/plugins/table.html"
text_enabled = True
fieldsets = (
(None, {
'fields': ('name',)
}),
(_('Headers'), {
'fields': (('headers_top', 'headers_left', 'headers_bottom'),)
}),
(None, {
'fields': ('table_data', 'csv_upload')
})
)
def render(self, context, instance, placeholder):
try:
data = simplejson.loads(instance.table_data)
except:
data = "error"
context.update({
'name': instance.name,
'data': data,
'instance':instance,
})
return context
def icon_src(self, instance):
return static_url("img/table.png")
def response_change(self, request, obj):
response = super(TablePlugin, self).response_change(request, obj)
if 'csv_upload' in request.FILES.keys():
self.object_successfully_changed = False
return response
plugin_pool.register_plugin(TablePlugin)
|
Fix tests for PHP 5.3 | <?php
/**
* PHP Version 5.3
*
* @copyright (c) 2006-2015 brian ridley
* @author brian ridley <[email protected]>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ptlis\ConNeg\Test\Negotiation;
use ptlis\ConNeg\Collection\TypeCollection;
use ptlis\ConNeg\Negotiation;
use ptlis\ConNeg\Type\Type;
use ptlis\ConNeg\TypePair\TypePair;
class NonStringAppTypeTest extends \PHPUnit_Framework_TestCase
{
public function testAppInvalidTypes()
{
$this->setExpectedException(
'\LogicException',
'Invalid application preferences passed to ptlis\ConNeg\Negotiation::sharedAppPrefsToTypes'
);
$negotiate = new Negotiation();
$negotiate->charsetAll('', new \DateTime());
}
public function testAppCollection()
{
$negotiate = new Negotiation();
$collection = $negotiate->charsetAll('', new TypeCollection(array()));
$this->assertEquals(
new TypePair(
new Type('', 0, Type::ABSENT_TYPE),
new Type('', 0, Type::ABSENT_TYPE)
),
$collection->getBest()
);
}
}
| <?php
/**
* PHP Version 5.3
*
* @copyright (c) 2006-2015 brian ridley
* @author brian ridley <[email protected]>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ptlis\ConNeg\Test\Negotiation;
use ptlis\ConNeg\Collection\TypeCollection;
use ptlis\ConNeg\Negotiation;
use ptlis\ConNeg\Type\Type;
use ptlis\ConNeg\TypePair\TypePair;
class NonStringAppTypeTest extends \PHPUnit_Framework_TestCase
{
public function testAppInvalidTypes()
{
$this->setExpectedException(
'\LogicException',
'Invalid application preferences passed to ptlis\ConNeg\Negotiation::sharedAppPrefsToTypes'
);
$negotiate = new Negotiation();
$negotiate->charsetAll('', new \DateTime());
}
public function testAppCollection()
{
$negotiate = new Negotiation();
$collection = $negotiate->charsetAll('', new TypeCollection([]));
$this->assertEquals(
new TypePair(
new Type('', 0, Type::ABSENT_TYPE),
new Type('', 0, Type::ABSENT_TYPE)
),
$collection->getBest()
);
}
}
|
fix: Solve the default random avatar path problem | const path = require('path');
const options = require('../utils/commandOptions');
module.exports = {
commonn: {
convertPxToRem: {
enable: false,
options: {
rootValue: 108, // 设计稿为3倍图
propList: ['*', '!border'],
unitPrecision: 4,
replace: true,
},
},
autoPrefix: {
enable: true,
options: {
browsers: ['last 3 versions'],
},
},
},
build: {
env: {
NODE_ENV: '"production"',
},
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist/fiora'),
assetsSubDirectory: options.subDirectory !== undefined ? options.subDirectory : '.',
assetsPublicPath: options.publicPath !== undefined ? options.publicPath : '/',
productionSourceMap: false,
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report,
},
dev: {
env: {
NODE_ENV: '"development"',
},
host: 'localhost',
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
cssSourceMap: false,
},
};
| const path = require('path');
const options = require('../utils/commandOptions');
module.exports = {
commonn: {
convertPxToRem: {
enable: false,
options: {
rootValue: 108, // 设计稿为3倍图
propList: ['*', '!border'],
unitPrecision: 4,
replace: true,
},
},
autoPrefix: {
enable: true,
options: {
browsers: ['last 3 versions'],
},
},
},
build: {
env: {
NODE_ENV: '"production"',
},
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist/fiora'),
assetsSubDirectory: options.subDirectory || '.',
assetsPublicPath: options.publicPath || '/',
productionSourceMap: false,
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report,
},
dev: {
env: {
NODE_ENV: '"development"',
},
host: 'localhost',
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
cssSourceMap: false,
},
};
|
Make the script check all the site package directories | import os
import site
# Check to see if the previous version was installed and clean up
# installed-files.txt
prune = ['var/', 'var/run/', 'var/log/']
package_directories = site.PREFIXES
if site.USER_SITE:
package_directories.append(site.USER_SITE)
for package_dir in package_directories:
print 'Checking %s for newrelic_plugin_agent installation manifest' % package_dir
fixed = False
for dir_path, dir_names, file_names in os.walk(package_dir):
for dir_name in dir_names:
if dir_name[:21] == 'newrelic_plugin_agent' and \
dir_name[-8:] == 'egg-info':
filename = '%s/%s/installed-files.txt' % (python_lib_dir, dir_name)
with open(filename, 'r') as handle:
output = []
for line in handle:
safe = True
for dir_path in prune:
if line[-(len(dir_path) + 1):].strip() == dir_path:
safe = False
fixed = True
break
if safe:
output.append(line.strip())
if fixed:
with open(filename, 'w') as handle:
handle.write('\n'.join(output))
break
break
if fixed:
print 'Fixed a serious uninstallation problem in previous version'
else:
print 'Did not find the installed-files.txt manifest uninstallation issue'
| import os
from distutils import sysconfig
# Check to see if the previous version was installed and clean up
# installed-files.txt
prune = ['var/', 'var/run/', 'var/log/']
python_lib_dir = sysconfig.get_python_lib()
fixed = False
for dir_path, dir_names, file_names in os.walk(python_lib_dir):
for dir_name in dir_names:
if dir_name[:21] == 'newrelic_plugin_agent' and \
dir_name[-8:] == 'egg-info':
filename = '%s/%s/installed-files.txt' % (python_lib_dir, dir_name)
with open(filename, 'r') as handle:
output = []
for line in handle:
safe = True
for dir_path in prune:
if line[-(len(dir_path) + 1):].strip() == dir_path:
safe = False
fixed = True
break
if safe:
output.append(line.strip())
with open(filename, 'w') as handle:
handle.write('\n'.join(output))
break
break
if fixed:
print 'Fixed a serious uninstallation problem in previous version'
|
Add changes forgotten in the last commit :-( | package de.ddb.pdc.storage;
import de.ddb.pdc.core.AnsweredQuestion;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.springframework.data.annotation.Id;
/**
* Entity representing the PDC record structure in storage.
*/
public class StorageModel {
@Id
private String id;
private final String itemId;
private final String itemCategory;
private final String institution;
private final Boolean publicDomain;
private final List<AnsweredQuestion> trace;
private final String timestamp;
/**
* Constructor for storing new records.
* The timestamp is automatically assigned to the current date and time.
*/
public StorageModel(String itemId, String itemCategory, String institution,
Boolean publicDomain, List<AnsweredQuestion> trace) {
this.itemId = itemId;
this.itemCategory = itemCategory;
this.institution = institution;
this.publicDomain = publicDomain;
this.trace = trace;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
this.timestamp = sdf.format(new Date());
}
public String getItemId() {
return itemId;
}
public String getItemCategory() {
return itemCategory;
}
public String getInstitution() {
return institution;
}
public boolean isPublicDomain() {
return publicDomain;
}
public List<AnsweredQuestion> getTrace() {
return trace;
}
public String getTimestampAsString() {
return timestamp;
}
}
| package de.ddb.pdc.storage;
import de.ddb.pdc.core.AnsweredQuestion;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.springframework.data.annotation.Id;
/**
* Entity representing the PDC record structure in storage.
*/
public class StorageModel {
@Id
private String id;
private final String itemId;
private final String itemCategory;
private final String institution;
private final boolean publicDomain;
private final List<AnsweredQuestion> trace;
private final String timestamp;
/**
* Constructor for storing new records.
* The timestamp is automatically assigned to the current date and time.
*/
public StorageModel(String itemId, String itemCategory, String institution,
boolean publicDomain, List<AnsweredQuestion> trace) {
this.itemId = itemId;
this.itemCategory = itemCategory;
this.institution = institution;
this.publicDomain = publicDomain;
this.trace = trace;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
this.timestamp = sdf.format(new Date());
}
public String getItemId() {
return itemId;
}
public String getItemCategory() {
return itemCategory;
}
public String getInstitution() {
return institution;
}
public boolean isPublicDomain() {
return publicDomain;
}
public List<AnsweredQuestion> getTrace() {
return trace;
}
public String getTimestampAsString() {
return timestamp;
}
}
|
Remove media screen to fix styles when printing. | <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<style>
body {margin: 20px}
</style>
</head>
<body>
<table class="table table-bordered table-condensed">
@foreach($data as $row)
@if ($row == reset($data))
<tr>
@foreach($row as $key => $value)
<th>{!! $key !!}</th>
@endforeach
</tr>
@endif
<tr>
@foreach($row as $key => $value)
@if (is_string($value) || trim($value)==='' || is_numeric($value))
<td>{!! $value !!}</td>
@endif
@endforeach
</tr>
@endforeach
</table>
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<style>
body {margin: 20px}
</style>
</head>
<body>
<table class="table table-bordered table-condensed">
@foreach($data as $row)
@if ($row == reset($data))
<tr>
@foreach($row as $key => $value)
<th>{!! $key !!}</th>
@endforeach
</tr>
@endif
<tr>
@foreach($row as $key => $value)
@if (is_string($value) || trim($value)==='' || is_numeric($value))
<td>{!! $value !!}</td>
@endif
@endforeach
</tr>
@endforeach
</table>
</body>
</html>
|
Set execution timeout to be lower
Otherwise the test would be much slower | from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
execution_timeout=5,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files()
| from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files()
|
Reduce poll time to 10ms. | package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A queue of incoming {@link ResponseMessage} objects. The queue is updated by the
* {@link Handler.GremlinResponseDecoder} until a response terminator is identified. At that point the fetch
* status is changed to {@link Status#COMPLETE} and all results have made it client side.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
class ResponseQueue {
public enum Status {
FETCHING,
COMPLETE
}
private final LinkedBlockingQueue<ResponseMessage> responseQueue;
private volatile Status status = Status.FETCHING;
public ResponseQueue(final LinkedBlockingQueue<ResponseMessage> responseQueue) {
this.responseQueue = responseQueue;
}
public void add(final ResponseMessage msg) {
this.responseQueue.offer(msg);
}
public int size() {
return this.responseQueue.size();
}
public ResponseMessage poll() {
try {
ResponseMessage msg;
do {
msg = responseQueue.poll(10, TimeUnit.MILLISECONDS);
} while (null == msg && status == Status.FETCHING);
return msg;
} catch (InterruptedException ie) {
throw new RuntimeException("Taking too long to get results");
}
}
public Status getStatus() {
return status;
}
void markComplete() {
this.status = Status.COMPLETE;
}
}
| package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A queue of incoming {@link ResponseMessage} objects. The queue is updated by the
* {@link Handler.GremlinResponseDecoder} until a response terminator is identified. At that point the fetch
* status is changed to {@link Status#COMPLETE} and all results have made it client side.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
class ResponseQueue {
public enum Status {
FETCHING,
COMPLETE
}
private final LinkedBlockingQueue<ResponseMessage> responseQueue;
private volatile Status status = Status.FETCHING;
public ResponseQueue(final LinkedBlockingQueue<ResponseMessage> responseQueue) {
this.responseQueue = responseQueue;
}
public void add(final ResponseMessage msg) {
this.responseQueue.offer(msg);
}
public int size() {
return this.responseQueue.size();
}
public ResponseMessage poll() {
try {
ResponseMessage msg;
do {
msg = responseQueue.poll(100, TimeUnit.MILLISECONDS);
} while (null == msg && status == Status.FETCHING);
return msg;
} catch (InterruptedException ie) {
throw new RuntimeException("Taking too long to get results");
}
}
public Status getStatus() {
return status;
}
void markComplete() {
this.status = Status.COMPLETE;
}
}
|
Fix a test to work on php 7.1 | <?php
namespace Rybakit\Bundle\NavigationBundle\Tests\Twig;
use PHPUnit\Framework\TestCase;
use Rybakit\Bundle\NavigationBundle\Tests\Fixtures\Item;
use Rybakit\Bundle\NavigationBundle\Twig\NavigationExtension;
class NavigationExtensionTest extends TestCase
{
/**
* @dataProvider provideGetAncestorData
*/
public function testGetAncestor(Item $item, $level, Item $ancestor = null)
{
$ext = new NavigationExtension('foo.bar.twig');
$this->assertSame($ancestor, $ext->getAncestor($item, $level));
}
public function provideGetAncestorData()
{
$root = new Item();
$level1 = new Item();
$level1->setParent($root);
$level2 = new Item();
$level2->setParent($level1);
return [
[$root, 0, $root],
[$root, 1, null],
[$root, -1, null],
[$level1, 0, $root],
[$level1, -1, $root],
[$level1, '-1', $root],
[$level1, '-9', null],
[$level1, 9, null],
[$level2, 1, $level1],
[$level2, '2', $level2],
[$level2, '0', $root],
[$level2, 'foo', null],
];
}
}
| <?php
namespace Rybakit\Bundle\NavigationBundle\Tests\Twig;
use PHPUnit\Framework\TestCase;
use Rybakit\Bundle\NavigationBundle\Tests\Fixtures\Item;
use Rybakit\Bundle\NavigationBundle\Twig\NavigationExtension;
class NavigationExtensionTest extends TestCase
{
/**
* @dataProvider provideGetAncestorData
*/
public function testGetAncestor(Item $item, $level, ?Item $ancestor)
{
$ext = new NavigationExtension('foo.bar.twig');
$this->assertSame($ancestor, $ext->getAncestor($item, $level));
}
public function provideGetAncestorData()
{
$root = new Item();
$level1 = new Item();
$level1->setParent($root);
$level2 = new Item();
$level2->setParent($level1);
return [
[$root, 0, $root],
[$root, 1, null],
[$root, -1, null],
[$level1, 0, $root],
[$level1, -1, $root],
[$level1, '-1', $root],
[$level1, '-9', null],
[$level1, 9, null],
[$level2, 1, $level1],
[$level2, '2', $level2],
[$level2, '0', $root],
[$level2, 'foo', null],
];
}
}
|
Update find owner to work with promises. | """
Command that will allow for a user to inject triples into a database.
"""
from rhobot.components.commands.base_command import BaseCommand
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
from rhobot.components.storage import StoragePayload
import logging
logger = logging.getLogger(__name__)
class FindOwner(BaseCommand):
def initialize_command(self):
super(FindOwner, self).initialize_command()
logger.info('Initialize Command')
self._initialize_command(identifier='find_owner', name='Find Owner',
additional_dependencies={'rho_bot_storage_client', 'rho_bot_scheduler', })
def command_start(self, request, initial_session):
"""
Provide the configuration details back to the requester and end the command.
:param request:
:param initial_session:
:return:
"""
storage = StoragePayload()
storage.add_type(FOAF.Person, RHO.Owner)
promise = self.xmpp['rho_bot_storage_client'].find_nodes(storage)
def find_nodes_processor(results):
"""
Process the results and place the payload into the initial session value.
:param results:
:return: the initial session value.
"""
initial_session['payload'] = results.populate_payload()
return initial_session
# Finish populating the rest of initial_session values.
initial_session['next'] = None
initial_session['has_next'] = False
return promise.then(find_nodes_processor)
find_owner = FindOwner
| """
Command that will allow for a user to inject triples into a database.
"""
from rhobot.components.commands.base_command import BaseCommand
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__name__)
class FindOwner(BaseCommand):
def initialize_command(self):
super(FindOwner, self).initialize_command()
logger.info('Initialize Command')
self._initialize_command(identifier='find_owner', name='Find Owner',
additional_dependencies={'rho_bot_storage_client', 'rho_bot_scheduler', })
def command_start(self, request, initial_session):
"""
Provide the configuration details back to the requester and end the command.
:param request:
:param initial_session:
:return:
"""
storage = self.xmpp['rho_bot_storage_client'].create_payload()
storage.add_type(FOAF.Person, RHO.Owner)
results = self.xmpp['rho_bot_storage_client'].find_nodes(storage)
initial_session['payload'] = results.populate_payload()
initial_session['next'] = None
initial_session['has_next'] = False
promise = self.xmpp['rho_bot_scheduler'].promise()
promise.resolved(initial_session)
return promise
find_owner = FindOwner
|
Use bytes instead of str where appropriate for Python 3 | class Console(object):
def __init__(self, shell, stdout):
self._shell = shell
self._stdout = stdout
def run(self, description, command, **kwargs):
return self.run_all(description, [command], **kwargs)
def run_all(self, description, commands, quiet=False, cwd=None):
stdout = None if quiet else self._stdout
# TODO: Test printing description
# TODO: detect terminal
self._stdout.write(b'\033[1m')
self._stdout.write(description.encode("utf8"))
self._stdout.write(b"\n")
self._stdout.write(b'\033[0m')
self._stdout.flush()
for command in commands:
# TODO: print command
result = self._shell.run(
command,
stdout=stdout,
stderr=stdout,
cwd=cwd,
allow_error=True
)
if result.return_code != 0:
return Result(result.return_code)
return Result(0)
class Result(object):
def __init__(self, return_code):
self.return_code = return_code
| class Console(object):
def __init__(self, shell, stdout):
self._shell = shell
self._stdout = stdout
def run(self, description, command, **kwargs):
return self.run_all(description, [command], **kwargs)
def run_all(self, description, commands, quiet=False, cwd=None):
stdout = None if quiet else self._stdout
# TODO: Test printing description
# TODO: detect terminal
self._stdout.write('\033[1m')
self._stdout.write(description)
self._stdout.write("\n")
self._stdout.write('\033[0m')
self._stdout.flush()
for command in commands:
# TODO: print command
result = self._shell.run(
command,
stdout=stdout,
stderr=stdout,
cwd=cwd,
allow_error=True
)
if result.return_code != 0:
return Result(result.return_code)
return Result(0)
class Result(object):
def __init__(self, return_code):
self.return_code = return_code
|
Reduce visibility of firebase analytics constructor | package com.alexstyl.specialdates.analytics;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.novoda.notils.logger.simple.Log;
import java.util.Locale;
public class Firebase implements Analytics {
private static final Bundle NO_DATA = null;
private final FirebaseAnalytics firebaseAnalytics;
private static Firebase INSTANCE;
public static Firebase get(Context context) {
if (INSTANCE == null) {
INSTANCE = new Firebase(FirebaseAnalytics.getInstance(context));
}
return INSTANCE;
}
private Firebase(FirebaseAnalytics firebaseAnalytics) {
this.firebaseAnalytics = firebaseAnalytics;
}
@Override
public void trackAction(Action goToToday) {
String actionName = goToToday.getName();
firebaseAnalytics.logEvent(actionName, NO_DATA);
Log.d("Tracking event:" + actionName);
}
@Override
public void trackAction(ActionWithParameters action) {
String formattedAction = format(action);
firebaseAnalytics.logEvent(formattedAction, NO_DATA);
Log.d("Tracking event:" + formattedAction);
}
@Override
public void trackScreen(Screen screen) {
firebaseAnalytics.logEvent("screen_view:" + screen.screenName(), NO_DATA);
Log.d("Tracking screen_view:" + screen);
}
private String format(ActionWithParameters action) {
return String.format(Locale.US, "%s:%s:%s", action.getName(), action.getLabel(), action.getValue());
}
}
| package com.alexstyl.specialdates.analytics;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.novoda.notils.logger.simple.Log;
import java.util.Locale;
public class Firebase implements Analytics {
private static final Bundle NO_DATA = null;
private final FirebaseAnalytics firebaseAnalytics;
private static Firebase INSTANCE;
public static Firebase get(Context context) {
if (INSTANCE == null) {
INSTANCE = new Firebase(FirebaseAnalytics.getInstance(context));
}
return INSTANCE;
}
public Firebase(FirebaseAnalytics firebaseAnalytics) {
this.firebaseAnalytics = firebaseAnalytics;
}
@Override
public void trackAction(Action goToToday) {
String actionName = goToToday.getName();
firebaseAnalytics.logEvent(actionName, NO_DATA);
Log.d("Tracking event:" + actionName);
}
@Override
public void trackAction(ActionWithParameters action) {
String formattedAction = format(action);
firebaseAnalytics.logEvent(formattedAction, NO_DATA);
Log.d("Tracking event:" + formattedAction);
}
@Override
public void trackScreen(Screen screen) {
firebaseAnalytics.logEvent("screen_view:" + screen.screenName(), NO_DATA);
Log.d("Tracking screen_view:" + screen);
}
private String format(ActionWithParameters action) {
return String.format(Locale.US, "%s:%s:%s", action.getName(), action.getLabel(), action.getValue());
}
}
|
Convert all os.system() to subprocess.check_output(). | '''
@date 2015-02-21
@author Hong-She Liang <[email protected]>
'''
import os
import re
import subprocess
from .mouse_constant import *
class Mouse(object):
## return current mouse absolute position
@classmethod
def position(cls):
output = subprocess.check_output(["xdotool", "getmouselocation"])
matched = re.match(".*x:(\d+)\s*y:(\d+)\s*.*", output)
return [int(matched.group(1)), int(matched.group(2))]
@classmethod
def move(cls, position):
subprocess.call(["xdotool", "mousemove", "--sync", position[0], position[1]])
##
@classmethod
def button_up(cls, button_type = ButtonType.LEFT ):
if ButtonType.LEFT == button_type:
subprocess.call(["xdotool", "mouseup", "1"])
elif ButtonType.RIGHT == button_type:
subprocess.call(["xdotool", "mouseup", "3"])
elif ButtonType.MIDDLE == button_type:
subprocess.call(["xdotool", "mouseup", "2"])
@classmethod
def button_down(cls, button_type = ButtonType.LEFT ):
if ButtonType.LEFT == button_type:
subprocess.call(["xdotool", "mousedown", "1"])
elif ButtonType.RIGHT == button_type:
subprocess.call(["xdotool", "mousedown", "3"])
elif ButtonType.MIDDLE == button_type:
subprocess.call(["xdotool", "mousedown", "2"])
| '''
@date 2015-02-21
@author Hong-She Liang <[email protected]>
'''
import os
import re
import subprocess
from .mouse_constant import *
class Mouse(object):
## return current mouse absolute position
@classmethod
def position(cls):
p = subprocess.Popen(["xdotool", "getmouselocation"], stdout=subprocess.PIPE)
output = p.communicate()[0]
matched = re.match(".*x:(\d+)\s*y:(\d+)\s*.*", output)
return [int(matched.group(1)), int(matched.group(2))]
@classmethod
def move(cls, position):
os.system("xdotool mousemove --sync %s %s" % (int(position[0]), int(position[1])))
##
@classmethod
def button_up(cls, button_type = ButtonType.LEFT ):
if ButtonType.LEFT == button_type:
os.system("xdotool mouseup 1")
elif ButtonType.RIGHT == button_type:
os.system("xdotool mouseup 3")
elif ButtonType.MIDDLE == button_type:
os.system("xdotool mouseup 2")
@classmethod
def button_down(cls, button_type = ButtonType.LEFT ):
if ButtonType.LEFT == button_type:
os.system("xdotool mousedown 1")
elif ButtonType.RIGHT == button_type:
os.system("xdotool mousedown 3")
elif ButtonType.MIDDLE == button_type:
os.system("xdotool mousedown 2")
|
Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404. | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/$',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/$',
FavoriteCreateDestroyView.as_view()),
url(r'layers/$', LayerListView.as_view()),
url(r'^$', home_page, name='home_page'),
url(r'login/$', home_page),
url(r'sign-up/$', home_page),
url(r'send-activation/$', home_page),
url(r'forgot/$', home_page),
url(r'logout/$', home_page),
url(r'activate/$', home_page),
)
| # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/',
FavoriteCreateDestroyView.as_view()),
url(r'layers/', LayerListView.as_view()),
url(r'', home_page, name='home_page'),
)
|
Test the new enforce method | <?php
namespace PhpAbac\Test;
use PhpAbac\Abac;
class AbacTest extends AbacTestCase {
/** @var Abac **/
protected $abac;
public function setUp() {
$this->abac = new Abac(new \PDO(
'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' .
'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'],
$GLOBALS['MYSQL_DB_USER'],
$GLOBALS['MYSQL_DB_PASSWD'],
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
]
));
$this->loadFixture('policy_rules');
}
public function tearDown() {
Abac::clearContainer();
}
public function testEnforce() {
$this->assertTrue($this->abac->enforce('nationality-access', 1));
$this->assertFalse($this->abac->enforce('nationality-access', 2));
}
public function testContainer() {
$item = new \stdClass();
$item->property = 'test';
// Test Set method
Abac::set('test-item', $item);
// Test Has method
$this->assertTrue(Abac::has('test-item'));
// Test Get method
$containedItem = Abac::get('test-item');
$this->assertInstanceof('StdClass', $containedItem);
$this->assertEquals('test', $containedItem->property);
// Test clearContainer
Abac::clearContainer();
$this->assertFalse(Abac::has('test-item'));
}
} | <?php
namespace PhpAbac\Test;
use PhpAbac\Abac;
class AbacTest extends AbacTestCase {
/** @var Abac **/
protected $abac;
public function setUp() {
$this->abac = new Abac(new \PDO(
'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' .
'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'],
$GLOBALS['MYSQL_DB_USER'],
$GLOBALS['MYSQL_DB_PASSWD'],
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
]
));
$this->loadFixture('policy_rules');
}
public function tearDown() {
Abac::clearContainer();
}
public function testEnforce() {
$this->abac->enforce('nationality-access', 1);
}
public function testContainer() {
$item = new \stdClass();
$item->property = 'test';
// Test Set method
Abac::set('test-item', $item);
// Test Has method
$this->assertTrue(Abac::has('test-item'));
// Test Get method
$containedItem = Abac::get('test-item');
$this->assertInstanceof('StdClass', $containedItem);
$this->assertEquals('test', $containedItem->property);
// Test clearContainer
Abac::clearContainer();
$this->assertFalse(Abac::has('test-item'));
}
} |
Fix required_fields looking at wrong jsonify file. | import flask
from flask import request
import functools
from . import jsonify
def required_fields(fields, forbid_whitespace=False):
'''
Declare that the endpoint requires certain POST body fields. Without them,
we respond with 400 and a message.
forbid_whitespace:
If True, then providing the field is not good enough. It must also
contain at least some non-whitespace characters.
'''
def wrapper(function):
@functools.wraps(function)
def wrapped(*args, **kwargs):
for requirement in fields:
missing = (
requirement not in request.form or
(forbid_whitespace and request.form[requirement].strip() == '')
)
if missing:
response = {
'error_type': 'MISSING_FIELDS',
'error_message': 'Required fields: %s' % ', '.join(fields),
}
response = jsonify.make_json_response(response, status=400)
return response
return function(*args, **kwargs)
return wrapped
return wrapper
| import flask
from flask import request
import functools
from etiquette import jsonify
def required_fields(fields, forbid_whitespace=False):
'''
Declare that the endpoint requires certain POST body fields. Without them,
we respond with 400 and a message.
forbid_whitespace:
If True, then providing the field is not good enough. It must also
contain at least some non-whitespace characters.
'''
def wrapper(function):
@functools.wraps(function)
def wrapped(*args, **kwargs):
for requirement in fields:
missing = (
requirement not in request.form or
(forbid_whitespace and request.form[requirement].strip() == '')
)
if missing:
response = {
'error_type': 'MISSING_FIELDS',
'error_message': 'Required fields: %s' % ', '.join(fields),
}
response = jsonify.make_json_response(response, status=400)
return response
return function(*args, **kwargs)
return wrapped
return wrapper
|
Use Grunt API to write file
This way it guarantees that all the intermediate directories are created. | var doxdox = require('doxdox'),
utils = require('doxdox/lib/utils'),
fs = require('fs'),
path = require('path'),
extend = require('extend');
module.exports = function (grunt) {
grunt.registerMultiTask('doxdox', 'Generate documentation with doxdox.', function () {
var done = this.async(),
input,
output,
config = {
title: '',
description: '',
layout: 'bootstrap'
};
if (this.data.input && this.data.output) {
input = this.data.input;
output = this.data.output;
if (this.data.config) {
config = extend(true, {}, config, this.data.config);
}
if (!config.package) {
config.package = utils.findPackagePath(input);
}
if (fs.existsSync(config.package)) {
config.package = require(config.package);
if (!config.title && config.package.name) {
config.title = config.package.name;
}
if (!config.description && config.package.description) {
config.description = config.package.description;
}
}
if (!config.title) {
config.title = 'Untitled Project';
}
doxdox.parseInput(
path.normalize(path.resolve(input)),
config,
config.package
).then(function (content) {
grunt.file.write(output, content, {encoding: 'utf8'});
done();
});
} else {
throw new Error('Valid input and output properties are required.');
}
});
};
| var doxdox = require('doxdox'),
utils = require('doxdox/lib/utils'),
fs = require('fs'),
path = require('path'),
extend = require('extend');
module.exports = function (grunt) {
grunt.registerMultiTask('doxdox', 'Generate documentation with doxdox.', function () {
var done = this.async(),
input,
output,
config = {
title: '',
description: '',
layout: 'bootstrap'
};
if (this.data.input && this.data.output) {
input = this.data.input;
output = this.data.output;
if (this.data.config) {
config = extend(true, {}, config, this.data.config);
}
if (!config.package) {
config.package = utils.findPackagePath(input);
}
if (fs.existsSync(config.package)) {
config.package = require(config.package);
if (!config.title && config.package.name) {
config.title = config.package.name;
}
if (!config.description && config.package.description) {
config.description = config.package.description;
}
}
if (!config.title) {
config.title = 'Untitled Project';
}
doxdox.parseInput(
path.normalize(path.resolve(input)),
config,
config.package
).then(function (content) {
fs.writeFileSync(output, content, 'utf8');
done();
});
} else {
throw new Error('Valid input and output properties are required.');
}
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.