text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Create a statsd_client anyway, even if there is no STATSD_URL env variable set | import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.StatsClient(host=ip, port=int(port),
prefix=os.environ.get('STATSD_PREFIX',
None))
else:
statsd_client = statsd.StatsClient()
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine
def fn_wrapper(*args, **kwargs):
def send_duration():
duration = (datetime.datetime.now() - start).total_seconds()
statsd_client.timing("{}.duration".format(name),
int(duration * 1000))
start = datetime.datetime.now()
ftr_result = fn(*args, **kwargs)
try:
result = yield tornado.gen.maybe_future(ftr_result)
except Exception as e:
if statsd_client:
statsd_client.incr("{}.exceptions.{}".format(
name, e.__class__.__name__.lower()))
send_duration()
raise e
else:
if statsd_client:
send_duration()
statsd_client.incr("{}.success".format(name))
raise tornado.gen.Return(result)
return fn_wrapper
return instrument_wrapper
| import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.StatsClient(host=ip, port=int(port),
prefix=os.environ.get('STATSD_PREFIX',
None))
else:
statsd_client = None
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine
def fn_wrapper(*args, **kwargs):
def send_duration():
duration = (datetime.datetime.now() - start).total_seconds()
statsd_client.timing("{}.duration".format(name),
int(duration * 1000))
start = datetime.datetime.now()
ftr_result = fn(*args, **kwargs)
try:
result = yield tornado.gen.maybe_future(ftr_result)
except Exception as e:
if statsd_client:
statsd_client.incr("{}.exceptions.{}".format(
name, e.__class__.__name__.lower()))
send_duration()
raise e
else:
if statsd_client:
send_duration()
statsd_client.incr("{}.success".format(name))
raise tornado.gen.Return(result)
return fn_wrapper
return instrument_wrapper
|
Return boolean instead of if statement. | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Stdlib\Hydrator\Filter;
use ReflectionException;
use ReflectionMethod;
use Zend\Stdlib\Exception\InvalidArgumentException;
class NumberOfParameterFilter implements FilterInterface
{
/**
* The number of parameters beeing accepted
* @var int
*/
protected $numberOfParameters = null;
/**
* @param int $numberOfParameters Number of accepted parameters
*/
public function __construct($numberOfParameters = 0)
{
$this->numberOfParameters = (int) $numberOfParameters;
}
/**
* @param string $property the name of the property
* @return bool
* @throws InvalidArgumentException
*/
public function filter($property)
{
try {
$reflectionMethod = new ReflectionMethod($property);
} catch (ReflectionException $exception) {
throw new InvalidArgumentException(
"Method $property doesn't exist"
);
}
return $reflectionMethod->getNumberOfParameters() === $this->numberOfParameters;
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Stdlib\Hydrator\Filter;
use ReflectionException;
use ReflectionMethod;
use Zend\Stdlib\Exception\InvalidArgumentException;
class NumberOfParameterFilter implements FilterInterface
{
/**
* The number of parameters beeing accepted
* @var int
*/
protected $numberOfParameters = null;
/**
* @param int $numberOfParameters Number of accepted parameters
*/
public function __construct($numberOfParameters = 0)
{
$this->numberOfParameters = (int) $numberOfParameters;
}
/**
* @param string $property the name of the property
* @return bool
* @throws InvalidArgumentException
*/
public function filter($property)
{
try {
$reflectionMethod = new ReflectionMethod($property);
} catch (ReflectionException $exception) {
throw new InvalidArgumentException(
"Method $property doesn't exist"
);
}
if ($reflectionMethod->getNumberOfParameters() !== $this->numberOfParameters) {
return false;
}
return true;
}
}
|
Throw a more user-friendly exception when the SearchBehavior is not attached
Rather than throw the following error/exception:
```
Unknown method "filterParams"
```
We throw a RuntimeException that informs the developer that they have misconfigured their application, allowing them to more quickly debug the issue. | <?php
namespace Crud\Listener;
use Cake\Core\Plugin;
use Cake\Event\Event;
use RuntimeException;
class SearchListener extends BaseListener
{
/**
* Settings
*
* @var array
*/
protected $_defaultConfig = [
'enabled' => [
'Crud.beforeLookup',
'Crud.beforePaginate'
]
];
/**
* Returns a list of all events that will fire in the controller during its lifecycle.
* You can override this function to add your own listener callbacks
*
* @return array
*/
public function implementedEvents()
{
return [
'Crud.beforeLookup' => ['callable' => 'injectSearch'],
'Crud.beforePaginate' => ['callable' => 'injectSearch']
];
}
/**
* Inject search conditions to the qeury object.
*
* @param \Cake\Event\Event $event Event
* @return void
*/
public function injectSearch(Event $event)
{
if (!Plugin::loaded('Search')) {
throw new RuntimeException(
'You need to load the Search plugin in order to use the SearchListener.'
);
}
if (!in_array($event->name, $this->config('enabled'))) {
return;
}
$table = $this->_table();
if (!method_exists($table, 'filterParams')) {
throw new RuntimeException(sprintf(
'Missing Search.Search behavior on %s',
get_class($table)
));
}
$filterParams = $table->filterParams($this->_request()->query);
$event->subject->query->find('search', $filterParams);
}
}
| <?php
namespace Crud\Listener;
use Cake\Core\Plugin;
use Cake\Event\Event;
use RuntimeException;
class SearchListener extends BaseListener
{
/**
* Settings
*
* @var array
*/
protected $_defaultConfig = [
'enabled' => [
'Crud.beforeLookup',
'Crud.beforePaginate'
]
];
/**
* Returns a list of all events that will fire in the controller during its lifecycle.
* You can override this function to add your own listener callbacks
*
* @return array
*/
public function implementedEvents()
{
return [
'Crud.beforeLookup' => ['callable' => 'injectSearch'],
'Crud.beforePaginate' => ['callable' => 'injectSearch']
];
}
/**
* Inject search conditions to the qeury object.
*
* @param \Cake\Event\Event $event Event
* @return void
*/
public function injectSearch(Event $event)
{
if (!Plugin::loaded('Search')) {
throw new RuntimeException(
'You need to load the Search plugin in order to use the SearchListener.'
);
}
if (!in_array($event->name, $this->config('enabled'))) {
return;
}
$filterParams = $this->_table()->filterParams($this->_request()->query);
$event->subject->query->find('search', $filterParams);
}
}
|
Add support for `CheckoutSession` on `Discount` | package stripe
import "encoding/json"
// DiscountParams is the set of parameters that can be used when deleting a discount.
type DiscountParams struct {
Params `form:"*"`
}
// Discount is the resource representing a Stripe discount.
// For more details see https://stripe.com/docs/api#discounts.
type Discount struct {
APIResource
CheckoutSession *CheckoutSession `json:"checkout_session"`
Coupon *Coupon `json:"coupon"`
Customer string `json:"customer"`
Deleted bool `json:"deleted"`
End int64 `json:"end"`
ID string `json:"id"`
Invoice string `json:"invoice"`
InvoiceItem string `json:"invoice_item"`
Object string `json:"object"`
PromotionCode *PromotionCode `json:"promotion_code"`
Start int64 `json:"start"`
Subscription string `json:"subscription"`
}
// UnmarshalJSON handles deserialization of a Discount.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (s *Discount) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
s.ID = id
return nil
}
type discount Discount
var v discount
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*s = Discount(v)
return nil
}
| package stripe
import "encoding/json"
// DiscountParams is the set of parameters that can be used when deleting a discount.
type DiscountParams struct {
Params `form:"*"`
}
// Discount is the resource representing a Stripe discount.
// For more details see https://stripe.com/docs/api#discounts.
type Discount struct {
APIResource
Coupon *Coupon `json:"coupon"`
Customer string `json:"customer"`
Deleted bool `json:"deleted"`
End int64 `json:"end"`
ID string `json:"id"`
Invoice string `json:"invoice"`
InvoiceItem string `json:"invoice_item"`
Object string `json:"object"`
PromotionCode *PromotionCode `json:"promotion_code"`
Start int64 `json:"start"`
Subscription string `json:"subscription"`
}
// UnmarshalJSON handles deserialization of a Discount.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (s *Discount) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
s.ID = id
return nil
}
type discount Discount
var v discount
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*s = Discount(v)
return nil
}
|
Update gearman client call due to changes | <?php
namespace Soil\QueueHttpEndpointBundle\Controller;
use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Created by PhpStorm.
* User: fliak
* Date: 5.2.15
* Time: 15.14
*/
class EndpointController {
/**
* @var GearmanClient
*/
protected $gearmanClient;
protected $queueStream;
public function __construct($gearmanClient, $queueStream) {
$this->gearmanClient = $gearmanClient;
$this->queueStream = $queueStream;
}
public function putJobAction(Request $request) {
$data = null;
try {
$data = $request->getContent();
$job = $this->gearmanClient->sendRaw($this->queueStream, $data);
$response = new JsonResponse([
'success' => true,
'stream' => $this->queueStream,
'job' => $job
]);
}
catch(\Exception $e) {
$response = new JsonResponse([
'success' => false,
'error' => $e->getMessage(),
'workload' => $data
], 500);
}
return $response;
}
} | <?php
namespace Soil\QueueHttpEndpointBundle\Controller;
use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Created by PhpStorm.
* User: fliak
* Date: 5.2.15
* Time: 15.14
*/
class EndpointController {
/**
* @var GearmanClient
*/
protected $gearmanClient;
protected $queueStream;
public function __construct($gearmanClient, $queueStream) {
$this->gearmanClient = $gearmanClient;
$this->queueStream = $queueStream;
}
public function putJobAction(Request $request) {
$data = null;
try {
$data = $request->getContent();
$job = $this->gearmanClient->send($this->queueStream, $data);
$response = new JsonResponse([
'success' => true,
'stream' => $this->queueStream,
'job' => $job
]);
}
catch(\Exception $e) {
$response = new JsonResponse([
'success' => false,
'error' => $e->getMessage(),
'workload' => $data
], 500);
}
return $response;
}
} |
Use runUnsafeAction in lazy binding implementation | package org.reactfx;
import java.util.function.Consumer;
/**
* Event stream that has one or more sources (most commonly event streams,
* but not necessarily) to which it is subscribed only when it itself has
* at least one subscriber.
*
* @param <T> type of events emitted by this event stream.
*/
public abstract class LazilyBoundStream<T>
extends EventStreamBase<T> {
private Subscription subscription = null;
public LazilyBoundStream() {
super();
}
LazilyBoundStream(EmptyPendingNotifications<Subscriber<? super T>, T> pn) {
super(pn);
}
protected abstract Subscription subscribeToInputs();
@Override
protected final void firstObserver() {
runUnsafeAction(() -> subscription = subscribeToInputs());
}
@Override
protected final void noObservers() {
runUnsafeAction(() -> {
subscription.unsubscribe();
subscription = null;
});
}
protected final boolean isBound() {
return subscription != null;
}
/**
* Subscribes to the given event stream by the given subscriber and also
* forwards errors reported by the given stream to this stream. This is
* equivalent to {@code stream.subscribe(subscriber, this::reportError)}.
* @return subscription used to unsubscribe {@code subscriber} from
* {@code stream} and stop forwarding the errors.
*/
protected final <U> Subscription subscribeTo(
EventStream<U> stream,
Consumer<? super U> subscriber) {
return stream.subscribe(subscriber, this::reportError);
}
} | package org.reactfx;
import java.util.function.Consumer;
/**
* Event stream that has one or more sources (most commonly event streams,
* but not necessarily) to which it is subscribed only when it itself has
* at least one subscriber.
*
* @param <T> type of events emitted by this event stream.
*/
public abstract class LazilyBoundStream<T>
extends EventStreamBase<T> {
private Subscription subscription = null;
public LazilyBoundStream() {
super();
}
LazilyBoundStream(EmptyPendingNotifications<Subscriber<? super T>, T> pn) {
super(pn);
}
protected abstract Subscription subscribeToInputs();
@Override
protected final void firstObserver() {
try {
subscription = subscribeToInputs();
} catch(Throwable t) {
reportError(t);
}
}
@Override
protected final void noObservers() {
try {
subscription.unsubscribe();
subscription = null;
} catch(Throwable t) {
reportError(t);
}
}
protected final boolean isBound() {
return subscription != null;
}
/**
* Subscribes to the given event stream by the given subscriber and also
* forwards errors reported by the given stream to this stream. This is
* equivalent to {@code stream.subscribe(subscriber, this::reportError)}.
* @return subscription used to unsubscribe {@code subscriber} from
* {@code stream} and stop forwarding the errors.
*/
protected final <U> Subscription subscribeTo(
EventStream<U> stream,
Consumer<? super U> subscriber) {
return stream.subscribe(subscriber, this::reportError);
}
} |
Stop changing moment locale twice | import { stringify } from 'querystring'
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'next/router'
import { translate } from 'react-i18next'
import Dropdown from '../../dropdown'
export class LanguageSelection extends React.PureComponent {
static propTypes = {
i18n: PropTypes.shape({
changeLanguage: PropTypes.func.isRequired
}).isRequired,
router: PropTypes.shape({
pathname: PropTypes.string.isRequired,
query: PropTypes.object.isRequired,
asPath: PropTypes.string.isRequired
}).isRequired
}
changeLanguage(language) {
const { i18n, router } = this.props
const current = i18n.language
i18n.changeLanguage(language)
router.replace(
`${router.pathname}?${stringify(router.query)}`,
`/${language}${router.asPath.substring(1 + current.length)}`
)
}
render() {
const { i18n } = this.props
return (
<Dropdown title={i18n.language === 'en' ? '🇬🇧' : '🇫🇷'} links={[
{
action: () => this.changeLanguage('en'),
text: 'English 🇬🇧'
},
{
action: () => this.changeLanguage('fr'),
text: 'Français 🇫🇷'
}
]} />
)
}
}
export default translate()(withRouter(LanguageSelection))
| import { stringify } from 'querystring'
import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { withRouter } from 'next/router'
import { translate } from 'react-i18next'
import Dropdown from '../../dropdown'
export class LanguageSelection extends React.PureComponent {
static propTypes = {
i18n: PropTypes.shape({
changeLanguage: PropTypes.func.isRequired
}).isRequired,
router: PropTypes.shape({
pathname: PropTypes.string.isRequired,
query: PropTypes.object.isRequired,
asPath: PropTypes.string.isRequired
}).isRequired
}
changeLanguage(language) {
const { i18n, router } = this.props
const current = i18n.language
moment.locale(language)
i18n.changeLanguage(language)
router.replace(
`${router.pathname}?${stringify(router.query)}`,
`/${language}${router.asPath.substring(1 + current.length)}`
)
}
render() {
const { i18n } = this.props
return (
<Dropdown title={i18n.language === 'en' ? '🇬🇧' : '🇫🇷'} links={[
{
action: () => this.changeLanguage('en'),
text: 'English 🇬🇧'
},
{
action: () => this.changeLanguage('fr'),
text: 'Français 🇫🇷'
}
]} />
)
}
}
export default translate()(withRouter(LanguageSelection))
|
Return res in inherit (even if res is empty in this case) | # -*- encoding: utf-8 -*-
##############################################################################
#
# Account Payment Partner module for OpenERP
# Copyright (C) 2014 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, api
class PaymentOrderCreate(models.TransientModel):
_inherit = 'payment.order.create'
@api.model
def extend_payment_order_domain(self, payment_order, domain):
res = super(PaymentOrderCreate, self).extend_payment_order_domain(
payment_order, domain)
domain += ['|', '|',
('invoice', '=', False),
('invoice.payment_mode_id', '=', False),
('invoice.payment_mode_id', '=', payment_order.mode.id)]
return res
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Account Payment Partner module for OpenERP
# Copyright (C) 2014 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, api
class PaymentOrderCreate(models.TransientModel):
_inherit = 'payment.order.create'
@api.model
def extend_payment_order_domain(self, payment_order, domain):
super(PaymentOrderCreate, self).extend_payment_order_domain(
payment_order, domain)
domain += ['|', '|',
('invoice', '=', False),
('invoice.payment_mode_id', '=', False),
('invoice.payment_mode_id', '=', payment_order.mode.id)]
return True
|
Detach debugger from process after each test. | """Tests for scripts/print_view_controller_hierarchy.py."""
import re
import unittest
from test_utils import import_utils
import_utils.prepare_lldb_import_or_exit()
import lldb
import_utils.prepare_for_scripts_imports()
from scripts import print_view_controller_hierarchy
class PrintViewControllerHierarchyTest(unittest.TestCase):
def testPrintViewControllerHierarchy(self):
"""Tests the expected output of the |pvc| command."""
debugger = lldb.SBDebugger.Create()
debugger.SetAsync(False)
target = debugger.CreateTarget('')
error = lldb.SBError()
process = target.AttachToProcessWithName(debugger.GetListener(), 'TestApp',
False, error)
if not process:
self.assertTrue(False, 'Could not attach to process "TestApp"')
debugger.SetSelectedTarget(target)
result = lldb.SBCommandReturnObject()
print_view_controller_hierarchy.print_view_controller_hierarchy(debugger,
None,
result,
None)
self.assertTrue(result.Succeeded())
expected_output_regex = r'<ViewController 0x\w{12}>, state: appeared, view: <UIView 0x\w{12}>'
self.assertTrue(re.match(expected_output_regex,
result.GetOutput().rstrip()))
debugger.DeleteTarget(target)
| """Tests for scripts/print_view_controller_hierarchy.py."""
import re
import unittest
from test_utils import import_utils
import_utils.prepare_lldb_import_or_exit()
import lldb
import_utils.prepare_for_scripts_imports()
from scripts import print_view_controller_hierarchy
class PrintViewControllerHierarchyTest(unittest.TestCase):
def testPrintViewControllerHierarchy(self):
"""Tests the expected output of the |pvc| command."""
debugger = lldb.SBDebugger.Create()
debugger.SetAsync(False)
target = debugger.CreateTarget('')
error = lldb.SBError()
process = target.AttachToProcessWithName(debugger.GetListener(), 'TestApp',
False, error)
if not process:
self.assertTrue(False, 'Could not attach to process "TestApp"')
debugger.SetSelectedTarget(target)
result = lldb.SBCommandReturnObject()
print_view_controller_hierarchy.print_view_controller_hierarchy(debugger,
None,
result,
None)
self.assertTrue(result.Succeeded())
expected_output_regex = r'<ViewController 0x\w{12}>, state: appeared, view: <UIView 0x\w{12}>'
self.assertTrue(re.match(expected_output_regex,
result.GetOutput().rstrip()))
debugger.Terminate()
|
Add node env to script
- helps with optimising production code like react | import gulp from 'gulp';
import gulpif from 'gulp-if';
import named from 'vinyl-named';
import webpack from 'webpack';
import gulpWebpack from 'webpack-stream';
import plumber from 'gulp-plumber';
import livereload from 'gulp-livereload';
import args from './lib/args';
const ENV = args.production ? 'production' : 'development';
gulp.task('scripts', (cb) => {
return gulp.src('app/scripts/*.js')
.pipe(plumber())
.pipe(named())
.pipe(gulpWebpack({
devtool: args.sourcemaps ? 'source-map': null,
watch: args.watch,
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(ENV)
},
'__ENV__': JSON.stringify(ENV),
'__VENDOR__': JSON.stringify(args.vendor)
}),
].concat(args.production ? [
new webpack.optimize.UglifyJsPlugin()
] : []),
module: {
preLoaders: [{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
}],
loaders: [{
test: /\.js$/,
loader: 'babel'
}]
},
eslint: {
configFile: '.eslintrc'
}
}))
.pipe(gulp.dest(`dist/${args.vendor}/scripts`))
.pipe(gulpif(args.watch, livereload()));
});
| import gulp from 'gulp';
import gulpif from 'gulp-if';
import named from 'vinyl-named';
import webpack from 'webpack';
import gulpWebpack from 'webpack-stream';
import plumber from 'gulp-plumber';
import livereload from 'gulp-livereload';
import args from './lib/args';
gulp.task('scripts', (cb) => {
return gulp.src('app/scripts/*.js')
.pipe(plumber())
.pipe(named())
.pipe(gulpWebpack({
devtool: args.sourcemaps ? 'source-map': null,
watch: args.watch,
plugins: [
new webpack.DefinePlugin({
'__ENV__': JSON.stringify(args.production ? 'production' : 'development'),
'__VENDOR__': JSON.stringify(args.vendor)
}),
].concat(args.production ? [
new webpack.optimize.UglifyJsPlugin()
] : []),
module: {
preLoaders: [{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
}],
loaders: [{
test: /\.js$/,
loader: 'babel'
}]
},
eslint: {
configFile: '.eslintrc'
}
}))
.pipe(gulp.dest(`dist/${args.vendor}/scripts`))
.pipe(gulpif(args.watch, livereload()));
});
|
Set default value for json.dumps
Use default value when type cannot be serialized. | import json
import logging
import platform
from django.core.serializers.json import DjangoJSONEncoder
from django.http import UnreadablePostError
def skip_unreadable_post(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, UnreadablePostError):
return False
return True
class AppendExtraJSONHandler(logging.StreamHandler):
DEFAULT_STREAM_HANDLER_VARIABLE_KEYS = {
'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename', 'module', 'exc_info', 'exc_text',
'stack_info', 'lineno', 'funcName', 'created', 'msecs', 'relativeCreated', 'thread', 'threadName',
'processName', 'process',
}
CUSTOM_STREAM_HANDLER_VARIABLE_KEYS = {'hostname'}
def emit(self, record):
extra = {
k: v
for k, v in record.__dict__.items()
if k not in self.DEFAULT_STREAM_HANDLER_VARIABLE_KEYS.union(self.CUSTOM_STREAM_HANDLER_VARIABLE_KEYS)
}
record.msg = '{} --- {}'.format(record.msg, json.dumps(extra, cls=DjangoJSONEncoder,
default=lambda x: '<<NON-SERIALIZABLE TYPE: {}>>'.format(type(x).__qualname__)))
super().emit(record)
class HostnameFilter(logging.Filter):
hostname = platform.node()
def filter(self, record):
record.hostname = self.hostname
return True
| import json
import logging
import platform
from django.core.serializers.json import DjangoJSONEncoder
from django.http import UnreadablePostError
def skip_unreadable_post(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, UnreadablePostError):
return False
return True
class AppendExtraJSONHandler(logging.StreamHandler):
DEFAULT_STREAM_HANDLER_VARIABLE_KEYS = {
'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename', 'module', 'exc_info', 'exc_text',
'stack_info', 'lineno', 'funcName', 'created', 'msecs', 'relativeCreated', 'thread', 'threadName',
'processName', 'process',
}
CUSTOM_STREAM_HANDLER_VARIABLE_KEYS = {'hostname'}
def emit(self, record):
extra = {
k: v
for k, v in record.__dict__.items()
if k not in self.DEFAULT_STREAM_HANDLER_VARIABLE_KEYS.union(self.CUSTOM_STREAM_HANDLER_VARIABLE_KEYS)
}
record.msg = '{} --- {}'.format(record.msg, json.dumps(extra, cls=DjangoJSONEncoder))
super().emit(record)
class HostnameFilter(logging.Filter):
hostname = platform.node()
def filter(self, record):
record.hostname = self.hostname
return True
|
Fix 500 error on Category show page. | <?php namespace VotingApp\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class Winner extends Model
{
/**
* The attributes which may be mass-assigned.
*
* @var array
*/
protected $fillable = [
'candidate_id', 'rank', 'description'
];
// No timestamps on the winners table.
public $timestamps = false;
/**
* A winner belongs to a candidate.
*/
public function candidate()
{
return $this->belongsTo('VotingApp\Models\Candidate');
}
/**
* Get the winners, given a category.
* @param Category $category
*/
public static function getCategoryWinners(Category $category)
{
$settings = app()->make('VotingApp\Repositories\SettingsRepository');
$secrets = \Request::get('winners');
if ($settings->get('show_winners') || $secrets == '✓') {
$winners = DB::table('winners')
->join('candidates', 'winners.candidate_id', '=', 'candidates.id')
->join('categories', 'candidates.category_id', '=', 'categories.id')
->where('categories.id', '=', $category->id)
->select('winners.rank', 'winners.description', 'candidates.name', 'candidates.slug', 'candidates.photo', 'candidates.id')
->orderBy('winners.rank')
->get();
return $winners;
}
return;
}
}
| <?php namespace VotingApp\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class Winner extends Model
{
/**
* The attributes which may be mass-assigned.
*
* @var array
*/
protected $fillable = [
'candidate_id', 'rank', 'description'
];
// No timestamps on the winners table.
public $timestamps = false;
/**
* A winner belongs to a candidate.
*/
public function candidate()
{
return $this->belongsTo('VotingApp\Models\Candidate');
}
/**
* Get the winners, given a category.
* @param Category $category
*/
public static function getCategoryWinners(Category $category)
{
$settings = app()->make('VotingApp\Repositories\SettingsRepository')->all();
$secrets = \Request::get('winners');
if ($settings['show_winners'] || $secrets == '✓') {
$winners = DB::table('winners')
->join('candidates', 'winners.candidate_id', '=', 'candidates.id')
->join('categories', 'candidates.category_id', '=', 'categories.id')
->where('categories.id', '=', $category->id)
->select('winners.rank', 'winners.description', 'candidates.name', 'candidates.slug', 'candidates.photo', 'candidates.id')
->orderBy('winners.rank')
->get();
return $winners;
}
return;
}
}
|
Change designer index page title. | @extends('layout.app', [
'title' => 'Design Stories',
'body_id' => 'designer-index-page',
'body_class' => 'designer-index index',
])
@section('main')
<div class="container">
<div class="row">
@foreach ($designers as $designer)
<article id="story-{{ $designer->id }}" class="story grid-item col-xs-12 col-sm-6 col-md-4 col-lg-3"
data-id="{{ $designer->id }}">
<a href="{{ $designer->url }}">
@if ($image = $designer->image)
<img class="featured-image" src="{{ $image->file_urls['thumb'] }}" />
@else
<img class="featured-image" src="http://placehold.it/300x300?text=NO+IMAGE" />
@endif
<div class="shadow"></div>
<div class="text">
{{ $designer->text('name') }}: {{ $designer->text('tagline') }}
</div>
</a>
</article>
@endforeach
</div><!-- .row -->
</div><!-- .container -->
@endsection
| @extends('layout.app', [
'title' => 'Designers',
'body_id' => 'designer-index-page',
'body_class' => 'designer-index index',
])
@section('main')
<div class="container">
<div class="row">
@foreach ($designers as $designer)
<article id="story-{{ $designer->id }}" class="story grid-item col-xs-12 col-sm-6 col-md-4 col-lg-3"
data-id="{{ $designer->id }}">
<a href="{{ $designer->url }}">
@if ($image = $designer->image)
<img class="featured-image" src="{{ $image->file_urls['thumb'] }}" />
@else
<img class="featured-image" src="http://placehold.it/300x300?text=NO+IMAGE" />
@endif
<div class="shadow"></div>
<div class="text">
{{ $designer->text('name') }}: {{ $designer->text('tagline') }}
</div>
</a>
</article>
@endforeach
</div><!-- .row -->
</div><!-- .container -->
@endsection
|
Increase machine model field size from 20 chars to 50 chars | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machines', function (Blueprint $table) {
$table->increments('id');
$table->integer('modality_id')->default(0)->unsigned();
$table->string('description', 60)->nullable();
$table->integer('manufacturer_id')->default(0)->unsigned();
$table->string('vend_site_id', 25)->nullable();
$table->string('model', 50)->nullable();
$table->string('serial_number', 20)->nullable();
$table->date('manuf_date')->nullable();
$table->date('install_date')->nullable();
$table->date('remove_date')->nullable();
$table->integer('location_id')->default(0)->unsigned();
$table->string('room', 20)->nullable();
$table->string('machine_status', 50)->default('Active');
$table->text('notes')->nullable();
$table->string('photo')->nullable();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('machines');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machines', function (Blueprint $table) {
$table->increments('id');
$table->integer('modality_id')->default(0)->unsigned();
$table->string('description', 60)->nullable();
$table->integer('manufacturer_id')->default(0)->unsigned();
$table->string('vend_site_id', 25)->nullable();
$table->string('model', 20)->nullable();
$table->string('serial_number', 20)->nullable();
$table->date('manuf_date')->nullable();
$table->date('install_date')->nullable();
$table->date('remove_date')->nullable();
$table->integer('location_id')->default(0)->unsigned();
$table->string('room', 20)->nullable();
$table->string('machine_status', 50)->default('Active');
$table->text('notes')->nullable();
$table->string('photo')->nullable();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('machines');
}
}
|
Adjust message code in exception | package de.innoaccel.wamp.server.converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import de.innoaccel.wamp.server.message.PrefixMessage;
public class PrefixMessageConverter extends JsonParsingConverter<PrefixMessage>
{
@Override
public boolean canConvert(int messageCode)
{
return Message.PREFIX == messageCode;
}
@Override
public String serialize(PrefixMessage message, Websocket socket) throws InvalidMessageCodeException
{
try {
return this.objectMapper.writeValueAsString(new Object[] {
Message.PREFIX,
message.getPrefix(),
message.getURI()
});
} catch (JsonProcessingException ex) {
throw new InvalidMessageCodeException(Message.PREFIX);
}
}
@Override
protected PrefixMessage deserialize(JsonNode message, Websocket socket) throws MessageParseException, InvalidMessageCodeException
{
this.assertMessageCode(message, Message.PREFIX);
String prefix = this.readStringAt(message, 1);
if (0 == prefix.length()) {
throw new MessageParseException("Prefix may not be empty");
}
String uri = this.readStringAt(message, 2);
if (0 == uri.length()) {
throw new MessageParseException("URI may not be empty");
}
return new PrefixMessage(prefix, uri);
}
}
| package de.innoaccel.wamp.server.converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import de.innoaccel.wamp.server.message.PrefixMessage;
public class PrefixMessageConverter extends JsonParsingConverter<PrefixMessage>
{
@Override
public boolean canConvert(int messageCode)
{
return Message.PREFIX == messageCode;
}
@Override
public String serialize(PrefixMessage message, Websocket socket) throws InvalidMessageCodeException
{
try {
return this.objectMapper.writeValueAsString(new Object[] {
Message.PREFIX,
message.getPrefix(),
message.getURI()
});
} catch (JsonProcessingException ex) {
throw new InvalidMessageCodeException(Message.EVENT);
}
}
@Override
protected PrefixMessage deserialize(JsonNode message, Websocket socket) throws MessageParseException, InvalidMessageCodeException
{
this.assertMessageCode(message, Message.PREFIX);
String prefix = this.readStringAt(message, 1);
if (0 == prefix.length()) {
throw new MessageParseException("Prefix may not be empty");
}
String uri = this.readStringAt(message, 2);
if (0 == uri.length()) {
throw new MessageParseException("URI may not be empty");
}
return new PrefixMessage(prefix, uri);
}
}
|
Add auth models and validators to initial db migration. | # -*- coding: utf-8 -*-
""" Initial migration file for creating Note model """
from __future__ import unicode_literals
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
""" Initial migration file for creating Note model """
dependencies = [
]
operations = [
migrations.CreateModel(
name='Note',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('user_id', models.CharField(
help_text=b'Anonymized user id, not course specific', max_length=255, db_index=True
)),
('course_id', models.CharField(max_length=255, db_index=True)),
('usage_id', models.CharField(help_text=b'ID of XBlock where the text comes from', max_length=255)),
('quote', models.TextField(default=b'')),
('text', models.TextField(default=b'', help_text=b"Student's thoughts on the quote", blank=True)),
('ranges', models.TextField(help_text=b'JSON, describes position of quote in the source text')),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
],
options={
},
bases=(models.Model,),
),
]
| # -*- coding: utf-8 -*-
""" Initial migration file for creating Note model """
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
""" Initial migration file for creating Note model """
dependencies = [
]
operations = [
migrations.CreateModel(
name='Note',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('user_id', models.CharField(
help_text=b'Anonymized user id, not course specific', max_length=255, db_index=True
)),
('course_id', models.CharField(max_length=255, db_index=True)),
('usage_id', models.CharField(help_text=b'ID of XBlock where the text comes from', max_length=255)),
('quote', models.TextField(default=b'')),
('text', models.TextField(default=b'', help_text=b"Student's thoughts on the quote", blank=True)),
('ranges', models.TextField(help_text=b'JSON, describes position of quote in the source text')),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
],
options={
},
bases=(models.Model,),
),
]
|
Remove a useless method declaration. | <?php
namespace Predis\Commands;
class InfoV24x extends Info {
public function canBeHashed() { return false; }
public function parseResponse($data) {
$info = array();
$current = null;
$infoLines = explode("\r\n", $data, -1);
foreach ($infoLines as $row) {
if ($row === '') {
continue;
}
if (preg_match('/^# (\w+)$/', $row, $matches)) {
$info[$matches[1]] = array();
$current = &$info[$matches[1]];
continue;
}
list($k, $v) = explode(':', $row);
if (!preg_match('/^db\d+$/', $k)) {
if ($k === 'allocation_stats') {
$current[$k] = $this->parseAllocationStats($v);
continue;
}
$current[$k] = $v;
}
else {
$current[$k] = $this->parseDatabaseStats($v);
}
}
return $info;
}
}
| <?php
namespace Predis\Commands;
class InfoV24x extends Info {
public function canBeHashed() { return false; }
public function getId() { return 'INFO'; }
public function parseResponse($data) {
$info = array();
$current = null;
$infoLines = explode("\r\n", $data, -1);
foreach ($infoLines as $row) {
if ($row === '') {
continue;
}
if (preg_match('/^# (\w+)$/', $row, $matches)) {
$info[$matches[1]] = array();
$current = &$info[$matches[1]];
continue;
}
list($k, $v) = explode(':', $row);
if (!preg_match('/^db\d+$/', $k)) {
if ($k === 'allocation_stats') {
$current[$k] = $this->parseAllocationStats($v);
continue;
}
$current[$k] = $v;
}
else {
$current[$k] = $this->parseDatabaseStats($v);
}
}
return $info;
}
}
|
Add event trigger when legend changes. | var OpenLayersPlusLegend = function(opts) {
if (opts == null) {
return;
}
var self = this;
this.map = $(opts).data('map');
this.setLegend = function(layer) {
// The layer param may vary based on the context from which we are called.
layer = layer.object ? layer.object : layer;
if ('legend' in layer) {
var legend_content = layer.legend || 'your mother';
var legends = $('div.openlayers-legends', self.map.div);
if (layer.visibility && !('legendDiv' in layer)) {
layer.legendDiv = $("<div class='openlayers-legend'></div>").append(legend_content);
legends.append(layer.legendDiv);
}
else if (!layer.visibility && ('legendDiv' in layer)) {
layer.legendDiv.remove();
delete layer.legendDiv;
}
$(opts).trigger('openlayersPlusLegendChange');
}
};
for (i in this.map.layers) {
var layer = this.map.layers[i];
if (!$('div.openlayers-legends', self.map.div).size()) {
$(self.map.div).append("<div class='openlayers-legends'></div>");
}
layer.events.register('visibilitychanged', layer, self.setLegend);
self.setLegend(layer);
}
};
| var OpenLayersPlusLegend = function(opts) {
if (opts == null) {
return;
}
var self = this;
this.map = $(opts).data('map');
this.setLegend = function(layer) {
// The layer param may vary based on the context from which we are called.
layer = layer.object ? layer.object : layer;
if ('legend' in layer) {
var legend_content = layer.legend || 'your mother';
var legends = $('div.openlayers-legends', self.map.div);
if (layer.visibility && !('legendDiv' in layer)) {
layer.legendDiv = $("<div class='openlayers-legend'></div>").append(legend_content);
legends.append(layer.legendDiv);
}
else if (!layer.visibility && ('legendDiv' in layer)) {
layer.legendDiv.remove();
delete layer.legendDiv;
}
}
};
for (i in this.map.layers) {
var layer = this.map.layers[i];
if (!$('div.openlayers-legends', self.map.div).size()) {
$(self.map.div).append("<div class='openlayers-legends'></div>");
}
layer.events.register('visibilitychanged', layer, self.setLegend);
self.setLegend(layer);
}
};
|
Set type to javascript to force JS compilation | 'use strict';
const compiler = require('vueify').compiler;
const fs = require('fs');
class VueBrunch {
constructor(config) {
this.config = config && config.plugins && config.plugins.vue || {};
this.styles = {};
}
compile(file) {
if (this.config) {
compiler.applyConfig(this.config);
}
compiler.on('style', args => {
this.styles[args.file] = args.style;
});
return new Promise((resolve, reject) => {
compiler.compile(file.data, file.path, (error, result) => {
if (error) {
reject(error);
}
resolve(result);
});
});
}
onCompile() {
if (this.config.extractCSS) {
this.extractCSS();
}
}
extractCSS() {
var outPath = this.config.out || this.config.o || 'bundle.css';
var css = Object.keys(this.styles || [])
.map(file => this.styles[file])
.join('\n');
if (typeof outPath === 'object' && outPath.write) {
outPath.write(css);
outPath.end();
} else if (typeof outPath === 'string') {
fs.writeFileSync(outPath, css);
}
}
}
VueBrunch.prototype.brunchPlugin = true;
VueBrunch.prototype.type = 'javascript';
VueBrunch.prototype.extension = 'vue';
module.exports = VueBrunch;
| 'use strict';
const compiler = require('vueify').compiler;
const fs = require('fs');
class VueBrunch {
constructor(config) {
this.config = config && config.plugins && config.plugins.vue || {};
this.styles = {};
}
compile(file) {
if (this.config) {
compiler.applyConfig(this.config);
}
compiler.on('style', args => {
this.styles[args.file] = args.style;
});
return new Promise((resolve, reject) => {
compiler.compile(file.data, file.path, (error, result) => {
if (error) {
reject(error);
}
resolve(result);
});
});
}
onCompile() {
if (this.config.extractCSS) {
this.extractCSS();
}
}
extractCSS() {
var outPath = this.config.out || this.config.o || 'bundle.css';
var css = Object.keys(this.styles || [])
.map(file => this.styles[file])
.join('\n');
if (typeof outPath === 'object' && outPath.write) {
outPath.write(css);
outPath.end();
} else if (typeof outPath === 'string') {
fs.writeFileSync(outPath, css);
}
}
}
VueBrunch.prototype.brunchPlugin = true;
VueBrunch.prototype.type = 'template';
VueBrunch.prototype.extension = 'vue';
module.exports = VueBrunch;
|
Fix issue with old wagtail core paths | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'wagtailgeowidget': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
},
},
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sites',
'wagtail.core',
'wagtail.sites',
'wagtail.users',
'wagtail.images',
'taggit',
'wagtailgeowidget',
"tests",
],
MIDDLEWARE_CLASSES=[],
ROOT_URLCONF='tests.urls',
)
settings.configure(**params)
def runtests():
argv = sys.argv[:1] + ["test"] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == "__main__":
runtests()
| #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'wagtailgeowidget': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
},
},
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sites',
'wagtail.wagtailcore',
'wagtail.wagtailsites',
'wagtail.wagtailusers',
'wagtail.wagtailimages',
'taggit',
'wagtailgeowidget',
"tests",
],
MIDDLEWARE_CLASSES=[],
ROOT_URLCONF='tests.urls',
)
settings.configure(**params)
def runtests():
argv = sys.argv[:1] + ["test"] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == "__main__":
runtests()
|
Fix issue with "titles" in SectionContainer.filter() | from plex.core.helpers import to_iterable
from plex.objects.container import Container
from plex.objects.core.base import Property
from plex.objects.directory import Directory
class Section(Directory):
uuid = Property
filters = Property(type=bool)
refreshing = Property(type=bool)
agent = Property
scanner = Property
language = Property
created_at = Property('createdAt', int)
def __transform__(self):
self.path = '/library/sections/%s' % self.key
def all(self):
response = self.http.get('all')
return self.parse(response, {
'MediaContainer': ('MediaContainer', {
'Directory': {
'artist': 'Artist',
'show': 'Show'
},
'Video': {
'movie': 'Movie'
}
})
})
class SectionContainer(Container):
filter_passes = lambda _, allowed, value: allowed is None or value in allowed
def filter(self, types=None, keys=None, titles=None):
types = to_iterable(types)
keys = to_iterable(keys)
titles = to_iterable(titles)
if titles:
# Normalize titles
titles = [x.lower() for x in titles]
for section in self:
if not self.filter_passes(types, section.type):
continue
if not self.filter_passes(keys, section.key):
continue
if not self.filter_passes(titles, section.title.lower()):
continue
yield section
| from plex.core.helpers import to_iterable
from plex.objects.container import Container
from plex.objects.core.base import Property
from plex.objects.directory import Directory
class Section(Directory):
uuid = Property
filters = Property(type=bool)
refreshing = Property(type=bool)
agent = Property
scanner = Property
language = Property
created_at = Property('createdAt', int)
def __transform__(self):
self.path = '/library/sections/%s' % self.key
def all(self):
response = self.http.get('all')
return self.parse(response, {
'MediaContainer': ('MediaContainer', {
'Directory': {
'artist': 'Artist',
'show': 'Show'
},
'Video': {
'movie': 'Movie'
}
})
})
class SectionContainer(Container):
filter_passes = lambda _, allowed, value: allowed is None or value in allowed
def filter(self, types=None, keys=None, titles=None):
types = to_iterable(types)
keys = to_iterable(keys)
titles = [x.lower() for x in to_iterable(titles)]
for section in self:
if not self.filter_passes(types, section.type):
continue
if not self.filter_passes(keys, section.key):
continue
if not self.filter_passes(titles, section.title.lower()):
continue
yield section
|
Fix bug in Pipeline call where we run the whole Pipeline on list input | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self.convert_token(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
| class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
|
:white_check_mark: Update completion tests, checking for printed message | import os
import subprocess
import sys
from pathlib import Path
import typer
from typer.testing import CliRunner
from first_steps import tutorial001 as mod
runner = CliRunner()
app = typer.Typer()
app.command()(mod.main)
def test_show_completion():
result = subprocess.run(
[
"bash",
"-c",
f"{sys.executable} -m coverage run {mod.__file__} --show-completion",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
env={**os.environ, "SHELL": "/bin/bash"},
)
assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in result.stdout
def test_install_completion():
bash_completion_path: Path = Path.home() / ".bash_completion"
text = ""
if bash_completion_path.is_file():
text = bash_completion_path.read_text()
result = subprocess.run(
[
"bash",
"-c",
f"{sys.executable} -m coverage run {mod.__file__} --install-completion",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
env={**os.environ, "SHELL": "/bin/bash"},
)
new_text = bash_completion_path.read_text()
bash_completion_path.write_text(text)
assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in new_text
assert "completion installed in" in result.stdout
assert "Completion will take effect once you restart the terminal." in result.stdout
| import os
import subprocess
import sys
from pathlib import Path
import typer
from typer.testing import CliRunner
from first_steps import tutorial001 as mod
runner = CliRunner()
app = typer.Typer()
app.command()(mod.main)
def test_show_completion():
result = subprocess.run(
[
"bash",
"-c",
f"{sys.executable} -m coverage run {mod.__file__} --show-completion",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
env={**os.environ, "SHELL": "/bin/bash"},
)
assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in result.stdout
def test_install_completion():
bash_completion_path: Path = Path.home() / ".bash_completion"
text = ""
if bash_completion_path.is_file():
text = bash_completion_path.read_text()
result = subprocess.run(
[
"bash",
"-c",
f"{sys.executable} -m coverage run {mod.__file__} --install-completion",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
env={**os.environ, "SHELL": "/bin/bash"},
)
new_text = bash_completion_path.read_text()
assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in new_text
bash_completion_path.write_text(text)
|
Allow the "crash early" behavior of snippets to be configured
This way it can be turned off in testing environment, making testing
setup simpler. | <?php
/**
* Garp_Model_Db_Snippet
* Snippet model. Snippets are small dynamic chunks of content.
*
* @package Garp_Model_Db
* @author Harmen Janssen <[email protected]>
*/
class Garp_Model_Db_Snippet extends Model_Base_Snippet {
/**
* Fetch a snippet by its identifier
*
* @param string $identifier
* @return Garp_Db_Table_Row
*/
public function fetchByIdentifier($identifier) {
if (!$identifier) {
throw new InvalidArgumentException('Snippet identifier is required');
}
$select = $this->select()->where('identifier = ?', $identifier);
if ($result = $this->fetchRow($select)) {
return $result;
}
if (!Zend_Registry::get('config')->snippets->ignoreMissing) {
throw new Exception('Snippet not found: ' . $identifier);
}
// Return fallback row, where text is set to $identifier, in order to provide some fallback.
return $this->createRow([
'has_text' => 1,
'text' => $identifier,
]);
}
/**
* BeforeFetch: filters out snippets where is_editable = 0 in the CMs.
*
* @param array $args
* @return void
*/
public function beforeFetch(&$args) {
$model = &$args[0];
$select = &$args[1];
if (!$model->isCmsContext()) {
return;
}
// Sanity check: this project might be spawned without the is_editable column,
// it was added to Snippet at May 1 2013.
if ($this->getFieldConfiguration('is_editable')) {
$select->where('is_editable = ?', 1);
}
}
}
| <?php
/**
* Garp_Model_Db_Snippet
* Snippet model. Snippets are small dynamic chunks of content.
*
* @package Garp_Model_Db
* @author Harmen Janssen <[email protected]>
*/
class Garp_Model_Db_Snippet extends Model_Base_Snippet {
/**
* Fetch a snippet by its identifier
*
* @param string $identifier
* @return Garp_Db_Table_Row
*/
public function fetchByIdentifier($identifier) {
if (!$identifier) {
throw new InvalidArgumentException('Snippet identifier is required');
}
$select = $this->select()->where('identifier = ?', $identifier);
if ($result = $this->fetchRow($select)) {
return $result;
}
throw new Exception('Snippet not found: ' . $identifier);
}
/**
* BeforeFetch: filters out snippets where is_editable = 0 in the CMs.
*
* @param array $args
* @return void
*/
public function beforeFetch(&$args) {
$model = &$args[0];
$select = &$args[1];
if (!$model->isCmsContext()) {
return;
}
// Sanity check: this project might be spawned without the is_editable column,
// it was added to Snippet at May 1 2013.
if ($this->getFieldConfiguration('is_editable')) {
$select->where('is_editable = ?', 1);
}
}
}
|
Revert "[ncl] fix Font examples"
This reverts commit 7af688afaac71c74de68b5ab42aed38f0196fd0d.
fbshipit-source-id: b91e873 | import React from 'react';
import { Platform, ScrollView, Text, View } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
export default class FontScreen extends React.Component {
static navigationOptions = {
title: 'Font',
};
render() {
return (
<ScrollView style={{ flex: 1 }}>
<View
style={{
paddingVertical: 10,
paddingHorizontal: 15,
flexDirection: 'row',
justifyContent: 'space-between',
flex: 1,
}}>
<MaterialIcons name="airplay" size={25} />
<MaterialIcons name="airport-shuttle" size={25} />
<MaterialIcons name="alarm" size={25} />
<MaterialIcons name="alarm-add" size={25} />
<MaterialIcons name="alarm-off" size={25} />
<MaterialIcons name="all-inclusive" size={25} />
</View>
<View style={{ paddingVertical: 10, paddingHorizontal: 15 }}>
<Text style={{ fontFamily: 'space-mono', fontSize: 16 }}>
Font icons sets and other custom fonts can be loaded from the web
</Text>
{Platform.OS === 'ios' ? (
<Text
adjustsFontSizeToFit
style={{
flex: 1,
height: 32,
fontFamily: 'space-mono',
fontSize: 420,
}}>
Custom font with `adjustsFontSizeToFit` on iOS
</Text>
) : null}
</View>
</ScrollView>
);
}
}
| import React from 'react';
import { Platform, ScrollView, Text, View } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
export default class FontScreen extends React.Component {
static navigationOptions = {
title: 'Font',
};
render() {
const fontFamily = Platform.OS === 'ios' ? 'Menlo' : 'monospace';
return (
<ScrollView style={{ flex: 1 }}>
<View
style={{
paddingVertical: 10,
paddingHorizontal: 15,
flexDirection: 'row',
justifyContent: 'space-between',
flex: 1,
}}>
<MaterialIcons name="airplay" size={25} />
<MaterialIcons name="airport-shuttle" size={25} />
<MaterialIcons name="alarm" size={25} />
<MaterialIcons name="alarm-add" size={25} />
<MaterialIcons name="alarm-off" size={25} />
<MaterialIcons name="all-inclusive" size={25} />
</View>
<View style={{ paddingVertical: 10, paddingHorizontal: 15 }}>
<Text style={{ fontFamily, fontSize: 16 }}>
Font icons sets and other custom fonts can be loaded from the web
</Text>
{Platform.OS === 'ios' ? (
<Text
adjustsFontSizeToFit
style={{
flex: 1,
height: 32,
fontFamily,
fontSize: 420,
}}>
Custom font with `adjustsFontSizeToFit` on iOS
</Text>
) : null}
</View>
</ScrollView>
);
}
}
|
Add some logging to the EVE API task | import logging
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
l = logging.getLogger('import_apikey')
l.info("Importing %s/%s" % (api_userid, api_key))
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
| from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
|
Refactor: Move some construction to __init__. | #!/usr/bin/python
import urlparse
import curie
import link
class Document(object):
def __init__(self, o, relative_to_url, parent_curie=None):
self.attrs = o
self.__dict__.update(o)
self.links = {}
for key, value in o.get("_links", {}).iteritems():
self.links[key] = link.Link.from_object(value, relative_to_url)
if 'self' in self.links:
self.url = self.links['self'].url
self.curie = curie.CurieCollection(relative_to_url)
if parent_curie is not None:
self.curie.update(parent_curie)
curies = self.links.get('curie', [])
if not isinstance(curies, list):
curies = [curies]
for curie_dict in curies:
self.curie[curie_dict.name] = curie_dict.href
self.embedded = {}
for key, value in o.get("_embedded", {}).iteritems():
self.embedded[key] = self.__class__.from_object(value,
relative_to_url,
self.curie)
def expand_curie(self, link):
return self.curie.expand(link)
@classmethod
def from_object(cls, o, relative_to_url=None, parent_curie=None):
if isinstance(o, list):
return map(lambda x: cls.from_object(x, relative_to_url), o)
return cls(o, relative_to_url, parent_curie)
| #!/usr/bin/python
import urlparse
import curie
import link
class Document(object):
def expand_curie(self, link):
return self.curie.expand(link)
@classmethod
def from_object(cls, o, relative_to_url=None, parent_curie=None):
if isinstance(o, list):
return map(lambda x: cls.from_object(x, relative_to_url), o)
result = Document()
result.attrs = o
result.__dict__.update(o)
result.links = {}
for key, value in o.get("_links", {}).iteritems():
result.links[key] = link.Link.from_object(value, relative_to_url)
if 'self' in result.links:
result.url = result.links['self'].url
result.curie = curie.CurieCollection(relative_to_url)
if parent_curie is not None:
result.curie.update(parent_curie)
curies = result.links.get('curie', [])
if not isinstance(curies, list):
curies = [curies]
for curie_dict in curies:
result.curie[curie_dict.name] = curie_dict.href
result.embedded = {}
for key, value in o.get("_embedded", {}).iteritems():
result.embedded[key] = cls.from_object(value,
relative_to_url,
result.curie)
return result
|
Make sure a project is set for the project-specific validator | from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
| from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
Use class for logout instead of href, to please IE8 | from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(NewmanTestCase, self).__init__()
self.elements = {
'navigation' : {
'logout' : "//a[@class='icn logout']"
},
'pages' : {
'login' : {
'submit' : "//input[@type='submit']"
}
}
}
def login_superuser(self):
self.selenium.open(self.NEWMAN_URI)
self.selenium.type("id_username", self.SUPERUSER_USERNAME)
self.selenium.type("id_password", self.SUPERUSER_PASSWORD)
self.selenium.click(self.elements['pages']['login']['submit'])
def logout(self):
self.selenium.click(self.elements['navigation']['logout'])
self.selenium.wait_for_page_to_load(30000)
self.selenium.is_text_present(u"Thanks for spending some quality time with the Web site today.")
| from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(NewmanTestCase, self).__init__()
self.elements = {
'navigation' : {
'logout' : '//a[@href="%slogout/"]' % self.NEWMAN_URI
},
'pages' : {
'login' : {
'submit' : "//input[@type='submit']"
}
}
}
def login_superuser(self):
self.selenium.open(self.NEWMAN_URI)
self.selenium.type("id_username", self.SUPERUSER_USERNAME)
self.selenium.type("id_password", self.SUPERUSER_PASSWORD)
self.selenium.click(self.elements['pages']['login']['submit'])
def logout(self):
self.selenium.click(self.elements['navigation']['logout'])
self.selenium.wait_for_page_to_load(30000)
self.selenium.is_text_present(u"Thanks for spending some quality time with the Web site today.")
|
Change classname in auth adapter listener | <?php
namespace EdpGithub;
use Zend\Module\Manager,
Zend\Module\Consumer\AutoloaderProvider,
Zend\EventManager\StaticEventManager;
class Module implements AutoloaderProvider
{
protected static $options;
public function init(Manager $moduleManager)
{
$moduleManager->events()->attach('loadModules.post', array($this, 'modulesLoaded'));
$events = StaticEventManager::getInstance();
$events->attach('ZfcUser\Authentication\Adapter\AdapterChain', 'authenticate.pre', function($e) {
$e->getTarget()->attach(new Authentication\Adapter\ZfcUserGithub);
});
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig($env = null)
{
return include __DIR__ . '/config/module.config.php';
}
public function modulesLoaded($e)
{
$config = $e->getConfigListener()->getMergedConfig();
static::$options = $config['edpgithub'];
}
public static function getOption($option)
{
if (!isset(static::$options[$option])) {
return null;
}
return static::$options[$option];
}
}
| <?php
namespace EdpGithub;
use Zend\Module\Manager,
Zend\Module\Consumer\AutoloaderProvider,
Zend\EventManager\StaticEventManager;
class Module implements AutoloaderProvider
{
protected static $options;
public function init(Manager $moduleManager)
{
$moduleManager->events()->attach('loadModules.post', array($this, 'modulesLoaded'));
$events = StaticEventManager::getInstance();
$events->attach('ZfcUser\Authentication\Adapter\AdapterChain', 'authenticate.pre', function($e) {
$e->getTarget()->attach(new Authentication\Adapter\EdpUserGithub);
});
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig($env = null)
{
return include __DIR__ . '/config/module.config.php';
}
public function modulesLoaded($e)
{
$config = $e->getConfigListener()->getMergedConfig();
static::$options = $config['edpgithub'];
}
public static function getOption($option)
{
if (!isset(static::$options[$option])) {
return null;
}
return static::$options[$option];
}
}
|
Fix missed plugin code update.
This `Meta` business is from an earlier draft. | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
| import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.Meta.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
|
Revert "Revert "Do not cache discovery""
This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998. | # -*- coding: utf-8 -*-
import logging
import httplib2
import json
import time
import random
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
class OAuth():
__services = dict()
@staticmethod
def getCredentials(email, scopes, client_secret, client_id):
key = file(client_secret, 'rb')
privateKey = key.read()
key.close()
credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email)
http = httplib2.Http()
http = credentials.authorize(http)
credentials.refresh(http)
return credentials, http
@staticmethod
def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None):
"""
Return the service with constant credential
@param email: email to execute the action
@return: the drive service
"""
if not email.strip():
raise Exception("OAuth.getService : Email for service is missing")
key = email + "/" + api + "/" + version
if key not in OAuth.__services:
credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id)
if discoveryUrl:
OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl,
cache_discovery=False, cache=None)
else:
OAuth.__services[key] = build(api, version, http=http,
cache_discovery=False, cache=None)
logging.info("OAuth.getService : Service request by - " + email)
return OAuth.__services[key]
| # -*- coding: utf-8 -*-
import logging
import httplib2
import json
import time
import random
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
class OAuth():
__services = dict()
@staticmethod
def getCredentials(email, scopes, client_secret, client_id):
key = file(client_secret, 'rb')
privateKey = key.read()
key.close()
credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email)
http = httplib2.Http()
http = credentials.authorize(http)
credentials.refresh(http)
return credentials, http
@staticmethod
def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None):
"""
Return the service with constant credential
@param email: email to execute the action
@return: the drive service
"""
if not email.strip():
raise Exception("OAuth.getService : Email for service is missing")
key = email + "/" + api + "/" + version
if key not in OAuth.__services:
credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id)
if discoveryUrl:
OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl)
else:
OAuth.__services[key] = build(api, version, http=http)
logging.info("OAuth.getService : Service request by - " + email)
return OAuth.__services[key]
|
Allow fallback translation for page path | <?php namespace Anomaly\PagesModule\Page\Command;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\PagesModule\Page\PageTranslationsModel;
/**
* Class SetPath
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
*/
class SetPath
{
/**
* The page translation instance.
*
* @var PageTranslationsModel
*/
protected $translation;
/**
* Create a new SetPath instance.
*
* @param PageTranslationsModel $translation
*/
public function __construct(PageTranslationsModel $translation)
{
$this->translation = $translation;
}
/**
* Handle the command.
*/
public function handle()
{
/* @var PageInterface $page */
$page = $this->translation->getParent();
if ($parent = $page->getParent()) {
$path = ($parent->isHome()
? $parent->translate($this->translation->getLocale(), true)->slug
: $parent->translate($this->translation->getLocale(), true)->path
) . '/' . $this->translation->slug;
} elseif ($page->isHome()) {
$path = '/';
} else {
$path = '/' . $this->translation->slug;
}
$this->translation->setAttribute('path', $path);
}
}
| <?php namespace Anomaly\PagesModule\Page\Command;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\PagesModule\Page\PageTranslationsModel;
/**
* Class SetPath
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
*/
class SetPath
{
/**
* The page translation instance.
*
* @var PageTranslationsModel
*/
protected $translation;
/**
* Create a new SetPath instance.
*
* @param PageTranslationsModel $translation
*/
public function __construct(PageTranslationsModel $translation)
{
$this->translation = $translation;
}
/**
* Handle the command.
*/
public function handle()
{
/* @var PageInterface $page */
$page = $this->translation->getParent();
if ($parent = $page->getParent()) {
$path = ($parent->isHome()
? $parent->translate($this->translation->getLocale())->slug
: $parent->translate($this->translation->getLocale())->path
) . '/' . $this->translation->slug;
} elseif ($page->isHome()) {
$path = '/';
} else {
$path = '/' . $this->translation->slug;
}
$this->translation->setAttribute('path', $path);
}
}
|
Fix middleware: an undefined value was being assigned in the Socket constructor | 'use strict';
const validate = require('./validate'),
_ = require('lodash'),
assert = require('assert'),
schema = {
properties: {
event: {
type: 'string',
required: true,
allowEmpty: false
},
onEvent: {
required: true,
allowEmpty: false,
conform(onEvent) {
return _.isFunction(onEvent);
},
messages: {
conform: 'onEvent must be a function'
},
},
middleware: {
conform(middleware) {
return _.isFunction(middleware) || _.isArray(middleware);
},
messages: {
conform: 'middleware must be a function or an array of functions'
},
required: false,
allowEmpty: true
}
}
};
function toArray(arg) {
return !_.isArray(arg) ? [arg] : arg;
}
class Socket {
/**
* @description Creates a new socket instance
* @param {String} packageName - The name of the LabShare package that created the socket definition
* @param {Object} options
* @param {String} options.event - The event name
* @param {String} options.onEvent - The main event handler
* @param {Array.<Function>|Function} [options.middleware] - One or more connect-style middleware functions
*/
constructor(packageName, options = {}) {
assert.ok(_.isString(packageName), 'Socket: "packageName" is required');
validate({object: options, packageName, type: 'socket', schema});
_.extend(this, options);
this.middleware = this.middleware || [];
this.middleware = toArray(this.middleware);
}
}
module.exports = Socket;
| 'use strict';
const validate = require('./validate'),
_ = require('lodash'),
assert = require('assert'),
schema = {
properties: {
event: {
type: 'string',
required: true,
allowEmpty: false
},
onEvent: {
required: true,
allowEmpty: false,
conform(onEvent) {
return _.isFunction(onEvent);
},
messages: {
conform: 'onEvent must be a function'
},
},
middleware: {
conform(middleware) {
return _.isFunction(middleware) || _.isArray(middleware);
},
messages: {
conform: 'middleware must be a function or an array of functions'
},
required: false,
allowEmpty: true
}
}
};
function toArray(arg) {
return !_.isArray(arg) ? [arg] : arg;
}
class Socket {
/**
* @description Creates a new socket instance
* @param {String} packageName - The name of the LabShare package that created the socket definition
* @param {Object} options
* @param {String} options.event - The event name
* @param {String} options.onEvent - The main event handler
* @param {Array.<Function>|Function} options.middleware - One or more connect-style middleware functions
*/
constructor(packageName, options = {}) {
assert.ok(_.isString(packageName), 'Socket: "packageName" is required');
validate({object: options, packageName, type: 'socket', schema});
_.extend(this, options);
this.middleware = toArray(this.middleware);
}
}
module.exports = Socket; |
Use __builtins__ directly instead of import __builtin__. | from disco import util
from discodb import DiscoDB, Q
def open(url, task=None):
if task:
disco_data = task.disco_data
ddfs_data = task.ddfs_data
else:
from disco.settings import DiscoSettings
settings = DiscoSettings()
disco_data = settings['DISCO_DATA']
ddfs_data = settings['DDFS_DATA']
scheme, netloc, rest = util.urlsplit(url)
path, rest = rest.split('!', 1) if '!' in rest else (rest, '')
discodb = DiscoDB.load(__builtins__.open(util.localize(path,
disco_data=disco_data,
ddfs_data=ddfs_data)))
if rest:
method_name, arg = rest.split('/', 1) if '/' in rest else (rest, None)
method = getattr(discodb, method_name)
if method_name in ('metaquery', 'query'):
return method(Q.urlscan(arg))
return method(*filter(None, arg))
return discodb
def input_stream(fd, size, url, params):
return open(url, task=globals().get('Task')), size, url
| import __builtin__
from disco import util
from discodb import DiscoDB, Q
def open(url, task=None):
if task:
disco_data = task.disco_data
ddfs_data = task.ddfs_data
else:
from disco.settings import DiscoSettings
settings = DiscoSettings()
disco_data = settings['DISCO_DATA']
ddfs_data = settings['DDFS_DATA']
scheme, netloc, rest = util.urlsplit(url)
path, rest = rest.split('!', 1) if '!' in rest else (rest, '')
discodb = DiscoDB.load(__builtin__.open(util.localize(path,
disco_data=disco_data,
ddfs_data=ddfs_data)))
if rest:
method_name, arg = rest.split('/', 1) if '/' in rest else (rest, None)
method = getattr(discodb, method_name)
if method_name in ('metaquery', 'query'):
return method(Q.urlscan(arg))
return method(*filter(None, arg))
return discodb
def input_stream(fd, size, url, params):
return open(url, task=globals().get('Task')), size, url
|
Add proper logging to tests when in verbose mode | #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################
import traceback
import logging
import arrayfire as af
def display_func(verbose):
if (verbose):
return af.display
else:
def eval_func(foo):
res = foo
return eval_func
def print_func(verbose):
def print_func_impl(*args):
if (verbose):
print(args)
else:
res = [args]
return print_func_impl
class _simple_test_dict(dict):
def __init__(self):
self.print_str = "Simple %16s: %s"
super(_simple_test_dict, self).__init__()
def run(self, name_list=None, verbose=False):
test_list = name_list if name_list is not None else self.keys()
for key in test_list:
try:
test = self[key]
except:
print(self.print_str % (key, "NOTFOUND"))
continue
try:
test(verbose)
print(self.print_str % (key, "PASSED"))
except Exception as e:
print(self.print_str % (key, "FAILED"))
if (verbose):
logging.error(traceback.format_exc())
tests = _simple_test_dict()
| #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################
import arrayfire as af
def display_func(verbose):
if (verbose):
return af.display
else:
def eval_func(foo):
res = foo
return eval_func
def print_func(verbose):
def print_func_impl(*args):
if (verbose):
print(args)
else:
res = [args]
return print_func_impl
class _simple_test_dict(dict):
def __init__(self):
self.print_str = "Simple %16s: %s"
super(_simple_test_dict, self).__init__()
def run(self, name_list=None, verbose=False):
test_list = name_list if name_list is not None else self.keys()
for key in test_list:
try:
test = self[key]
except:
print(self.print_str % (key, "NOTFOUND"))
continue
try:
test(verbose)
print(self.print_str % (key, "PASSED"))
except:
print(self.print_str % (key, "FAILED"))
tests = _simple_test_dict()
|
Add tests for the Field class. | # -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Field()
f.validate("foo")
f.validate(object())
def test_get_descriptor(self):
f = Field()
descriptor = f.get_descriptor("foo")
self.assertEqual(descriptor.key, "foo")
self.assertEqual(descriptor.field, f)
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
| # -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
|
Send emails to [email protected] until we find what is wrong in sending to tech | package uk.ac.ebi.biosamples.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
public class MailSender {
private static final String BODY_PART_FAIL = " failed execution on ";
private static final String MAILX = "mailx";
private static final String SUBJECT = "-s Email from pipeline ";
private static final String RECIPIENT = "[email protected]";
private static final String BODY_PART_SUCCESS = " pipeline execution successful for ";
public static final String FAILED_FILES_ARE = " Failed files are: ";
private static Logger log = LoggerFactory.getLogger("MailSender");
public static void sendEmail(final String pipelineName, final String failures, final boolean isPassed) {
try {
final String[] cmd = {MAILX, SUBJECT + pipelineName, RECIPIENT};
final Process p = Runtime.getRuntime().exec(cmd);
final OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());
if (isPassed) {
if (failures != null && !failures.isEmpty())
osw.write(pipelineName + BODY_PART_SUCCESS + new Date() + FAILED_FILES_ARE + failures);
else
osw.write(pipelineName + BODY_PART_SUCCESS + new Date());
} else osw.write(pipelineName + BODY_PART_FAIL + new Date());
osw.close();
} catch (final IOException ioe) {
log.error("Email send failed");
}
}
}
| package uk.ac.ebi.biosamples.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
public class MailSender {
private static final String BODY_PART_FAIL = " failed execution on ";
private static final String MAILX = "mailx";
private static final String SUBJECT = "-s Email from pipeline ";
private static final String RECIPIENT = "[email protected]";
private static final String BODY_PART_SUCCESS = " pipeline execution successful for ";
public static final String FAILED_FILES_ARE = " Failed files are: ";
private static Logger log = LoggerFactory.getLogger("MailSender");
public static void sendEmail(final String pipelineName, final String failures, final boolean isPassed) {
try {
final String[] cmd = {MAILX, SUBJECT + pipelineName, RECIPIENT};
final Process p = Runtime.getRuntime().exec(cmd);
final OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());
if (isPassed) {
if (failures != null && !failures.isEmpty())
osw.write(pipelineName + BODY_PART_SUCCESS + new Date() + FAILED_FILES_ARE + failures);
else
osw.write(pipelineName + BODY_PART_SUCCESS + new Date());
} else osw.write(pipelineName + BODY_PART_FAIL + new Date());
osw.close();
} catch (final IOException ioe) {
log.error("Email send failed");
}
}
}
|
Support for value coming in as a string (eg. from URLs). | import Webiny from 'Webiny';
import styles from './styles.css';
class Switch extends Webiny.Ui.FormComponent {
constructor(props) {
super(props);
this.bindMethods('switch');
}
componentWillMount() {
super.componentWillMount();
this.id = _.uniqueId('switch-');
}
switch() {
if (this.isDisabled()) {
return;
}
const el = ReactDOM.findDOMNode(this).querySelector('input');
const checked = !el.checked;
this.props.onChange(checked);
}
}
Switch.defaultProps = _.merge({}, Webiny.Ui.FormComponent.defaultProps, {
style: {},
renderer() {
const {FormGroup, styles} = this.props;
let classes = this.classSet(styles.switch, styles.switchInline);
if (this.props.disabled) {
classes += ' ' + styles.disabled;
}
// The JSON.parse was added since sometimes value can come in as a string (eg. when value is coming from URL, as a query parameter).
// With the JSON.parse, we ensure we get non-string, pure boolean value, and that the switch button is correctly rendered.
const value = JSON.parse(this.props.value || null);
return (
<FormGroup>
{this.renderLabel()}
<div className="clearfix"/>
<div className={classes}>
<input id={this.id} type="checkbox" readOnly checked={value === true}/>
<label htmlFor={this.id} onClick={this.switch}/>
</div>
{this.renderDescription()}
</FormGroup>
);
}
});
export default Webiny.createComponent(Switch, {modules: ['FormGroup'], styles});
| import Webiny from 'Webiny';
import styles from './styles.css';
class Switch extends Webiny.Ui.FormComponent {
constructor(props) {
super(props);
this.bindMethods('switch');
}
componentWillMount() {
super.componentWillMount();
this.id = _.uniqueId('switch-');
}
switch() {
if (this.isDisabled()) {
return;
}
const el = ReactDOM.findDOMNode(this).querySelector('input');
const checked = !el.checked;
this.props.onChange(checked);
}
}
Switch.defaultProps = _.merge({}, Webiny.Ui.FormComponent.defaultProps, {
style: {},
renderer() {
const {FormGroup, styles} = this.props;
let classes = this.classSet(styles.switch, styles.switchInline);
if (this.props.disabled) {
classes += ' ' + styles.disabled;
}
return (
<FormGroup>
{this.renderLabel()}
<div className="clearfix"/>
<div className={classes}>
<input id={this.id} type="checkbox" readOnly checked={this.props.value === true}/>
<label htmlFor={this.id} onClick={this.switch}/>
</div>
{this.renderDescription()}
</FormGroup>
);
}
});
export default Webiny.createComponent(Switch, {modules: ['FormGroup'], styles});
|
Use the filetime of the actual file instead of that of the parameters.yml file for caching assets | <?php
namespace Common\Core\Header;
use DateTimeImmutable;
final class Asset
{
/** @var string */
private $file;
/** @var Priority */
private $priority;
/** @var bool */
private $addTimestamp;
/** @var DateTimeImmutable */
private $createdOn;
public function __construct(string $file, bool $addTimestamp = false, Priority $priority = null)
{
$this->file = $file;
$this->addTimestamp = $addTimestamp;
$this->priority = $priority ?? Priority::standard();
$this->createdOn = new DateTimeImmutable();
}
public function compare(Asset $asset): int
{
$comparison = $this->priority->compare($asset->priority);
if ($comparison === 0) {
$comparison = $this->createdOn <=> $asset->createdOn;
}
return $comparison;
}
public function getFile(): string
{
return $this->file;
}
public function getPriority(): Priority
{
return $this->priority;
}
public function forCacheUrl(string $cacheUrl): self
{
$cacheAsset = clone $this;
$cacheAsset->file = $cacheUrl;
return $cacheAsset;
}
public function __toString(): string
{
if (!$this->addTimestamp) {
return $this->file;
}
// check if we need to use a ? or &
$separator = mb_strpos($this->file, '?') === false ? '?' : '&';
return $this->file . $separator . 'm=' . filemtime(__DIR__ . '/../../../../' . $this->file);
}
}
| <?php
namespace Common\Core\Header;
use DateTimeImmutable;
final class Asset
{
/** @var string */
private $file;
/** @var Priority */
private $priority;
/** @var bool */
private $addTimestamp;
/** @var DateTimeImmutable */
private $createdOn;
public function __construct(string $file, bool $addTimestamp = false, Priority $priority = null)
{
$this->file = $file;
$this->addTimestamp = $addTimestamp;
$this->priority = $priority ?? Priority::standard();
$this->createdOn = new DateTimeImmutable();
}
public function compare(Asset $asset)
{
$comparison = $this->priority->compare($asset->priority);
if ($comparison === 0) {
$comparison = $this->createdOn <=> $asset->createdOn;
}
return $comparison;
}
public function getFile(): string
{
return $this->file;
}
public function getPriority(): Priority
{
return $this->priority;
}
public function forCacheUrl(string $cacheUrl): self
{
$cacheAsset = clone $this;
$cacheAsset->file = $cacheUrl;
return $cacheAsset;
}
public function __toString(): string
{
if (!$this->addTimestamp) {
return $this->file;
}
// check if we need to use a ? or &
return $this->file . (mb_strpos($this->file, '?') === false ? '?' : '&') . 'm=' . LAST_MODIFIED_TIME;
}
}
|
Handle no results from category page | from bs4 import BeautifulSoup
import logging
from jetcomcrawl import browser
import jetcomcrawl.libs.queue
class Worker(object):
def __init__(self):
self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories')
self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items')
def work(self):
'''Keeps running indefinitely, retrieving jobs from sqs'''
while True:
# TODO: Handle no items left in queue
data = self.queue_categories.retrieve()
cid = data['cid']
page = data['page']
logging.info('Finding products for category {}, page {}'.format(cid, page))
html = browser.get('https://jet.com/search/results?category={}&page={}'.format(cid, page))
try:
soup = BeautifulSoup(html.text, 'html.parser')
if soup.find('div', {'class': 'no-results'}):
logging.info('Skipping process of {}:{}. No results available'.format(cid, page))
else:
results = []
for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}):
url = item.a['href']
uid = url.split('/')[-1]
results.append({'uid': uid, 'url': url})
except:
logging.info(html.text)
raise
logging.info('{} products found for category {}, page {}, inserting into sqs'.format(len(results), cid, page))
self.queue_items.insert_bulk(results)
self.queue_categories.remove_processed()
| from bs4 import BeautifulSoup
import logging
from jetcomcrawl import browser
import jetcomcrawl.libs.queue
class Worker(object):
def __init__(self):
self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories')
self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items')
def work(self):
'''Keeps running indefinitely, retrieving jobs from sqs'''
while True:
# TODO: Handle no items left in queue
data = self.queue_categories.retrieve()
cid = data['cid']
page = data['page']
logging.info('Finding products for category {}, page {}'.format(cid, page))
html = browser.get('https://jet.com/search/results?category={}&page={}'.format(cid, page))
try:
soup = BeautifulSoup(html.text, 'html.parser')
results = []
for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}):
url = item.a['href']
uid = url.split('/')[-1]
results.append({'uid': uid, 'url': url})
except:
logging.info(html.text)
raise
logging.info('{} products found for category {}, page {}, inserting into sqs'.format(len(results), cid, page))
self.queue_items.insert_bulk(results)
self.queue_categories.remove_processed()
|
[TIMOB-19435] Allow for setting of the Title | package ti.modules.titanium.ui.android;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiRHelper;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class TiPreferencesFragment extends PreferenceFragment {
private static final String TAG = "TiPreferencesFragment";
private CharSequence title = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String prefsName = getArguments().getString(TiPreferencesActivity.PREFS_KEY);
// Find the layout file, do nothing if not found
try {
getPreferenceManager().setSharedPreferencesName(TiApplication.APPLICATION_PREFERENCES_NAME);
int resid = TiRHelper.getResource("xml." + prefsName);
if (resid != 0) {
addPreferencesFromResource(resid);
if (getPreferenceScreen() != null) {
title = getPreferenceScreen().getTitle();
}
} else {
Log.e(TAG, "xml." + prefsName + " preferences not found.");
return;
}
} catch (TiRHelper.ResourceNotFoundException e) {
Log.e(TAG, "Error loading preferences: " + e.getMessage());
return;
}
}
@Override
public void onResume() {
super.onResume();
if (title != null && getActivity() != null) {
getActivity().setTitle(title);
}
}
}
| package ti.modules.titanium.ui.android;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiRHelper;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class TiPreferencesFragment extends PreferenceFragment {
private static final String TAG = "TiPreferencesFragment";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String prefsName = getArguments().getString(TiPreferencesActivity.PREFS_KEY);
// Find the layout file, do nothing if not found
try {
getPreferenceManager().setSharedPreferencesName(TiApplication.APPLICATION_PREFERENCES_NAME);
int resid = TiRHelper.getResource("xml." + prefsName);
if (resid != 0) {
addPreferencesFromResource(resid);
} else {
Log.e(TAG, "xml." + prefsName + " preferences not found.");
return;
}
} catch (TiRHelper.ResourceNotFoundException e) {
Log.e(TAG, "Error loading preferences: " + e.getMessage());
return;
}
}
}
|
Correct the name of the test class
Was different from the filename | <?php
use Lfj\ZfRenderer\Service\Renderer;
use Zend\View\Resolver;
class RendererTest extends PHPUnit_Framework_TestCase
{
public function testRenderSimpleView()
{
$template = realpath('view/template-simple.phtml');
$expectedContent = file_get_contents($template);
$renderer = new Renderer();
$renderedContent = $renderer->render($template);
$this->assertEquals('Zend\Stdlib\Response', get_class($renderedContent->getResponse()));
$this->assertEquals($expectedContent, $renderedContent->getResponse()->getContent());
}
public function testRenderMediumView()
{
$template = realpath('view/template-medium.phtml');
$expectedContent = 'hello world';
$renderer = new Renderer();
$renderedContent = $renderer->render($template, array('name' => 'world'));
$this->assertEquals('Zend\Stdlib\Response', get_class($renderedContent->getResponse()));
$this->assertEquals($expectedContent, $renderedContent->getResponse()->getContent());
}
public function testRenderHardView()
{
$template = realpath('view/template-hard.phtml');
$expectedContent = 'hello world';
$templatePathStack = new Resolver\TemplatePathStack();
$templatePathStack->addPath(realpath('view'));
$renderer = new Renderer();
$renderedContent = $renderer->render($template, array('name' => 'world'), array($templatePathStack));
$this->assertEquals('Zend\Stdlib\Response', get_class($renderedContent->getResponse()));
$this->assertEquals($expectedContent, $renderedContent->getResponse()->getContent());
}
}
| <?php
use Lfj\ZfRenderer\Service\Renderer;
use Zend\View\Resolver;
class StackTest extends PHPUnit_Framework_TestCase
{
public function testRenderSimpleView()
{
$template = realpath('view/template-simple.phtml');
$expectedContent = file_get_contents($template);
$renderer = new Renderer();
$renderedContent = $renderer->render($template);
$this->assertEquals('Zend\Stdlib\Response', get_class($renderedContent->getResponse()));
$this->assertEquals($expectedContent, $renderedContent->getResponse()->getContent());
}
public function testRenderMediumView()
{
$template = realpath('view/template-medium.phtml');
$expectedContent = 'hello world';
$renderer = new Renderer();
$renderedContent = $renderer->render($template, array('name' => 'world'));
$this->assertEquals('Zend\Stdlib\Response', get_class($renderedContent->getResponse()));
$this->assertEquals($expectedContent, $renderedContent->getResponse()->getContent());
}
public function testRenderHardView()
{
$template = realpath('view/template-hard.phtml');
$expectedContent = 'hello world';
$templatePathStack = new Resolver\TemplatePathStack();
$templatePathStack->addPath(realpath('view'));
$renderer = new Renderer();
$renderedContent = $renderer->render($template, array('name' => 'world'), array($templatePathStack));
$this->assertEquals('Zend\Stdlib\Response', get_class($renderedContent->getResponse()));
$this->assertEquals($expectedContent, $renderedContent->getResponse()->getContent());
}
}
|
Raise modern browser support bar | // External
const mem = require('mem');
// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');
const PROJECT_TYPES_CONFIG = {
preact: {
plugins: [
[
require.resolve('@babel/plugin-transform-react-jsx'),
{
pragma: 'h'
}
]
]
},
react: {
presets: [require.resolve('@babel/preset-react')]
}
};
module.exports.getBabelConfig = mem(({ isModernJS } = {}) => {
const { babel: projectBabelConfig, pkg, type } = getProjectConfig();
return merge(
{
presets: [
[
require.resolve('@babel/preset-env'),
{
targets: {
browsers: isModernJS
? ['Chrome >= 76', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 69', 'Edge >= 18']
: pkg.browserslist || ['> 1% in au', '> 5%', 'Firefox ESR']
},
useBuiltIns: 'entry',
corejs: 3,
modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false
}
]
],
plugins: [
require.resolve('@babel/plugin-proposal-object-rest-spread'),
require.resolve('@babel/plugin-syntax-dynamic-import'),
require.resolve('@babel/plugin-proposal-class-properties')
]
},
PROJECT_TYPES_CONFIG[type],
projectBabelConfig
);
});
| // External
const mem = require('mem');
// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');
const PROJECT_TYPES_CONFIG = {
preact: {
plugins: [
[
require.resolve('@babel/plugin-transform-react-jsx'),
{
pragma: 'h'
}
]
]
},
react: {
presets: [require.resolve('@babel/preset-react')]
}
};
module.exports.getBabelConfig = mem(({ isModernJS } = {}) => {
const { babel: projectBabelConfig, pkg, type } = getProjectConfig();
return merge(
{
presets: [
[
require.resolve('@babel/preset-env'),
{
targets: {
browsers: isModernJS
? ['Chrome >= 60', 'Safari >= 10.1', 'iOS >= 10.3', 'Firefox >= 54', 'Edge >= 15']
: pkg.browserslist || ['> 1% in au', '> 5%', 'Firefox ESR']
},
useBuiltIns: 'entry',
corejs: 3,
modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false
}
]
],
plugins: [
require.resolve('@babel/plugin-proposal-object-rest-spread'),
require.resolve('@babel/plugin-syntax-dynamic-import'),
require.resolve('@babel/plugin-proposal-class-properties')
]
},
PROJECT_TYPES_CONFIG[type],
projectBabelConfig
);
});
|
Fix up for Django 1.9 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedContentTypeManager
class ContentTypesConfig(AppConfig):
name = 'djangae.contrib.contenttypes'
verbose_name = _("Djangae Content Types")
label = "djangae_contenttypes"
def ready(self):
if django_update_contenttypes != update_contenttypes:
post_migrate.disconnect(django_update_contenttypes)
from django.db import models
from django.contrib.contenttypes import models as django_models
if not isinstance(django_models.ContentType.objects, SimulatedContentTypeManager):
django_models.ContentType.objects = SimulatedContentTypeManager(django_models.ContentType)
django_models.ContentType.objects.auto_created = True
# Really force the default manager to use the Simulated one
meta = django_models.ContentType._meta
if hasattr(meta, "local_managers"):
# Django >= 1.10
meta.local_managers[0] = SimulatedContentTypeManager()
else:
django_models.ContentType._default_manager = SimulatedContentTypeManager(django_models.ContentType)
meta._expire_cache()
# Our generated IDs take up a 64 bit range (signed) but aren't auto
# incrementing so update the field to reflect that (for validation)
meta.pk.__class__ = models.BigIntegerField
| from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedContentTypeManager
class ContentTypesConfig(AppConfig):
name = 'djangae.contrib.contenttypes'
verbose_name = _("Djangae Content Types")
label = "djangae_contenttypes"
def ready(self):
if django_update_contenttypes != update_contenttypes:
post_migrate.disconnect(django_update_contenttypes)
from django.db import models
from django.contrib.contenttypes import models as django_models
if not isinstance(django_models.ContentType.objects, SimulatedContentTypeManager):
django_models.ContentType.objects = SimulatedContentTypeManager()
django_models.ContentType.objects.auto_created = True
# Really force the default manager to use the Simulated one
meta = django_models.ContentType._meta
meta.local_managers[0] = SimulatedContentTypeManager()
meta._expire_cache()
# Our generated IDs take up a 64 bit range (signed) but aren't auto
# incrementing so update the field to reflect that (for validation)
meta.pk.__class__ = models.BigIntegerField
|
Add documentation to the method. | <?php
namespace ValueObjects\Base;
use ValueObjects\ValueObject;
/**
* Class Strings
* ValueObject that represents a String with lots of useful methods.
* It is called string since string is a reserved word in Php 7.
* @package ValueObjects\Base
*/
class Strings extends ValueObject
{
public function __construct(string $value)
{
parent::__construct($value);
}
/**
* Creates a string from an integer.
* @param $int
* @return Strings
*/
public static function fromInt(int $int)
{
return new self((string) $int);
}
/**
* Cretes a string from a double.
* @param float $double
* @return Strings
*/
public static function fromFloat(float $double)
{
return new static((string) $double);
}
/**
* Returns a new string converted to uppercase.
* @return self
*/
public function toUpperCase()
{
return new static(strtoupper($this->value));
}
/**
* Returns a new string converted to low case.
* @return self
*/
public function toLowerCase()
{
return new static(strtolower($this->value));
}
/**
* Returns a new trimmed string.
* @return self
*/
public function trim(): self
{
return new static(trim($this->value));
}
/**
* Returns the length of a string.
* @return int
*/
public function length(): int
{
return strlen($this->value);
}
}
| <?php
namespace ValueObjects\Base;
use ValueObjects\ValueObject;
/**
* Class Strings
* ValueObject that represents a String with lots of useful methods.
* It is called string since string is a reserved word in Php 7.
* @package ValueObjects\Base
*/
class Strings extends ValueObject
{
public function __construct(string $value)
{
parent::__construct($value);
}
/**
* Creates a string from an integer.
* @param $int
* @return Strings
*/
public static function fromInt(int $int)
{
return new self((string) $int);
}
/**
* Cretes a string from a double.
* @param float $double
* @return Strings
*/
public static function fromFloat(float $double)
{
return new static((string) $double);
}
/**
* Returns a new string converted to uppercase.
* @return self
*/
public function toUpperCase()
{
return new static(strtoupper($this->value));
}
/**
* Returns a new string converted to low case.
* @return self
*/
public function toLowerCase()
{
return new static(strtolower($this->value));
}
public function trim()
{
return new static(trim($this->value));
}
public function length(): int
{
return strlen($this->value);
}
}
|
Make tick thicker to facilitate hovering
cc: da39a3ee5e6b4b0d3255bfef95601890afd80709@zeningqu | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
scale: {useRawDomain: false},
mark: {
tickThickness: 2
}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
mark: {
tickThickness: 2
}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
|
Fix inverted longitude and latitude when saving the coordinates to the DB | <?php
namespace geotime\helpers;
use geotime\models\CalibrationPoint;
use geotime\models\CoordinateLatLng;
use geotime\models\CoordinateXY;
use Logger;
Logger::configure("lib/geotime/logger.xml");
class CalibrationPointHelper
{
/** @var \Logger */
static $log;
/**
* @param $calibrationPoint \stdClass
* @return CalibrationPoint
*/
public static function generateFromStrings($calibrationPoint) {
$bgPointCoordinates = new CoordinateLatLng($calibrationPoint->bgMap->lat, $calibrationPoint->bgMap->lng);
$fgPointCoordinates = new CoordinateXY($calibrationPoint->fgMap->x, $calibrationPoint->fgMap->y);
return new CalibrationPoint($bgPointCoordinates, $fgPointCoordinates);
}
/**
* @param $calibrationPoint CalibrationPoint
* @param $coordinates \stdClass
*/
public static function addCoordinatesForCalibrationPoint(&$calibrationPoint, $type, $coordinates) {
if ($type === 'fgMap') {
$calibrationPoint->setFgPoint(new CoordinateXY($coordinates->x, $coordinates->y));
}
else if ($type === 'bgMap') {
$calibrationPoint->setBgPoint(new CoordinateLatLng($coordinates->lng, $coordinates->lat));
}
}
}
CalibrationPointHelper::$log = Logger::getLogger("main");
| <?php
namespace geotime\helpers;
use geotime\models\CalibrationPoint;
use geotime\models\CoordinateLatLng;
use geotime\models\CoordinateXY;
use Logger;
Logger::configure("lib/geotime/logger.xml");
class CalibrationPointHelper
{
/** @var \Logger */
static $log;
/**
* @param $calibrationPoint \stdClass
* @return CalibrationPoint
*/
public static function generateFromStrings($calibrationPoint) {
$bgPointCoordinates = new CoordinateLatLng($calibrationPoint->bgMap->lng, $calibrationPoint->bgMap->lat);
$fgPointCoordinates = new CoordinateXY($calibrationPoint->fgMap->x, $calibrationPoint->fgMap->y);
return new CalibrationPoint($bgPointCoordinates, $fgPointCoordinates);
}
/**
* @param $calibrationPoint CalibrationPoint
* @param $coordinates \stdClass
*/
public static function addCoordinatesForCalibrationPoint(&$calibrationPoint, $type, $coordinates) {
if ($type === 'fgMap') {
$calibrationPoint->setFgPoint(new CoordinateXY($coordinates->x, $coordinates->y));
}
else if ($type === 'bgMap') {
$calibrationPoint->setBgPoint(new CoordinateLatLng($coordinates->lng, $coordinates->lat));
}
}
}
CalibrationPointHelper::$log = Logger::getLogger("main");
|
Add "гугли" google search query | <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Class GoogleSearchMiddleware
* @package App\Gitter\Middleware
*/
class GoogleSearchMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
* @return mixed
*/
public function handle(Message $message)
{
$text = $message->escaped_text;
if (preg_match('/^(@.*?\s)?(?:погугли|гугли)\s(.*?)$/isu', $text, $matches)) {
if (!trim($matches[2])) {
return $message;
}
$hasMentions = count($message->mentions) && $message->mentions[0]->login !== \Auth::user()->login;
$answer = trim($matches[1]) && $hasMentions
? \Lang::get('google.personal', [
'user' => $message->mentions[0]->login,
'query' => urlencode($matches[2])
])
: \Lang::get('google.common', [
'query' => urlencode($matches[2])
]);
$message->answer($answer);
}
return $message;
}
}
| <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Class GoogleSearchMiddleware
* @package App\Gitter\Middleware
*/
class GoogleSearchMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
* @return mixed
*/
public function handle(Message $message)
{
$text = $message->escaped_text;
if (preg_match('/^(@.*?\s)?погугли\s(.*?)$/isu', $text, $matches)) {
if (!trim($matches[2])) {
return $message;
}
$hasMentions = count($message->mentions) && $message->mentions[0]->login !== \Auth::user()->login;
$answer = trim($matches[1]) && $hasMentions
? \Lang::get('google.personal', [
'user' => $message->mentions[0]->login,
'query' => urlencode($matches[2])
])
: \Lang::get('google.common', [
'query' => urlencode($matches[2])
]);
$message->answer($answer);
}
return $message;
}
}
|
Fix incorrect option causing crash on logout | import chalk from 'chalk'
import getUserConfig from '../../util/getUserConfig'
export default {
name: 'logout',
signature: 'logout',
description: 'Logs out of the Sanity.io session',
async action(args, {output, prompt, apiClient}) {
const cfg = getUserConfig()
const token = cfg.get('authToken')
const type = cfg.get('authType')
if (!token) {
output.print(chalk.red('No login credentials found'))
return
}
if (token && type !== 'provisional') {
logout(cfg)
return
}
if (type === 'provisional') {
output.print(chalk.yellow.inverse('[WARN]') + chalk.yellow(' You are currently logged in as a temporary user!'))
output.print(chalk.yellow('Logging out will make it super hard to claim your beautiful project :\'('))
}
const confirm = await prompt.single({
type: 'confirm',
message: 'Are you sure you want to log out?',
default: false
})
if (!confirm) {
output.print(chalk.red('Aborted'))
return
}
logout(cfg)
async function logout() {
const client = apiClient({requireUser: false, requireProject: false})
if (token) {
await client.request({uri: '/auth/logout'})
}
cfg.del('authType')
cfg.del('authToken')
output.print(chalk.green('Logged out'))
}
}
}
| import chalk from 'chalk'
import getUserConfig from '../../util/getUserConfig'
export default {
name: 'logout',
signature: 'logout',
description: 'Logs out of the Sanity.io session',
async action(args, {output, prompt, apiClient}) {
const cfg = getUserConfig()
const token = cfg.get('authToken')
const type = cfg.get('authType')
if (!token) {
output.print(chalk.red('No login credentials found'))
return
}
if (token && type !== 'provisional') {
logout(cfg)
return
}
if (type === 'provisional') {
output.print(chalk.yellow.inverse('[WARN]') + chalk.yellow(' You are currently logged in as a temporary user!'))
output.print(chalk.yellow('Logging out will make it super hard to claim your beautiful project :\'('))
}
const confirm = await prompt.single({
type: 'confirm',
message: 'Are you sure you want to log out?',
default: false
})
if (!confirm) {
output.print(chalk.red('Aborted'))
return
}
logout(cfg)
async function logout() {
const client = apiClient({requireUser: false, requireProject: false})
if (token) {
await client.request({url: '/auth/logout'})
}
cfg.del('authType')
cfg.del('authToken')
output.print(chalk.green('Logged out'))
}
}
}
|
Use config schema singleton instance if none was provided | <?php
class HTMLPurifier_HTML5Config
{
/**
* @param string|array|HTMLPurifier_Config $config
* @param HTMLPurifier_ConfigSchema $schema
* @return HTMLPurifier_Config
*/
public static function create($config = null, HTMLPurifier_ConfigSchema $schema = null)
{
if (!$schema instanceof HTMLPurifier_ConfigSchema) {
$schema = HTMLPurifier_ConfigSchema::instance();
}
if ($config instanceof HTMLPurifier_Config) {
$configObj = $config;
} else {
$configObj = new HTMLPurifier_Config($schema);
$configObj->set('Core.Encoding', 'UTF-8');
$configObj->set('HTML.Doctype', 'HTML 4.01 Transitional');
if (is_string($config)) {
$configObj->loadIni($config);
} elseif (is_array($config)) {
$configObj->loadArray($config);
}
}
$def = $configObj->getHTMLDefinition(true); // this finalizes config
HTMLPurifier_HTML5Definition::setup($def);
return $configObj;
}
/**
* Creates a configuration object using the default config schema instance
*
* @return HTMLPurifier_Config
*/
public static function createDefault()
{
$schema = HTMLPurifier_ConfigSchema::instance();
$config = self::create(null, $schema);
return $config;
}
}
// vim: et sw=4 sts=4
| <?php
class HTMLPurifier_HTML5Config
{
/**
* @param string|array|HTMLPurifier_Config $config
* @param HTMLPurifier_ConfigSchema $schema
* @return HTMLPurifier_Config
*/
public static function create($config = null, HTMLPurifier_ConfigSchema $schema = null)
{
if (!$schema instanceof HTMLPurifier_ConfigSchema) {
$schema = HTMLPurifier_ConfigSchema::makeFromSerial();
}
if ($config instanceof HTMLPurifier_Config) {
$configObj = $config;
} else {
$configObj = new HTMLPurifier_Config($schema);
$configObj->set('Core.Encoding', 'UTF-8');
$configObj->set('HTML.Doctype', 'HTML 4.01 Transitional');
if (is_string($config)) {
$configObj->loadIni($config);
} elseif (is_array($config)) {
$configObj->loadArray($config);
}
}
$def = $configObj->getHTMLDefinition(true); // this finalizes config
HTMLPurifier_HTML5Definition::setup($def);
return $configObj;
}
/**
* Creates a configuration object using the default config schema instance
*
* @return HTMLPurifier_Config
*/
public static function createDefault()
{
$schema = HTMLPurifier_ConfigSchema::instance();
$config = self::create(null, $schema);
return $config;
}
}
// vim: et sw=4 sts=4
|
Update double-width emoji list to improve "sbase print FILE" | from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
word_wrap=word_wrap,
)
return syntax
def display_markdown(code):
try:
markdown = Markdown(code)
console = Console()
console.print(markdown) # noqa
return True # Success
except Exception:
return False # Failure
def display_code(code):
try:
console = Console()
console.print(code) # noqa
return True # Success
except Exception:
return False # Failure
def fix_emoji_spacing(code):
try:
# Fix the display width of certain emojis that take up two spaces
double_width_emojis = [
"🗺️",
"🖼️",
"🗄️",
"⏺️",
"♻️",
"🗂️",
"🖥️",
"🕹️",
"🎞️",
"🎛️",
"🎖️",
"↘️",
"⬇️",
"↙️",
"⬅️",
"↖️",
"⬆️",
"↗️",
"➡️",
]
for emoji in double_width_emojis:
if emoji in code:
code = code.replace(emoji, emoji + " ")
except Exception:
pass
return code
| from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
word_wrap=word_wrap,
)
return syntax
def display_markdown(code):
try:
markdown = Markdown(code)
console = Console()
console.print(markdown) # noqa
return True # Success
except Exception:
return False # Failure
def display_code(code):
try:
console = Console()
console.print(code) # noqa
return True # Success
except Exception:
return False # Failure
def fix_emoji_spacing(code):
try:
# Fix the display width of certain emojis that take up two spaces
double_width_emojis = [
"🗺️",
"🖼️",
"🗄️",
"⏺️",
"♻️",
"🗂️",
"🖥️",
"🕹️",
"🎞️",
]
for emoji in double_width_emojis:
if emoji in code:
code = code.replace(emoji, emoji + " ")
except Exception:
pass
return code
|
Replace big alerts with inline alerts for register view | @extends('layout')
@section('body')
<div class="row">
<div class="column size-560 align-center">
<h1 class="spacing-bottom-large">Register</h1>
<div class="box spacing-small">
<form method="POST">
{{ csrf_field() }}
<label>Name</label>
<input type="text" name="name" />
@if ($errors->has('name'))
<div class="alert-inline">{{ $errors->first('name') }}</div>
@endif
<label>E-mail</label>
<input type="email" name="email" />
@if ($errors->has('email'))
<div class="alert-inline">{{ $errors->first('email') }}</div>
@endif
<label>Password</label>
<input type="password" name="password" />
@if ($errors->has('password'))
<div class="alert-inline">{{ $errors->first('password') }}</div>
@endif
<label>Currency</label>
<select name="currency">
@foreach ($currencies as $currency)
<option value="{{ $currency->id }}">{{ $currency->symbol }} · {{ $currency->name }}</option>
@endforeach
</select>
@if ($errors->has('currency_id'))
<div class="alert-inline">{{ $errors->first('currency_id') }}</div>
@endif
<div class="row tight">
<div class="column">
<input type="submit" value="Register" />
</div>
<div class="column align-middle">
<a href="/login">Log in</a>
</div>
</div>
</form>
</div>
</div>
</div>
@endsection
| @extends('layout')
@section('body')
<div class="row">
<div class="column size-560 align-center">
@if ($errors->any())
@foreach ($errors->all() as $error)
<div class="alert spacing-bottom-large">{{ $error }}</div>
@endforeach
@endif
<h1 class="spacing-bottom-large">Register</h1>
<div class="box spacing-small">
<form method="POST">
{{ csrf_field() }}
<label>Name</label>
<input type="text" name="name" />
<label>E-mail</label>
<input type="email" name="email" />
<label>Password</label>
<input type="password" name="password" />
<label>Currency</label>
<select name="currency">
@foreach ($currencies as $currency)
<option value="{{ $currency->id }}">{{ $currency->symbol }} · {{ $currency->name }}</option>
@endforeach
</select>
<div class="row tight">
<div class="column">
<input type="submit" value="Register" />
</div>
<div class="column align-middle">
<a href="/login">Log in</a>
</div>
</div>
</form>
</div>
</div>
</div>
@endsection
|
Fix name of an attribute and PEP8-ify | #! /usr/bin/env python3
""" A Word class
Originally obtained from the 'pharm' repository, but modified.
"""
class Word(object):
doc_id = None
sent_id = None
in_sent_idx = None
word = None
pos = None
ner = None
lemma = None
dep_path = None
dep_parent = None
sent_id = None
box = None
def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner,
_lemma, _dep_path, _dep_parent, _box):
self.doc_id = _doc_id
self.sent_id = _sent_id
self.in_sent_idx = _in_sent_idx
self.word = _word
self.pos = _pos
self.ner = _ner
self.dep_parent = _dep_parent
self.dep_path = _dep_path
self.box = _box
self.lemma = _lemma
# If do not do the following, outputting an Array in the language will
# crash
# XXX (Matteo) This was in the pharm code, not sure what it means
# I actually don't think this should go here.
# self.lemma = self.lemma.replace('"', "''")
# self.lemma = self.lemma.replace('\\', "_")
def __repr__(self):
return self.word
# Return the NER tag if different than 'O', otherwise return the lemma
def get_feature(self):
if self.ner == 'O':
return self.lemma
else:
return self.ner
| #! /usr/bin/env python3
""" A Word class
Originally obtained from the 'pharm' repository, but modified.
"""
class Word(object):
doc_id = None
sent_id = None
insent_idx = None
word = None
pos = None
ner = None
lemma = None
dep_path = None
dep_parent = None
sent_id = None
box = None
def __init__(self, _doc_id, _sent_id, _in_sent_idx, _word, _pos, _ner, _lemma, _dep_path, _dep_parent, _box):
self.doc_id = _doc_id
self.sent_id = _sent_id
self.in_sent_idx = _in_sent_idx
self.word = _word
self.pos = _pos
self.ner = _ner
self.dep_parent = _dep_parent
self.dep_path = _dep_path
self.box = _box
self.lemma = _lemma
# If do not do the following, outputting an Array in the language will crash
# XXX (Matteo) This was in the pharm code, not sure what it means
# I actually don't think this should go here.
#self.lemma = self.lemma.replace('"', "''")
#self.lemma = self.lemma.replace('\\', "_")
def __repr__(self):
return self.word
# Return the NER tag if different than 'O', otherwise return the lemma
def get_feature(self):
if self.ner == 'O':
return self.lemma
else:
return self.ner
|
Allow notifications to be send async | <?php declare(strict_types = 1);
namespace Cmnty\Push;
use Cmnty\Push\Crypto\Cryptograph;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
class Client implements PushClient
{
/**
* @var PushService
*/
private $pushService;
/**
* @var Client
*/
private $httpClient;
/**
* Constructor.
*
* @param PushService $pushService
* @param HttpClient $httpClient
* @param Cryptograph $cryptograph
*/
public function __construct(PushService $pushService, HttpClient $httpClient = null, Cryptograph $cryptograph = null)
{
$this->pushService = $pushService;
$this->httpClient = $httpClient ?: new HttpClient();
$this->cryptograph = $cryptograph ?: new Cryptograph();
}
/**
* Send a push notification.
*
* @param PushNotification $notification
* @param PushSubscription $subscription
*
* @return ResponseInterface
*/
public function pushNotification(PushNotification $notification, PushSubscription $subscription)
{
return $this->pushNotificationAsync($notification, $subscription)->wait();
}
/**
* Send a push notification asynchronously.
*
* @param PushNotification $notification
* @param PushSubscription $subscription
*
* @return PromiseInterface
*/
public function pushNotificationAsync(PushNotification $notification, PushSubscription $subscription)
{
$cipher = $this->cryptograph->encrypt($notification, $subscription);
$pushMessage = new Message($cipher, $subscription);
$request = $this->pushService->createRequest($pushMessage, $subscription);
$promise = $this->httpClient->sendAsync($request);
return $promise;
}
}
| <?php declare(strict_types = 1);
namespace Cmnty\Push;
use Cmnty\Push\Crypto\Cryptograph;
use GuzzleHttp\Client as HttpClient;
use Psr\Http\Message\ResponseInterface;
class Client implements PushClient
{
/**
* @var PushService
*/
private $pushService;
/**
* @var Client
*/
private $httpClient;
/**
* Constructor.
*
* @param PushService $pushService
* @param HttpClient $httpClient
* @param Cryptograph $cryptograph
*/
public function __construct(PushService $pushService, HttpClient $httpClient = null, Cryptograph $cryptograph = null)
{
$this->pushService = $pushService;
$this->httpClient = $httpClient ?: new HttpClient();
$this->cryptograph = $cryptograph ?: new Cryptograph();
}
/**
* Send a push notification.
*
* @param PushNotification $notification
* @param PushSubscription $subscription
*
* @param ResponseInterface
*/
public function pushNotification(PushNotification $notification, PushSubscription $subscription)
{
$cipher = $this->cryptograph->encrypt($notification, $subscription);
$pushMessage = new Message($cipher, $subscription);
$request = $this->pushService->createRequest($pushMessage, $subscription);
$response = $this->httpClient->send($request);
return $response;
}
}
|
Add parameters for dealing with SNAP output to Pathoscope sam module | from virtool.pathoscope import sam
def run(isolate_sam, host_sam, snap=False):
# Get a mapping score for every read mapped to the host genome
host_scores = sam.all_scores(host_sam, snap=snap)
# This list will contain the read_ids for all reads that had better mapping qualities against the host
# genome
skipped = list()
subtracted_list = list()
for line in isolate_sam:
# Parse the virus SAM file and get the alignment score for each line
if line[0] in ["#", "@"]:
subtracted_list.append(line)
continue
l = line.split("\t")
read_id = l[0]
virus_score = sam.get_score(l, snap=snap)
# Write each line from the virus SAM to a new file if its score is better against the virus
# than the host. Discard it if it isn't and add the read_id to the list of skipped reads
if virus_score is not None:
try:
if host_scores[read_id] >= virus_score:
subtracted_list.append(line)
else:
skipped.append(read_id)
except KeyError:
subtracted_list.append(line)
# Return the number of read mapping that were eliminated due to higher similarity to the host than to
# the intitially mapped virus
return subtracted_list, len((set(skipped))) | from virtool.pathoscope import sam
def run(isolate_sam, host_sam):
# Get a mapping score for every read mapped to the host genome
host_scores = sam.all_scores(host_sam)
# This list will contain the read_ids for all reads that had better mapping qualities against the host
# genome
skipped = list()
subtracted_list = list()
for line in isolate_sam:
# Parse the virus SAM file and get the alignment score for each line
if line[0] in ["#", "@"]:
subtracted_list.append(line)
continue
l = line.split("\t")
read_id = l[0]
virus_score = sam.high_score(l)
# Write each line from the virus SAM to a new file if its score is better against the virus
# than the host. Discard it if it isn't and add the read_id to the list of skipped reads
if virus_score is not None:
try:
if host_scores[read_id] >= virus_score:
subtracted_list.append(line)
else:
skipped.append(read_id)
except KeyError:
subtracted_list.append(line)
# Return the number of read mapping that were eliminated due to higher similarity to the host than to
# the intitially mapped virus
return subtracted_list, len((set(skipped))) |
Fix errors reported by php-cs-fixer | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Code\Generator;
use Zend\Code\Generator\AbstractMemberGenerator;
use Zend\Code\Generator\Exception\InvalidArgumentException;
class AbstractMemberGeneratorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AbstractMemberGenerator
*/
private $fixture;
protected function setUp()
{
$this->fixture = $this->getMockForAbstractClass('Zend\Code\Generator\AbstractMemberGenerator');
}
public function testSetFlagsWithArray()
{
$this->fixture->setFlags(
array(
AbstractMemberGenerator::FLAG_FINAL,
AbstractMemberGenerator::FLAG_PUBLIC,
)
);
$this->assertEquals(AbstractMemberGenerator::VISIBILITY_PUBLIC, $this->fixture->getVisibility());
$this->assertEquals(true, $this->fixture->isFinal());
}
/**
* @expectedException InvalidArgumentException
*/
public function testSetDocBlockThrowsExceptionWithInvalidType()
{
$this->fixture->setDocBlock(new \stdClass());
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Code\Generator;
use Zend\Code\Generator\AbstractMemberGenerator;
use Zend\Code\Generator\Exception\InvalidArgumentException;
class AbstractMemberGeneratorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AbstractMemberGenerator
*/
private $fixture;
protected function setUp()
{
$this->fixture = $this->getMockForAbstractClass('Zend\Code\Generator\AbstractMemberGenerator');
}
public function testSetFlagsWithArray()
{
$this->fixture->setFlags(
array(
AbstractMemberGenerator::FLAG_FINAL,
AbstractMemberGenerator::FLAG_PUBLIC,
)
);
$this->assertEquals(AbstractMemberGenerator::VISIBILITY_PUBLIC, $this->fixture->getVisibility());
$this->assertEquals(true, $this->fixture->isFinal());
}
/**
* @expectedException InvalidArgumentException
*/
public function testSetDocBlockThrowsExceptionWithInvalidType()
{
$this->fixture->setDocBlock(new \stdClass());
}
} |
Fix mono-extensions checkout for PR branches ('origin/pull/N/merge') | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = '[email protected]:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if 'pull/' in self.git_branch: # pull request
self.sh('%{git} checkout origin/master')
else:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
self.sh ('%{git} reset --hard')
except Exception as e:
self.popd ()
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = '[email protected]:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
self.sh ('%{git} reset --hard')
except Exception as e:
self.popd ()
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() |
Remove me from song title report send | # Django
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from openpyxl import Workbook
# First-Party
from api.models import Chart
class Command(BaseCommand):
help = "Command to sync database with BHS ."
def handle(self, *args, **options):
self.stdout.write("Sending song title report...")
wb = Workbook()
ws = wb.active
fieldnames = [
'title',
]
ws.append(fieldnames)
charts = Chart.objects.all().distinct(
'title'
).order_by(
'title'
)
for chart in charts:
title = chart.title.strip()
row = [
title,
]
ws.append(row)
wb.save('song_title_report.xlsx')
message = EmailMessage(
subject='Song Title Report',
body='Song Title Report Attached',
from_email='[email protected]',
to=['[email protected]', ]
)
message.attach_file('song_title_report.xlsx')
result = message.send()
if result == 1:
self.stdout.write("Sent.")
else:
self.stdout.write("Error. Not sent.")
| # Django
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from openpyxl import Workbook
# First-Party
from api.models import Chart
class Command(BaseCommand):
help = "Command to sync database with BHS ."
def handle(self, *args, **options):
self.stdout.write("Sending song title report...")
wb = Workbook()
ws = wb.active
fieldnames = [
'title',
]
ws.append(fieldnames)
charts = Chart.objects.all().distinct(
'title'
).order_by(
'title'
)
for chart in charts:
title = chart.title.strip()
row = [
title,
]
ws.append(row)
wb.save('song_title_report.xlsx')
message = EmailMessage(
subject='Song Title Report',
body='Song Title Report Attached',
from_email='[email protected]',
to=['[email protected]', '[email protected]']
)
message.attach_file('song_title_report.xlsx')
result = message.send()
if result == 1:
self.stdout.write("Sent.")
else:
self.stdout.write("Error. Not sent.")
|
Correct typo of 'injector' method name as 'inject'. | 'use strict';
var contextify = require('contextify');
var fs = require('fs');
var Context = function () {
var rawContext = contextify();
rawContext.globals = rawContext.getGlobal();
return {
run: function (source, filename) {
rawContext.run(source, filename);
},
runFile: function (fileName, callback) {
fs.readFile(
fileName,
'utf8',
function (err, data) {
if (err) {
callback(undefined, err);
}
else {
callback(rawContext.run(data, fileName));
}
}
);
},
hasAngular: function () {
return typeof rawContext.angular === 'object';
},
getAngular: function () {
return rawContext.angular;
},
module: function () {
return rawContext.angular.module.apply(
rawContext.angular.module,
arguments
);
},
injector: function (modules) {
return rawContext.angular.injector(modules);
},
dispose: function () {
rawContext.dispose();
}
};
};
exports.Context = Context;
| 'use strict';
var contextify = require('contextify');
var fs = require('fs');
var Context = function () {
var rawContext = contextify();
rawContext.globals = rawContext.getGlobal();
return {
run: function (source, filename) {
rawContext.run(source, filename);
},
runFile: function (fileName, callback) {
fs.readFile(
fileName,
'utf8',
function (err, data) {
if (err) {
callback(undefined, err);
}
else {
callback(rawContext.run(data, fileName));
}
}
);
},
hasAngular: function () {
return typeof rawContext.angular === 'object';
},
getAngular: function () {
return rawContext.angular;
},
module: function () {
return rawContext.angular.module.apply(
rawContext.angular.module,
arguments
);
},
injector: function (modules) {
return rawContext.angular.inject(modules);
},
dispose: function () {
rawContext.dispose();
}
};
};
exports.Context = Context;
|
Make the UI use the native look and feel of the system itself.. Don't hardcode it! | import guiLayer.startUpFrame;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.SQLException;
public class startUI extends Thread {
private static JPanel startupFrame;
public void run() {
try {
startUI();
} catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException | SQLException e) {
System.out.println("An error occured, oh shit.");
}
}
// Start up everything
public static void startUI() throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, SQLException {
// Setup the window decorator
JFrame.setDefaultLookAndFeelDecorated(true);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// Load the UI
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
final JFrame frame = new JFrame();
frame.setTitle("Morocco Holiday Center");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 660, 430);
frame.setVisible(true);
startupFrame = new JPanel();
startupFrame.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setContentPane(startupFrame);
startupFrame.setLayout(null);
startUpFrame startUpFrame = new startUpFrame(frame);
frame.setContentPane(startUpFrame);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} | import guiLayer.startUpFrame;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.SQLException;
public class startUI extends Thread {
private static JPanel startupFrame;
public void run() {
try {
startUI();
} catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException | SQLException e) {
System.out.println("An error occured, oh shit.");
}
}
// Start up everything
public static void startUI() throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, SQLException {
// Setup the window decorator
JFrame.setDefaultLookAndFeelDecorated(true);
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
// Load the UI
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
final JFrame frame = new JFrame();
frame.setTitle("Morocco Holiday Center");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 660, 430);
frame.setVisible(true);
startupFrame = new JPanel();
startupFrame.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setContentPane(startupFrame);
startupFrame.setLayout(null);
startUpFrame startUpFrame = new startUpFrame(frame);
frame.setContentPane(startUpFrame);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} |
Stop the loader in the finally to make sure it allways stops | 'use strict';
angular.module('app.controllers')
.controller('HomeController', ['$scope', '$state', 'fileModel', 'imageModel', function HomeController($scope, $state, fileModel, imageModel) {
// private
var _this = {
onCreate: function() {
if(imageModel.getImages().length === 0) {
$scope.loading(true);
imageModel.loadImages()
.finally(function() {
$scope.loading(false);
});
}
}
};
// public
$scope.model = imageModel;
/**
* Triggered when the user presses the upload button in the navigation bar.
*/
$scope.upload = function(file) {
if(file && file.length) {
// Set the file
fileModel.setFile(file[0]);
// Navigate to the upload state
$state.go('upload');
}
};
$scope.loadMore = function() {
if(!$scope._data.loading) {
$scope.loading(true);
imageModel.loadMore()
.finally(function() {
$scope.loading(false);
});
}
};
// Initialize the controller
_this.onCreate();
}]); | 'use strict';
angular.module('app.controllers')
.controller('HomeController', ['$scope', '$state', 'fileModel', 'imageModel', function HomeController($scope, $state, fileModel, imageModel) {
// private
var _this = {
onCreate: function() {
if(imageModel.getImages().length === 0) {
$scope.loading(true);
imageModel.loadImages()
.then(function() {
$scope.loading(false);
});
}
}
};
// public
$scope.model = imageModel;
/**
* Triggered when the user presses the upload button in the navigation bar.
*/
$scope.upload = function(file) {
if(file && file.length) {
// Set the file
fileModel.setFile(file[0]);
// Navigate to the upload state
$state.go('upload');
}
};
$scope.loadMore = function() {
if(!$scope._data.loading) {
$scope.loading(true);
imageModel.loadMore()
.then(function() {
$scope.loading(false);
});
}
};
// Initialize the controller
_this.onCreate();
}]); |
[FrameworkBundle] Fix BrowserKit assertions to make them compatible with Panther | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorAttributeValueSame extends Constraint
{
private $selector;
private $attribute;
private $expectedText;
public function __construct(string $selector, string $attribute, string $expectedText)
{
$this->selector = $selector;
$this->attribute = $attribute;
$this->expectedText = $expectedText;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has a node matching selector "%s" with attribute "%s" of value "%s"', $this->selector, $this->attribute, $this->expectedText);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
$crawler = $crawler->filter($this->selector);
if (!\count($crawler)) {
return false;
}
return $this->expectedText === trim($crawler->attr($this->attribute));
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return 'the Crawler '.$this->toString();
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorAttributeValueSame extends Constraint
{
private $selector;
private $attribute;
private $expectedText;
public function __construct(string $selector, string $attribute, string $expectedText)
{
$this->selector = $selector;
$this->attribute = $attribute;
$this->expectedText = $expectedText;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has a node matching selector "%s" with attribute "%s" of value "%s"', $this->selector, $this->attribute, $this->expectedText);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
$crawler = $crawler->filter($this->selector);
if (!\count($crawler)) {
return false;
}
return $this->expectedText === trim($crawler->getNode(0)->getAttribute($this->attribute));
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return 'the Crawler '.$this->toString();
}
}
|
Put workspaces in a top-level Firebase key | import values from 'lodash/values';
import {Promise} from 'es6-promise';
import appFirebase from '../services/appFirebase';
class FirebasePersistor {
constructor(user) {
this.user = user;
this.firebase = appFirebase.child(`workspaces/${user.id}`);
}
getCurrentProjectKey() {
return new Promise((resolve) => {
this.firebase.child('currentProjectKey').once('value', (snapshot) => {
resolve(snapshot.val());
});
});
}
setCurrentProjectKey(projectKey) {
return new Promise((resolve, reject) => {
this.firebase.child('currentProjectKey').set(projectKey, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
all() {
return new Promise((resolve) => {
this.firebase.child('projects').once('value', (projects) => {
resolve(values(projects.val() || {}));
});
});
}
load(projectKey) {
return new Promise((resolve) => {
this.firebase.child('projects').child(projectKey).
once('value', (snapshot) => {
resolve(snapshot.val());
});
});
}
save(project) {
return new Promise((resolve, reject) => {
this.firebase.child('projects').child(project.projectKey).
setWithPriority(project, -Date.now(), (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
}
export default FirebasePersistor;
| import values from 'lodash/values';
import {Promise} from 'es6-promise';
import appFirebase from '../services/appFirebase';
class FirebasePersistor {
constructor(user) {
this.user = user;
this.firebase = appFirebase.child(user.id);
}
getCurrentProjectKey() {
return new Promise((resolve) => {
this.firebase.child('currentProjectKey').once('value', (snapshot) => {
resolve(snapshot.val());
});
});
}
setCurrentProjectKey(projectKey) {
return new Promise((resolve, reject) => {
this.firebase.child('currentProjectKey').set(projectKey, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
all() {
return new Promise((resolve) => {
this.firebase.child('projects').once('value', (projects) => {
resolve(values(projects.val() || {}));
});
});
}
load(projectKey) {
return new Promise((resolve) => {
this.firebase.child('projects').child(projectKey).
once('value', (snapshot) => {
resolve(snapshot.val());
});
});
}
save(project) {
return new Promise((resolve, reject) => {
this.firebase.child('projects').child(project.projectKey).
setWithPriority(project, -Date.now(), (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
}
export default FirebasePersistor;
|
Add country code to country table. | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('country', function (Blueprint $table) {
$table->increments('id');
// Non-translated content
$table->string('url_name')->unique(); // Name in URL
$table->integer('image_id')->unsigned()->nullable(); // ID of image
$table->string('country_code')->unique(); // Name in URL
// Timestamps
$table->timestamps();
$table->softDeletes();
// When deleted image, set image_id to null
$table->foreign('image_id')->references('id')->on('image')->onDelete('set null');
});
Schema::create('country_translation', function (Blueprint $table) {
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->string('language')->index();
$table->boolean('complete');
// Translated content
$table->string('name');
$table->text('content');
$table->timestamps();
// Unique and foreign key
// When deleting country model, also delete all translation models
$table->unique(['country_id','language']);
$table->foreign('country_id')->references('id')->on('country')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('country_translation');
Schema::drop('country');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('country', function (Blueprint $table) {
$table->increments('id');
// Non-translated content
$table->string('url_name')->unique(); // Name in URL
$table->integer('image_id')->unsigned()->nullable(); // ID of image
// Timestamps
$table->timestamps();
$table->softDeletes();
// When deleted image, set image_id to null
$table->foreign('image_id')->references('id')->on('image')->onDelete('set null');
});
Schema::create('country_translation', function (Blueprint $table) {
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->string('language')->index();
$table->boolean('complete');
// Translated content
$table->string('name');
$table->text('content');
$table->timestamps();
// Unique and foreign key
// When deleting country model, also delete all translation models
$table->unique(['country_id','language']);
$table->foreign('country_id')->references('id')->on('country')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('country_translation');
Schema::drop('country');
}
}
|
Revert "avoid unnecesary call to onLoad"
This reverts commit 5a81300cb8a99c7428d9aeea26276d4415efcf64. | 'use strict';
/**
* @ngdoc function
* @name Pear2Pear.controller:NavbarTopCtrl
* @description
* # NavbarTop Ctrl
*/
angular.module('Pear2Pear')
.controller(
'NavbarTopCtrl', [
'SwellRTSession', '$scope',
function(SwellRTSession, $scope){
var getSharedMode = function(){
if ($scope.project){
return $scope.project.shareMode;
}
return null;
};
$scope.$on('$locationChangeStart', function(event) {
SwellRTSession.onLoad(function(){
if ($route.current.params.id){
pear.projects.find($route.current.params.id)
.then(function(proxy) {
$scope.project = proxy;
});
}
});
});
$scope.shareIcon = function shareIcon() {
switch (getSharedMode()) {
case 'link':
return 'fa-link';
case 'public':
return 'fa-globe';
default:
return '';
}
};
$scope.isShared = function(mode) {
if ($scope.project){
return getSharedMode() === mode;
}
return false;
};
$scope.setShared = function setShared(mode){
$scope.project.setShareMode(mode);
};
$scope.timestampProjectAccess = function(){
$scope.project.timestampProjectAccess();
};
}]);
| 'use strict';
/**
* @ngdoc function
* @name Pear2Pear.controller:NavbarTopCtrl
* @description
* # NavbarTop Ctrl
*/
angular.module('Pear2Pear')
.controller(
'NavbarTopCtrl', [
'SwellRTSession', '$scope',
function(SwellRTSession, $scope){
var getSharedMode = function(){
if ($scope.project){
return $scope.project.shareMode;
}
return null;
};
$scope.shareIcon = function shareIcon() {
switch (getSharedMode()) {
case 'link':
return 'fa-link';
case 'public':
return 'fa-globe';
default:
return '';
}
};
$scope.isShared = function(mode) {
if ($scope.project){
return getSharedMode() === mode;
}
return false;
};
$scope.setShared = function setShared(mode){
$scope.project.setShareMode(mode);
};
$scope.timestampProjectAccess = function(){
$scope.project.timestampProjectAccess();
};
}]);
|
Remove unnecessary import of logging | from rdflib import Graph
class BenchableGraph(object):
"""
Provides a convenient way to use a graph for benchmarks.
"""
def __init__(self, store, graph_id, store_config, graph_create=False):
"""
:param str store: Type of store to use.
:param str graph_id: The graph identifier.
:param store_config: Configuration to open the store.
:type store_config: str or tuple
:param bool graph_create: True to create the graph upon connecting.
"""
self.graph = Graph(store=store, identifier=graph_id)
self._graph_id = graph_id
self._store_config = store_config
self._graph_create = graph_create
def connect(self):
"""Connect to the store.
For some configurations, the connection is postponed until needed
(e.g. when doing a graph.query() or graph.add()).
This behaviour comes from RDFLib implementation of graph.open().
"""
return self.graph.open(configuration=self._store_config, create=self._graph_create)
def close(self, commit_pending_transaction=True):
"""Close a connection to a store.
:param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise.
.. note::
The graph.close() method is not implemented for SPARQL Store in RDFLib
"""
self.graph.close(commit_pending_transaction=commit_pending_transaction)
| import logging
from rdflib import Graph
class BenchableGraph(object):
"""
Provides a convenient way to use a graph for benchmarks.
"""
def __init__(self, store, graph_id, store_config, graph_create=False):
"""
:param str store: Type of store to use.
:param str graph_id: The graph identifier.
:param store_config: Configuration to open the store.
:type store_config: str or tuple
:param bool graph_create: True to create the graph upon connecting.
"""
self.graph = Graph(store=store, identifier=graph_id)
self._graph_id = graph_id
self._store_config = store_config
self._graph_create = graph_create
def connect(self):
"""Connect to the store.
For some configurations, the connection is postponed until needed
(e.g. when doing a graph.query() or graph.add()).
This behaviour comes from RDFLib implementation of graph.open().
"""
return self.graph.open(configuration=self._store_config, create=self._graph_create)
def close(self, commit_pending_transaction=True):
"""Close a connection to a store.
:param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise.
.. note::
The graph.close() method is not implemented for SPARQL Store in RDFLib
"""
self.graph.close(commit_pending_transaction=commit_pending_transaction)
|
Bump version: 1.0.0 -> 1.1.0 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
try:
from setuptools import setup, find_packages, Command
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages, Command
description = 'Generate version strings based on semantic versioning rules.'
long_description = str(open('README.rst', 'rb').read())
setup(name='versionbump',
version='1.1.0',
license='MIT',
author='Fabian Kochem',
url='https://github.com/vortec/versionbump',
description=description,
long_description=long_description,
packages=find_packages(),
install_requires=[
],
entry_points={
'console_scripts': [
'versionbump = versionbump.command_line:main',
]
},
classifiers=(
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Build Tools',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities'
),
)
| # -*- coding: utf-8 -*-
#!/usr/bin/env python
try:
from setuptools import setup, find_packages, Command
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages, Command
description = 'Generate version strings based on semantic versioning rules.'
long_description = str(open('README.rst', 'rb').read())
setup(name='versionbump',
version='1.0.0',
license='MIT',
author='Fabian Kochem',
url='https://github.com/vortec/versionbump',
description=description,
long_description=long_description,
packages=find_packages(),
install_requires=[
],
entry_points={
'console_scripts': [
'versionbump = versionbump.command_line:main',
]
},
classifiers=(
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Build Tools',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities'
),
)
|
Undo functionality. In case you typed the wrong number... | import React from 'react';
import styles from "../css/App.css";
export class PlayerScoreComponent extends React.Component {
/**
* Constructor
* @param props
*/
constructor(props) {
super(props);
this.state = {
score: 0,
history: []
}
}
updateScore = () => {
let score = parseInt(this.refs.score.value);
if (Number.isInteger(score)) {
this.setState({score: this.state.score + score});
let history = this.state.history;
history.push(score);
this.setState({history: history});
}
};
undo = () => {
let lastValue = this.state.history.slice(-1)[0];
if (Number.isInteger(parseInt(lastValue))) {
this.state.history.pop();
this.setState({score: this.state.score - lastValue});
}
}
render() {
return (
<div key={Math.random()}>
<div className={styles["user-score"] + " input-group"}>
<span className="input-group-btn">
<button className="btn btn-warning" type="button"
onClick={score => this.undo()}>Undo</button>
</span>
<input type="number" className="form-control" ref="score" />
<span className="input-group-btn">
<button className="btn btn-success" type="button"
onClick={score => this.updateScore()}>{this.props.player.name} - {this.state.score}</button>
</span>
</div>
</div>
);
}
}
| import React from 'react';
import styles from "../css/App.css";
export class PlayerScoreComponent extends React.Component {
/**
* Constructor
* @param props
*/
constructor(props) {
super(props);
this.state = {
score: 0
}
}
updateScore = () => {
let score = parseInt(this.refs.score.value);
if (Number.isInteger(score)) {
this.setState({score: this.state.score + score});
}
};
render() {
return (
<div key={Math.random()}>
<div className={styles["user-score"] + " input-group"}>
<input type="number" className="form-control" ref="score" />
<span className="input-group-btn">
<button className="btn btn-default" type="button"
onClick={score => this.updateScore()}>{this.props.player.name} - {this.state.score}</button>
</span>
</div>
</div>
);
}
}
|
Fix SimpleXMLElement::asXML() can also be of type false | <?php
namespace CfdiUtils\Nodes;
use DOMDocument;
use DOMElement;
use SimpleXMLElement;
class XmlNodeUtils
{
public static function nodeToXmlElement(NodeInterface $node, DOMDocument $document = null): DOMElement
{
return (new XmlNodeExporter($document))->export($node);
}
public static function nodeToXmlString(NodeInterface $node, DOMDocument $document = null): string
{
$element = static::nodeToXmlElement($node, $document);
return $element->ownerDocument->saveXML($element);
}
public static function nodeToSimpleXmlElement(NodeInterface $node, DOMDocument $document = null): SimpleXMLElement
{
$element = static::nodeToXmlElement($node, $document);
$simpleXmlElement = simplexml_import_dom($element);
if (false === $simpleXmlElement) {
throw new \InvalidArgumentException('Cannot convert to SimpleXmlElement');
}
return $simpleXmlElement;
}
public static function nodeFromXmlElement(DOMElement $element): NodeInterface
{
return (new XmlNodeImporter())->import($element);
}
public static function nodeFromXmlString(string $content): NodeInterface
{
$document = new DOMDocument();
$document->formatOutput = true;
$document->preserveWhiteSpace = false;
$document->loadXML($content);
return static::nodeFromXmlElement($document->documentElement);
}
public static function nodeFromSimpleXmlElement(SimpleXMLElement $element): NodeInterface
{
return static::nodeFromXmlString((string) $element->asXML());
}
}
| <?php
namespace CfdiUtils\Nodes;
use DOMDocument;
use DOMElement;
use SimpleXMLElement;
class XmlNodeUtils
{
public static function nodeToXmlElement(NodeInterface $node, DOMDocument $document = null): DOMElement
{
return (new XmlNodeExporter($document))->export($node);
}
public static function nodeToXmlString(NodeInterface $node, DOMDocument $document = null): string
{
$element = static::nodeToXmlElement($node, $document);
return $element->ownerDocument->saveXML($element);
}
public static function nodeToSimpleXmlElement(NodeInterface $node, DOMDocument $document = null): SimpleXMLElement
{
$element = static::nodeToXmlElement($node, $document);
$simpleXmlElement = simplexml_import_dom($element);
if (false === $simpleXmlElement) {
throw new \InvalidArgumentException('Cannot convert to SimpleXmlElement');
}
return $simpleXmlElement;
}
public static function nodeFromXmlElement(DOMElement $element): NodeInterface
{
return (new XmlNodeImporter())->import($element);
}
public static function nodeFromXmlString(string $content): NodeInterface
{
$document = new DOMDocument();
$document->formatOutput = true;
$document->preserveWhiteSpace = false;
$document->loadXML($content);
return static::nodeFromXmlElement($document->documentElement);
}
public static function nodeFromSimpleXmlElement(SimpleXMLElement $element): NodeInterface
{
return static::nodeFromXmlString($element->asXML());
}
}
|
Allow overridable message formatting in the RSS bot. |
try:
from feedparser import parse
except ImportError:
parse = None
from gnotty.bots import events
class RSSMixin(object):
"""
Mixin for bots that consume RSS feeds and post them to the
channel. Feeds are defined by the ``feeds`` keyword arg to
``__init__``, and should contain a sequence of RSS feed URLs.
Requires the ``feedparser`` library to be installed.
"""
def __init__(self, *args, **kwargs):
if parse is None:
from warnings import warn
warn("RSSMixin requires feedparser installed")
self.feeds = kwargs.pop("feeds", [])
self.feed_items = set()
# Consume initial feed items without posting them.
self.parse_feeds(message_channel=False)
super(RSSMixin, self).__init__(*args, **kwargs)
@events.on("timer", seconds=60)
def parse_feeds(self, message_channel=True):
"""
Iterates through each of the feed URLs, parses their items, and
sends any items to the channel that have not been previously
been parsed.
"""
if parse:
for feed_url in self.feeds:
feed = parse(feed_url)
for item in feed.entries:
if item["id"] not in self.feed_items:
self.feed_items.add(item["id"])
if message_channel:
message = self.format_item_message(feed, item)
self.message_channel(message)
return
def format_item_message(self, feed, item):
item["feed_title"] = feed.feed.title or feed.url
return "%(title)s: %(id)s (via %(feed_title)s)" % item
|
try:
from feedparser import parse
except ImportError:
parse = None
from gnotty.bots import events
class RSSMixin(object):
"""
Mixin for bots that consume RSS feeds and post them to the
channel. Feeds are defined by the ``feeds`` keyword arg to
``__init__``, and should contain a sequence of RSS feed URLs.
Requires the ``feedparser`` library to be installed.
"""
def __init__(self, *args, **kwargs):
if parse is None:
from warnings import warn
warn("RSSMixin requires feedparser installed")
self.feeds = kwargs.pop("feeds", [])
self.feed_items = set()
# Consume initial feed items without posting them.
self.parse_feeds(message_channel=False)
super(RSSMixin, self).__init__(*args, **kwargs)
@events.on("timer", seconds=60)
def parse_feeds(self, message_channel=True):
"""
Iterates through each of the feed URLs, parses their items, and
sends any items to the channel that have not been previously
been parsed.
"""
if parse:
for feed in self.feeds:
for item in parse(feed).entries:
if item["id"] not in self.feed_items:
self.feed_items.add(item["id"])
if message_channel:
self.message_channel("%(title)s: %(id)s" % item)
return
|
Rename const to be more obvious | import glob from 'glob';
import path from 'path';
import immutable from 'immutable';
import merger from './merger';
function loadLanguages() {
const files = glob
.sync('src/client/*/i18n/*.js')
.map(file => {
const translations = require(path.join(__dirname, '../../../', file));
const tokens = file.match(/([^/]+)\/i18n\/([^/]+).js$/);
return {
language: tokens[2],
feature: tokens[1],
translations
};
});
const messages = {};
const locales = [];
files.forEach(({language, feature, translations}) => {
if (!messages[language]) messages[language] = {};
messages[language][feature] = translations;
if (locales.indexOf(language) < 0) locales.push(language);
});
return {
formats: {},
locales,
messages
};
}
function extractLocaleFromReq(req, locales) {
return req.acceptsLanguages(locales);
}
export default function middleware({defaultLocale, getLocaleFromRequest = extractLocaleFromReq}) {
const {locales, messages} = loadLanguages();
return (req, res, next) => {
const userLocale = getLocaleFromRequest(req, locales);
const defaultMessages = messages[defaultLocale];
const userMessages = messages[userLocale];
req.i18n = {
locale,
messages: defaultLocale !== userLocale
? immutable.fromJS(defaultMessages).mergeWith(merger, userMessages)
: defaultMessages
};
next();
};
}
| import glob from 'glob';
import path from 'path';
import immutable from 'immutable';
import merger from './merger';
function loadLanguages() {
const files = glob
.sync('src/client/*/i18n/*.js')
.map(file => {
const translations = require(path.join(__dirname, '../../../', file));
const tokens = file.match(/([^/]+)\/i18n\/([^/]+).js$/);
return {
language: tokens[2],
feature: tokens[1],
translations
};
});
const messages = {};
const locales = [];
files.forEach(({language, feature, translations}) => {
if (!messages[language]) messages[language] = {};
messages[language][feature] = translations;
if (locales.indexOf(language) < 0) locales.push(language);
});
return {
formats: {},
locales,
messages
};
}
function extractLocaleFromReq(req, locales) {
return req.acceptsLanguages(locales);
}
export default function middleware({defaultLocale, getLocaleFromRequest = extractLocaleFromReq}) {
const {locales, messages} = loadLanguages();
return (req, res, next) => {
const locale = getLocaleFromRequest(req, locales);
const defaultMessages = messages[defaultLocale];
const localeMessages = messages[locale];
req.i18n = {
locale,
messages: defaultLocale !== locale
? immutable.fromJS(defaultMessages).mergeWith(merger, localeMessages)
: defaultMessages
};
next();
};
}
|
Fix var. In strict mode | /*global define */
define(['jquery'], function($) {
'use strict';
// Loads the specified JSON config file and returns a promise
// to tell you when it's done.
return function(url) {
var loaded = $.Deferred();
// Uses a HEAD request to figure out if
// the file exists so it doesn't load it
// and trigger a fail
var ajax = $.ajax(url, {
type: 'HEAD',
dataType: 'text'
});
ajax.then(function(result) {
console.log(result);
return $.ajax(url, {
type: 'GET',
dataType: 'text'
});
}, function(jqXHR, textStatus, errorThrown) {
console.log('No config, empty file, or bad json. Error: ' + textStatus);
// It's ok if there's no config file
// just return an empty object.
if (errorThrown === 'Not Found') {
loaded.resolve({});
} else {
loaded.reject(jqXHR);
}
}).done(function(responseText, textStatus) {
console.log('Loaded Config File ' + textStatus);
try {
var jsonResult = JSON.parse(responseText);
loaded.resolve(jsonResult);
} catch (e) {
loaded.reject('Unable to parse config.json! Please contact Calamari Admin');
}
});
return loaded.promise();
};
});
| /*global define */
define(['jquery'], function($) {
'use strict';
// Loads the specified JSON config file and returns a promise
// to tell you when it's done.
return function(url) {
var loaded = $.Deferred();
// Uses a HEAD request to figure out if
// the file exists so it doesn't load it
// and trigger a fail
var ajax = $.ajax(url, {
type: 'HEAD',
dataType: 'text'
});
ajax.then(function(result) {
console.log(result);
return $.ajax(url, {
type: 'GET',
dataType: 'text'
});
}, function(jqXHR, textStatus, errorThrown) {
console.log('No config, empty file, or bad json. Error: ' + textStatus);
// It's ok if there's no config file
// just return an empty object.
if (errorThrown === 'Not Found') {
loaded.resolve({});
} else {
loaded.reject(jqXHR);
}
}).done(function(result, textStatus) {
console.log('Loaded Config File ' + textStatus);
try {
jsonResult = JSON.parse(result);
loaded.resolve(jsonResult);
} catch (e) {
loaded.reject('Unable to parse config.json! Please contact Calamari Admin');
}
});
return loaded.promise();
};
});
|
Add error return strings to the NHS number validator | package uk.ac.ox.ndm.grails.utils.validator;
import com.google.common.base.Strings;
/**
* @since 14/08/2015
*/
public class NhsNumberValidator implements Validator<String> {
public Object isValid(String nhsNumberStr) {
if (!Strings.isNullOrEmpty(nhsNumberStr)) {
nhsNumberStr = nhsNumberStr.replaceAll(" ", "");
if (nhsNumberStr.length() != 10) {
return "validation.nhsnumber.wronglength";
}
try {
int checkDigit = 0;
int[] nhsNumber = new int[nhsNumberStr.length()];
for (int i = 0; i < nhsNumberStr.length(); i++) {
nhsNumber[i] = Integer.parseInt(nhsNumberStr.charAt(i) + "");
}
if (nhsNumber.length == 10) {
for (int i = 0; i <= 8; i++) {
checkDigit += nhsNumber[i] * (10 - i);
}
checkDigit = (11 - (checkDigit % 11));
if (checkDigit == 11) checkDigit = 0;
if (checkDigit != 10)
return checkDigit == nhsNumber[9] ? true : "validation.nhsnumber.invalid";
}
} catch (NumberFormatException ignored) {
return "validation.nhsnumber.not.numeric";
}
}
return "validation.empty";
}
}
| package uk.ac.ox.ndm.grails.utils.validator;
import com.google.common.base.Strings;
/**
* @since 14/08/2015
*/
public class NhsNumberValidator implements Validator<String> {
public Object isValid(String nhsNumberStr) {
if (!Strings.isNullOrEmpty(nhsNumberStr)) {
nhsNumberStr = nhsNumberStr.replaceAll(" ", "");
if (nhsNumberStr.length() != 10) {
return "validation.nhsnumber.wronglength";
}
try {
int checkDigit = 0;
int[] nhsNumber = new int[nhsNumberStr.length()];
for (int i = 0; i < nhsNumberStr.length(); i++) {
nhsNumber[i] = Integer.parseInt(nhsNumberStr.charAt(i) + "");
}
if (nhsNumber.length == 10) {
for (int i = 0; i <= 8; i++) {
checkDigit += nhsNumber[i] * (10 - i);
}
checkDigit = (11 - (checkDigit % 11));
if (checkDigit == 11) checkDigit = 0;
if (checkDigit != 10) return checkDigit == nhsNumber[9];
}
} catch (NumberFormatException ignored) {
// Just ignore this as we will return false
}
}
return "validation.empty";
}
}
|
Fix issue where server error thrown if user does not have aecData | AECData = new Mongo.Collection('aecData');
Meteor.methods({
profileInsert: function (profileData) {
check(Meteor.userId(), String);
//check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
familyName: String,
federalDivision: String,
stateDistrict: String,
localCouncil: String,
locality: String,
ward: String,
stateCode: String
});
var user = Meteor.user();
fullProfile = _.extend(profileData, {
userId: user._id,
creationDate: new Date(),
});
if (Meteor.user().profile) {throw new Meteor.Error('invalid', 'You\'ve already registered to vote')
} else {
var fullProfileId = AECData.insert(fullProfile);
Meteor.users.update(user, {
$set:{
profile: {
aecData: fullProfileId
}
}
})
}
},
profileData: function (data) {
if (Meteor.user().profile.aecData) {
var id = Meteor.user().profile.aecData;
return AECData.findOne({_id:id}, {})[data];
} else {throw new Meteor.Error('invalid', 'AEC Data Not Found');};
}
}) | AECData = new Mongo.Collection('aecData');
Meteor.methods({
profileInsert: function (profileData) {
check(Meteor.userId(), String);
check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
familyName: String,
federalDivision: String,
stateDistrict: String,
localCouncil: String,
locality: String,
ward: String,
stateCode: String
});
var user = Meteor.user();
fullProfile = _.extend(profileData, {
userId: user._id,
creationDate: new Date(),
});
var fullProfileId = AECData.insert(fullProfile);
Meteor.users.update(user, {
$set:{
profile: {
aecData: fullProfileId
}
}
})},
profileData: function (data) {
if (Meteor.user().profile.aecData) {
var id = Meteor.user().profile.aecData;
return AECData.findOne({_id:id}, {})[data];
} else {throw new Meteor.Error('invalid', 'AEC Data Not Found');};
}
}) |
Fix a bug with incorrect param | @extends('layouts._one_column')
@section('content')
<section class="auth">
<h1>We're going to create an account with this information.</h1>
<div class="user">
{{ ReCaptcha::getScript() }}
{{ Form::open() }}
<div class="bio">
<p><img src="{{ $githubUser['image_url'] }}"/></p>
<p>
{{ Form::label('name') }}
{{ Form::text('name', Input::old('name', $githubUser['name'])) }}
</p>
@if ($errors->has('name'))
<p>{{ $errors->first('name') }}</p>
@endif
<p>
{{ Form::label('email') }}
{{ Form::email('email', Input::old('email', $githubUser['email'])) }}
</p>
@if ($errors->has('email'))
<p>{{ $errors->first('email') }}</p>
@endif
<p>{{ ReCaptcha::getWidget() }}</p>
@if ($errors->has('g-recaptcha-response'))
<p>Please fill in the captcha field correctly.</p>
@endif
{{ Form::submit('Create My Laravel.IO Account', ['class' => 'button']) }}
</div>
{{ Form::close() }}
</div>
</section>
@stop | @extends('layouts._one_column')
@section('content')
<section class="auth">
<h1>We're going to create an account with this information.</h1>
<div class="user">
{{ ReCaptcha::getScript() }}
{{ Form::open() }}
<div class="bio">
<p><img src="{{ $githubUser['image_url'] }}"/></p>
<p>
{{ Form::label('name') }}
{{ Form::text('name', Input::old('email', $githubUser['name'])) }}
</p>
@if ($errors->has('name'))
<p>{{ $errors->first('name') }}</p>
@endif
<p>
{{ Form::label('email') }}
{{ Form::email('email', Input::old('email', $githubUser['email'])) }}
</p>
@if ($errors->has('email'))
<p>{{ $errors->first('email') }}</p>
@endif
<p>{{ ReCaptcha::getWidget() }}</p>
@if ($errors->has('g-recaptcha-response'))
<p>Please fill in the captcha field correctly.</p>
@endif
{{ Form::submit('Create My Laravel.IO Account', ['class' => 'button']) }}
</div>
{{ Form::close() }}
</div>
</section>
@stop |
Replace inline array copy with Arrays.clone | package org.bouncycastle.bcpg;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
/**
* Generic literal data packet.
*/
public class LiteralDataPacket
extends InputStreamPacket
{
int format;
byte[] fileName;
long modDate;
LiteralDataPacket(
BCPGInputStream in)
throws IOException
{
super(in);
format = in.read();
int l = in.read();
fileName = new byte[l];
for (int i = 0; i != fileName.length; i++)
{
fileName[i] = (byte)in.read();
}
modDate = ((long)in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read();
}
/**
* Return the format tag of the data packet.
*/
public int getFormat()
{
return format;
}
/**
* Return the modification time for the file (milliseconds at second level precision).
*/
public long getModificationTime()
{
return modDate * 1000L;
}
/**
* Return the file name associated with the data packet.
*/
public String getFileName()
{
return Strings.fromUTF8ByteArray(fileName);
}
/**
* Return the file name as an uninterpreted byte array.
*/
public byte[] getRawFileName()
{
return Arrays.clone(fileName);
}
}
| package org.bouncycastle.bcpg;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
/**
* Generic literal data packet.
*/
public class LiteralDataPacket
extends InputStreamPacket
{
int format;
byte[] fileName;
long modDate;
LiteralDataPacket(
BCPGInputStream in)
throws IOException
{
super(in);
format = in.read();
int l = in.read();
fileName = new byte[l];
for (int i = 0; i != fileName.length; i++)
{
fileName[i] = (byte)in.read();
}
modDate = ((long)in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read();
}
/**
* Return the format tag of the data packet.
*/
public int getFormat()
{
return format;
}
/**
* Return the modification time for the file (milliseconds at second level precision).
*/
public long getModificationTime()
{
return modDate * 1000L;
}
/**
* Return the file name associated with the data packet.
*/
public String getFileName()
{
return Strings.fromUTF8ByteArray(fileName);
}
/**
* Return the file name as an uninterpreted byte array.
*/
public byte[] getRawFileName()
{
byte[] tmp = new byte[fileName.length];
for (int i = 0; i != tmp.length; i++)
{
tmp[i] = fileName[i];
}
return tmp;
}
}
|
Clean up some PEP8 stuff | from __future__ import absolute_import
# Import python libs
from StringIO import StringIO
# Import salt libs
from salt.exceptions import SaltRenderError
import salt.utils.templates
def render(template_file, env='', sls='', argline='',
context=None, tmplpath=None, **kws):
'''
Render the template_file, passing the functions and grains into the
Jinja rendering system.
:rtype: string
'''
from_str = argline == '-s'
if not from_str and argline:
raise SaltRenderError(
'Unknown renderer option: {opt}'.format(opt=argline)
)
tmp_data = salt.utils.templates.JINJA(template_file,
to_str=True,
salt=__salt__,
grains=__grains__,
opts=__opts__,
pillar=__pillar__,
env=env,
sls=sls,
context=context,
tmplpath=tmplpath,
**kws)
if not tmp_data.get('result', False):
raise SaltRenderError(
tmp_data.get('data', 'Unknown render error in jinja renderer')
)
return StringIO(tmp_data['data'])
| from __future__ import absolute_import
# Import python libs
from StringIO import StringIO
# Import salt libs
from salt.exceptions import SaltRenderError
import salt.utils.templates
def render(template_file, env='', sls='', argline='',
context=None, tmplpath=None, **kws):
'''
Render the template_file, passing the functions and grains into the
Jinja rendering system.
:rtype: string
'''
from_str = argline=='-s'
if not from_str and argline:
raise SaltRenderError(
'Unknown renderer option: {opt}'.format(opt=argline)
)
tmp_data = salt.utils.templates.JINJA(template_file, to_str=True,
salt=__salt__,
grains=__grains__,
opts=__opts__,
pillar=__pillar__,
env=env,
sls=sls,
context=context,
tmplpath=tmplpath,
**kws)
if not tmp_data.get('result', False):
raise SaltRenderError(tmp_data.get('data',
'Unknown render error in jinja renderer'))
return StringIO(tmp_data['data'])
|
Set main method to also run gui for testing. |
import ClassLibrary.CmdRepl;
import GUI.ConcordanatorWindow;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Concordanator{
public static void main(String[] args) {
ConcordanatorWindow window = new ConcordanatorWindow();
window.setVisible(true);
// Start the repl from here
CmdRepl repl = new CmdRepl();
try {
if (args.length != 0 && args[0].equals("gui")) {
// Launch the gui from here
//ConcordanatorWindow window = new ConcordanatorWindow();
window.setVisible(true);
} else if (args.length == 1 || args.length == 0) {
repl.startRepl("");
} else {
// Print out usage to term
}
} catch (IOException ex) {
Logger.getLogger(Concordanator.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
import ClassLibrary.CmdRepl;
import GUI.ConcordanatorWindow;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Concordanator{
public static void main(String[] args) {
//ConcordanatorWindow window = new ConcordanatorWindow();
//window.setVisible(true);
// Start the repl from here
CmdRepl repl = new CmdRepl();
try {
if (args.length != 0 && args[0].equals("gui")) {
// Launch the gui from here
ConcordanatorWindow window = new ConcordanatorWindow();
window.setVisible(true);
} else if (args.length == 1 || args.length == 0) {
repl.startRepl("");
} else {
// Print out usage to term
}
} catch (IOException ex) {
Logger.getLogger(Concordanator.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
Fix bugs from thrown exceptions
In the drag and drop functions, variables are checked if null before being worked on. This stops exceptions from being thrown and further bugs from happening. | /* Source file for graphical functionality for Gear Bag project */
function dragging() {
$$('.device_block').addEvent('mousedown', function(event) {
event.stop();
console.log("boom");
// This refers to element with 'device_block' class
var device = this;
var clone = device.clone().setStyles(device.getCoordinates()).setStyles({
opacity: 0.9,
position: 'absolute'
}).inject(document.body);
var drag = new Drag.Move(clone, {
droppables: $('drop_device'),
onDrop: function(dragging, drop) {
dragging.destroy();
if (drop != null && !drop.contains(device)) {
device.clone().inject(drop);
}
if (drop)
drop.tween('background-color', '#E0E0E0');
if (drop && drop.contains($('drop_inner')))
$('drop_inner').destroy();
},
onEnter: function(dragging, drop) {
drop.tween('background-color', '#98B5C1');
},
onLeave: function(dragging, drop) {
drop.tween('background-color', '#E0E0E0');
},
onCancel: function(dragging) {
dragging.destroy();
}
});
drag.start(event);
});
}
| /* Source file for graphical functionality for Gear Bag project */
function dragging() {
$$('.device_block').addEvent('mousedown', function(event) {
event.stop();
console.log("boom");
// This refers to element with 'device_block' class
var device = this;
var clone = device.clone().setStyles(device.getCoordinates()).setStyles({
opacity: 0.9,
position: 'absolute'
}).inject(document.body);
var drag = new Drag.Move(clone, {
droppables: $('drop_device'),
onDrop: function(dragging, drop) {
dragging.destroy();
if (drop != null && !drop.contains(device)) {
device.clone().inject(drop);
}
drop.tween('background-color', '#E0E0E0');
if (drop.contains($('drop_inner')))
$('drop_inner').destroy();
},
onEnter: function(dragging, drop) {
drop.tween('background-color', '#98B5C1');
},
onLeave: function(dragging, drop) {
drop.tween('background-color', '#E0E0E0');
},
onCancel: function(dragging) {
dragging.destroy();
}
});
drag.start(event);
});
}
|
Handle missing route definition with meaningful error message | !function() {
'use strict';
angular.module('crumble', ['ngRoute'])
.factory('crumble', function ($location, $route, $interpolate) {
var crumble = {
trail: [],
context: {},
};
crumble.update = function (context) {
crumble.context = context || crumble.context;
crumble.trail = build($location.path());
};
crumble.getParent = function (path) {
return path.replace(/[^\/]*\/?$/, '');
};
crumble.getCrumb = function (path) {
var route = crumble.getRoute(path);
if (!route) throw new Error('Could not find matching route for path "' + path + '"');
return {
path: $interpolate(path)(crumble.context),
label: $interpolate(route.label)(crumble.context),
};
};
crumble.getRoute = function (path) {
var route = find($route.routes, function (route) {
return route.regexp && route.regexp.test(path);
});
return (route && route.redirectTo) ? $route.routes[route.redirectTo] : route;
};
function build(path) {
return !path ? [] : build(crumble.getParent(path)).concat(crumble.getCrumb(path));
}
function find(obj, fn, thisArg) {
for (var key in obj) {
if (obj.hasOwnProperty(key) && fn.call(thisArg, obj[key], key, obj)) {
return obj[key];
}
}
}
return crumble;
});
}();
| !function() {
'use strict';
angular.module('crumble', ['ngRoute'])
.factory('crumble', function ($location, $route, $interpolate) {
var crumble = {
trail: [],
context: {},
};
crumble.update = function (context) {
crumble.context = context || crumble.context;
crumble.trail = build($location.path());
};
crumble.getParent = function (path) {
return path.replace(/[^\/]*\/?$/, '');
};
crumble.getCrumb = function (path) {
var route = crumble.getRoute(path);
return {
path: $interpolate(path)(crumble.context),
label: $interpolate(route.label)(crumble.context),
};
};
crumble.getRoute = function (path) {
var route = find($route.routes, function (route) {
return route.regexp && route.regexp.test(path);
});
return route.redirectTo ? $route.routes[route.redirectTo] : route;
};
function build(path) {
return !path ? [] : build(crumble.getParent(path)).concat(crumble.getCrumb(path));
}
function find(obj, fn, thisArg) {
for (var key in obj) {
if (obj.hasOwnProperty(key) && fn.call(thisArg, obj[key], key, obj)) {
return obj[key];
}
}
}
return crumble;
});
}();
|
Allow overriding database name with DBNAME environment variable | from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': environ.get("DBNAME", "taarifa_backend")}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
| from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
|
Fix minor issue in REST controller | <?php
namespace CuteControllers\Base;
class Rest extends Controller
{
public function route()
{
$method = strtolower($this->request->method) . '_';
if ($this->request->file_name === '') {
$method .= 'index';
} else {
$method .= $this->request->file_name;
}
if (method_exists($this, $method)) {
$reflection = new \ReflectionMethod($this, $method);
if (!$reflection->isPublic()) {
throw new \CuteControllers\HttpError(403);
}
$this->generate_response($this->$method());
} else {
throw new \CuteControllers\HttpError(404);
}
}
public function generate_response($response)
{
if (!isset($response)) {
return;
}
switch($this->request->file_ext) {
case 'txt':
header("Content-type: text/plain");
echo $response;
break;
case 'json':
header("Content-type: application/json");
echo json_encode($response);
break;
case 'jsonp':
header("Content-type: text/javascript");
echo $this->request->request('callback') . '(' . json_encode($response) . ');';
break;
case 'html':
default:
header("Content-type: text/html");
echo $response;
break;
case 'serialized':
case 'php':
header("Content-type: application/vnd.php.serialized");
echo serialize($response);
break;
}
}
}
| <?php
namespace CuteControllers\Base;
class Rest extends Controller
{
public function route()
{
$method = strtolower($this->request->method) . '_';
if ($this->request->file_name === '') {
$method .= 'index';
} else {
$method .= $this->request->file_name;
}
if (method_exists($this, $method)) {
$reflection = new \ReflectionMethod($this, $method);
if (!$reflection->isPublic()) {
throw new \CuteControllers\HttpError(403);
}
$this->generate_response($this->$method());
} else {
throw new \CuteControllers\HttpError(404);
}
}
public function generate_response($response)
{
if (!isset($response)) {
return;
}
switch($this->request->file_ext || 'html') {
case 'txt':
header("Content-type: text/plain");
echo $response;
break;
case 'json':
header("Content-type: application/json");
echo json_encode($response);
break;
case 'jsonp':
header("Content-type: text/javascript");
echo $this->request->request('callback') . '(' . json_encode($response) . ');';
break;
case 'html':
header("Content-type: text/html");
echo $response;
break;
case 'serialized':
case 'php':
header("Content-type: application/vnd.php.serialized");
echo serialize($response);
break;
}
}
} |
Resolve symlinks when detecting YUNO_HOME. | #!/usr/bin/env python3
import os
import re
import sys
from yuno.core import cli, config
from yuno.core.util import working_dir
def main(argv=None):
# Figure out where Yuno lives so plugins can cd correctly if they need to.
yuno_home = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
config.update('YUNO_HOME', yuno_home)
with working_dir(yuno_home):
args, subcommand_args = cli.get_cli_args()
load_settings(args.runtime_settings, args.command)
program = __import__(
'yuno.{command}.{command}'.format(command=args.command),
fromlist=['yuno.' + args.command]
)
program.main(subcommand_args)
def load_settings(runtime_settings, plugin_name):
plugin_name = re.sub('[^a-z0-9_]', '', plugin_name, flags=re.I)
plugin_settings_file = 'yuno/%s/settings/config.json' % plugin_name
config.load_default()
if os.path.isfile(plugin_settings_file):
config.load_json(plugin_settings_file)
for override in runtime_settings or []:
key = override[0]
if isinstance(getattr(config.config, key), list):
value = override[1:]
else:
value = override[1]
config.update(key, value)
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import os
import re
import sys
from yuno.core import cli, config
from yuno.core.util import working_dir
def main(argv=None):
# Figure out where Yuno lives so plugins can cd correctly if they need to.
yuno_home = os.path.abspath(os.path.dirname(__file__))
config.update('YUNO_HOME', yuno_home)
with working_dir(yuno_home):
args, subcommand_args = cli.get_cli_args()
load_settings(args.runtime_settings, args.command)
program = __import__(
'yuno.{command}.{command}'.format(command=args.command),
fromlist=['yuno.' + args.command]
)
program.main(subcommand_args)
def load_settings(runtime_settings, plugin_name):
plugin_name = re.sub('[^a-z0-9_]', '', plugin_name, flags=re.I)
plugin_settings_file = 'yuno/%s/settings/config.json' % plugin_name
config.load_default()
if os.path.isfile(plugin_settings_file):
config.load_json(plugin_settings_file)
for override in runtime_settings or []:
key = override[0]
if isinstance(getattr(config.config, key), list):
value = override[1:]
else:
value = override[1]
config.update(key, value)
if __name__ == '__main__':
main()
|
Revert "Construct proper URL for org projects"
This reverts commit 8748f46ce1e1f93de5c343e3f2d2bcaf3844b4e9. | import React from 'react'
import { NavLink } from 'react-router-dom'
import EditTools from './EditTools'
import PreviewTools from './PreviewTools'
import styles from './Toolbar.styl'
export default ({ params, project, layout, theme, onLayoutChanged, onThemeChanged }) => {
const { username, owner, project: projectName, mode } = params
const linkBase = ['', username, owner, projectName].join('/').replace('//', '/')
return (
<div className={styles.container}>
<nav role="navigation" className={styles.nav}>
<NavLink to={linkBase + '/edit'} className={styles.navLink} activeClassName={styles.active}>
<img src="/public/img/toolbar/edit.png" />
Edit
</NavLink>
<NavLink
to={linkBase + '/preview'}
className={styles.navLink}
activeClassName={styles.active}
>
<img src="/public/img/toolbar/preview.png" />
Preview
</NavLink>
</nav>
{mode === 'edit' && <EditTools />}
{mode === 'preview' &&
<PreviewTools
href={`/preview/${username}/${projectName}`}
layout={layout}
theme={theme}
onLayoutChanged={onLayoutChanged}
onThemeChanged={onThemeChanged}
/>}
</div>
)
}
| import React from 'react'
import { NavLink } from 'react-router-dom'
import EditTools from './EditTools'
import PreviewTools from './PreviewTools'
import styles from './Toolbar.styl'
export default ({ params, project, layout, theme, onLayoutChanged, onThemeChanged }) => {
const { username, owner, project: projectName, mode } = params
const linkBase = ['', username, owner, projectName].join('/').replace('//', '/')
return (
<div className={styles.container}>
<nav role="navigation" className={styles.nav}>
<NavLink to={linkBase + '/edit'} className={styles.navLink} activeClassName={styles.active}>
<img src="/public/img/toolbar/edit.png" />
Edit
</NavLink>
<NavLink
to={linkBase + '/preview'}
className={styles.navLink}
activeClassName={styles.active}
>
<img src="/public/img/toolbar/preview.png" />
Preview
</NavLink>
</nav>
{mode === 'edit' && <EditTools />}
{mode === 'preview' &&
<PreviewTools
href={`/preview/${owner || username}/${projectName}`}
layout={layout}
theme={theme}
onLayoutChanged={onLayoutChanged}
onThemeChanged={onThemeChanged}
/>}
</div>
)
}
|
Revert "check multiple acheteurs popup formulaire validation parcellaire"
This reverts commit 8c66cde56f88d699a468d6515a1d8c8e9e1df8b2. | <?php
class ParcellaireValidationForm extends acCouchdbObjectForm {
public function configure() {
if(!$this->getObject()->isPapier()) {
$this->setWidget('autorisation_acheteur', new sfWidgetFormInputCheckbox());
$this->setValidator('autorisation_acheteur', new sfValidatorBoolean());
}
if($this->getObject()->isPapier()) {
$this->setWidget('date', new sfWidgetFormInput());
$this->setValidator('date', new sfValidatorDate(array('date_output' => 'Y-m-d', 'date_format' => '~(?P<day>\d{2})/(?P<month>\d{2})/(?P<year>\d{4})~', 'required' => true)));
$this->getWidget('date')->setLabel("Date de réception du document");
$this->getValidator('date')->setMessage("required", "La date de réception du document est requise");
}
$this->widgetSchema->setNameFormat('parcellaire_validation[%s]');
}
protected function doUpdateObject($values) {
if(!$this->getObject()->isPapier()) {
$this->getObject()->autorisation_acheteur = $values['autorisation_acheteur'];
$this->getObject()->validate();
return;
}
if($this->getObject()->isPapier()) {
$this->getObject()->autorisation_acheteur = false;
$this->getObject()->validate($values['date']);
return;
}
}
}
| <?php
class ParcellaireValidationForm extends acCouchdbObjectForm {
public function configure() {
if(!$this->getObject()->isPapier() && $this->getObject()->hasProduitWithMultipleAcheteur()) {
$this->setWidget('autorisation_acheteur', new sfWidgetFormInputCheckbox());
$this->setValidator('autorisation_acheteur', new sfValidatorBoolean());
}
if($this->getObject()->isPapier()) {
$this->setWidget('date', new sfWidgetFormInput());
$this->setValidator('date', new sfValidatorDate(array('date_output' => 'Y-m-d', 'date_format' => '~(?P<day>\d{2})/(?P<month>\d{2})/(?P<year>\d{4})~', 'required' => true)));
$this->getWidget('date')->setLabel("Date de réception du document");
$this->getValidator('date')->setMessage("required", "La date de réception du document est requise");
}
$this->widgetSchema->setNameFormat('parcellaire_validation[%s]');
}
protected function doUpdateObject($values) {
if(!$this->getObject()->isPapier()) {
$this->getObject()->autorisation_acheteur = $values['autorisation_acheteur'];
$this->getObject()->validate();
return;
}
if($this->getObject()->isPapier()) {
$this->getObject()->autorisation_acheteur = false;
$this->getObject()->validate($values['date']);
return;
}
}
}
|
Read installation requirements from dedicated file
Removes duplication. | import codecs
from setuptools import setup
def read_lines_from_file(filename):
with codecs.open(filename, encoding='utf-8') as f:
return [line.rstrip('\n') for line in f]
long_description = read_lines_from_file('README.rst')
requirements = read_lines_from_file('requirements.txt')
setup(
name='Weitersager',
version='0.2-dev',
description='A proxy to forward messages received via HTTP to to IRC',
long_description=long_description,
url='http://homework.nwsnet.de/releases/1cda/#weitersager',
author='Jochen Kupperschmidt',
author_email='[email protected]',
license='MIT',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: Other Audience',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Communications :: Chat :: Internet Relay Chat',
'Topic :: Internet :: WWW/HTTP',
'Topic :: System :: Logging',
'Topic :: System :: Systems Administration',
'Topic :: Utilities',
],
packages=['weitersager'],
install_requires=requirements,
)
| import codecs
from setuptools import setup
def read_lines_from_file(filename):
with codecs.open(filename, encoding='utf-8') as f:
return [line.rstrip('\n') for line in f]
long_description = read_lines_from_file('README.rst')
setup(
name='Weitersager',
version='0.2-dev',
description='A proxy to forward messages received via HTTP to to IRC',
long_description=long_description,
url='http://homework.nwsnet.de/releases/1cda/#weitersager',
author='Jochen Kupperschmidt',
author_email='[email protected]',
license='MIT',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: Other Audience',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Communications :: Chat :: Internet Relay Chat',
'Topic :: Internet :: WWW/HTTP',
'Topic :: System :: Logging',
'Topic :: System :: Systems Administration',
'Topic :: Utilities',
],
packages=['weitersager'],
install_requires=[
'blinker==1.4',
'irc==12.3',
],
)
|
Fix broken reference in documentation | """This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.DummyPlugin` to only override
methods selectively.
"""
__metaclass__ = ABCMeta
@abstractmethod
def before_invoke(self, invocation):
"""
Called right before the invoker calls the objective function
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_invoke(self, invocation):
"""
Called after the invoker called the objective function
Since objective functions are usually called asyncronously `invocation`
will not contain any results yet.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_result(self, invocation):
"""
Called when the invocation of the objective function was successful
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_error(self, invocation):
"""
Called when the invocation of the objective function was not successful
Since the invocation was not successful `invocation` will not contain
any result.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass | """This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.DummyInvocationPlugin` to only override
methods selectively.
"""
__metaclass__ = ABCMeta
@abstractmethod
def before_invoke(self, invocation):
"""
Called right before the invoker calls the objective function
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_invoke(self, invocation):
"""
Called after the invoker called the objective function
Since objective functions are usually called asyncronously `invocation`
will not contain any results yet.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_result(self, invocation):
"""
Called when the invocation of the objective function was successful
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass
@abstractmethod
def on_error(self, invocation):
"""
Called when the invocation of the objective function was not successful
Since the invocation was not successful `invocation` will not contain
any result.
:param invocation: Information about the current (and past) invocations
:type invocation: :class:`orges.invoker.pluggable.Invocation`
"""
pass |
Change import method so components show up | var RouteHandler = require( 'react-router' ).RouteHandler,
classNames = require('classnames'),
{ connect } = require('react-redux'),
{ routeActions } = require('react-router-redux'),
{ compose } = require( 'redux' ),
HTML5Backend = require('react-dnd-html5-backend'),
DragDropContext = require('react-dnd').DragDropContext
;
import React, { Component, PropTypes } from 'react';
import Header from './header';
import Modal from './modal';
// depends Header, Nav
class App extends Component {
componentDidMount() {
const {
dispatch,
} = this.props;
if ( this.props.routing.location.pathname === "/" ) {
dispatch(routeActions.push('/home'));
}
}
render() {
var pathname = this.props.routing.location.pathname;
var appContentClasses = classNames({
'app-wide-view': true,
'home-page-view': pathname === '/home'
});
return(
<div className="view">
<Header />
<div id="content">
<div className={appContentClasses}>
{this.props.children}
</div>
</div>
<Modal />
</div>
);
}
};
function selectState(newState) {
return {
routing: newState.routing
};
}
export default connect(selectState)(App);
| var RouteHandler = require( 'react-router' ).RouteHandler,
Header = require( './header' ),
Modal = require( './modal' ),
classNames = require('classnames'),
{ connect } = require('react-redux'),
{ routeActions } = require('react-router-redux'),
{ compose } = require( 'redux' ),
HTML5Backend = require('react-dnd-html5-backend'),
DragDropContext = require('react-dnd').DragDropContext
;
import React, { Component, PropTypes } from 'react';
// depends Header, Nav
class App extends Component {
componentDidMount() {
const {
dispatch,
} = this.props;
if ( this.props.routing.location.pathname === "/" ) {
dispatch(routeActions.push('/home'));
}
}
render() {
var pathname = this.props.routing.location.pathname;
var appContentClasses = classNames({
'app-wide-view': true,
'home-page-view': pathname === '/home'
});
return(
<div className="view">
<Header />
<div id="content">
<div className={appContentClasses}>
{this.props.children}
</div>
</div>
<Modal />
</div>
);
}
};
function selectState(newState) {
return {
routing: newState.routing
};
}
export default connect(selectState)(App);
|
Make English the fallback language in i18next.
Fixes: #1580 | // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json'
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':'
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__"
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions,
fallbackLng: 'en'
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i++) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
| // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json'
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':'
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__"
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i++) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
|
Update migration history to include trackchanges migrations | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0004_edited_content_migration'),
]
operations = [
migrations.CreateModel(
name='StaffWorkflow',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('scorer_id', models.CharField(max_length=40, db_index=True)),
('course_id', models.CharField(max_length=40, db_index=True)),
('item_id', models.CharField(max_length=128, db_index=True)),
('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)),
('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)),
('grading_completed_at', models.DateTimeField(null=True, db_index=True)),
('grading_started_at', models.DateTimeField(null=True, db_index=True)),
('cancelled_at', models.DateTimeField(null=True, db_index=True)),
('assessment', models.CharField(max_length=128, null=True, db_index=True)),
],
options={
'ordering': ['created_at', 'id'],
},
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='StaffWorkflow',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('scorer_id', models.CharField(max_length=40, db_index=True)),
('course_id', models.CharField(max_length=40, db_index=True)),
('item_id', models.CharField(max_length=128, db_index=True)),
('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)),
('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)),
('grading_completed_at', models.DateTimeField(null=True, db_index=True)),
('grading_started_at', models.DateTimeField(null=True, db_index=True)),
('cancelled_at', models.DateTimeField(null=True, db_index=True)),
('assessment', models.CharField(max_length=128, null=True, db_index=True)),
],
options={
'ordering': ['created_at', 'id'],
},
),
]
|
[FIX] stock_request_ux: Fix a problem with the allocations
For this change https://github.com/OCA/stock-logistics-warehouse/commit/4464be475999c8ada492c56a1c30ca2b0eaa264e
If you confirm with a rute with 3 steps and create 3 pickings them has related with the request by allocation, and the qty_done, qty_In_progress are the sum of all of them moves and the are duplicated the values, that it's wrong behavior
In this Module are introduce the modification in the "Split" method to fix the behavior related when do an backorder or not. | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, fields
class StockMove(models.Model):
_inherit = 'stock.move'
request_order_id = fields.Many2one(
related='stock_request_ids.order_id',
readonly=True,
)
def _split(self, qty, restrict_partner_id=False):
""" When we are on a move created by a stock_request and we create a
backorder, we create a new allocation linked to this new move and
update quantities
"""
new_move_id = super(StockMove, self)._split(
qty, restrict_partner_id=restrict_partner_id)
remaining_to_allocate = qty
for allocation in self.allocation_ids:
if not remaining_to_allocate:
break
to_allocate = min(
remaining_to_allocate, allocation.requested_product_uom_qty)
remaining_to_allocate -= to_allocate
allocation.copy({
'stock_move_id': new_move_id,
'requested_product_uom_qty': to_allocate,
})
allocation.requested_product_uom_qty -= to_allocate
return new_move_id
# TODO remove in v12 if this part are not implemented
def copy_data(self, default=None):
""" Nosotros ya copiamos la allocation en el split de arriba y ademas
si se copiasen en el copy data, con algunas rutas se esta duplicando
el allocation en casos donde no debe hacerlo, solo queremos duplicar
allocation en entregas parciales (con el split)
"""
if 'allocation_ids' in default:
default.pop('allocation_ids')
return super(StockMove, self).copy_data(default)
| ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, fields
class StockMove(models.Model):
_inherit = 'stock.move'
request_order_id = fields.Many2one(
related='stock_request_ids.order_id',
readonly=True,
)
def _split(self, qty, restrict_partner_id=False):
""" When we are on a move created by a stock_request and we create a
backorder, we create a new allocation linked to this new move and
update quantities
"""
new_move_id = super(StockMove, self)._split(
qty, restrict_partner_id=restrict_partner_id)
remaining_to_allocate = qty
for allocation in self.allocation_ids:
if not remaining_to_allocate:
break
to_allocate = min(
remaining_to_allocate, allocation.requested_product_uom_qty)
remaining_to_allocate -= to_allocate
allocation.copy({
'stock_move_id': new_move_id,
'requested_product_uom_qty': to_allocate,
})
allocation.requested_product_uom_qty -= to_allocate
return new_move_id
|
Fix issue where first selection in detail pane after refresh would not be possible |
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
if (!rangy.initialized) rangy.init();
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
var e = rangy.createRange();
e.setStart(range.startContainer, range.startOffset);
e.setEnd(range.endContainer, range.endOffset);
// Move range start to include n more of words
e.moveStart('word', -numberWords);
// Move range end to include n more words
e.moveEnd('word', numberWords);
// Calculate what we just included and send that back
if (splitBeforeAfterOutput) {
var output = rangy.createRange();
output.setStart(e.startContainer, e.startOffset);
output.setEnd(range.startContainer, range.startOffset);
splitBeforeAfterOutput.before = output.text();
output.setStart(range.endContainer, range.endOffset);
output.setEnd(e.endContainer, e.endOffset);
splitBeforeAfterOutput.after = output.text();
}
return e;
}
};
});
|
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
if (!rangy.initialized) rangy.init();
var e = rangy.createRange();
e.setStart(range.startContainer, range.startOffset);
e.setEnd(range.endContainer, range.endOffset);
// Move range start to include n more of words
e.moveStart('word', -numberWords);
// Move range end to include n more words
e.moveEnd('word', numberWords);
// Calculate what we just included and send that back
if (splitBeforeAfterOutput) {
var output = rangy.createRange();
output.setStart(e.startContainer, e.startOffset);
output.setEnd(range.startContainer, range.startOffset);
splitBeforeAfterOutput.before = output.text();
output.setStart(range.endContainer, range.endOffset);
output.setEnd(e.endContainer, e.endOffset);
splitBeforeAfterOutput.after = output.text();
}
return e;
}
};
});
|
Make a single template for markdown editor | 'use strict';
angular
.module('flashcardModule.directives')
.directive('markdownEditor', function() {
var converter = new Showdown.converter();
return {
restrict: 'E',
scope: {
text: '=text'
},
template: '<div ng-hide="isEditMode" ng-dblclick="toEditMode()" class="preview"></div><textarea ng-show="isEditMode" class="editor input-block-level"></textarea>',
compile: function(tElement, tAttrs, transclude) {
return function(scope, iElement, iAttrs, controller) {
scope.isEditMode = false;
if (scope.text) {
var htmlText = converter.makeHtml(scope.text);
iElement.find('div').html(htmlText);
}
scope.toEditMode = function() {
iElement.find('textarea').html(scope.text);
scope.isEditMode = true;
}
}
}
};
}); | 'use strict';
angular
.module('flashcardModule.directives')
.directive('markdownEditor', function() {
var converter = new Showdown.converter();
var previewTemplate = '<div ng-hide="isEditMode" ng-dblclick="toEditMode()" class="preview"></div>';
var editorTemplate = '<textarea ng-show="isEditMode" class="editor input-block-level"></textarea>';
return {
restrict: 'E',
scope: {
text: '=text'
},
compile: function(tElement, tAttrs, transclude) {
tElement.html(editorTemplate);
tElement.append(previewTemplate);
return function(scope, iElement, iAttrs, controller) {
scope.isEditMode = false;
if (scope.text) {
var htmlText = converter.makeHtml(scope.text);
iElement.find('div').html(htmlText);
}
scope.toEditMode = function() {
iElement.find('textarea').html(scope.text);
scope.isEditMode = true;
}
}
}
};
}); |
Enable strict validation of `package.json`. | 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
jshintrc: true
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: 'test/**/*.js'
},
'npm-validate': {
options: {
strict: true
}
}
});
// Load tasks.
grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.renameTask('release', 'bump');
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('release', function() {
grunt.task.run('lint', Array.prototype.concat.apply('bump', arguments).join(':'));
});
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'test', 'validate']);
grunt.registerTask('validate', ['npm-validate']);
grunt.registerTask('default', ['lint', 'test', 'validate']);
};
| 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
jshintrc: true
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: 'test/**/*.js'
}
});
// Load tasks.
grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.renameTask('release', 'bump');
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('release', function() {
grunt.task.run('lint', Array.prototype.concat.apply('bump', arguments).join(':'));
});
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'test', 'validate']);
grunt.registerTask('validate', ['npm-validate']);
grunt.registerTask('default', ['lint', 'test', 'validate']);
};
|
Improve code by avoiding flow through exception handling | import json
import jsonschema
from jsonschema import validate
with open("schemata/g6-scs-schema.json") as json_file1:
G6_SCS_SCHEMA = json.load(json_file1)
with open("schemata/g6-saas-schema.json") as json_file2:
G6_SAAS_SCHEMA = json.load(json_file2)
with open("schemata/g6-iaas-schema.json") as json_file3:
G6_IAAS_SCHEMA = json.load(json_file3)
with open("schemata/g6-paas-schema.json") as json_file4:
G6_PAAS_SCHEMA = json.load(json_file4)
def validate_json(submitted_json):
if validates_against_schema(G6_SCS_SCHEMA,submitted_json):
return 'G6-SCS'
elif validates_against_schema(G6_SAAS_SCHEMA,submitted_json):
return 'G6-SaaS'
elif validates_against_schema(G6_PAAS_SCHEMA,submitted_json):
return 'G6-PaaS'
elif validates_against_schema(G6_IAAS_SCHEMA,submitted_json):
return 'G6-IaaS'
else:
print 'Failed validation'
return False
def validates_against_schema(schema, submitted_json):
try:
validate(submitted_json, schema)
except jsonschema.ValidationError:
return False
else:
return True
| import json
import jsonschema
from flask import current_app
from jsonschema import validate
with open("schemata/g6-scs-schema.json") as json_file1:
G6_SCS_SCHEMA = json.load(json_file1)
with open("schemata/g6-saas-schema.json") as json_file2:
G6_SAAS_SCHEMA = json.load(json_file2)
with open("schemata/g6-iaas-schema.json") as json_file3:
G6_IAAS_SCHEMA = json.load(json_file3)
with open("schemata/g6-paas-schema.json") as json_file4:
G6_PAAS_SCHEMA = json.load(json_file4)
def validate_json(submitted_json):
#current_app.logger.info('Validating JSON:' + str(submitted_json))
try:
validate(submitted_json, G6_SCS_SCHEMA)
return 'G6-SCS'
except jsonschema.ValidationError as e1:
try:
validate(submitted_json, G6_SAAS_SCHEMA)
return 'G6-SaaS'
except jsonschema.ValidationError as e2:
try:
validate(submitted_json, G6_IAAS_SCHEMA)
return 'G6-IaaS'
except jsonschema.ValidationError as e3:
try:
validate(submitted_json, G6_PAAS_SCHEMA)
return 'G6-PaaS'
except jsonschema.ValidationError as e4:
print e4.message
print 'Failed validation'
return False
else:
return True
|
Add 4 and 8 hours update intervals again | 'use strict';
angular.module('Reader.optionsPage', ['Reader.services', 'Reader.directives']);
function OptionsCtrl($scope, options) {
$scope.syncEnabled = options.isSyncEnabled;
$scope.options = options.get();
$scope.$watch('options', function(newValue, oldValue) {
options.set($scope.options);
}, true);
$scope.$watch('cssColorNoUnread', function(newValue, oldValue) {
console.log(newValue);
});
$scope.enableSync = function ($event) {
options.enableSync($event.target.checked);
};
$scope.refreshIntervals = [
{
value: 1,
description: '1 minute'
},
{
value: 5,
description: '5 minutes'
},
{
value: 10,
description: '10 minutes'
},
{
value: 15,
description: '15 minutes'
},
{
value: 30,
description: '30 minutes'
},
{
value: 60,
description: '1 hour'
},
{
value: 240,
description: '4 hours'
},
{
value: 480,
description: '8 hours'
}
];
} | 'use strict';
angular.module('Reader.optionsPage', ['Reader.services', 'Reader.directives']);
function OptionsCtrl($scope, options) {
$scope.syncEnabled = options.isSyncEnabled;
$scope.options = options.get();
$scope.$watch('options', function(newValue, oldValue) {
options.set($scope.options);
}, true);
$scope.$watch('cssColorNoUnread', function(newValue, oldValue) {
console.log(newValue);
});
$scope.enableSync = function ($event) {
options.enableSync($event.target.checked);
};
$scope.refreshIntervals = [
{
value: 1,
description: '1 minute'
},
{
value: 5,
description: '5 minutes'
},
{
value: 10,
description: '10 minutes'
},
{
value: 15,
description: '15 minutes'
},
{
value: 30,
description: '30 minutes'
},
{
value: 60,
description: '1 hour'
}
];
} |
i18next: Add i18next: to the local storage cache prefix.
This just makes it easier to see what these local storage entries are
related to. | // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json',
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement,
};
var cacheOptions = {
enabled: true,
prefix: 'i18next:' + page_params.server_generation + ':',
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__",
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions,
fallbackLng: 'en',
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i += 1) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
| // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json',
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement,
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':',
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__",
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions,
fallbackLng: 'en',
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i += 1) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
|
Make Ace save the user's code on failures | $(document).ready(function() {
configureDataTables();
configureCodeBox();
});
function configureDataTables(){
$('#problem-table').dataTable( {
"iDisplayLength": 25,
"aaSorting": [[ 3, "desc" ]],
"aoColumns": [
null,
null,
null,
null
]
} );
$('#user-table').dataTable( {
"iDisplayLength":25,
"aaSorting": [[ 0, "asc" ]],
"aoColumns": [
null,
null,
null
]
} );
}
function configureCodeBox(){
//For no javascript version we have the code-box text area
//If we have javascript on then we remove it and replace it with
//the proper div
var oldBox = $('#code-box');
oldBox.replaceWith("<div id=\"code-div\"> <pre id=\"editor\">" + oldBox.val() + "</pre></div>");
var hiddenCodeInput = "<input type=\"hidden\" value=\"blank\" name=\"code\" id=\"code\">";
$(hiddenCodeInput).insertBefore('#id');
if ($("#run-button").length){
var editor = ace.edit("editor");
editor.setTheme("ace/theme/textmate");
var ClojureMode = require("ace/mode/clojure").Mode;
editor.getSession().setMode(new ClojureMode());
document.getElementById('editor').style.fontSize='13px';
$("#run-button").click(function(){
var text = editor.getSession().getValue();
$('#code').val(text);
});
}
}
| $(document).ready(function() {
configureDataTables();
configureCodeBox();
});
function configureDataTables(){
$('#problem-table').dataTable( {
"iDisplayLength": 25,
"aaSorting": [[ 3, "desc" ]],
"aoColumns": [
null,
null,
null,
null
]
} );
$('#user-table').dataTable( {
"iDisplayLength":25,
"aaSorting": [[ 0, "asc" ]],
"aoColumns": [
null,
null,
null
]
} );
}
function configureCodeBox(){
//For no javascript version we have the code-box text area
//If we have javascript on then we remove it and replace it with
//the proper div
$('#code-box').replaceWith("<div id=\"code-div\"> <pre id=\"editor\"></pre></div>");
var hiddenCodeInput = "<input type=\"hidden\" value=\"blank\" name=\"code\" id=\"code\">";
$(hiddenCodeInput).insertBefore('#id');
if ($("#run-button").length){
var editor = ace.edit("editor");
editor.setTheme("ace/theme/textmate");
var ClojureMode = require("ace/mode/clojure").Mode;
editor.getSession().setMode(new ClojureMode());
document.getElementById('editor').style.fontSize='13px';
$("#run-button").click(function(){
var text = editor.getSession().getValue();
$('#code').val(text);
});
}
}
|
Make the app externally visible | import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"ports": wol.get_wol_ports()})
@app.route('/wake/<string:mac_address>', methods=['GET'])
def wake(mac_address):
try:
args = request.args.to_dict()
ip = args['ip'] if 'ip' in args else '192.168.1.255'
port = args['port'] if 'port' in args else wol.get_wol_ports()[2]
payload = wol.build_payload(mac_address)
if app.config['DEBUG']:
print 'Mac :', mac_address
print 'Ip :', ip
print 'Port :', port
else:
app.logger.info({
'Mac': mac_address,
'Ip': ip,
'Port': port
})
wol.send(payload, ip, port)
return json.dumps({"success": True})
except Exception as e:
app.logger.error(e.message)
return json.dumps({"error": e.message})
if __name__ == "__main__":
app.run(host='0.0.0.0')
| import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"ports": wol.get_wol_ports()})
@app.route('/wake/<string:mac_address>', methods=['GET'])
def wake(mac_address):
try:
args = request.args.to_dict()
ip = args['ip'] if 'ip' in args else '192.168.1.255'
port = args['port'] if 'port' in args else wol.get_wol_ports()[2]
payload = wol.build_payload(mac_address)
if app.config['DEBUG']:
print 'Mac :', mac_address
print 'Ip :', ip
print 'Port :', port
else:
app.logger.info({
'Mac': mac_address,
'Ip': ip,
'Port': port
})
wol.send(payload, ip, port)
return json.dumps({"success": True})
except Exception as e:
app.logger.error(e.message)
return json.dumps({"error": e.message})
if __name__ == "__main__":
app.run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.