text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
herobrine: Include the missing project config
Need to include the project config prj_herobrine_npcx9.conf to
the build. It defines CONFIG_BOARD_HEROBRINE_NPCX9=y. The board
specific alternative component code (alt_dev_replacement.c)
requires this Kconfig option.
BRANCH=None
BUG=b:216836197
TEST=Booted the herobrine_npcx9 image. No PPC access error and
PD message loop.
Change-Id: I73a9987ff49a4dfb346ebe7c994418278817c03b
Signed-off-by: Wai-Hong Tam <[email protected]>
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/ec/+/3422771
Reviewed-by: Keith Short <[email protected]> | # Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def register_variant(project_name, extra_dts_overlays=(), extra_kconfig_files=()):
register_npcx_project(
project_name=project_name,
zephyr_board="npcx9",
dts_overlays=[
# Common to all projects.
here / "adc.dts",
here / "battery.dts",
here / "gpio.dts",
here / "common.dts",
here / "i2c.dts",
here / "interrupts.dts",
here / "motionsense.dts",
here / "pwm.dts",
here / "switchcap.dts",
here / "usbc.dts",
# Project-specific DTS customization.
*extra_dts_overlays,
],
kconfig_files=[
# Common to all projects.
here / "prj.conf",
# Project-specific KConfig customization.
*extra_kconfig_files,
],
)
register_variant(
project_name="herobrine_npcx9",
extra_kconfig_files=[here / "prj_herobrine_npcx9.conf"],
)
register_variant(
project_name="hoglin",
extra_kconfig_files=[here / "prj_hoglin.conf"],
)
| # Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def register_variant(project_name, extra_dts_overlays=(), extra_kconfig_files=()):
register_npcx_project(
project_name=project_name,
zephyr_board="npcx9",
dts_overlays=[
# Common to all projects.
here / "adc.dts",
here / "battery.dts",
here / "gpio.dts",
here / "common.dts",
here / "i2c.dts",
here / "interrupts.dts",
here / "motionsense.dts",
here / "pwm.dts",
here / "switchcap.dts",
here / "usbc.dts",
# Project-specific DTS customization.
*extra_dts_overlays,
],
kconfig_files=[
# Common to all projects.
here / "prj.conf",
# Project-specific KConfig customization.
*extra_kconfig_files,
],
)
register_variant(
project_name="herobrine_npcx9",
)
register_variant(
project_name="hoglin",
extra_kconfig_files=[here / "prj_hoglin.conf"],
)
|
Use willRender instead of didInsertElement/afterRender | import Ember from 'ember';
import layout from '../templates/components/mapbox-marker';
export default Ember.Component.extend({
classNameBindings: ['isLoaded'],
layout: layout,
symbol: '',
color: '#444444',
marker: null,
isLoaded: Ember.computed('map', 'marker', function() {
let map = this.get('map');
let marker = this.get('marker');
if (!Ember.isEmpty(map) && !Ember.isEmpty(marker)) {
marker.addTo(map);
return true;
} else {
return false;
}
}),
setup: Ember.on('willRender', function() {
let marker = L.marker(this.get('coordinates'), {
icon: L.mapbox.marker.icon({
'marker-color': this.get('color'),
'marker-size': this.get('size'),
'marker-symbol': this.get('symbol'),
}),
});
marker.bindPopup(this.get('popup-title'));
marker.on('click', () => {
this.sendAction('onclick');
});
this.set('marker', marker);
}),
teardown: Ember.on('willDestroyElement', function() {
let marker = this.get('marker');
let map = this.get('map');
if (map && marker) {
map.removeLayer(marker);
}
}),
popup: Ember.on('didRender', function() {
if (this.get('is-open')) {
this.get('marker').openPopup();
}
}),
});
| import Ember from 'ember';
import layout from '../templates/components/mapbox-marker';
export default Ember.Component.extend({
classNameBindings: ['isLoaded'],
layout: layout,
symbol: '',
color: '#444444',
marker: null,
isLoaded: Ember.computed('map', 'marker', function() {
let map = this.get('map');
let marker = this.get('marker');
if (!Ember.isEmpty(map) && !Ember.isEmpty(marker)) {
marker.addTo(map);
return true;
} else {
return false;
}
}),
setup: Ember.on('didInsertElement', function() {
Ember.run.scheduleOnce('afterRender', this, function () {
let marker = L.marker(this.get('coordinates'), {
icon: L.mapbox.marker.icon({
'marker-color': this.get('color'),
'marker-size': this.get('size'),
'marker-symbol': this.get('symbol'),
}),
});
marker.bindPopup(this.get('popup-title'));
marker.on('click', () => {
this.sendAction('onclick');
});
this.set('marker', marker);
});
}),
teardown: Ember.on('willDestroyElement', function() {
let marker = this.get('marker');
let map = this.get('map');
if (map && marker) {
map.removeLayer(marker);
}
}),
popup: Ember.on('didRender', function() {
if (this.get('is-open')) {
this.get('marker').openPopup();
}
}),
});
|
Write bytes object to mmap instead of string
This fixes compatibility with python3 | from .format import DrmFormat
from .framebuffer import DrmFramebuffer
from .buffer import DrmDumbBuffer
class DrmImageFramebuffer(DrmFramebuffer):
def __init__(self, drm=None, format_=None, width=None, height=None, bo=None):
if drm and format_ and width and height and bo is None:
bo = DrmDumbBuffer(drm, format_, width, height)
elif (drm or format_ or width or height) and bo is None:
raise TypeError()
super(DrmImageFramebuffer, self).__init__(bo)
self._setup()
def _setup(self):
from PIL import Image
self.bo.mmap()
if self.format.name == 'XR24':
# didn't find an XRGB format
self.image = Image.new("RGBX", (self.width, self.height))
else:
raise ValueError("DrmImageFramebuffer does not support format '%s'" % self.format.name)
def flush(self, x1=None, y1=None, x2=None, y2=None):
# FIXME: Revisit and see if this can be sped up and support big endian
# Convert RGBX -> Little Endian XRGB
b = bytearray(self.image.tobytes())
b[0::4], b[2::4] = b[2::4], b[0::4]
self.bo.map[:] = bytes(b)
super(DrmImageFramebuffer, self).flush(x1, y1, x2, y2)
| from .format import DrmFormat
from .framebuffer import DrmFramebuffer
from .buffer import DrmDumbBuffer
class DrmImageFramebuffer(DrmFramebuffer):
def __init__(self, drm=None, format_=None, width=None, height=None, bo=None):
if drm and format_ and width and height and bo is None:
bo = DrmDumbBuffer(drm, format_, width, height)
elif (drm or format_ or width or height) and bo is None:
raise TypeError()
super(DrmImageFramebuffer, self).__init__(bo)
self._setup()
def _setup(self):
from PIL import Image
self.bo.mmap()
if self.format.name == 'XR24':
# didn't find an XRGB format
self.image = Image.new("RGBX", (self.width, self.height))
else:
raise ValueError("DrmImageFramebuffer does not support format '%s'" % self.format.name)
def flush(self, x1=None, y1=None, x2=None, y2=None):
# FIXME: Revisit and see if this can be sped up and support big endian
# Convert RGBX -> Little Endian XRGB
b = bytearray(self.image.tobytes())
b[0::4], b[2::4] = b[2::4], b[0::4]
self.bo.map[:] = str(b)
super(DrmImageFramebuffer, self).flush(x1, y1, x2, y2)
|
Add unit test for unicode line breaks in strings. | var serializeLogResult = require('./serialize-log-result').serializeLogResult,
_countObjectProperties = require('./serialize-log-result')._countObjectProperties;
describe('Serialization of non-string primitives', function(){
it('Just calls toString on numbers and booleans', function(){
expect(serializeLogResult(88.22)).toBe("88.22");
expect(serializeLogResult(false)).toBe("false");
})
it('Should return the normal names for undefined and null', function(){
expect(serializeLogResult(undefined)).toBe("undefined");
expect(serializeLogResult(null)).toBe("null");
});
it('Should handle arrays decently', function(){
expect(serializeLogResult([1,2,3])).toEqual({
vaType: 'list',
items: ['1', '2', '3'],
length: 3
});
expect(serializeLogResult(['1','2','3'])).toEqual({
vaType: 'list',
items: ['"1"', '"2"', '"3"'],
length: 3
});
});
it('Should just return strings the way they are', function(){
expect(serializeLogResult('string')).toBe('"string"');
});
it('Should be able to count object properties', function(){
expect(_countObjectProperties({a: 1, b:2})).toEqual({
total: 2,
functions: 0,
values:2,
isMinimum: false
});
})
it('Should not put break up strings into multiple lines in JSON', function(){
expect(serializeLogResult('\u2028')).toBe('"\\u2028"')
})
});
| var serializeLogResult = require('./serialize-log-result').serializeLogResult,
_countObjectProperties = require('./serialize-log-result')._countObjectProperties;
describe('Serialization of non-string primitives', function(){
it('Just calls toString on numbers and booleans', function(){
expect(serializeLogResult(88.22)).toBe("88.22");
expect(serializeLogResult(false)).toBe("false");
})
it('Should return the normal names for undefined and null', function(){
expect(serializeLogResult(undefined)).toBe("undefined");
expect(serializeLogResult(null)).toBe("null");
});
it('Should handle arrays decently', function(){
expect(serializeLogResult([1,2,3])).toEqual({
vaType: 'list',
items: ['1', '2', '3'],
length: 3
});
expect(serializeLogResult(['1','2','3'])).toEqual({
vaType: 'list',
items: ['"1"', '"2"', '"3"'],
length: 3
});
});
it('Should just return strings the way they are', function(){
expect(serializeLogResult('string')).toBe('"string"');
});
it('Should be able to count object properties', function(){
expect(_countObjectProperties({a: 1, b:2})).toEqual({
total: 2,
functions: 0,
values:2,
isMinimum: false
});
})
});
|
Return project configuration in the polygulp factory method | 'use strict';
/* global module, require */
var customMedia = require("postcss-custom-media");
var nested = require('postcss-nested');
var autoprefixer = require('autoprefixer');
var extend = require('deep-extend');
module.exports = function(gulp, appSettings) {
var defaults = {
PATHS: {
src: 'app',
dist: 'dist',
test: 'test'
},
postcssProcessors: [
customMedia,
nested,
autoprefixer({
browsers: [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
]
})
]
};
// Merge user settings with default config
var config = extend({}, defaults, appSettings);
// Load tasks
require('./tasks/default')(gulp, config);
require('./tasks/deploy')(gulp, config);
require('./tasks/release')(gulp);
require('./tasks/testing')(gulp, config);
require('./tasks/server')(gulp, config);
require('./tasks/dist')(gulp, config);
require('./tasks/translate')(gulp, config);
return config;
};
| 'use strict';
/* global module, require */
var customMedia = require("postcss-custom-media");
var nested = require('postcss-nested');
var autoprefixer = require('autoprefixer');
var extend = require('deep-extend');
module.exports = function(gulp, appSettings) {
var defaults = {
PATHS: {
src: 'app',
dist: 'dist',
test: 'test'
},
postcssProcessors: [
customMedia,
nested,
autoprefixer({
browsers: [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
]
})
]
};
// Merge user settings with default config
var config = extend({}, defaults, appSettings);
// Load tasks
require('./tasks/default')(gulp, config);
require('./tasks/deploy')(gulp, config);
require('./tasks/release')(gulp);
require('./tasks/testing')(gulp, config);
require('./tasks/server')(gulp, config);
require('./tasks/dist')(gulp, config);
require('./tasks/translate')(gulp, config);
};
|
Use list reporter so we know which test failed. |
'use strict';
module.exports = function( grunt )
{
grunt.initConfig( {
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: [ 'index.js', 'lib/**/*.js' ]
},
test: {
src: [ 'test/**/*.js' ]
},
},
simplemocha: {
all: {
src: 'test/**/*.js',
options: {
globals: [ 'should' ],
timeout: 10000,
ignoreLeaks: false,
ui: 'bdd',
reporter: 'list' //'dot'
}
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: [ 'jshint:gruntfile' ]
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: [ 'jshint:lib', 'simplemocha' ]
},
test: {
files: '<%= jshint.test.src %>',
tasks: [ 'jshint:test', 'simplemocha' ]
}
}
} );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-simple-mocha' );
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask( 'default', [ 'jshint', 'simplemocha' ] );
};
|
'use strict';
module.exports = function( grunt )
{
grunt.initConfig( {
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: [ 'index.js', 'lib/**/*.js' ]
},
test: {
src: [ 'test/**/*.js' ]
},
},
simplemocha: {
all: {
src: 'test/**/*.js',
options: {
globals: [ 'should' ],
timeout: 10000,
ignoreLeaks: false,
ui: 'bdd',
reporter: 'dot'
}
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: [ 'jshint:gruntfile' ]
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: [ 'jshint:lib', 'simplemocha' ]
},
test: {
files: '<%= jshint.test.src %>',
tasks: [ 'jshint:test', 'simplemocha' ]
}
}
} );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-simple-mocha' );
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask( 'default', [ 'jshint', 'simplemocha' ] );
};
|
Fix default value on medialibrary categories table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMedialibraryCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('medialibrary_categories', function (Blueprint $table) {
// Primary key
$table->increments('id');
// Foreign key
/** @var \Illuminate\Database\Eloquent\Model $owner */
$owner = app(config('medialibrary.relations.owner.model'));
$table->integer('owner_id')->unsigned();
$table->foreign('owner_id')
->references($owner->getKeyName())
->on($owner->getTable())
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')
->references('id')
->on('medialibrary_categories')
->onUpdate('CASCADE')
->onDelete('CASCADE');
// Data
$table->string('name');
$table->integer('order')->unsigned()->default(0);
// Metadata
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('medialibrary_categories');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMedialibraryCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('medialibrary_categories', function (Blueprint $table) {
// Primary key
$table->increments('id');
// Foreign key
/** @var \Illuminate\Database\Eloquent\Model $owner */
$owner = app(config('medialibrary.relations.owner.model'));
$table->integer('owner_id')->unsigned();
$table->foreign('owner_id')
->references($owner->getKeyName())
->on($owner->getTable())
->onUpdate('CASCADE')
->onDelete('CASCADE');
$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')
->references('id')
->on('medialibrary_categories')
->onUpdate('CASCADE')
->onDelete('CASCADE');
// Data
$table->string('name');
$table->integer('order')->unsigned();
// Metadata
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('medialibrary_categories');
}
}
|
Fix test for PHP 5.3 | <?php
namespace SlmQueueSqsTest\Controller;
use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueSqs\Controller\SqsWorkerController;
use Zend\Mvc\Router\RouteMatch;
class SqsWorkerControllerTest extends TestCase
{
public function testCorrectlyCountJobs()
{
$queue = $this->getMock('SlmQueue\Queue\QueueInterface');
$worker = $this->getMock('SlmQueue\Worker\WorkerInterface');
$pluginManager = $this->getMock('SlmQueue\Queue\QueuePluginManager', array(), array(), '', false);
$pluginManager->expects($this->once())
->method('get')
->with('newsletter')
->will($this->returnValue($queue));
$controller = new SqsWorkerController($worker, $pluginManager);
$routeMatch = new RouteMatch(array('queue' => 'newsletter'));
$controller->getEvent()->setRouteMatch($routeMatch);
$worker->expects($this->once())
->method('processQueue')
->with($queue)
->will($this->returnValue(1));
$result = $controller->processAction();
$this->assertEquals("Finished worker for queue 'newsletter' with 1 jobs\n", $result);
}
}
| <?php
namespace SlmQueueSqsTest\Controller;
use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueSqs\Controller\SqsWorkerController;
use Zend\Mvc\Router\RouteMatch;
class SqsWorkerControllerTest extends TestCase
{
public function testCorrectlyCountJobs()
{
$queue = $this->getMock('SlmQueue\Queue\QueueInterface');
$worker = $this->getMock('SlmQueue\Worker\WorkerInterface');
$pluginManager = $this->getMock('SlmQueue\Queue\QueuePluginManager', [], [], '', false);
$pluginManager->expects($this->once())
->method('get')
->with('newsletter')
->will($this->returnValue($queue));
$controller = new SqsWorkerController($worker, $pluginManager);
$routeMatch = new RouteMatch(array('queue' => 'newsletter'));
$controller->getEvent()->setRouteMatch($routeMatch);
$worker->expects($this->once())
->method('processQueue')
->with($queue)
->will($this->returnValue(1));
$result = $controller->processAction();
$this->assertEquals("Finished worker for queue 'newsletter' with 1 jobs\n", $result);
}
}
|
Normalize license header. Update format.
Signed-off-by: Philippe Ombredanne <[email protected]> | #!/usr/bin/env python
# Copyright (C) 2017 BMW AG
# Author: Thomas Hafner
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import codecs
import sys
from spdx.parsers.tagvalue import Parser
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.tagvaluebuilders import Builder
from spdx.writers.rdf import write_document
def tv_to_rdf(infile_name, outfile_name):
"""
Convert a SPDX file from tag/value format to RDF format.
"""
parser = Parser(Builder(), StandardLogger())
parser.build()
with open(infile_name) as infile:
data = infile.read()
document, error = parser.parse(data)
if not error:
with open(outfile_name, mode='w') as outfile:
write_document(document, outfile)
else:
print 'Errors encountered while parsing RDF file.'
messages = []
document.validate(messages)
print '\n'.join(messages)
if __name__ == '__main__':
tv_to_rdf(*sys.argv[1:])
| #!/usr/bin/env python
# Copyright (C) 2017 BMW AG
# Author: Thomas Hafner
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import codecs
from spdx.parsers.tagvalue import Parser
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.tagvaluebuilders import Builder
from spdx.writers.rdf import write_document
def tv_to_rdf(infile_name, outfile_name):
"""Converts a SPDX file from tag/value format to RDF format."""
parser = Parser(Builder(), StandardLogger())
parser.build()
with open(infile_name) as infile:
data = infile.read()
document, error = parser.parse(data)
if not error:
with open(outfile_name, mode='w') as outfile:
write_document(document, outfile)
else:
print 'Errors encountered while parsing RDF file.'
messages = []
document.validate(messages)
print '\n'.join(messages)
if __name__ == '__main__':
tv_to_rdf(*sys.argv[1:])
|
Use operationCreator instead of operationType in ConnectedOperationContainer | import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import OperationContainer from './operation-container';
const ConnectedOperationContainer = connect(
(state, { operation, requestSelector, operationType, operationCreator }) => ({
operation:
operation ||
(requestSelector
? requestSelector(state).operations[
operationType || operationCreator.toString()
]
: state.network.mutations[
operationType || operationCreator.toString()
] || {}),
}),
(dispatch, ownProps) => ({
sendOperation: ownProps.operationCreator
? bindActionCreators(ownProps.operationCreator, dispatch)
: null,
}),
(
stateProps,
dispatchProps,
{ requestSelector, operationType, operationCreator, ...ownProps },
) => ({
...ownProps,
...stateProps,
...dispatchProps,
}),
)(OperationContainer);
ConnectedOperationContainer.propTypes /* remove-proptypes */ = {
...OperationContainer.propTypes,
operation: PropTypes.oneOfType([
PropTypes.shape({
error: PropTypes.any,
pending: PropTypes.number.isRequired,
}),
PropTypes.objectOf(
PropTypes.shape({
error: PropTypes.any,
pending: PropTypes.number.isRequired,
}),
),
]),
requestSelector: PropTypes.func,
operationType: PropTypes.string,
operationCreator: PropTypes.func,
};
export default ConnectedOperationContainer;
| import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import OperationContainer from './operation-container';
const ConnectedOperationContainer = connect(
(state, { operation, requestSelector, operationType, operationCreator }) => ({
operation:
operation ||
(requestSelector
? requestSelector(state).operations[
operationType || operationCreator.toString()
]
: state.network.mutations[operationType] || {}),
}),
(dispatch, ownProps) => ({
sendOperation: ownProps.operationCreator
? bindActionCreators(ownProps.operationCreator, dispatch)
: null,
}),
(
stateProps,
dispatchProps,
{ requestSelector, operationType, operationCreator, ...ownProps },
) => ({
...ownProps,
...stateProps,
...dispatchProps,
}),
)(OperationContainer);
ConnectedOperationContainer.propTypes /* remove-proptypes */ = {
...OperationContainer.propTypes,
operation: PropTypes.oneOfType([
PropTypes.shape({
error: PropTypes.any,
pending: PropTypes.number.isRequired,
}),
PropTypes.objectOf(
PropTypes.shape({
error: PropTypes.any,
pending: PropTypes.number.isRequired,
}),
),
]),
requestSelector: PropTypes.func,
operationType: PropTypes.string,
operationCreator: PropTypes.func,
};
export default ConnectedOperationContainer;
|
Fix product remove from cart | import React, { Component } from 'react';
export default class Cart extends Component {
constructor(props) {
super(props);
this.removeProductFromCart = this.removeProductFromCart.bind(this);
this.changeCount = this.changeCount.bind(this);
}
removeProductFromCart(lineItem) {
this.props.removeProductFromCart(lineItem.getIn(['product', 'id']));
}
changeCount(e, productId) {
this.props.changeProductCount(productId, Number(e.target.value));
}
render() {
const lineItems = this.props.cart.get('lineItems');
return (
<div>
<h3>Cart</h3>
<div>
{
lineItems.map((lineItem, i) => {
const product = lineItem.get('product');
return (
<p key={i}>
{product.get('title')} { ' x ' }
<input type="number" min="1" step="1" value={lineItem.get('count')}
onChange={ (e) => this.changeCount(e, product.get('id')) } />
<button onClick={ (e) => this.removeProductFromCart(lineItem)}>
Delete
</button>
</p>
);
})
}
</div>
</div>
);
}
}
| import React, { Component } from 'react';
export default class Cart extends Component {
constructor(props) {
super(props);
this.removeProductFromCart = this.removeProductFromCart.bind(this);
this.changeCount = this.changeCount.bind(this);
}
removeProductFromCart() {
this.props.removeProductFromCart(lineItem.getIn(['product', 'id']));
}
changeCount(e, productId) {
this.props.changeProductCount(productId, Number(e.target.value));
}
render() {
const lineItems = this.props.cart.get('lineItems');
return (
<div>
<h3>Cart</h3>
<div>
{
lineItems.map((lineItem, i) => {
const product = lineItem.get('product');
return (
<p key={i}>
{product.get('title')} { ' x ' }
<input type="number" min="1" step="1" value={lineItem.get('count')}
onChange={ (e) => this.changeCount(e, product.get('id')) } />
<button onClick={this.removeProductFromCart}>Delete</button>
</p>
);
})
}
</div>
</div>
);
}
}
|
Fix bug with uploading octed data like images | var ssh2 = require('ssh2');
var SocketIOFileUpload = require('socketio-file-upload');
var completeFileUpload = function(client, sshCredentials) {
return function(event) {
var credentials = sshCredentials(client.instance);
var connection = ssh2();
connection.on('end', function() {
});
connection.on('ready', function() {
connection.sftp(function(err, sftp) {
if (err) {
console.log("There was an error while connecting via sftp: " + err);
}
var stream = sftp.createWriteStream(event.file.name);
stream.write(client.fileUploadBuffer);
stream.end(function() {
connection.end();
});
client.fileUploadBuffer = "";
});
});
connection.connect(credentials);
};
};
module.exports = function(logExceptOnTest, sshCredentials) {
return {
attachUploadListenerToSocket: function(client, socket) {
var uploader = new SocketIOFileUpload();
uploader.listen(socket);
uploader.on("error", function(event) {
console.error("Error in upload " + event);
});
uploader.on("start", function(event) {
client.fileUploadBuffer = "";
logExceptOnTest('File upload name:' + event.file.name);
logExceptOnTest('File upload encoding: ' + event.file.encoding);
});
uploader.on("progress", function(event) {
client.fileUploadBuffer = event.buffer;
});
uploader.on("complete", completeFileUpload(client, sshCredentials));
}
};
};
| var ssh2 = require('ssh2');
var SocketIOFileUpload = require('socketio-file-upload');
var completeFileUpload = function(client, sshCredentials) {
return function(event) {
var credentials = sshCredentials(client.instance);
var connection = ssh2();
connection.on('end', function() {
});
connection.on('ready', function() {
connection.sftp(function(err, sftp) {
if (err) {
console.log("There was an error while connecting via sftp: " + err);
}
var stream = sftp.createWriteStream(event.file.name);
stream.write(client.fileUploadBuffer.toString());
stream.end(function() {
connection.end();
});
client.fileUploadBuffer = "";
});
});
connection.connect(credentials);
};
};
module.exports = function(logExceptOnTest, sshCredentials) {
return {
attachUploadListenerToSocket: function(client, socket) {
var uploader = new SocketIOFileUpload();
uploader.listen(socket);
uploader.on("error", function(event) {
console.error("Error in upload " + event);
});
uploader.on("start", function(event) {
client.fileUploadBuffer = "";
logExceptOnTest('File upload ' + event.file.name);
});
uploader.on("progress", function(event) {
client.fileUploadBuffer += event.buffer;
});
uploader.on("complete", completeFileUpload(client, sshCredentials));
}
};
};
|
Handle unset default currency better | from PySide import QtGui
import cbpos
import cbpos.mod.currency.controllers as currency
from cbpos.mod.currency.models.currency import Currency
class CurrencyConfigPage(QtGui.QWidget):
label = 'Currency'
def __init__(self):
super(CurrencyConfigPage, self).__init__()
self.default = QtGui.QComboBox()
form = QtGui.QFormLayout()
form.setSpacing(10)
form.addRow('Default Currency', self.default)
self.setLayout(form)
def populate(self):
session = cbpos.database.session()
default_id = currency.default.id
selected_index = -1
self.default.clear()
for i, c in enumerate(session.query(Currency)):
self.default.addItem(c.display, c)
if default_id == c.id:
selected_index = i
self.default.setCurrentIndex(selected_index)
def update(self):
default = self.default.itemData(self.default.currentIndex())
cbpos.config['mod.currency', 'default'] = unicode(default.id)
| from PySide import QtGui
import cbpos
from cbpos.mod.currency.models.currency import Currency
class CurrencyConfigPage(QtGui.QWidget):
label = 'Currency'
def __init__(self):
super(CurrencyConfigPage, self).__init__()
self.default = QtGui.QComboBox()
form = QtGui.QFormLayout()
form.setSpacing(10)
form.addRow('Default Currency', self.default)
self.setLayout(form)
def populate(self):
session = cbpos.database.session()
default_id = cbpos.config['mod.currency', 'default']
selected_index = -1
self.default.clear()
for i, c in enumerate(session.query(Currency)):
self.default.addItem(c.display, c)
if default_id == c.id:
selected_index = i
self.default.setCurrentIndex(selected_index)
def update(self):
default = self.default.itemData(self.default.currentIndex())
cbpos.config['mod.currency', 'default'] = unicode(default.id)
|
Fix an injection definition for the Twig_Environment | <?php
namespace Asmaster\EquipTwig\Configuration;
use Asmaster\EquipTwig\TwigFormatter;
use Auryn\Injector;
use Equip\Configuration\ConfigurationInterface;
use Equip\Configuration\EnvTrait;
use Equip\Responder\FormattedResponder;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;
final class TwigResponderConfiguration implements ConfigurationInterface
{
use EnvTrait;
/**
* @param Injector $injector
*/
public function apply(Injector $injector)
{
$injector->prepare(FormattedResponder::class, function(FormattedResponder $responder) {
return $responder->withValue(TwigFormatter::class, 1.0);
});
$injector->define(TwigLoaderFilesystem::class, [
':paths' => $this->env->getValue('TWIG_TEMPLATES')
]);
$injector->define(TwigEnvironment::class, [
'loader' => TwigLoaderFilesystem::class,
':options' => $this->getEnvOptions()
]);
}
/**
* @return array Configuration options from environment variables
*/
public function getEnvOptions()
{
$env = $this->env;
$options = [
'debug' => $env->getValue('TWIG_DEBUG', false),
'auto_reload' => $env->getValue('TWIG_AUTO_RELOAD', true),
'strict_variables' => $env->getValue('TWIG_STRICT_VARIABLES', false),
'cache' => $env->getValue('TWIG_CACHE', false)
];
return $options;
}
}
| <?php
namespace Asmaster\EquipTwig\Configuration;
use Asmaster\EquipTwig\TwigFormatter;
use Auryn\Injector;
use Equip\Configuration\ConfigurationInterface;
use Equip\Configuration\EnvTrait;
use Equip\Responder\FormattedResponder;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;
final class TwigResponderConfiguration implements ConfigurationInterface
{
use EnvTrait;
/**
* @param Injector $injector
*/
public function apply(Injector $injector)
{
$injector->prepare(FormattedResponder::class, function(FormattedResponder $responder) {
return $responder->withValue(TwigFormatter::class, 1.0);
});
$injector->define(TwigLoaderFilesystem::class, [
':paths' => $this->env->getValue('TWIG_TEMPLATES')
]);
$injector->define(TwigEnvironment::class, [
':loader' => TwigLoaderFilesystem::class,
':options' => $this->getEnvOptions()
]);
}
/**
* @return array Configuration options from environment variables
*/
public function getEnvOptions()
{
$env = $this->env;
$options = [
'debug' => $env->getValue('TWIG_DEBUG', false),
'auto_reload' => $env->getValue('TWIG_AUTO_RELOAD', true),
'strict_variables' => $env->getValue('TWIG_STRICT_VARIABLES', false),
'cache' => $env->getValue('TWIG_CACHE', false)
];
return $options;
}
}
|
Add 1 to row and column, since the numbers are 0-based and the Eclipse editor shows 1-based | package org.metaborg.core.tracing;
import javax.annotation.Nullable;
import org.metaborg.core.source.ISourceLocation;
import org.metaborg.core.source.ISourceRegion;
/**
* Represents a resolution produced by reference resolution.
*/
public class Resolution {
/**
* Area in the source file to highlight as a hyperlink.
*/
public final ISourceRegion highlight;
/**
* Resolution targets. Multiple targets indicate resolution to multiple valid locations.
*/
public final Iterable<Resolution.Target> targets;
public Resolution(ISourceRegion highlight, Iterable<Resolution.Target> targets) {
this.highlight = highlight;
this.targets = targets;
}
public static class Target {
public final @Nullable String hyperlinkName;
public final ISourceLocation location;
public Target(ISourceLocation location) {
this(null, location);
}
public Target(String hyperlinkName, ISourceLocation location) {
this.hyperlinkName = hyperlinkName == null ? defaultHyperlinkName(location) : hyperlinkName;
this.location = location;
}
private static String defaultHyperlinkName(ISourceLocation location) {
String fileName = location.resource().getName().getBaseName();
ISourceRegion region = location.region();
int row = region.startRow();
int col = region.startColumn();
return fileName + ":" + (row+1) + ":" + (col+1);
}
}
}
| package org.metaborg.core.tracing;
import javax.annotation.Nullable;
import org.metaborg.core.source.ISourceLocation;
import org.metaborg.core.source.ISourceRegion;
/**
* Represents a resolution produced by reference resolution.
*/
public class Resolution {
/**
* Area in the source file to highlight as a hyperlink.
*/
public final ISourceRegion highlight;
/**
* Resolution targets. Multiple targets indicate resolution to multiple valid locations.
*/
public final Iterable<Resolution.Target> targets;
public Resolution(ISourceRegion highlight, Iterable<Resolution.Target> targets) {
this.highlight = highlight;
this.targets = targets;
}
public static class Target {
public final @Nullable String hyperlinkName;
public final ISourceLocation location;
public Target(ISourceLocation location) {
this(null, location);
}
public Target(String hyperlinkName, ISourceLocation location) {
this.hyperlinkName = hyperlinkName == null ? defaultHyperlinkName(location) : hyperlinkName;
this.location = location;
}
private static String defaultHyperlinkName(ISourceLocation location) {
String fileName = location.resource().getName().getBaseName();
ISourceRegion region = location.region();
int row = region.startRow();
int col = region.startColumn();
return fileName + ":" + row + ":" + col;
}
}
}
|
Delete Group and User Dialog | $(function(){
// Delete users/groups via ajax
$('.listFilterContainer').find(".deleteIcon").bind("click", function(){
var me = $(this);
var url = me.attr("href");
var title = me.attr("data-name");
if(!$('body').data('mbPopup')) {
$("body").mbPopup();
$("body").mbPopup('showModal',
{title:"Confirm delete",
subTitle: " - " + title,
content:"Do you really want to delete the group/user " + title + "?"},
function(){
$.ajax({
url: url,
type: 'POST',
success: function(data) {
me.parent().parent().remove();
}
});
});
}
return false;
});
$(".checkbox").bind("click", function(e){
$("#selectedUsersGroups").text(($(".tableUserGroups").find(".iconCheckboxActive").length))
});
// Delete group via Ajax
$('#listFilterGroups').find(".iconRemove").bind("click", function(){
var me = $(this);
var title = me.attr('title');
if(!$('body').data('mbPopup')) {
$("body").mbPopup();
$("body").mbPopup('showModal',
{
title:"Confirm delete",
subTitle: title,
content:"Do you really want to delete the group " + title + "?"
},
function(){
$.ajax({
url: me.attr('data-url'),
data : {'id': me.attr('data-id')},
type: 'POST',
success: function(data) {
window.location.reload();
}
});
});
}
return false;
});
// Delete user via Ajax
$('#listFilterUsers').find(".iconRemove").bind("click", function(){
var me = $(this);
var title = me.attr('title');
if(!$('body').data('mbPopup')) {
$("body").mbPopup();
$("body").mbPopup('showModal',
{
title:"Confirm delete",
subTitle: title,
content:"Do you really want to delete the user " + title + "?"
},
function(){
$.ajax({
url: me.attr('data-url'),
data : {'id': me.attr('data-id')},
type: 'POST',
success: function(data) {
window.location.reload();
}
});
});
}
return false;
});
}); | // Delete users/groups via ajax
$('.listFilterContainer').find(".deleteIcon").bind("click", function(){
var me = $(this);
var url = me.attr("href");
var title = me.attr("data-name");
if(!$('body').data('mbPopup')) {
$("body").mbPopup();
$("body").mbPopup('showModal',
{title:"Confirm delete",
subTitle: " - " + title,
content:"Do you really want to delete the group/user " + title + "?"},
function(){
$.ajax({
url: url,
type: 'POST',
success: function(data) {
me.parent().parent().remove();
}
});
});
}
return false;
});
$(".checkbox").bind("click", function(e){
$("#selectedUsersGroups").text(($(".tableUserGroups").find(".iconCheckboxActive").length))
}); |
Fix passing wrong entry to chat_id | module.exports=function (text_msg, interval) {
const https = require('https');
let options = {
host: "api.telegram.org",
path: `/bot${process.env.TELEGRAM_TOKEN}/sendMessage`,
method: "POST",
headers: {
'Content-Type': "application/json"
}
};
let msg_db=require('./telegram_db');
msg_db(function (rows) {
for(let i=0;i<=rows.length;i+=1) {
if(i===rows.length){
clearInterval(interval);
return;
}
let post_data = {
"chat_id": rows[i].telegram_id,
"text": text_msg
};
let post_req = https.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('[TELEGRAM SEND] Res: ' + chunk);
});
});
// post the data
post_req.write(JSON.stringify(post_data));
post_req.end();
}
});
}; | module.exports=function (text_msg, interval) {
const https = require('https');
let options = {
host: "api.telegram.org",
path: `/bot${process.env.TELEGRAM_TOKEN}/sendMessage`,
method: "POST",
headers: {
'Content-Type': "application/json"
}
};
let msg_db=require('./telegram_db');
msg_db(function (rows) {
for(let i=0;i<=rows.length;i+=1) {
if(i===rows.length){
clearInterval(interval);
return;
}
let post_data = {
"chat_id": rows[i].chat_id,
"text": text_msg
};
let post_req = https.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('[MSG SEND] Res: ' + chunk);
});
});
// post the data
post_req.write(JSON.stringify(post_data));
post_req.end();
}
});
}; |
Store tool's name when parsing container |
def imprint_container(tool,
name,
namespace,
context,
loader=None):
"""Imprint a Loader with metadata
Containerisation enables a tracking of version, author and origin
for loaded assets.
Arguments:
tool (object): The node in Fusion to imprint as container, usually a
Loader.
name (str): Name of resulting assembly
namespace (str): Namespace under which to host container
context (dict): Asset information
loader (str, optional): Name of loader used to produce this container.
Returns:
None
"""
data = [
("schema", "avalon-core:container-2.0"),
("id", "pyblish.avalon.container"),
("name", str(name)),
("namespace", str(namespace)),
("loader", str(loader)),
("representation", str(context["representation"]["_id"])),
]
for key, value in data:
tool.SetData("avalon.{}".format(key), value)
def parse_container(tool):
"""Returns imprinted container data of a tool
This reads the imprinted data from `imprint_container`.
"""
container = {}
for key in ['schema', 'id', 'name', 'namespace',
'loader', 'representation']:
value = tool.GetData('avalon.{}'.format(key))
container[key] = value
# Store the tool's name
container["objectName"] = tool.Name
return container
|
def imprint_container(tool,
name,
namespace,
context,
loader=None):
"""Imprint a Loader with metadata
Containerisation enables a tracking of version, author and origin
for loaded assets.
Arguments:
tool (object): The node in Fusion to imprint as container, usually a
Loader.
name (str): Name of resulting assembly
namespace (str): Namespace under which to host container
context (dict): Asset information
loader (str, optional): Name of loader used to produce this container.
Returns:
None
"""
data = [
("schema", "avalon-core:container-2.0"),
("id", "pyblish.avalon.container"),
("name", str(name)),
("namespace", str(namespace)),
("loader", str(loader)),
("representation", str(context["representation"]["_id"])),
]
for key, value in data:
tool.SetData("avalon.{}".format(key), value)
def parse_container(tool):
"""Returns imprinted container data of a tool
This reads the imprinted data from `imprint_container`.
"""
container = {}
for key in ['schema', 'id', 'name', 'namespace',
'loader', 'representation']:
value = tool.GetData('avalon.{}'.format(key))
container[key] = value
return container
|
Add module directory to include paths for sass | var components = require('../modules/components');
var sass = require('node-sass');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
/**
* Function to build out the CSS
* @return {Promise} Promise which resolves with the path to the CSS output
* when the SASS has been built
*/
function compileSass(config, stylesheets) {
console.time('Compile SASS');
var promises = [];
stylesheets.forEach(function(stylesheet) {
promises.push(new Promise(function(resolve, reject) {
// Compile
sass.render({
data: stylesheet.data,
includePaths: [
config.moduleDir,
path.join(config.moduleDir, 'src/elements')
],
outputStyle: (config.mode === 'production') ? 'compressed' : 'expanded'
}, function(err, result) {
if(err) {
reject(err);
return;
}
// Write out the sass
mkdirp(path.join(config.destination, 'assets/stylesheets'), function() {
fs.writeFile(path.join(config.destination, 'assets/stylesheets', stylesheet.filename) + '.css', result.css, function(err) {
if(err) {
reject(err);
}
resolve(path.join(config.destination, 'assets/stylesheets'));
});
});
});
}));
});
return Promise.all(promises).then(function() {
console.timeEnd('Compile SASS');
});
}
module.exports = compileSass;
| var components = require('../modules/components');
var sass = require('node-sass');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
/**
* Function to build out the CSS
* @return {Promise} Promise which resolves with the path to the CSS output
* when the SASS has been built
*/
function compileSass(config, stylesheets) {
console.time('Compile SASS');
var promises = [];
stylesheets.forEach(function(stylesheet) {
promises.push(new Promise(function(resolve, reject) {
// Compile
sass.render({
data: stylesheet.data,
includePaths: [
path.join(config.moduleDir, 'src/elements')
],
outputStyle: (config.mode === 'production') ? 'compressed' : 'expanded'
}, function(err, result) {
if(err) {
reject(err);
return;
}
// Write out the sass
mkdirp(path.join(config.destination, 'assets/stylesheets'), function() {
fs.writeFile(path.join(config.destination, 'assets/stylesheets', stylesheet.filename) + '.css', result.css, function(err) {
if(err) {
reject(err);
}
resolve(path.join(config.destination, 'assets/stylesheets'));
});
});
});
}));
});
return Promise.all(promises).then(function() {
console.timeEnd('Compile SASS');
});
}
module.exports = compileSass;
|
Make community card horizontal by default | 'use strict';
import React from 'react';
import c from 'classnames';
var CommunityCard = React.createClass({
displayName: 'CommunityCard',
propTypes: {
title: React.PropTypes.string,
linkTitle: React.PropTypes.string,
url: React.PropTypes.string,
imageNode: React.PropTypes.node,
horizontal: React.PropTypes.bool,
children: React.PropTypes.object
},
getDefaultProps: function () {
return {
horizontal: false
};
},
render: function () {
return (
<article className={c('card', {'card--horizontal card--horizontal--align-middle': this.props.horizontal})}>
<div className='card__contents'>
<figure className='card__media'>
<div className='card__thumbnail'>
{this.props.imageNode}
</div>
</figure>
<div className="card__copy">
<header className='card__header'>
<h1 className='card__title'><a title={this.props.linkTitle} href={this.props.url}>{this.props.title}</a></h1>
</header>
<div className='card__body'>
{this.props.children}
<a title={this.props.linkTitle} href={this.props.url}>Learn More</a>
</div>
</div>
</div>
</article>
);
}
});
module.exports = CommunityCard;
| 'use strict';
import React from 'react';
var CommunityCard = React.createClass({
displayName: 'CommunityCard',
propTypes: {
title: React.PropTypes.string,
linkTitle: React.PropTypes.string,
url: React.PropTypes.string,
imageNode: React.PropTypes.node,
children: React.PropTypes.object
},
render: function () {
return (
<article className='card card--horizontal card--horizontal--align-middle'>
<div className='card__contents'>
<figure className='card__media'>
<div className='card__thumbnail'>
{this.props.imageNode}
</div>
</figure>
<div className="card__copy">
<header className='card__header'>
<h1 className='card__title'><a title={this.props.linkTitle} href={this.props.url}>{this.props.title}</a></h1>
</header>
<div className='card__body'>
{this.props.children}
<a title={this.props.linkTitle} href={this.props.url}>Learn More</a>
</div>
</div>
</div>
</article>
);
}
});
module.exports = CommunityCard;
|
Add optional fields argument to list and read | var systemError = require( '../utils' ).systemError;
exports.MongooseDataManager = function ( model ) {
return {
create: function ( data, callback ) {
model.create( data, function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, result );
} );
},
list: function ( data, fields, callback ) {
var query = model.find( data );
if ( arguments.length === 2 ) {
callback = fields;
} else {
query.select( fields );
}
query.exec( function ( err, results ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, results );
} );
},
read: function ( id, fields, callback ) {
var query = model.findById( id );
if ( arguments.length === 2 ) {
callback = fields;
} else {
query.select( fields );
}
query.exec( function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, result );
} );
},
update: function ( id, update, callback ) {
model.findByIdAndUpdate( id, update, function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, result );
} );
},
delete: function ( id, callback ) {
model.findByIdAndRemove( id, function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, {} );
} );
}
};
};
| var systemError = require( '../utils' ).systemError;
exports.MongooseDataManager = function ( model ) {
return {
create: function ( data, callback ) {
model.create( data, function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, result );
} );
},
list: function ( data, callback ) {
model.find( data, function ( err, results ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, results );
} );
},
read: function ( id, callback ) {
model.findById( id, function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, result );
} );
},
update: function ( id, update, callback ) {
model.findByIdAndUpdate( id, update, function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, result );
} );
},
delete: function ( id, callback ) {
model.findByIdAndRemove( id, function ( err, result ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, {} );
} );
}
};
};
|
Test fix for IE8 delete-confirm problem. | (function() {
window.utils = {
initDeleteConfirm: function(formSelector) {
$(".delete-btn").click(function() {
window.utils.openDeleteConfirm(formSelector);
});
},
openDeleteConfirm: function(formSelector) {
if ($(formSelector + " input[type=checkbox]").is(":checked")) {
var dialog = $(".delete-confirm");
if (!dialog.hasClass("ui-dialog-content")) {
dialog.dialog({
"modal": true,
"autoopen": false,
"appendTo": "body",
"buttons": [{
"text": gettext("Cancel"),
"class": "btn btn-primary",
"click": function(ev) {
$(this).dialog("close");
}
},
{
"text": gettext("OK"),
"class": "btn",
"click": function(ev) {
$(this).dialog("close");
$(formSelector).submit();
}
}],
"open": function() {
var dialog = $(this).closest(".ui-dialog");
dialog.find(".ui-dialog-titlebar > button").remove();
}
});
} else {
dialog.dialog("open");
}
}
}
}
})();
| (function() {
window.utils = {
initDeleteConfirm: function(formSelector) {
$(".delete-btn").click(function() {
window.utils.openDeleteConfirm(formSelector);
});
},
openDeleteConfirm: function(formSelector) {
if ($(formSelector + " input[type=checkbox]").is(":checked")) {
var dialog = $(".delete-confirm");
if (!dialog.hasClass("ui-dialog-content")) {
dialog.dialog({
modal: true,
autoopen: false,
appendTo: "body",
buttons: [{
text: gettext("Cancel"),
class: "btn btn-primary",
click: function(ev) {
$(this).dialog("close");
}
},
{
text: gettext("OK"),
class: "btn",
click: function(ev) {
$(this).dialog("close");
$(formSelector).submit();
}
}],
open: function() {
var dialog = $(this).closest(".ui-dialog");
dialog.find(".ui-dialog-titlebar > button").remove();
}
});
} else {
dialog.dialog("open");
}
}
}
}
})();
|
Fix Null Id, on create user Postgresql | <?php
namespace ZfcUser\Mapper;
use Zend\Stdlib\Hydrator\ClassMethods;
use ZfcUser\Entity\UserInterface as UserEntityInterface;
class UserHydrator extends ClassMethods {
/**
* Extract values from an object
*
* @param object $object
* @return array
* @throws Exception\InvalidArgumentException
*/
public function extract($object) {
if (!$object instanceof UserEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
}
/* @var $object UserInterface */
$data = parent::extract($object);
if ($data['id'] !== null) {
$data = $this->mapField('id', 'user_id', $data);
} else {
unset($data['id']);
}
return $data;
}
/**
* Hydrate $object with the provided $data.
*
* @param array $data
* @param object $object
* @return UserInterface
* @throws Exception\InvalidArgumentException
*/
public function hydrate(array $data, $object) {
if (!$object instanceof UserEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
}
$data = $this->mapField('user_id', 'id', $data);
return parent::hydrate($data, $object);
}
protected function mapField($keyFrom, $keyTo, array $array) {
$array[$keyTo] = $array[$keyFrom];
unset($array[$keyFrom]);
return $array;
}
}
| <?php
namespace ZfcUser\Mapper;
use Zend\Stdlib\Hydrator\ClassMethods;
use ZfcUser\Entity\UserInterface as UserEntityInterface;
class UserHydrator extends ClassMethods
{
/**
* Extract values from an object
*
* @param object $object
* @return array
* @throws Exception\InvalidArgumentException
*/
public function extract($object)
{
if (!$object instanceof UserEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
}
/* @var $object UserInterface*/
$data = parent::extract($object);
$data = $this->mapField('id', 'user_id', $data);
return $data;
}
/**
* Hydrate $object with the provided $data.
*
* @param array $data
* @param object $object
* @return UserInterface
* @throws Exception\InvalidArgumentException
*/
public function hydrate(array $data, $object)
{
if (!$object instanceof UserEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
}
$data = $this->mapField('user_id', 'id', $data);
return parent::hydrate($data, $object);
}
protected function mapField($keyFrom, $keyTo, array $array)
{
$array[$keyTo] = $array[$keyFrom];
unset($array[$keyFrom]);
return $array;
}
}
|
Use session cookie encryption key from environment variable | package au.gov.dto.dibp.appointments.config;
import au.gov.dto.dibp.appointments.initializer.HttpsOnlyFilter;
import au.gov.dto.dibp.appointments.initializer.LogClientIdFilter;
import au.gov.dto.dibp.appointments.initializer.NoHttpSessionFilter;
import com.oakfusion.security.SecurityCookieService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "au.gov.dto.dibp.appointments")
public class AppConfig {
@Bean
public FilterRegistrationBean httpsFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new HttpsOnlyFilter());
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public FilterRegistrationBean noHttpSessionFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new NoHttpSessionFilter());
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public FilterRegistrationBean logClientIdFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LogClientIdFilter());
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public SecurityCookieService securityCookieService(@Value("${session.encryption.key}") String sessionEncryptionKey) {
return new SecurityCookieService("session", sessionEncryptionKey);
}
}
| package au.gov.dto.dibp.appointments.config;
import au.gov.dto.dibp.appointments.initializer.HttpsOnlyFilter;
import au.gov.dto.dibp.appointments.initializer.LogClientIdFilter;
import au.gov.dto.dibp.appointments.initializer.NoHttpSessionFilter;
import com.oakfusion.security.SecurityCookieService;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "au.gov.dto.dibp.appointments")
public class AppConfig {
@Bean
public FilterRegistrationBean httpsFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new HttpsOnlyFilter());
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public FilterRegistrationBean noHttpSessionFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new NoHttpSessionFilter());
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public FilterRegistrationBean logClientIdFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LogClientIdFilter());
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public SecurityCookieService securityCookieService() {
return new SecurityCookieService("session", "secretkey");
}
}
|
Revert "Wagtailmenus works with wagtail 1.8 too"
This reverts commit 1e4b7eb5301c0db3e29abf539c5f4b54d11720b8. | import os
from setuptools import setup, find_packages
from wagtailmenus import __version__
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="wagtailmenus",
version=__version__,
author="Andy Babic",
author_email="[email protected]",
description=("An app to help you manage menus in your Wagtail projects "
"more consistently."),
long_description=README,
packages=find_packages(),
license="MIT",
keywords="wagtail cms model utility",
download_url="https://github.com/rkhleics/wagtailmenus/tarball/v2.0.1",
url="https://github.com/rkhleics/wagtailmenus/tree/stable/2.0.x",
include_package_data=True,
zip_safe=False,
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
'Topic :: Internet :: WWW/HTTP',
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
install_requires=[
"wagtail>=1.5,<1.8",
],
)
| import os
from setuptools import setup, find_packages
from wagtailmenus import __version__
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="wagtailmenus",
version=__version__,
author="Andy Babic",
author_email="[email protected]",
description=("An app to help you manage menus in your Wagtail projects "
"more consistently."),
long_description=README,
packages=find_packages(),
license="MIT",
keywords="wagtail cms model utility",
download_url="https://github.com/rkhleics/wagtailmenus/tarball/v2.0.1",
url="https://github.com/rkhleics/wagtailmenus/tree/stable/2.0.x",
include_package_data=True,
zip_safe=False,
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
'Topic :: Internet :: WWW/HTTP',
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
install_requires=[
"wagtail>=1.5,<1.9",
],
)
|
Fix posts como conteúdo restrito para usuários não logados | <?php get_header(); ?>
<div class="row">
<?php while (have_posts()): the_post(); ?>
<article id="post-<?php the_ID(); ?>" class="post-container">
<?php if (get_post_status(get_the_ID()) == 'publish' || current_user_can('read_post', get_the_ID())): ?>
<div class="col-xs-12">
<?php
//Pega o paineldosposts para mostrar na pagina front-page os posts.
get_template_part( 'partes-templates/painel-single', get_post_format());
?>
</div>
<?php else: ?>
<div class="col-xs-12">
<div class="panel panel-default padding-bottom">
<div class="panel-heading" style="padding: 21px;">
<div class="row post-titulo">
<div class="col-xs-12">
Conteúdo restrito
</div>
</div>
</div>
</div>
</div>
<?php endif; ?>
</article><!-- #post-## -->
<?php endwhile; ?>
</div>
<?php get_footer(); | <?php get_header(); ?>
<div class="row">
<?php while (have_posts()): the_post(); ?>
<article id="post-<?php the_ID(); ?>" class="post-container">
<?php if (current_user_can('read_post', get_the_ID())): ?>
<div class="col-xs-12">
<?php
//Pega o paineldosposts para mostrar na pagina front-page os posts.
get_template_part( 'partes-templates/painel-single', get_post_format());
?>
</div>
<?php else: ?>
<div class="col-xs-12">
<div class="panel panel-default padding-bottom">
<div class="panel-heading" style="padding: 21px;">
<div class="row post-titulo">
<div class="col-xs-12">
Conteúdo restrito
</div>
</div>
</div>
</div>
</div>
<?php endif; ?>
</article><!-- #post-## -->
<?php endwhile; ?>
</div>
<?php get_footer(); |
Remove unneccesary webpack node_modules path adjustment | var path = require('path');
const webpack = require('webpack')
const baseConfig = module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: '/'
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': path.resolve(__dirname, '../src'),
}
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
include: path.resolve('src')
}, {
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'static/img/[name].[hash:7].[ext]'
}
}, {
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'static/fonts/[name].[hash:7].[ext]'
}
}]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Tether: 'tether'
}),
]
}; | var path = require('path');
const webpack = require('webpack')
const baseConfig = module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: '/'
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': path.resolve(__dirname, '../src'),
},
modules: [path.resolve(__dirname, "../../node_modules")]
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
include: path.resolve('src')
}, {
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'static/img/[name].[hash:7].[ext]'
}
}, {
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'static/fonts/[name].[hash:7].[ext]'
}
}]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Tether: 'tether'
}),
]
}; |
Fix bug where it skips starting point | var dom = require('./src/dom.js');
var notify = require('./src/notify.js');
var end = 0;
var state = 0;
var message = '';
var timeoutID = null;
var output = dom('title, h1');
var icon = './noticon.png';
var notification;
function go() {
if(state) {
var diff = Math.round((end - Date.now()) / 1000);
if(diff > 0) {
output.html(format(diff));
timeoutID = setTimeout(go, 100);
}
else {
notification = notify(message, icon);
reset();
}
}
}
function reset() {
state = 0;
output.html(format(0));
if(timeoutID) {
clearTimeout(timeoutID);
}
}
function format(diff) {
return [diff / 60, diff % 60]
.map(Math.floor)
.map(function(int){
if(int >= 10) {
return int
}
return '0' + int;
})
.join(':');
}
dom('button').on('click', function(){
reset();
if(notification) {
notification.close();
}
notification = null;
state = 1;
end = Date.now() + (this.getAttribute('data-interval') * 60000);
message = this.getAttribute('data-message');
go();
});
notify.grant();
| var dom = require('./src/dom.js');
var notify = require('./src/notify.js');
var end = 0;
var state = 0;
var message = '';
var timeoutID = null;
var output = dom('title, h1');
var icon = './noticon.png';
var notification;
function go() {
if(state) {
var diff = (end - Date.now()) / 1000;
if(diff > 0) {
output.html(format(diff));
timeoutID = setTimeout(go, 300);
}
else {
notification = notify(message, icon);
reset();
}
}
}
function reset() {
state = 0;
output.html(format(0));
if(timeoutID) {
clearTimeout(timeoutID);
}
}
function format(diff) {
return [diff / 60, diff % 60]
.map(Math.floor)
.map(function(int){
if(int >= 10) {
return int
}
return '0' + int;
})
.join(':');
}
dom('button').on('click', function(){
reset();
if(notification) {
notification.close();
}
notification = null;
state = 1;
end = Date.now() + (this.getAttribute('data-interval') * 60000);
message = this.getAttribute('data-message');
go();
});
notify.grant();
|
Change the location of unit suffix | define(['jquery', 'base/js/utils'], function ($, utils) {
function createDisplayDiv() {
$('#maintoolbar-container').append(
$('<div>').attr('id', 'nbresuse-display')
.addClass('btn-group')
.addClass('pull-right')
.append(
$('<strong>').text('Mem: ')
).append(
$('<span>').attr('id', 'nbresuse-mem')
.attr('title', 'Actively used Memory (updates every 5s)')
)
);
}
var displayMetrics = function() {
$.getJSON(utils.get_body_data('baseUrl') + 'metrics', function(data) {
// FIXME: Proper setups for MB and GB. MB should have 0 things
// after the ., but GB should have 2.
var display = Math.round(data['rss'] / (1024 * 1024));
if (data['limits']['memory'] !== null) {
display += " / " + (data['limits']['memory'] / (1024 * 1024));
}
$('#nbresuse-mem').text(display + ' MB');
});
}
var load_ipython_extension = function () {
createDisplayDiv();
displayMetrics();
// Update every five seconds, eh?
setInterval(displayMetrics, 1000 * 5);
};
return {
load_ipython_extension: load_ipython_extension,
};
});
| define(['jquery', 'base/js/utils'], function ($, utils) {
function createDisplayDiv() {
$('#maintoolbar-container').append(
$('<div>').attr('id', 'nbresuse-display')
.addClass('btn-group')
.addClass('pull-right')
.append(
$('<strong>').text('Mem: ')
).append(
$('<span>').attr('id', 'nbresuse-mem')
.attr('title', 'Actively used Memory (updates every 5s)')
)
);
}
var displayMetrics = function() {
$.getJSON(utils.get_body_data('baseUrl') + 'metrics', function(data) {
// FIXME: Proper setups for MB and GB. MB should have 0 things
// after the ., but GB should have 2.
var display = Math.round(data['rss'] / (1024 * 1024)) + " MB";
if (data['limits']['memory'] !== null) {
display += " / " + (data['limits']['memory'] / (1024 * 1024));
}
$('#nbresuse-mem').text(display);
});
}
var load_ipython_extension = function () {
createDisplayDiv();
displayMetrics();
// Update every five seconds, eh?
setInterval(displayMetrics, 1000 * 5);
};
return {
load_ipython_extension: load_ipython_extension,
};
});
|
Fix - iterable type introduced in PHP 7.1 | <?php
declare(strict_types=1);
namespace Rector\ValueObject;
final class PhpVersionFeature
{
/**
* @var string
*/
public const SCALAR_TYPES = '7.0';
/**
* @var string
*/
public const NULL_COALESCE = '7.0';
/**
* @var string
*/
public const SPACESHIP = '7.0';
/**
* @var string
*/
public const ITERABLE_TYPE = '7.1';
/**
* @var string
*/
public const VOID_TYPE = '7.1';
/**
* @var string
*/
public const OBJECT_TYPE = '7.2';
/**
* @var string
*/
public const IS_COUNTABLE = '7.3';
/**
* @var string
*/
public const ARROW_FUNCTION = '7.4';
/**
* @var string
*/
public const LITERAL_SEPARATOR = '7.4';
/**
* @var string
*/
public const NULL_COALESCE_ASSIGN = '7.4';
/**
* @var string
*/
public const TYPED_PROPERTIES = '7.4';
/**
* @var string
*/
public const BEFORE_UNION_TYPES = '7.4';
/**
* @var string
*/
public const UNION_TYPES = '8.0';
}
| <?php
declare(strict_types=1);
namespace Rector\ValueObject;
final class PhpVersionFeature
{
/**
* @var string
*/
public const SCALAR_TYPES = '7.0';
/**
* @var string
*/
public const NULL_COALESCE = '7.0';
/**
* @var string
*/
public const ITERABLE_TYPE = '7.0';
/**
* @var string
*/
public const SPACESHIP = '7.0';
/**
* @var string
*/
public const VOID_TYPE = '7.1';
/**
* @var string
*/
public const OBJECT_TYPE = '7.2';
/**
* @var string
*/
public const IS_COUNTABLE = '7.3';
/**
* @var string
*/
public const ARROW_FUNCTION = '7.4';
/**
* @var string
*/
public const LITERAL_SEPARATOR = '7.4';
/**
* @var string
*/
public const NULL_COALESCE_ASSIGN = '7.4';
/**
* @var string
*/
public const TYPED_PROPERTIES = '7.4';
/**
* @var string
*/
public const BEFORE_UNION_TYPES = '7.4';
/**
* @var string
*/
public const UNION_TYPES = '8.0';
}
|
Fix uploaded file tmp path | <?php
namespace Colorium\Http\Request;
class File
{
const OK = 0;
const MAX_SIZE = 1;
const FORM_SIZE = 2;
const PARTIAL = 3;
const NO_FILE = 4;
const NO_TMP_DIR = 6;
const CANT_WRITE = 7;
const ERR_EXTENSION = 8;
/** @var string */
public $name;
/** @var string */
public $ext;
/** @var string */
public $tmp;
/** @var string */
public $type;
/** @var int */
public $size;
/** @var int */
public $error = self::OK;
/**
* Create from $_FILES
*
* @param array $file
*/
public function __construct(array $file)
{
$this->name = basename($file['name']);
$this->ext = pathinfo($this->name, PATHINFO_EXTENSION);
$this->tmp = $file['tmp_name'];
$this->type = $file['type'];
$this->size = $file['size'];
$this->error = (int)$file['error'];
}
/**
* Save file to directory
*
* @param string $dir
* @param string $filename
*
* @return bool
*/
public function save($dir, $filename = null)
{
// clean
$dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if(!$filename) {
$filename = $this->name;
}
return move_uploaded_file($this->tmp, $dir . $filename);
}
} | <?php
namespace Colorium\Http\Request;
class File
{
const OK = 0;
const MAX_SIZE = 1;
const FORM_SIZE = 2;
const PARTIAL = 3;
const NO_FILE = 4;
const NO_TMP_DIR = 6;
const CANT_WRITE = 7;
const ERR_EXTENSION = 8;
/** @var string */
public $name;
/** @var string */
public $ext;
/** @var string */
public $tmp;
/** @var string */
public $type;
/** @var int */
public $size;
/** @var int */
public $error = self::OK;
/**
* Create from $_FILES
*
* @param array $file
*/
public function __construct(array $file)
{
$this->name = basename($file['name']);
$this->ext = pathinfo($this->name, PATHINFO_EXTENSION);
$this->tmp = $file['tmp_file'];
$this->type = $file['type'];
$this->size = $file['size'];
$this->error = (int)$file['error'];
}
/**
* Save file to directory
*
* @param string $dir
* @param string $filename
*
* @return bool
*/
public function save($dir, $filename = null)
{
// clean
$dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if(!$filename) {
$filename = $this->name;
}
return move_uploaded_file($this->tmp, $dir . $filename);
}
} |
Make the Future transient so not serialized | package co.phoenixlab.discord.commands.tempstorage;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Future;
public class ServerTimeout {
private final String serverId;
private final String userId;
private final Instant startTime;
private final Duration duration;
private final Instant endTime;
private final String issuedByUserId;
private final transient Future<Void> timerFuture;
public ServerTimeout(Duration duration, Instant startTime, String userId, String serverId, String issuedByUserId,
Future<Void> timerFuture) {
this.duration = duration;
this.startTime = startTime;
this.userId = userId;
this.serverId = serverId;
this.timerFuture = timerFuture;
this.endTime = startTime.plus(duration);
this.issuedByUserId = issuedByUserId;
}
public String getServerId() {
return serverId;
}
public String getUserId() {
return userId;
}
public Instant getStartTime() {
return startTime;
}
public Duration getDuration() {
return duration;
}
public Instant getEndTime() {
return endTime;
}
public String getIssuedByUserId() {
return issuedByUserId;
}
public Future<Void> getTimerFuture() {
return timerFuture;
}
}
| package co.phoenixlab.discord.commands.tempstorage;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Future;
public class ServerTimeout {
private final String serverId;
private final String userId;
private final Instant startTime;
private final Duration duration;
private final Instant endTime;
private final String issuedByUserId;
private final Future<Void> timerFuture;
public ServerTimeout(Duration duration, Instant startTime, String userId, String serverId, String issuedByUserId,
Future<Void> timerFuture) {
this.duration = duration;
this.startTime = startTime;
this.userId = userId;
this.serverId = serverId;
this.timerFuture = timerFuture;
this.endTime = startTime.plus(duration);
this.issuedByUserId = issuedByUserId;
}
public String getServerId() {
return serverId;
}
public String getUserId() {
return userId;
}
public Instant getStartTime() {
return startTime;
}
public Duration getDuration() {
return duration;
}
public Instant getEndTime() {
return endTime;
}
public String getIssuedByUserId() {
return issuedByUserId;
}
public Future<Void> getTimerFuture() {
return timerFuture;
}
}
|
Hide Contact when Demo button is clicked | define(['jquery', 'spine/spine', 'app/controller/hero', 'app/basepath'], function($, Spine, Hero, basepath) {
"use strict";
console.log('app/controller/demo-button.js');
var DemoButton = Spine.Controller.sub({
el: $('#demo_button'),
events: {
'click': 'click'
},
init: function() { },
click: function() {
_gaq.push(['_trackEvent', 'Demo', 'Create']);
$('#info').fadeOut();
$('#screenshots').fadeOut();
$('#github_ribbon').fadeOut();
$('#whos-using').fadeOut();
$('#what-said').fadeOut();
$('#contact').fadeOut();
Hero.instance.el.fadeOut(function() {
$('#loader').show();
$.ajax({
url: 'create',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({isDemo: true}),
error: function(err) {
// FIXME
},
complete: function(response) {
var id = response.responseText;
Spine.Route.navigate(basepath.getPath() + id);
$('#loader').hide();
$('#outer-container').show();
$('#editor_container').show('slow');
}
});
});
}
});
return new DemoButton();
});
| define(['jquery', 'spine/spine', 'app/controller/hero', 'app/basepath'], function($, Spine, Hero, basepath) {
"use strict";
console.log('app/controller/demo-button.js');
var DemoButton = Spine.Controller.sub({
el: $('#demo_button'),
events: {
'click': 'click'
},
init: function() { },
click: function() {
_gaq.push(['_trackEvent', 'Demo', 'Create']);
$('#info').fadeOut();
$('#screenshots').fadeOut();
$('#github_ribbon').fadeOut();
$('#whos-using').fadeOut();
$('#what-said').fadeOut();
Hero.instance.el.fadeOut(function() {
$('#loader').show();
$.ajax({
url: 'create',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({isDemo: true}),
error: function(err) {
// FIXME
},
complete: function(response) {
var id = response.responseText;
Spine.Route.navigate(basepath.getPath() + id);
$('#loader').hide();
$('#outer-container').show();
$('#editor_container').show('slow');
}
});
});
}
});
return new DemoButton();
});
|
Change the way tags are rendered. | <?php
/**
* The template for displaying post snippets. Used for both single and index/archive/search.
*
* @package NotebookHeavy
* @subpackage NH2013
* @since NH2013 1.0
*/
?>
<article id="post-<?php the_ID(); ?>">
<div style="background-image: url(img/image-sliver.jpg)" class="sliver">
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"> </a>
</div>
<div class="postInfo">
<h2><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<footer>
<time><?php the_date('Y-m-d'); ?></time>
<div class="tags">
<?php the_tags('', ', ',''); ?>
</div>
</footer>
</div>
<div class="postSample">
<section>
<?php the_excerpt(); ?>
</section>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark">Continue Reading</a>
</div>
</article> | <?php
/**
* The template for displaying post snippets. Used for both single and index/archive/search.
*
* @package NotebookHeavy
* @subpackage NH2013
* @since NH2013 1.0
*/
?>
<article id="post-<?php the_ID(); ?>">
<div style="background-image: url(img/image-sliver.jpg)" class="sliver">
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"> </a>
</div>
<div class="postInfo">
<h2><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<footer>
<time><?php the_date('Y-m-d'); ?></time>
<div class="tags">
<?php the_tags(); ?>
</div>
</footer>
</div>
<div class="postSample">
<section>
<?php the_excerpt(); ?>
</section>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( 'Permalink to %s', the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark">Continue Reading</a>
</div>
</article> |
Use Django's bundled six version instead of requiring to install another one. | from django.utils.translation import gettext as _
from django.utils import six
from django_enumfield.exceptions import InvalidStatusOperationError
def validate_valid_transition(enum, from_value, to_value):
"""
Validate that to_value is a valid choice and that to_value is a valid transition from from_value.
"""
validate_available_choice(enum, to_value)
if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value):
message = _(six.text_type('{enum} can not go from "{from_value}" to "{to_value}"'))
raise InvalidStatusOperationError(message.format(
enum=enum.__name__,
from_value=enum.name(from_value),
to_value=enum.name(to_value) or to_value
))
def validate_available_choice(enum, to_value):
"""
Validate that to_value is defined as a value in enum.
"""
if to_value is None:
return
if type(to_value) is not int:
try:
to_value = int(to_value)
except ValueError:
message_str = "'{value}' cannot be converted to int"
message = _(six.text_type(message_str))
raise InvalidStatusOperationError(message.format(value=to_value))
if to_value not in list(dict(enum.choices()).keys()):
message = _(six.text_type('Select a valid choice. {value} is not one of the available choices.'))
raise InvalidStatusOperationError(message.format(value=to_value))
| from django.utils.translation import gettext as _
import six
from django_enumfield.exceptions import InvalidStatusOperationError
def validate_valid_transition(enum, from_value, to_value):
"""
Validate that to_value is a valid choice and that to_value is a valid transition from from_value.
"""
validate_available_choice(enum, to_value)
if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value):
message = _(six.text_type('{enum} can not go from "{from_value}" to "{to_value}"'))
raise InvalidStatusOperationError(message.format(
enum=enum.__name__,
from_value=enum.name(from_value),
to_value=enum.name(to_value) or to_value
))
def validate_available_choice(enum, to_value):
"""
Validate that to_value is defined as a value in enum.
"""
if to_value is None:
return
if type(to_value) is not int:
try:
to_value = int(to_value)
except ValueError:
message_str = "'{value}' cannot be converted to int"
message = _(six.text_type(message_str))
raise InvalidStatusOperationError(message.format(value=to_value))
if to_value not in list(dict(enum.choices()).keys()):
message = _(six.text_type('Select a valid choice. {value} is not one of the available choices.'))
raise InvalidStatusOperationError(message.format(value=to_value))
|
Discard notification of activities with null GroupId or type | const axios = require('axios');
const activitiesLib = require('../lib/activities');
const slackLib = require('./slack');
const ACTIVITY_ALL = 'all';
module.exports = (Sequelize, activity) => {
if(!activity.GroupId || !activity.type) {
return;
}
Sequelize.models.Notification.findAll({
where: {
type: [
ACTIVITY_ALL,
activity.type
],
GroupId: activity.GroupId,
// for now, only handle gitter and slack webhooks in this lib
// TODO sdubois: move email + internal slack channels to this lib
channel: ['gitter', 'slack'],
active: true
}
}).then(notifConfigs => {
return notifConfigs.map(notifConfig => {
if (notifConfig.channel === 'gitter') {
return publishToGitter(activity, notifConfig);
} else if (notifConfig.channel === 'slack') {
return publishToSlack(activity, notifConfig);
}
})
})
.catch(err => {
console.error(`Error while publishing activity type ${activity.type} for group ${activity.GroupId}`, err);
});
};
function publishToGitter(activity, notifConfig) {
return axios
.post(notifConfig.webhookUrl, {
message: activitiesLib.formatMessage(activity, false)
});
}
function publishToSlack(activity, notifConfig) {
return slackLib.postActivity(activity, {
webhookUrl: notifConfig.webhookUrl,
channel: undefined
});
}
| const axios = require('axios');
const activitiesLib = require('../lib/activities');
const slackLib = require('./slack');
const ACTIVITY_ALL = 'all';
module.exports = (Sequelize, activity) => {
if(typeof activity.GroupId === 'undefined' || typeof activity.type === 'undefined') {
return;
}
Sequelize.models.Notification.findAll({
where: {
type: [
ACTIVITY_ALL,
activity.type
],
GroupId: activity.GroupId,
// for now, only handle gitter and slack webhooks in this lib
// TODO sdubois: move email + internal slack channels to this lib
channel: ['gitter', 'slack'],
active: true
}
}).then(notifConfigs => {
return notifConfigs.map(notifConfig => {
if (notifConfig.channel === 'gitter') {
return publishToGitter(activity, notifConfig);
} else if (notifConfig.channel === 'slack') {
return publishToSlack(activity, notifConfig);
}
})
})
.catch(err => {
console.error(`Error while publishing activity type ${activity.type} for group ${activity.GroupId}`, err);
});
};
function publishToGitter(activity, notifConfig) {
return axios
.post(notifConfig.webhookUrl, {
message: activitiesLib.formatMessage(activity, false)
});
}
function publishToSlack(activity, notifConfig) {
return slackLib.postActivity(activity, {
webhookUrl: notifConfig.webhookUrl,
channel: undefined
});
}
|
Update to support config files that are passed to it. | from imhotep.tools import Tool
from collections import defaultdict
import json
import os
class RubyLintLinter(Tool):
def invoke(self, dirname, filenames=set(), linter_configs=set()):
retval = defaultdict(lambda: defaultdict(list))
config = ''
for config_file in linter_configs:
if 'rubocop' in config_file:
config = "-c %s " % config_file
if len(filenames) == 0:
cmd = "find %s -name '*.rb' | xargs rubocop %s -f j" % (dirname, config)
else:
ruby_files = []
for filename in filenames:
if '.rb' in filename:
ruby_files.append("%s/%s" % (dirname, filename))
cmd = "rubocop %s -f j %s" % (config, " ".join(ruby_files))
try:
output = json.loads(self.executor(cmd))
for linted_file in output['files']:
# The path should be relative to the repo,
# without a leading slash
# example db/file.rb
file_name = os.path.abspath(linted_file['path'])
file_name = file_name.replace(dirname, "")[1:]
for offence in linted_file['offences']:
line_number = str(offence['location']['line'])
retval[str(file_name)][line_number].append(
str(offence['message']))
retval[str(file_name)][line_number] = list(set(retval[str(file_name)][line_number]))
except:
pass
return retval
| from imhotep.tools import Tool
from collections import defaultdict
import json
import os
class RubyLintLinter(Tool):
def invoke(self, dirname, filenames=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = "find %s -name '*.rb' | xargs rubocop -f j" % dirname
else:
ruby_files = []
for filename in filenames:
if '.rb' in filename:
ruby_files.append("%s/%s" % (dirname, filename))
cmd = "rubocop -f j %s" % (" ".join(ruby_files))
try:
output = json.loads(self.executor(cmd))
for linted_file in output['files']:
# The path should be relative to the repo,
# without a leading slash
# example db/file.rb
file_name = os.path.abspath(linted_file['path'])
file_name = file_name.replace(dirname, "")[1:]
for offence in linted_file['offences']:
line_number = str(offence['location']['line'])
retval[str(file_name)][line_number].append(
str(offence['message']))
retval[str(file_name)][line_number] = list(set(retval[str(file_name)][line_number]))
except:
pass
return retval
|
Make it possible to upload files to Company Images | <?php
class Infusionsoft_FileServiceBase extends Infusionsoft_Service{
public static function getFile($fileId, Infusionsoft_App $app = null){
$params = array(
(int) $fileId
);
return parent::send($app, "FileService.getFile", $params);
}
public static function getDownloadUrl($fileId, Infusionsoft_App $app = null){
$params = array(
(int) $fileId
);
return parent::send($app, "FileService.getDownloadUrl", $params);
}
public static function uploadFile($contactId, $fileName, $base64encoded, Infusionsoft_App $app = null){
// If contactId is null, do not include it in the params
if ($contactId === null) {
$params = array(
$fileName,
$base64encoded
);
} else {
$params = array(
(int) $contactId,
$fileName,
$base64encoded
);
}
return parent::send($app, "FileService.uploadFile", $params);
}
public static function replaceFile($fileId, $base64encoded, Infusionsoft_App $app = null){
$params = array(
(int) $fileId,
$base64encoded
);
return parent::send($app, "FileService.replaceFile", $params);
}
public static function renameFile($fileId, $fileName, Infusionsoft_App $app = null){
$params = array(
(int) $fileId,
$fileName
);
return parent::send($app, "FileService.renameFile", $params);
}
}
| <?php
class Infusionsoft_FileServiceBase extends Infusionsoft_Service{
public static function getFile($fileId, Infusionsoft_App $app = null){
$params = array(
(int) $fileId
);
return parent::send($app, "FileService.getFile", $params);
}
public static function getDownloadUrl($fileId, Infusionsoft_App $app = null){
$params = array(
(int) $fileId
);
return parent::send($app, "FileService.getDownloadUrl", $params);
}
public static function uploadFile($contactId, $fileName, $base64encoded, Infusionsoft_App $app = null){
$params = array(
(int) $contactId,
$fileName,
$base64encoded
);
return parent::send($app, "FileService.uploadFile", $params);
}
public static function replaceFile($fileId, $base64encoded, Infusionsoft_App $app = null){
$params = array(
(int) $fileId,
$base64encoded
);
return parent::send($app, "FileService.replaceFile", $params);
}
public static function renameFile($fileId, $fileName, Infusionsoft_App $app = null){
$params = array(
(int) $fileId,
$fileName
);
return parent::send($app, "FileService.renameFile", $params);
}
} |
Add msgs to null check | package stroom.kafka.api;
import stroom.kafka.shared.KafkaConfigDoc;
import java.util.Objects;
public class KafkaProducerSupplierKey {
private final String uuid;
private final String version;
public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
Objects.requireNonNull(kafkaConfigDoc);
this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid(), "KafkaConfigDoc is missing a UUID");
this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion(), "KafkaConfigDoc is missing a version");
}
public KafkaProducerSupplierKey(final String uuid, final String version) {
this.uuid = Objects.requireNonNull(uuid);
this.version = Objects.requireNonNull(version);
}
public String getUuid() {
return uuid;
}
public String getVersion() {
return version;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
return uuid.equals(that.uuid) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(uuid, version);
}
@Override
public String toString() {
return "KafkaProducerSupplierKey{" +
"uuid='" + uuid + '\'' +
", version='" + version + '\'' +
'}';
}
}
| package stroom.kafka.api;
import stroom.kafka.shared.KafkaConfigDoc;
import java.util.Objects;
public class KafkaProducerSupplierKey {
private final String uuid;
private final String version;
public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
Objects.requireNonNull(kafkaConfigDoc);
this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid());
this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion());
}
public KafkaProducerSupplierKey(final String uuid, final String version) {
this.uuid = Objects.requireNonNull(uuid);
this.version = Objects.requireNonNull(version);
}
public String getUuid() {
return uuid;
}
public String getVersion() {
return version;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
return uuid.equals(that.uuid) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(uuid, version);
}
@Override
public String toString() {
return "KafkaProducerSupplierKey{" +
"uuid='" + uuid + '\'' +
", version='" + version + '\'' +
'}';
}
}
|
Clarify test_containers_to_host not using libnetwork
Former-commit-id: fbd7c3b5627ba288ac400944ee242f3369143291 | from subprocess import CalledProcessError
from test_base import TestBase
from tests.st.utils.docker_host import DockerHost
class TestContainerToHost(TestBase):
def test_container_to_host(self):
"""
Test that a container can ping the host.
This function is important for Mesos, since the containerized executor
needs to exchange messages with the Mesos Slave process on the host.
Note also that we do not use the Docker Network driver for this test.
The Docker Container Network Model defines a "network" as a group of
endpoints that can communicate with each other, but are isolated from
everything else. Thus, an endpoint of a Docker network should not be
able to ping the host.
"""
with DockerHost('host', dind=False) as host:
host.calicoctl("profile add TEST")
# Use standard docker bridge networking.
node1 = host.create_workload("node1")
# Add the nodes to Calico networking.
host.calicoctl("container add %s 192.168.100.1" % node1)
# Get the endpoint IDs for the containers
ep1 = host.calicoctl("container %s endpoint-id show" % node1)
# Now add the profiles.
host.calicoctl("endpoint %s profile set TEST" % ep1)
# Check it works. Note that the profile allows all outgoing
# traffic by default, and conntrack should allow the reply.
node1.assert_can_ping(host.ip, retries=10)
| from subprocess import CalledProcessError
from test_base import TestBase
from tests.st.utils.docker_host import DockerHost
class TestContainerToHost(TestBase):
def test_container_to_host(self):
"""
Test that a container can ping the host. (Without using the docker
network driver, since it doesn't support that yet.)
This function is important for Mesos, since the containerized executor
needs to exchange messages with the Mesos Slave process on the host.
"""
with DockerHost('host', dind=False) as host:
host.calicoctl("profile add TEST")
# Use standard docker bridge networking.
node1 = host.create_workload("node1")
# Add the nodes to Calico networking.
host.calicoctl("container add %s 192.168.100.1" % node1)
# Get the endpoint IDs for the containers
ep1 = host.calicoctl("container %s endpoint-id show" % node1)
# Now add the profiles.
host.calicoctl("endpoint %s profile set TEST" % ep1)
# Check it works. Note that the profile allows all outgoing
# traffic by default, and conntrack should allow the reply.
node1.assert_can_ping(host.ip, retries=10)
# Test the teardown commands
host.calicoctl("profile remove TEST")
host.calicoctl("container remove %s" % node1)
host.calicoctl("pool remove 192.168.0.0/16")
host.calicoctl("node stop")
|
Use MockitoJUnitRunner instead of initMocks. | package com.github.ajalt.reprint.core;
import com.github.ajalt.reprint.testing.TestReprintModule;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(MockitoJUnitRunner.class)
public class ReprintTest {
public TestReprintModule module;
@Mock
public AuthenticationListener listener;
@Before
public void setup() {
module = new TestReprintModule();
module.listener = null;
module.cancellationSignal = null;
Reprint.registerModule(module);
Reprint.authenticate(listener);
assertThat(module.listener).isNotNull();
}
@Test
public void successfulRequest() throws Exception {
verifyZeroInteractions(listener);
module.listener.onSuccess(module.TAG);
verify(listener).onSuccess(anyInt());
}
@Test
public void failedRequest() throws Exception {
verifyZeroInteractions(listener);
module.listener.onFailure(AuthenticationFailureReason.AUTHENTICATION_FAILED, false, "", module.TAG, 0);
verify(listener).onFailure(eq(AuthenticationFailureReason.AUTHENTICATION_FAILED), eq(false), anyString(), anyInt(), anyInt());
}
}
| package com.github.ajalt.reprint.core;
import com.github.ajalt.reprint.testing.TestReprintModule;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
public class ReprintTest {
public TestReprintModule module;
@Mock
public AuthenticationListener listener;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
module = new TestReprintModule();
module.listener = null;
module.cancellationSignal = null;
Reprint.registerModule(module);
Reprint.authenticate(listener);
assertThat(module.listener).isNotNull();
}
@Test
public void successfulRequest() throws Exception {
verifyZeroInteractions(listener);
module.listener.onSuccess(module.TAG);
verify(listener).onSuccess(anyInt());
}
@Test
public void failedRequest() throws Exception {
verifyZeroInteractions(listener);
module.listener.onFailure(AuthenticationFailureReason.AUTHENTICATION_FAILED, false, "", module.TAG, 0);
verify(listener).onFailure(eq(AuthenticationFailureReason.AUTHENTICATION_FAILED), eq(false), anyString(), anyInt(), anyInt());
}
}
|
Disable BrowserSync synchronisation of scroll and clicks | 'use strict';
var path = require('path');
var serveTask = function (gulp, plugins, config, helpers, generator_config) {
<% if(projectType == 'wp-with-fe') { %>
var startTasks = ['styles-watch', 'assets-watch'];
<% } else { %>
var startTasks = ['styles-watch', 'templates-watch', 'assets-watch'];
<% } %>
gulp.task('serve', startTasks, function() {
<% if(projectType == 'wp-with-fe') { %>
var name = generator_config.nameSlug;
var browserSyncConfig = {
proxy: {
target: generator_config.proxyTarget || name+'.dev',
reqHeaders: {
'x-chisel-proxy': '1'
}
},
ghostMode: false,
online: true
}
<% } else { %>
var browserSyncConfig = {
server: './',
ghostMode: false,
online: true
}
<% } %>
plugins.browserSync.init(browserSyncConfig);
gulp.watch(path.join(config.src.base, config.src.styles), ['styles-watch']);
<% if(projectType == 'fe') { %>
gulp.watch(config.src.templatesWatch, ['templates-watch']);
<% } %>
gulp.watch(path.join(config.src.base, config.src.assets), ['assets-watch']);
<% if(projectType == 'wp-with-fe') { %>
gulp.watch('**/*.{php,twig}').on('change', plugins.browserSync.reload);
<% } %>
});
};
module.exports = serveTask;
| 'use strict';
var path = require('path');
var serveTask = function (gulp, plugins, config, helpers, generator_config) {
<% if(projectType == 'wp-with-fe') { %>
var startTasks = ['styles-watch', 'assets-watch'];
<% } else { %>
var startTasks = ['styles-watch', 'templates-watch', 'assets-watch'];
<% } %>
gulp.task('serve', startTasks, function() {
<% if(projectType == 'wp-with-fe') { %>
var name = generator_config.nameSlug;
var browserSyncConfig = {
proxy: {
target: generator_config.proxyTarget || name+'.dev',
reqHeaders: {
'x-chisel-proxy': '1'
}
},
online: true
}
<% } else { %>
var browserSyncConfig = {
server: './',
online: true
}
<% } %>
plugins.browserSync.init(browserSyncConfig);
gulp.watch(path.join(config.src.base, config.src.styles), ['styles-watch']);
<% if(projectType == 'fe') { %>
gulp.watch(config.src.templatesWatch, ['templates-watch']);
<% } %>
gulp.watch(path.join(config.src.base, config.src.assets), ['assets-watch']);
<% if(projectType == 'wp-with-fe') { %>
gulp.watch('**/*.{php,twig}').on('change', plugins.browserSync.reload);
<% } %>
});
};
module.exports = serveTask;
|
Correct spacing between brace and paren | (function (env) {
"use strict";
env.ddg_spice_<: $ia_id :> = function(api_result) {
// Validate the response (customize for your Spice)
if (!api_result || api_result.error) {
return Spice.failed('<: $ia_id :>');
}
// Render the response
Spice.add({
id: "<: $ia_id :>",
// Customize these properties
name: "AnswerBar title",
data: api_result,
meta: {
sourceName: "Example.com",
sourceUrl: 'http://example.com/url/to/details/' + api_result.name
},
normalize: function(item) {
return {
// customize as needed for your chosen template
title: item.title,
subtitle: item.subtitle,
image: item.icon
};
},
templates: {
group: 'your-template-group',
options: {
content: Spice.<: $ia_id :>.content,
moreAt: true
}
}
});
};
}(this));
| (function (env) {
"use strict";
env.ddg_spice_<: $ia_id :> = function(api_result){
// Validate the response (customize for your Spice)
if (!api_result || api_result.error) {
return Spice.failed('<: $ia_id :>');
}
// Render the response
Spice.add({
id: "<: $ia_id :>",
// Customize these properties
name: "AnswerBar title",
data: api_result,
meta: {
sourceName: "Example.com",
sourceUrl: 'http://example.com/url/to/details/' + api_result.name
},
normalize: function(item) {
return {
// customize as needed for your chosen template
title: item.title,
subtitle: item.subtitle,
image: item.icon
};
},
templates: {
group: 'your-template-group',
options: {
content: Spice.<: $ia_id :>.content,
moreAt: true
}
}
});
};
}(this));
|
Fix critical bug with patched Lock | from asyncio.locks import Lock as _Lock
from asyncio import coroutine
from asyncio import futures
from .util import create_future
# Fixes an issue with all Python versions that leaves pending waiters
# without being awakened when the first waiter is canceled.
# Code adapted from the PR https://github.com/python/cpython/pull/1031
# Waiting once it is merged to make a proper condition to relay on
# the stdlib implementation or this one patched
class Lock(_Lock):
@coroutine
def acquire(self):
"""Acquire a lock.
This method blocks until the lock is unlocked, then sets it to
locked and returns True.
"""
if not self._locked and all(w.cancelled() for w in self._waiters):
self._locked = True
return True
fut = create_future(self._loop)
self._waiters.append(fut)
try:
yield from fut
self._locked = True
return True
except futures.CancelledError:
if not self._locked: # pragma: no cover
self._wake_up_first()
raise
finally:
self._waiters.remove(fut)
def _wake_up_first(self):
"""Wake up the first waiter who isn't cancelled."""
for fut in self._waiters:
if not fut.done():
fut.set_result(True)
break
| from asyncio.locks import Lock as _Lock
from asyncio import coroutine
from asyncio import futures
from .util import create_future
# Fixes an issue with all Python versions that leaves pending waiters
# without being awakened when the first waiter is canceled.
# Code adapted from the PR https://github.com/python/cpython/pull/1031
# Waiting once it is merged to make a proper condition to relay on
# the stdlib implementation or this one patched
class Lock(_Lock):
@coroutine
def acquire(self):
"""Acquire a lock.
This method blocks until the lock is unlocked, then sets it to
locked and returns True.
"""
if not self._locked and all(w.cancelled() for w in self._waiters):
self._locked = True
return True
fut = create_future(self._loop)
self._waiters.append(fut)
try:
yield from fut
self._locked = True
return True
except futures.CancelledError:
if not self._locked: # pragma: no cover
self._wake_up_first()
raise
finally:
self._waiters.remove(fut)
def _wake_up_first(self):
"""Wake up the first waiter who isn't cancelled."""
for fut in self._waiters:
if not fut.done():
fut.set_result(True)
|
Allow username search to work with apostrophes | <?php
namespace Bethel\EntityBundle\Form\Handler;
use Bethel\EntityBundle\Entity\TutorSession;
use Bethel\WsapiBundle\Wsapi\WsRestApi;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\RequestStack;
class UserSearchFormHandler {
protected $em;
protected $requestStack;
protected $wsapi;
public function __construct(EntityManager $em, RequestStack $requestStack, WsRestApi $wsapi) {
$this->em = $em;
$this->request = $requestStack->getCurrentRequest();
$this->wsapi = $wsapi;
}
public function process(Form $form) {
if('POST' !== $this->request->getMethod()) {
return false;
}
$form->submit($this->request);
if($form->isValid()) {
return $this->processValidForm($form);
}
return false;
}
/**
* Processes the valid form
*
* @param Form $form
* @return \Bethel\EntityBundle\Entity\Session
*/
public function processValidForm(Form $form) {
/** @var $session \Bethel\EntityBundle\Entity\Session */
$searchTerms = $form->getData();
$encode_percent = urlencode('%');
$usernameResults = $this->wsapi->getUsername($encode_percent . $searchTerms['firstName'], $encode_percent . $searchTerms['lastName'] . $encode_percent);
return $usernameResults;
}
} | <?php
namespace Bethel\EntityBundle\Form\Handler;
use Bethel\EntityBundle\Entity\TutorSession;
use Bethel\WsapiBundle\Wsapi\WsRestApi;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\RequestStack;
class UserSearchFormHandler {
protected $em;
protected $requestStack;
protected $wsapi;
public function __construct(EntityManager $em, RequestStack $requestStack, WsRestApi $wsapi) {
$this->em = $em;
$this->request = $requestStack->getCurrentRequest();
$this->wsapi = $wsapi;
}
public function process(Form $form) {
if('POST' !== $this->request->getMethod()) {
return false;
}
$form->submit($this->request);
if($form->isValid()) {
return $this->processValidForm($form);
}
return false;
}
/**
* Processes the valid form
*
* @param Form $form
* @return \Bethel\EntityBundle\Entity\Session
*/
public function processValidForm(Form $form) {
/** @var $session \Bethel\EntityBundle\Entity\Session */
$searchTerms = $form->getData();
$usernameResults = $this->wsapi->getUsername(urlencode("%" . $searchTerms['firstName'] . "%"), urlencode("%" . $searchTerms['lastName'] . "%"));
return $usernameResults;
}
} |
Add a comment explaining AttributeError | from django.contrib import admin
from django.core.urlresolvers import reverse
from jmbo.admin import ModelBaseAdmin
from jmbo_twitter import models
class FeedAdmin(ModelBaseAdmin):
inlines = []
list_display = ('title', '_image', 'subtitle', 'publish_on', 'retract_on', \
'_get_absolute_url', 'owner', 'created', '_actions'
)
def _image(self, obj):
if obj.profile_image_url:
return '<img src="%s" />' % obj.profile_image_url
else:
return ''
_image.short_description = 'Image'
_image.allow_tags = True
def _actions(self, obj):
# Once a newer version of jmbo is out the try-except can be removed
try:
parent = super(FeedAdmin, self)._actions(obj)
except AttributeError:
parent = ''
return parent + '''<ul>
<li><a href="%s">Fetch tweets</a></li>
<li><a href="%s">View tweets</a></li>
</ul>''' % (
reverse('feed-fetch-force', args=[obj.name]),
reverse('feed-tweets', args=[obj.name])
)
_actions.short_description = 'Actions'
_actions.allow_tags = True
admin.site.register(models.Feed, FeedAdmin)
| from django.contrib import admin
from django.core.urlresolvers import reverse
from jmbo.admin import ModelBaseAdmin
from jmbo_twitter import models
class FeedAdmin(ModelBaseAdmin):
inlines = []
list_display = ('title', '_image', 'subtitle', 'publish_on', 'retract_on', \
'_get_absolute_url', 'owner', 'created', '_actions'
)
def _image(self, obj):
if obj.profile_image_url:
return '<img src="%s" />' % obj.profile_image_url
else:
return ''
_image.short_description = 'Image'
_image.allow_tags = True
def _actions(self, obj):
try:
parent = super(FeedAdmin, self)._actions(obj)
except AttributeError:
parent = ''
return parent + '''<ul>
<li><a href="%s">Fetch tweets</a></li>
<li><a href="%s">View tweets</a></li>
</ul>''' % (
reverse('feed-fetch-force', args=[obj.name]),
reverse('feed-tweets', args=[obj.name])
)
_actions.short_description = 'Actions'
_actions.allow_tags = True
admin.site.register(models.Feed, FeedAdmin)
|
Replace child_process.spawn with .exec . Sacrifice streaming output in favour of simpler multi commands. | var _ = require('underscore'),
async = require('async'),
child_process = require('child_process');
function Repoman(opts) {
function _exec(command, cb) {
child = child_process.exec(command,
function (err, stdout, stderr) {
if (stdout) {
console.log(stdout);
}
if (stderr) {
console.error(stderr);
}
if (err) {
cb(err);
} else {
cb(null, { status: 'ok' })
}
});
}
function _apply(command, params) {
_.keys(params).forEach(function (param) {
command = command.replace(new RegExp('{' + param + '}'), params[param]);
});
return command;
}
function run(action, cb) {
var tasks = {};
_.keys(opts.repos).forEach(function (repo) {
var params = _.clone(opts.repos[repo]),
command = opts.scms[opts.repos[repo].type][action];
params.name = repo;
params.workspace = opts.workspace;
command = _apply(command, params);
tasks[repo] = function (cb) {
console.log('+ ' + params.name);
console.log(command);
_exec(command, cb);
}
});
async.series(tasks, cb);
}
return {
run: run
};
}
exports.Repoman = Repoman; | var _ = require('underscore'),
async = require('async'),
child_process = require('child_process');
function Repoman(opts) {
function _exec(command, cb) {
command = command.split(' ');
spawn = child_process.spawn(command.shift(), command);
spawn.stdout.on('data', function (data) {
process.stdout.write(data);
});
spawn.stderr.on('data', function (data) {
process.stderr.write(data);
});
spawn.on('exit', function (code) {
// consider all exit code as non-error
// this is to allow any command to fail and proceed with the rest of the commands
cb(null, { code: code });
});
}
function _apply(command, params) {
_.keys(params).forEach(function (param) {
command = command.replace(new RegExp('{' + param + '}'), params[param]);
});
return command;
}
function run(action, cb) {
var tasks = {};
_.keys(opts.repos).forEach(function (repo) {
var params = _.clone(opts.repos[repo]),
command = opts.scms[opts.repos[repo].type][action];
params.name = repo;
params.workspace = opts.workspace;
command = _apply(command, params);
tasks[repo] = function (cb) {
console.log('+ ' + params.name);
console.log(command);
_exec(command, cb);
}
});
async.series(tasks, cb);
}
return {
run: run
};
}
exports.Repoman = Repoman; |
Fix tests failing with Python 3 | import json
from django.test import TestCase
from django.utils import six
from rest_framework import status
from tests.models import TestModel
class ProxyPaginationTests(TestCase):
"""
Tests for drf-proxy-pagination
"""
def setUp(self):
for n in range(200):
TestModel.objects.create(n=n)
def test_without_pager_param(self):
resp = self.client.get('/data/', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertIn('count', content)
self.assertIn('page=', content['next'])
self.assertNotIn('cursor=', content['next'])
def test_with_pager_param(self):
resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(str(resp.content, encoding='utf8') if six.PY3 else resp.content)
self.assertIn('next', content)
self.assertNotIn('count', content)
self.assertNotIn('page=', content['next'])
self.assertIn('cursor=', content['next'])
| import json
from django.test import TestCase
from rest_framework import status
from tests.models import TestModel
class ProxyPaginationTests(TestCase):
"""
Tests for drf-proxy-pagination
"""
def setUp(self):
for n in range(200):
TestModel.objects.create(n=n)
def test_without_pager_param(self):
resp = self.client.get('/data/', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
content = json.loads(resp.content)
self.assertIn('next', content)
self.assertIn('count', content)
self.assertIn('page=', content['next'])
self.assertNotIn('cursor=', content['next'])
def test_with_pager_param(self):
resp = self.client.get('/data/?pager=cursor', HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/json')
self.assertNotIn('count', resp.content)
content = json.loads(resp.content)
self.assertIn('next', content)
self.assertNotIn('page=', content['next'])
self.assertIn('cursor=', content['next'])
|
Add pykqml dependency lower limit | from setuptools import setup, find_packages
def main():
setup(name='bioagents',
version='0.0.1',
description='Biological Reasoning Agents',
long_description='Biological Reasoning Agents',
author='Benjamin Gyori',
author_email='[email protected]',
url='http://github.com/sorgerlab/bioagents',
packages=find_packages(),
install_requires=['indra', 'pykqml>=1.2'],
include_package_data=True,
keywords=['systems', 'biology', 'model', 'pathway', 'assembler',
'nlp', 'mechanism', 'biochemistry'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Mathematics',
],
)
if __name__ == '__main__':
main()
| from setuptools import setup, find_packages
def main():
setup(name='bioagents',
version='0.0.1',
description='Biological Reasoning Agents',
long_description='Biological Reasoning Agents',
author='Benjamin Gyori',
author_email='[email protected]',
url='http://github.com/sorgerlab/bioagents',
packages=find_packages(),
install_requires=['indra', 'pykqml'],
include_package_data=True,
keywords=['systems', 'biology', 'model', 'pathway', 'assembler',
'nlp', 'mechanism', 'biochemistry'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Mathematics',
],
)
if __name__ == '__main__':
main()
|
Update pixel's template file name to meta.xlsx | from pathlib import PurePath
from tempfile import mkdtemp
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from .io.xlsx import generate_template
class DownloadXLSXTemplateView(LoginRequiredMixin, TemplateView):
template_name = 'submission/download_xlsx_template.html'
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx.update({
'step': 'download',
})
return ctx
class GenerateXLSXTemplateView(LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
template_file_name = 'meta.xlsx'
template_path = PurePath(mkdtemp(), template_file_name)
generate_template(template_path)
response = HttpResponse(
content_type=(
'application/vnd'
'.openxmlformats-officedocument'
'.spreadsheetml'
'.sheet'
)
)
content_disposition = 'attachment; filename="{}"'.format(
template_file_name
)
response['Content-Disposition'] = content_disposition
with open(template_path, 'rb') as template:
response.write(template.read())
return response
| from pathlib import PurePath
from tempfile import mkdtemp
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from .io.xlsx import generate_template
class DownloadXLSXTemplateView(LoginRequiredMixin, TemplateView):
template_name = 'submission/download_xlsx_template.html'
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx.update({
'step': 'download',
})
return ctx
class GenerateXLSXTemplateView(LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
template_file_name = 'pixel_template.xlsx'
template_path = PurePath(mkdtemp(), template_file_name)
generate_template(template_path)
response = HttpResponse(
content_type=(
'application/vnd'
'.openxmlformats-officedocument'
'.spreadsheetml'
'.sheet'
)
)
content_disposition = 'attachment; filename="{}"'.format(
template_file_name
)
response['Content-Disposition'] = content_disposition
with open(template_path, 'rb') as template:
response.write(template.read())
return response
|
Read the readme instead of the test requirements | import codecs
import setuptools
setuptools.setup(
name='sprockets.handlers.status',
version='0.1.2',
description='A small handler for reporting application status',
long_description=codecs.open('README.rst', 'r', 'utf8').read(),
url='https://github.com/sprockets/sprockets.handlers.status',
author='AWeber Communications',
author_email='[email protected]',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=['sprockets',
'sprockets.handlers',
'sprockets.handlers.status'],
package_data={'': ['LICENSE', 'README.md']},
include_package_data=True,
install_requires=['tornado'],
namespace_packages=['sprockets',
'sprockets.handlers'],
zip_safe=False)
| import setuptools
setuptools.setup(
name='sprockets.handlers.status',
version='0.1.2',
description='A small handler for reporting application status',
long_description=open('test-requirements.txt', 'r').read(),
url='https://github.com/sprockets/sprockets.handlers.status',
author='AWeber Communications',
author_email='[email protected]',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=['sprockets',
'sprockets.handlers',
'sprockets.handlers.status'],
package_data={'': ['LICENSE', 'README.md']},
include_package_data=True,
install_requires=['tornado'],
namespace_packages=['sprockets',
'sprockets.handlers'],
zip_safe=False)
|
Update test to valid use case | <?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Mapping\JoinColumn;
class MergeCompositeToOneKeyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyCountry'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyState'),
));
}
public function testIssue()
{
$country = new MergeCompositeToOneKeyCountry();
$country->country = 'US';
$state = new MergeCompositeToOneKeyState();
$state->state = 'CA';
$state->country = $country;
$this->_em->merge($state);
}
}
/**
* @Entity
*/
class MergeCompositeToOneKeyCountry
{
/**
* @Id
* @Column(type="string", name="country")
* @GeneratedValue(strategy="NONE")
*/
public $country;
}
/**
* @Entity
*/
class MergeCompositeToOneKeyState
{
/**
* @Id
* @Column(type="string")
* @GeneratedValue(strategy="NONE")
*/
public $state;
/**
* @Id
* @ManyToOne(targetEntity="MergeCompositeToOneKeyCountry", cascade={"MERGE"})
* @JoinColumn(name="country", referencedColumnName="country")
*/
public $country;
}
| <?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Mapping\JoinColumn;
class MergeCompositeToOneKeyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyCountry'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\MergeCompositeToOneKeyState'),
));
}
public function testIssue()
{
$country = new MergeCompositeToOneKeyCountry();
$country->country = 'US';
$state = new MergeCompositeToOneKeyState();
$state->state = 'CA';
$state->country = $country;
$this->_em->merge($country);
$this->_em->merge($state);
}
}
/**
* @Entity
*/
class MergeCompositeToOneKeyCountry
{
/**
* @Id
* @Column(type="string", name="country")
* @GeneratedValue(strategy="NONE")
*/
public $country;
}
/**
* @Entity
*/
class MergeCompositeToOneKeyState
{
/**
* @Id
* @Column(type="string")
* @GeneratedValue(strategy="NONE")
*/
public $state;
/**
* @Id
* @ManyToOne(targetEntity="MergeCompositeToOneKeyCountry")
* @JoinColumn(name="country", referencedColumnName="country")
*/
public $country;
}
|
Save one request on bookmark delete. | angular.module('caco.bookmark.crtl', ['caco.bookmark.REST'])
.controller('BookMarkCrtl', function ($rootScope, $scope, $stateParams, $location, BookMarkREST) {
$rootScope.module = 'bookmark';
if ($stateParams.id) {
BookMarkREST.one({id: $stateParams.id}, function (data) {
$scope.bookmark = data.response;
});
}
if ($location.path() === '/bookmark') {
BookMarkREST.all({}, function (data) {
$scope.bookmarks = data.response;
});
}
$scope.add = function () {
BookMarkREST.add({}, $scope.newBookmark, function () {
$location.path('/bookmark');
});
};
$scope.delete = function (id) {
if (!confirm('Confirm delete')) {
return;
}
BookMarkREST.remove({id: id}, {}, function(data) {
if (data.status != 200) {
return;
}
for (var i = $scope.bookmarks.length - 1; i >= 0; i--) {
if ($scope.bookmarks[i].id != id) {
continue;
}
$scope.bookmarks.splice(i, 1);
}
});
};
$scope.edit = function () {
BookMarkREST.edit({id: $scope.bookmark.id}, $scope.bookmark, function (data) {
$location.path('/bookmark');
});
};
}); | angular.module('caco.bookmark.crtl', ['caco.bookmark.REST'])
.controller('BookMarkCrtl', function ($rootScope, $scope, $stateParams, $location, BookMarkREST) {
$rootScope.module = 'bookmark';
if ($stateParams.id) {
BookMarkREST.one({id: $stateParams.id}, function (data) {
$scope.bookmark = data.response;
});
}
if ($location.path() === '/bookmark') {
BookMarkREST.all({}, function (data) {
$scope.bookmarks = data.response;
});
}
$scope.add = function () {
BookMarkREST.add({}, $scope.newBookmark, function () {
$location.path('/bookmark');
});
};
$scope.delete = function (id) {
if (!confirm('Confirm delete')) {
return;
}
BookMarkREST.remove({id: id}, {}, function(data) {
BookMarkREST.all({}, function (data) {
$scope.bookmarks = data.response;
});
});
};
$scope.edit = function () {
BookMarkREST.edit({id: $scope.bookmark.id}, $scope.bookmark, function (data) {
$location.path('/bookmark');
});
};
}); |
Use a list for DummyStorage() for ordering. | from django.contrib.auth.models import AnonymousUser
from django.test import TestCase, RequestFactory
class DummyStorage:
def __init__(self):
self.store = list()
def add(self, level, message, extra_tags=''):
self.store.add(message)
def __iter__(self):
for item in self.store:
yield item
class BaseRequestTestCase(TestCase):
"""
Extend django.test.TestCase with a create_request method.
BaseRequestTestCase must be subclassed with a user_factory attribute to
create a default user for the request.
"""
request_factory = RequestFactory
def create_request(self, method='get', url='/', user=None, auth=True, **kwargs):
if user is None:
user = self.create_user(auth=auth)
request = getattr(self.request_factory(), method)(url, **kwargs)
request.user = user
if 'data' in kwargs:
request.DATA = kwargs['data']
if 'messages' in kwargs:
request._messages = kwargs['messages']
else:
request._messages = DummyStorage()
return request
def create_user(self, auth=True, **kwargs):
if auth:
return self.user_factory.create(**kwargs)
else:
return AnonymousUser()
| from django.contrib.auth.models import AnonymousUser
from django.test import TestCase, RequestFactory
class DummyStorage:
def __init__(self):
self.store = set()
def add(self, level, message, extra_tags=''):
self.store.add(message)
def __iter__(self):
for item in self.store:
yield item
class BaseRequestTestCase(TestCase):
"""
Extend django.test.TestCase with a create_request method.
BaseRequestTestCase must be subclassed with a user_factory attribute to
create a default user for the request.
"""
request_factory = RequestFactory
def create_request(self, method='get', url='/', user=None, auth=True, **kwargs):
if user is None:
user = self.create_user(auth=auth)
request = getattr(self.request_factory(), method)(url, **kwargs)
request.user = user
if 'data' in kwargs:
request.DATA = kwargs['data']
if 'messages' in kwargs:
request._messages = kwargs['messages']
else:
request._messages = DummyStorage()
return request
def create_user(self, auth=True, **kwargs):
if auth:
return self.user_factory.create(**kwargs)
else:
return AnonymousUser()
|
Disable changing a line's height | var MarkupLine = {
HandlesType: function(type) {
return type == 'line';
},
Paint: function(elementObject) {
$('#' + elementObject.Handle).css({
left: SizeCalculator.ToPixels(elementObject.x) + 'px',
top: SizeCalculator.ToPixels(elementObject.y) + 'px',
width: SizeCalculator.ToPixels(elementObject.width) + 'px',
height: SizeCalculator.ToPixels(elementObject.height) + 'px',
backgroundColor: elementObject.color
});
},
Activate: function(elementObject) {
},
Update: function(elementObject) {
this.Paint(elementObject);
},
New: function(markup) {
markup.AddElement({
type: "line",
x: 10,
y: 10,
width: 190,
height: 1,
color: '#00000',
properties: {
x: {
label: 'Left (mm)',
component: 'number'
},
y: {
label: 'Top (mm)',
component: 'number'
},
width: {
label: 'Width (mm)',
component: 'number'
},
color: {
label: 'Color',
component: 'select',
items: {
'Black': '#00000',
'Silver': '#C0C0C0',
}
}
}
});
}
};
| var MarkupLine = {
HandlesType: function(type) {
return type == 'line';
},
Paint: function(elementObject) {
$('#' + elementObject.Handle).css({
left: SizeCalculator.ToPixels(elementObject.x) + 'px',
top: SizeCalculator.ToPixels(elementObject.y) + 'px',
width: SizeCalculator.ToPixels(elementObject.width) + 'px',
heigth: SizeCalculator.ToPixels(elementObject.heigth) + 'px',
backgroundColor: elementObject.color
});
},
Activate: function(elementObject) {
},
Update: function(elementObject) {
this.Paint(elementObject);
},
New: function(markup) {
markup.AddElement({
type: "line",
x: 10,
y: 10,
width: 190,
height: 1,
color: '#00000',
properties: {
x: {
label: 'Left (mm)',
component: 'number'
},
y: {
label: 'Top (mm)',
component: 'number'
},
width: {
label: 'Width (mm)',
component: 'number'
},
height: {
label: 'Height (mm)',
component: 'number'
},
color: {
label: 'Color',
component: 'select',
items: {
'Black': '#00000',
'Silver': '#C0C0C0',
}
}
}
});
}
};
|
Prepare FOREIGN_KEY as ALTER TABLE | package nl.myndocs.database.migrator.definition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
public class Constraint {
public enum TYPE {
INDEX, UNIQUE, FOREIGN_KEY
}
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
private Constraint(Builder builder) {
constraintName = builder.getConstraintName();
type = builder.getType();
columnNames = builder.getColumnNames();
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
public static class Builder {
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
public Builder(String constraintName) {
this.constraintName = constraintName;
}
public Builder(String constraintName, TYPE type) {
this.constraintName = constraintName;
this.type = Optional.ofNullable(type);
}
public Builder columns(String... columnNames) {
this.columnNames = Arrays.asList(columnNames);
return this;
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
}
}
| package nl.myndocs.database.migrator.definition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
public class Constraint {
public enum TYPE {
INDEX, UNIQUE
}
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
private Constraint(Builder builder) {
constraintName = builder.getConstraintName();
type = builder.getType();
columnNames = builder.getColumnNames();
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
public static class Builder {
private String constraintName;
private Optional<TYPE> type;
private Collection<String> columnNames = new ArrayList<>();
public Builder(String constraintName) {
this.constraintName = constraintName;
}
public Builder(String constraintName, TYPE type) {
this.constraintName = constraintName;
this.type = Optional.ofNullable(type);
}
public Builder columns(String... columnNames) {
this.columnNames = Arrays.asList(columnNames);
return this;
}
public String getConstraintName() {
return constraintName;
}
public Optional<TYPE> getType() {
return type;
}
public Collection<String> getColumnNames() {
return columnNames;
}
}
}
|
Make API uppercase in human-readable type output | <?php
namespace Apigee\SmartDocs\Security;
/**
* Class ApiKeyScheme
* @package Apigee\SmartDocs\Security
*/
class ApiKeyScheme extends SecurityScheme
{
/**
* @var string
*/
protected $paramName;
/**
* @var string
*/
protected $in;
/**
* Gets the parameter name identifying the API key.
*
* @return string
*/
public function getParamName()
{
return $this->paramName;
}
/**
* Sets the parameter name identifying the API key.
*
* @param string $name
*/
public function setParamName($name)
{
$this->paramName = $name;
}
/**
* Returns how the API key is transmitted (header, query, etc.).
*
* @return string
*/
public function getIn()
{
return $this->in;
}
/**
* Sets how the API key is transmitted (header, query, etc.).
*
* @param string $in
*/
public function setIn($in) {
// TODO: validate $in
$this->in = $in;
}
/**
* {@inheritdoc}
*/
public function getType($humanReadable = false)
{
if ($humanReadable) {
return 'API Key';
}
return 'APIKEY';
}
/**
* {@inheritdoc}
*/
public function toArray($is_update = false)
{
return parent::toArray($is_update) + array(
'paramName' => $this->paramName,
'in' => $this->in,
);
}
} | <?php
namespace Apigee\SmartDocs\Security;
/**
* Class ApiKeyScheme
* @package Apigee\SmartDocs\Security
*/
class ApiKeyScheme extends SecurityScheme
{
/**
* @var string
*/
protected $paramName;
/**
* @var string
*/
protected $in;
/**
* Gets the parameter name identifying the API key.
*
* @return string
*/
public function getParamName()
{
return $this->paramName;
}
/**
* Sets the parameter name identifying the API key.
*
* @param string $name
*/
public function setParamName($name)
{
$this->paramName = $name;
}
/**
* Returns how the API key is transmitted (header, query, etc.).
*
* @return string
*/
public function getIn()
{
return $this->in;
}
/**
* Sets how the API key is transmitted (header, query, etc.).
*
* @param string $in
*/
public function setIn($in) {
// TODO: validate $in
$this->in = $in;
}
/**
* {@inheritdoc}
*/
public function getType($humanReadable = false)
{
if ($humanReadable) {
return 'Api Key';
}
return 'APIKEY';
}
/**
* {@inheritdoc}
*/
public function toArray($is_update = false)
{
return parent::toArray($is_update) + array(
'paramName' => $this->paramName,
'in' => $this->in,
);
}
} |
Order templates by theme and name | <?php
namespace BoomCMS\Core\Template;
use BoomCMS\Core\Models\Template as Model;
class Provider
{
public function deleteById($id)
{
Model::destroy($id);
return $this;
}
public function findAll()
{
$models = Model::query()
->orderBy('theme', 'asc')
->orderBy('name', 'asc')
->get();
$templates = [];
foreach ($models as $model) {
$templates[] = new Template($model->toArray());
}
return $templates;
}
public function findById($id)
{
$model = Model::find($id);
$attrs = $model ? $model->toArray() : [];
return new Template($attrs);
}
public function findByThemeAndFilename($theme, $filename)
{
$model = Model::where('filename', '=', $filename)
->where('theme', '=', $theme)
->first();
return $model ? new Template($model->toArray()) : new Template([]);
}
public function save(Template $template)
{
$model = Model::find($template->getId());
if ($model) {
$model->filename = $template->getFilename();
$model->description = $template->getDescription();
$model->name = $template->getName();
$model->save();
}
return $this;
}
}
| <?php
namespace BoomCMS\Core\Template;
use BoomCMS\Core\Models\Template as Model;
class Provider
{
public function deleteById($id)
{
Model::destroy($id);
return $this;
}
public function findAll()
{
$models = Model::query()
->orderBy('name', 'asc')
->get();
$templates = [];
foreach ($models as $model) {
$templates[] = new Template($model->toArray());
}
return $templates;
}
public function findById($id)
{
$model = Model::find($id);
$attrs = $model ? $model->toArray() : [];
return new Template($attrs);
}
public function findByThemeAndFilename($theme, $filename)
{
$model = Model::where('filename', '=', $filename)
->where('theme', '=', $theme)
->first();
return $model ? new Template($model->toArray()) : new Template([]);
}
public function save(Template $template)
{
$model = Model::find($template->getId());
if ($model) {
$model->filename = $template->getFilename();
$model->description = $template->getDescription();
$model->name = $template->getName();
$model->save();
}
return $this;
}
}
|
Validate token when fetching channels | import json
from slackclient import SlackClient
class SlackBotConf(object):
def __init__(self):
self.username = 'Luigi-slack Bot'
class SlackAPI(object):
def __init__(self, token, bot_conf=SlackBotConf()):
self.client = SlackClient(token)
self._all_channels = self._get_channels()
self.bot = bot_conf
def _get_channels(self):
res = self.client.api_call('channels.list')
_channels = json.loads(res.decode())
_parsed_channels = _channels.get('channels', None)
if _parsed_channels is None:
raise Exception("Could not get Slack channels. Are you sure your token is correct?")
return _parsed_channels
def get_channels(self, reload_channels=False):
if not self._all_channels or reload_channels:
self._all_channels = self._get_channels()
return self._all_channels
def channel_name_to_id(self, names):
name_to_id = []
for name in names:
for channel in self._all_channels:
if channel['name'] == name:
name_to_id.append({'name': channel['name'], 'id': channel['id']})
return name_to_id
def bulk_message(self, message, post_to=[]):
channel_map = self.channel_name_to_id(post_to)
for channel in channel_map:
self.client.api_call('chat.postMessage',
text=message,
channel=channel['id'],
username=self.bot.username)
return True
| import json
from slackclient import SlackClient
class SlackBotConf(object):
def __init__(self):
self.username = 'Luigi-slack Bot'
class SlackAPI(object):
def __init__(self, token, bot_conf=SlackBotConf()):
self.client = SlackClient(token)
self._all_channels = self._get_channels()
self.bot = bot_conf
def _get_channels(self):
res = self.client.api_call('channels.list')
_channels = json.loads(res.decode())
return _channels['channels']
def get_channels(self, reload_channels=False):
if not self._all_channels or reload_channels:
self._all_channels = self._get_channels()
return self._all_channels
def channel_name_to_id(self, names):
name_to_id = []
for name in names:
for channel in self._all_channels:
if channel['name'] == name:
name_to_id.append({'name': channel['name'], 'id': channel['id']})
return name_to_id
def bulk_message(self, message, post_to=[]):
channel_map = self.channel_name_to_id(post_to)
for channel in channel_map:
self.client.api_call('chat.postMessage',
text=message,
channel=channel['id'],
username=self.bot.username)
return True
|
Remove duplicate code; fix docblock | <?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <[email protected]>
*
* Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
* - (c) John MacFarlane
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Inline\Element;
class Image extends AbstractWebResource
{
/**
* @var InlineCollection
*/
protected $altText;
/**
* @param string $url
* @param InlineCollection|string $label
* @param string $title
*/
public function __construct($url, $label = null, $title = '')
{
parent::__construct($url);
$this->setAltText($label);
if (!empty($title)) {
$this->attributes['title'] = $title;
}
}
/**
* @return InlineCollection
*/
public function getAltText()
{
return $this->altText;
}
/**
* @param InlineCollection|string $label
*
* @return $this
*/
public function setAltText($label)
{
if (is_string($label)) {
$this->altText = new InlineCollection(array(new Text($label)));
} else {
$this->altText = $label;
}
return $this;
}
}
| <?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <[email protected]>
*
* Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
* - (c) John MacFarlane
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Inline\Element;
class Image extends AbstractWebResource
{
/**
* @var InlineCollection
*/
protected $altText;
/**
* @param string $url
* @param InlineCollection|string $label
* @param string $title
*/
public function __construct($url, $label = null, $title = '')
{
parent::__construct($url);
if (is_string($label)) {
$this->altText = new InlineCollection(array(new Text($label)));
} else {
$this->altText = $label;
}
if (!empty($title)) {
$this->attributes['title'] = $title;
}
}
/**
* @return InlineCollection
*/
public function getAltText()
{
return $this->altText;
}
/**
* @param InlineCollection $label
*
* @return $this
*/
public function setAltText($label)
{
if (is_string($label)) {
$this->altText = new InlineCollection(array(new Text($label)));
} else {
$this->altText = $label;
}
return $this;
}
}
|
Remove unnecessary check for dict attr conflicts. | # Attribute prefix for allowing dotlookups when keys conflict with dict
# attributes.
PREFIX = '_bd_'
class BetterDict(dict):
def __init__(self, *args, **kwargs):
# Prefix that will be appended to keys for dot lookups that would
# otherwise conflict with dict attributes.
self.__prefix = PREFIX
# Determine the attributes a dictionary has. We use this to prevent
# exposing properties that conflict with a dict's properties
self.__dict_attrs = dir(dict)
return super(BetterDict, self).__init__(*args, **kwargs)
def __getattr__(self, attr):
# If the requested attribute is prefixed with self.__prefix,
# we need to unprefix it and do a lookup for that key.
if attr.startswith(self.__prefix) and attr != self.__prefix:
unprefixed_attr = attr.partition(self.__prefix)[-1]
if unprefixed_attr in self and (
unprefixed_attr in self.__dict_attrs or
unprefixed_attr.startswith(self.__prefix)):
return self.__dict_to_BetterDict(self[unprefixed_attr])
if attr in self:
return self.__dict_to_BetterDict(self[attr])
raise AttributeError
def __dict_to_BetterDict(self, value):
"""Convert the passed value to a BetterDict if the value is a dict"""
return BetterDict(value) if type(value) == dict else value
| # Attribute prefix for allowing dotlookups when keys conflict with dict
# attributes.
PREFIX = '_bd_'
class BetterDict(dict):
def __init__(self, *args, **kwargs):
# Prefix that will be appended to keys for dot lookups that would
# otherwise conflict with dict attributes.
self.__prefix = PREFIX
# Determine the attributes a dictionary has. We use this to prevent
# exposing properties that conflict with a dict's properties
self.__dict_attrs = dir(dict)
return super(BetterDict, self).__init__(*args, **kwargs)
def __getattr__(self, attr):
# Don't attempt lookups for things that conflict with dict attrs
if attr in self.__dict_attrs:
raise AttributeError
# If the requested attribute is prefixed with self.__prefix,
# we need to unprefix it and do a lookup for that key.
if attr.startswith(self.__prefix) and attr != self.__prefix:
unprefixed_attr = attr.partition(self.__prefix)[-1]
if unprefixed_attr in self and (
unprefixed_attr in self.__dict_attrs or
unprefixed_attr.startswith(self.__prefix)):
return self.__dict_to_BetterDict(self[unprefixed_attr])
if attr in self:
return self.__dict_to_BetterDict(self[attr])
raise AttributeError
def __dict_to_BetterDict(self, value):
"""Convert the passed value to a BetterDict if the value is a dict"""
return BetterDict(value) if type(value) == dict else value
|
Allow foriegn keys on photo table to default to null so we can rollback migrations | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RemoveEventIdFromPhotos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('photos', function (Blueprint $table) {
$table->dropForeign('photos_event_id_foreign');
$table->dropIndex('photos_event_id_index');
$table->dropColumn('event_id');
$table->dropForeign('photos_signup_id_foreign');
$table->dropIndex('photos_signup_id_index');
$table->dropColumn('signup_id');
$table->increments('id')->first();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('photos', function (Blueprint $table) {
$table->integer('event_id')->unsigned()->nullable()->index()->comment('The event this post corresponds to.');
$table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
$table->integer('signup_id')->unsigned()->nullable()->index()->comment('The signup this Post references.');
$table->foreign('signup_id')->references('id')->on('signups')->onDelete('cascade');
$table->dropColumn('id');
});
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RemoveEventIdFromPhotos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('photos', function (Blueprint $table) {
$table->dropForeign('photos_event_id_foreign');
$table->dropIndex('photos_event_id_index');
$table->dropColumn('event_id');
$table->dropForeign('photos_signup_id_foreign');
$table->dropIndex('photos_signup_id_index');
$table->dropColumn('signup_id');
$table->increments('id')->first();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('photos', function (Blueprint $table) {
$table->dropColumn('id');
$table->integer('event_id')->unsigned()->index()->comment('The event this post corresponds to.');
$table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
$table->integer('signup_id')->unsigned()->index()->comment('The signup this Post references.');
$table->foreign('signup_id')->references('id')->on('signups')->onDelete('cascade');
});
}
}
|
Send traces to multiple sessions if started. | 'use strict';
var sessions = require('../sessions');
var kafkaConsumer = function (kafkaConfig) {
var kafka = require('../services/kafka')(kafkaConfig.uri);
var players = require('../players');
return {
addTraces: function (playerId, versionId, gameplayId, data) {
return sessions.find({
versionId: sessions.toObjectID(versionId),
end: null
}, false).then(function (sessions) {
if (!sessions) {
return false;
}
return players.findById(playerId)
.then(function(player) {
if(!player) {
return false;
}
var promises = [];
for(var i = 0; i < sessions.length; ++i) {
var session = sessions[i];
if(!session.allowAnonymous) {
if (!session.students || session.students.indexOf(player.name) === -1) {
continue;
}
}
promises.push(kafka.send(session._id.toString(), data));
}
return promises;
});
});
}
};
};
module.exports = kafkaConsumer; | 'use strict';
var sessions = require('../sessions');
var kafkaConsumer = function (kafkaConfig) {
var kafka = require('../services/kafka')(kafkaConfig.uri);
var players = require('../players');
return {
addTraces: function (playerId, versionId, gameplayId, data) {
return sessions.find({
versionId: sessions.toObjectID(versionId),
end: null
}, true).then(function (session) {
if (!session) {
return false;
}
return players.findById(playerId)
.then(function(player) {
if(!player) {
return false;
}
if(!session.allowAnonymous) {
if (!session.students || session.students.indexOf(player.name) === -1) {
return false;
}
}
return kafka.send(session._id.toString(), data);
});
});
}
};
};
module.exports = kafkaConsumer; |
Add vertical scroll for the left navigation menu | "use strict";
var React = require("react");
var LeftNav = require("material-ui/lib/left-nav");
var List = require('material-ui/lib/lists/list');
var ListItem = require('material-ui/lib/lists/list-item');
var PlayerStore = require("../stores/playerStore");
var CountryList = React.createClass({
getInitialState: function () {
return {
countryList: []
};
},
componentWillMount: function () {
PlayerStore.addChangeListener(this._onChange)
},
componentWillUnmount: function () {
PlayerStore.removeChangeListener(this._onChange)
},
_onChange: function () {
var players = PlayerStore.getCountries();
var self = this;
players.forEach(function (element, index, array) {
var imgStyle = {
verticalAlign: "middle"
};
self.state.countryList.push(
<ListItem key={index}>
<img src={element.thumbnailUrl} height="24" width="24" style={imgStyle}/>
{element.name}
</ListItem>
)
});
this.setState({countryList: this.state.countryList});
},
_toggleNav: function () {
this.refs.leftNav.toggle();
},
render: function () {
var listStyle = {
maxHeight: 800,
overflowY: "auto"
};
return (
<div>
<LeftNav ref="leftNav" docked={false}>
<List style={listStyle}>
{this.state.countryList}
</List>
</LeftNav>
</div>
)
}
});
module.exports = CountryList; | "use strict";
var React = require("react");
var LeftNav = require("material-ui/lib/left-nav");
var List = require('material-ui/lib/lists/list');
var ListItem = require('material-ui/lib/lists/list-item');
var PlayerStore = require("../stores/playerStore");
var CountryList = React.createClass({
getInitialState: function () {
return {
countryList: []
};
},
componentWillMount: function () {
PlayerStore.addChangeListener(this._onChange)
},
componentWillUnmount: function () {
PlayerStore.removeChangeListener(this._onChange)
},
_onChange: function () {
var players = PlayerStore.getCountries();
var self = this;
players.forEach(function (element, index, array) {
var imgStyle = {
verticalAlign: "middle"
};
self.state.countryList.push(
<ListItem key={index}>
<img src={element.thumbnailUrl} height="24" width="24" style={imgStyle}/>
{element.name}
</ListItem>
)
});
this.setState({countryList: this.state.countryList});
},
_toggleNav: function () {
this.refs.leftNav.toggle();
},
render: function () {
return (
<div>
<LeftNav ref="leftNav" docked={false}>
{this.state.countryList}
</LeftNav>
</div>
)
}
});
module.exports = CountryList; |
Fix ImportError when installing without BeautifulSoup | from setuptools import setup, find_packages
import re
VERSION = re.search(r"__version__ = '(.*?)'",
open("ofxparse/__init__.py").read()).group(1)
setup(name='ofxparse',
version=VERSION,
description="Tools for working with the OFX (Open Financial Exchange) file format",
long_description=open("./README", "r").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='ofx, Open Financial Exchange, file formats',
author='Jerry Seutter',
author_email='[email protected]',
url='http://sites.google.com/site/ofxparse',
license='MIT License',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
# -*- Extra requirements: -*-
"BeautifulSoup>=3.0",
],
entry_points="""
""",
use_2to3 = True,
test_suite = 'tests',
)
| from setuptools import setup, find_packages
import ofxparse
setup(name='ofxparse',
version=ofxparse.__version__,
description="Tools for working with the OFX (Open Financial Exchange) file format",
long_description=open("./README", "r").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='ofx, Open Financial Exchange, file formats',
author='Jerry Seutter',
author_email='[email protected]',
url='http://sites.google.com/site/ofxparse',
license='MIT License',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
# -*- Extra requirements: -*-
"BeautifulSoup>=3.0",
],
entry_points="""
""",
use_2to3 = True,
test_suite = 'tests',
)
|
Remove all tasks before testing report completion all | <?php
namespace SimplyTestable\WorkerBundle\Tests\Command\Task;
use SimplyTestable\WorkerBundle\Tests\Command\ConsoleCommandBaseTestCase;
use SimplyTestable\WorkerBundle\Entity\TimePeriod;
class ReportCompletionAllCommandTest extends ConsoleCommandBaseTestCase {
public static function setUpBeforeClass() {
self::setupDatabaseIfNotExists();
}
/**
* @group standard
*/
public function testReportCompletionAll() {
$this->setHttpFixtures($this->getHttpFixtures($this->getFixturesDataPath(__FUNCTION__ . '/HttpResponses')));
$this->removeAllTasks();
$taskProperties = $this->createTask('http://example.com/', 'HTML validation');
$task = $this->getTaskService()->getById($taskProperties->id);
$taskTimePeriod = new TimePeriod();
$taskTimePeriod->setStartDateTime(new \DateTime('1970-01-01'));
$taskTimePeriod->setEndDateTime(new \DateTime('1970-01-02'));
$task->setTimePeriod($taskTimePeriod);
$this->createCompletedTaskOutputForTask($task);
$response = $this->runConsole('simplytestable:task:reportcompletion:all');
$this->assertEquals(0, $response);
}
}
| <?php
namespace SimplyTestable\WorkerBundle\Tests\Command\Task;
use SimplyTestable\WorkerBundle\Tests\Command\ConsoleCommandBaseTestCase;
use SimplyTestable\WorkerBundle\Entity\TimePeriod;
class ReportCompletionAllCommandTest extends ConsoleCommandBaseTestCase {
public static function setUpBeforeClass() {
self::setupDatabaseIfNotExists();
}
/**
* @group standard
*/
public function testReportCompletionAll() {
$this->setHttpFixtures($this->getHttpFixtures($this->getFixturesDataPath(__FUNCTION__ . '/HttpResponses')));
$taskProperties = $this->createTask('http://example.com/', 'HTML validation');
$task = $this->getTaskService()->getById($taskProperties->id);
$taskTimePeriod = new TimePeriod();
$taskTimePeriod->setStartDateTime(new \DateTime('1970-01-01'));
$taskTimePeriod->setEndDateTime(new \DateTime('1970-01-02'));
$task->setTimePeriod($taskTimePeriod);
$this->createCompletedTaskOutputForTask($task);
$response = $this->runConsole('simplytestable:task:reportcompletion:all');
$this->assertEquals(0, $response);
}
}
|
Reduce code to a simpler form that checks if a user is already in the DB | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self[event.target][nick]
except KeyError:
for i in self[event.target].values():
if i['host'] == event.source.host:
del self[event.target][i['hostmask'].split("!")[0]]
break
def add_entry(self, channel, nick, hostmask, account):
temp = {
'hostmask': hostmask,
'host': hostmask.split("@")[1],
'account': account,
'seen': [__import__("time").time(), ""]
}
if nick in self[channel]:
del temp['seen']
self[channel][nick].update(temp)
else:
self[channel][nick] = temp
def get_user_host(self, channel, nick):
try:
host = "*!*@" + self[channel][nick]['host']
except KeyError:
self.irc.send("WHO {0} nuhs%nhuac".format(channel))
host = "*!*@" + self[channel][nick]['host']
return host
def flush(self):
with open('userdb.json', 'w') as f:
json.dump(self, f, indent=2, separators=(',', ': '))
f.write("\n")
| import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self[event.target][nick]
except KeyError:
for i in self[event.target].values():
if i['host'] == event.source.host:
del self[event.target][i['hostmask'].split("!")[0]]
break
def add_entry(self, channel, nick, hostmask, account):
temp = {
'hostmask': hostmask,
'host': hostmask.split("@")[1],
'account': account,
'seen': [__import__("time").time(), ""]
}
failed = False
try:
user = self[channel][nick]
except KeyError:
failed = True
self[channel][nick] = temp
if not failed:
del temp['seen']
user.update(temp)
def get_user_host(self, channel, nick):
try:
host = "*!*@" + self[channel][nick]['host']
except KeyError:
self.irc.send("WHO {0} nuhs%nhuac".format(channel))
host = "*!*@" + self[channel][nick]['host']
return host
def flush(self):
with open('userdb.json', 'w') as f:
json.dump(self, f, indent=2, separators=(',', ': '))
f.write("\n")
|
Update Spaghetti default recipe to have servings and allergens. | import { ADD_RECIPE, EDIT_RECIPE, REMOVE_RECIPE } from '../actions';
import { v4 } from 'uuid';
export const defaultRecipes = [
{
titleDetails: {
title: 'Pumpkin Pie',
servings: '4',
allergens: 'Eggs, Milk'
},
ingredients: [
{ name: 'Pumpkin Puree'},
{ name: 'Sweetened Condensed Milk' },
{ name: 'Eggs' },
{ name: 'Pumpkin Pie Spice' },
{ name: 'Pie Crust'}
],
id: v4()
},
{
titleDetails: {
title: 'Spaghetti',
servings: '4',
allergens: 'Tomatoes'
},
ingredients: [
{ name: 'Noodles' },
{ name: 'Pasta Sauce' },
{ name: 'Meatballs' }
],
id: v4()
}
];
const Recipes = (state = defaultRecipes, action) => {
switch (action.type) {
case ADD_RECIPE:
return [
...state,
action.recipe
];
case EDIT_RECIPE:
return state.map(recipe => {
return recipe.id === action.id ? action.recipe : recipe;
});
case REMOVE_RECIPE:
return state.filter(recipe => recipe.id !== action.id);
default:
return state;
}
};
export default Recipes;
| import { ADD_RECIPE, EDIT_RECIPE, REMOVE_RECIPE } from '../actions';
import { v4 } from 'uuid';
export const defaultRecipes = [
{
titleDetails: {
title: 'Pumpkin Pie',
servings: '4',
allergens: 'Eggs, Milk'
},
ingredients: [
{ name: 'Pumpkin Puree'},
{ name: 'Sweetened Condensed Milk' },
{ name: 'Eggs' },
{ name: 'Pumpkin Pie Spice' },
{ name: 'Pie Crust'}
],
id: v4()
},
{
titleDetails: {
title: 'Spaghetti',
ingredients: 'Noodles, Pasta Sauce, Meatballs',
},
ingredients: [
{ name: 'Noodles' },
{ name: 'Pasta Sauce' },
{ name: 'Meatballs' }
],
id: v4()
}
];
const Recipes = (state = defaultRecipes, action) => {
switch (action.type) {
case ADD_RECIPE:
return [
...state,
action.recipe
];
case EDIT_RECIPE:
return state.map(recipe => {
return recipe.id === action.id ? action.recipe : recipe;
});
case REMOVE_RECIPE:
return state.filter(recipe => recipe.id !== action.id);
default:
return state;
}
};
export default Recipes;
|
Fix error message in example project | import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by oauth provider"}, status=400)
| import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by facebook"}, status=400)
|
Use TestUtils to get data path. | <?php
use PHPUnit\Framework\TestCase;
require_once dirname(__FILE__) . '/../bootstrap.php';
class Test extends TestCase {
function test_match_schema_markup() {
$html = file_get_contents(TestUtils::getDataPath("schema_spec.html"));
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(RecipeParser::SCHEMA_SPEC, $type);
}
function test_match_datavocabulary_markup() {
$html = file_get_contents(TestUtils::getDataPath("datavocabulary_spec.html"));
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(RecipeParser::DATA_VOCABULARY_SPEC, $type);
}
function test_match_microformat_markup() {
$html = file_get_contents(TestUtils::getDataPath("microformat_spec.html"));
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(RecipeParser::MICROFORMAT_SPEC, $type);
}
function test_null_match_markup() {
$html = file_get_contents(TestUtils::getDataPath("no_semantic_markup.html"));
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(null, $type);
}
/**
* @expectedException NoMatchingParserException
*/
function test_parser_no_matching_parser_exception() {
$html = "";
$url = "http://www.example.com/";
$recipe = RecipeParser::parse($html, $url);
}
}
| <?php
use PHPUnit\Framework\TestCase;
require_once dirname(__FILE__) . '/../bootstrap.php';
class Test extends TestCase {
private function getDataDir() {
return dirname(__FILE__) . "/data";
}
function test_match_schema_markup() {
$html = file_get_contents($this->getDataDir() . "/schema_spec.html");
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(RecipeParser::SCHEMA_SPEC, $type);
}
function test_match_datavocabulary_markup() {
$html = file_get_contents($this->getDataDir() . "/datavocabulary_spec.html");
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(RecipeParser::DATA_VOCABULARY_SPEC, $type);
}
function test_match_microformat_markup() {
$html = file_get_contents($this->getDataDir() . "/microformat_spec.html");
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(RecipeParser::MICROFORMAT_SPEC, $type);
}
function test_null_match_markup() {
$html = file_get_contents($this->getDataDir() . "/no_semantic_markup.html");
$type = RecipeParser::matchMarkupFormat($html);
$this->assertEquals(null, $type);
}
/**
* @expectedException NoMatchingParserException
*/
function test_parser_no_matching_parser_exception() {
$html = "";
$url = "http://www.example.com/";
$recipe = RecipeParser::parse($html, $url);
}
}
|
Clean up & node-webkit version bump | /*jshint node:true */
"use strict";
module.exports = function(grunt) {
var nwDir = grunt.option("nwdir") || "./bin/node-webkit-v0.5.1-win-ia32/";
grunt.loadNpmTasks("grunt-contrib-compress");
grunt.loadNpmTasks("grunt-mkdir");
grunt.loadNpmTasks("grunt-shell");
grunt.loadTasks("./build/");
grunt.initConfig({
mkdir : {
bin : {
options : {
create : [ "bin" ]
}
}
},
compress : {
tristis : {
src : [ "src/*", "package.json" ],
options : {
mode : "zip",
archive : "./bin/tristis.nw"
}
}
},
shell : {
launch : {
command : "nw.exe ../../",
options : {
execOptions : {
cwd : nwDir
}
}
},
debug : {
command : "nw.exe ../../ --debug",
options : {
execOptions : {
cwd : nwDir
}
}
}
}
});
grunt.registerTask("default", [ "shell:launch" ]);
grunt.registerTask("debug", [ "shell:debug" ]);
grunt.registerTask("release", [ "mkdir", "compress", "package" ]);
};
| /*jshint node:true */
"use strict";
var fs = require("fs"),
async = require("async");
module.exports = function(grunt) {
var nwDir = grunt.option("nwdir") || "./bin/node-webkit-v0.5.0-win-ia32/";
grunt.loadNpmTasks("grunt-contrib-compress");
grunt.loadNpmTasks("grunt-mkdir");
grunt.loadNpmTasks("grunt-shell");
grunt.loadTasks("./build/");
grunt.initConfig({
mkdir : {
bin : {
options : {
create : [ "bin" ]
}
}
},
compress : {
tristis : {
src : [ "src/*", "package.json" ],
options : {
mode : "zip",
archive : "./bin/tristis.nw"
}
}
},
shell : {
launch : {
command : "nw.exe ../../",
options : {
execOptions : {
cwd : nwDir
}
}
},
debug : {
command : "nw.exe ../../ --debug",
options : {
execOptions : {
cwd : nwDir
}
}
}
}
});
grunt.registerTask("default", [ "shell:launch" ]);
grunt.registerTask("debug", [ "shell:debug" ]);
grunt.registerTask("release", [ "mkdir", "compress", "package" ]);
};
|
Reorganize the CreateServer to allow optimization. | 'use strict';
var NET = require('net');
var PORTS = {};
function CreateServer(
port,
callback
){
if(
(typeof port === 'number')
){
port = parseFloat(port);
if(
(PORTS[port.toString()])
){
process.nextTick(CreateServer,port,callback);
return;
}
PORTS[port.toString()] = true;
NET.createServer()
.on('error',function CreateServerError(error){
CloseServer(this);
delete PORTS[port.toString()];
if(error.code === 'EADDRINUSE') callback(null,false,port);
else callback(true,error,port);
})
.on('listening',function CreateServerListening(){
CloseServer(this);
delete PORTS[port.toString()];
callback(null,true,port);
})
.listen(port);
}
else if(typeof callback === 'function') callback(null,false);
}
/* Older versions of Node.js throw hard
// errors when closing an error'd server.
// This function is to allow 'CreateServer'
// to be optimized by moving out the 'try'.
// Because this is just to try and close the
// server, if it's somehow listening after
// erroring, we won't handle any errors that
// come out of this `CloseServer`.
*/
function CloseServer(
server
){
try{
server.close();
}
catch(error){}
}
module.exports = CreateServer;
| 'use strict';
var NET = require('net');
var PORTS = {};
function CreateServer(
port,
callback
){
if(
(typeof port === 'number')
){
port = parseFloat(port);
if(
(PORTS[port.toString()])
){
process.nextTick(CreateServer,port,callback);
return;
}
PORTS[port.toString()] = true;
NET.createServer()
.on('error',function CreateServerError(error){
delete PORTS[port.toString()];
/* Older versions of Node.js throw hard
// errors when .closing an error'd server.
*/
try{
this.close();
}
catch(error){
/* Ignore the error, simply try and close
// the server if for whatever reason it
// is somehow listening.
*/
}
if(error.code === 'EADDRINUSE') callback(null,false,port);
else callback(true,error,port);
})
.on('listening',function CreateServerListening(){
this.close(function CreateServerClose(){
delete PORTS[port.toString()];
callback(null,true,port);
});
})
.listen(port);
}
else if(typeof callback === 'function') callback(null,false);
}
module.exports = CreateServer;
|
Check project exists when viewing a test | <?php
namespace Criterion\UI\Controller;
class TestController
{
public function view(\Silex\Application $app)
{
$data['test'] = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $data['test'])
{
return $app->abort(404, 'Test not found.');
}
$data['project'] = $app['mongo']->projects->findOne(array(
'_id' => $data['test']['project_id']
));
if ( ! $data['project'])
{
return $app->abort(404, 'Project not found.');
}
$logs = $app['mongo']->logs->find(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
$data['log'] = array();
foreach ($logs as $log)
{
$data['log'][] = $log;
}
return $app['twig']->render('Test.twig', $data);
}
public function delete(\Silex\Application $app)
{
$test = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $test)
{
return $app->abort(404, 'Test not found.');
}
$app['mongo']->tests->remove(array(
'_id' => new \MongoId($app['request']->get('id'))
));
$app['mongo']->logs->remove(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
return $app->redirect('/project/' . $test['project_id']);
}
}
| <?php
namespace Criterion\UI\Controller;
class TestController
{
public function view(\Silex\Application $app)
{
$data['test'] = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $data['test'])
{
return $app->abort(404, 'Test not found.');
}
$logs = $app['mongo']->logs->find(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
$data['log'] = array();
foreach ($logs as $log)
{
$data['log'][] = $log;
}
return $app['twig']->render('Test.twig', $data);
}
public function delete(\Silex\Application $app)
{
$test = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $test)
{
return $app->abort(404, 'Test not found.');
}
$app['mongo']->tests->remove(array(
'_id' => new \MongoId($app['request']->get('id'))
));
$app['mongo']->logs->remove(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
return $app->redirect('/project/' . $test['project_id']);
}
}
|
Convert left over 5.4 closing bracket
Stumbled against another wrong closing bracket. | <?php
namespace Aura\Html;
return array(
'anchor' => function () { return new Helper\Anchor; },
'attr' => function () { return new Helper\EscapeAttr; },
'base' => function () { return new Helper\Base; },
'form' => function () { return new Helper\Form; },
'escapeHtml' => function () { return new Helper\EscapeHtml; },
'input' => function () {
$helper_locator = new HelperLocator(new HelperFactory(
new Escaper,
require __DIR__ . '/input_registry.php'
));
$input = new Helper\Input;
$input->setHelperLocator($helper_locator);
return $input;
},
'img' => function () { return new Helper\Img; },
'links' => function () { return new Helper\Links; },
'metas' => function () { return new Helper\Metas; },
'ol' => function () { return new Helper\Ol; },
'scripts' => function () { return new Helper\Scripts; },
'scriptsFoot' => function () { return new Helper\Scripts; },
'styles' => function () { return new Helper\Styles; },
'tag' => function () { return new Helper\Tag; },
'title' => function () { return new Helper\Title; },
'ul' => function () { return new Helper\Ul; },
);
| <?php
namespace Aura\Html;
return array(
'anchor' => function () { return new Helper\Anchor; },
'attr' => function () { return new Helper\EscapeAttr; },
'base' => function () { return new Helper\Base; },
'form' => function () { return new Helper\Form; },
'escapeHtml' => function () { return new Helper\EscapeHtml; },
'input' => function () {
$helper_locator = new HelperLocator(new HelperFactory(
new Escaper,
require __DIR__ . '/input_registry.php'
));
$input = new Helper\Input;
$input->setHelperLocator($helper_locator);
return $input;
},
'img' => function () { return new Helper\Img; },
'links' => function () { return new Helper\Links; },
'metas' => function () { return new Helper\Metas; },
'ol' => function () { return new Helper\Ol; },
'scripts' => function () { return new Helper\Scripts; },
'scriptsFoot' => function () { return new Helper\Scripts; },
'styles' => function () { return new Helper\Styles; },
'tag' => function () { return new Helper\Tag; },
'title' => function () { return new Helper\Title; },
'ul' => function () { return new Helper\Ul; },
];
|
Remove extraneous semicolon at beginning of js helper | (function() {
window.stubFileUpload = function(el) {
return new FakeFileUpload(el);
};
function FakeFileUpload(fileInputElement) {
var self = this;
spyOn($.fn, 'fileupload').andCallFake(function(uploadOptions) {
self.options = uploadOptions;
});
}
_.extend(FakeFileUpload.prototype, {
add: function(filenames) {
var self = this;
this.files = _.map(filenames, function(name) {
return {
name: name,
size: 1234,
type: "text/plain"
};
});
this.options.add(this.fakeEvent(), {
files: self.files,
submit: function() {
self.wasSubmitted = true;
return self.fakeRequest();
}
});
},
fakeEvent: function() {
return { preventDefault: $.noop };
},
fakeRequest: function() {
var self = this;
return {
abort: function() {
self.wasAborted = true;
}
};
},
succeed: function(bodyJson) {
this.options.done({}, {
result: JSON.stringify(bodyJson)
});
},
fail: function(bodyJson) {
this.options.fail(this.fakeEvent(), {
jqXHR: {
responseText: JSON.stringify(bodyJson)
}
})
}
});
})();
| ;(function() {
window.stubFileUpload = function(el) {
return new FakeFileUpload(el);
};
function FakeFileUpload(fileInputElement) {
var self = this;
spyOn($.fn, 'fileupload').andCallFake(function(uploadOptions) {
self.options = uploadOptions;
});
}
_.extend(FakeFileUpload.prototype, {
add: function(filenames) {
var self = this;
this.files = _.map(filenames, function(name) {
return {
name: name,
size: 1234,
type: "text/plain"
};
});
this.options.add(this.fakeEvent(), {
files: self.files,
submit: function() {
self.wasSubmitted = true;
return self.fakeRequest();
}
});
},
fakeEvent: function() {
return { preventDefault: $.noop };
},
fakeRequest: function() {
var self = this;
return {
abort: function() {
self.wasAborted = true;
}
};
},
succeed: function(bodyJson) {
this.options.done({}, {
result: JSON.stringify(bodyJson)
});
},
fail: function(bodyJson) {
this.options.fail(this.fakeEvent(), {
jqXHR: {
responseText: JSON.stringify(bodyJson)
}
})
}
});
})();
|
Remove auto open of the browser on gulp serve | const lit = require('fountain-generator').lit;
module.exports = function browsersyncConf(props) {
const conf = {
server: {
baseDir: [],
browser: []
}
};
if (props.dist) {
conf.server.baseDir.push(lit`conf.paths.dist`);
} else {
conf.server.baseDir.push(lit`conf.paths.tmp`);
if (props.modules === 'systemjs') {
conf.server.baseDir.push('.');
} else {
conf.server.baseDir.push(lit`conf.paths.src`);
}
if (props.modules === 'inject') {
conf.server.routes = {
'/bower_components': 'bower_components'
};
}
if (props.modules === 'systemjs') {
conf.server.routes = {
'/index.html': 'src/index.html'
};
conf.server.index = 'src/index.html';
}
if (props.webpackHotReload) {
conf.server.middleware = [
lit`webpackDevMiddleware(webpackBundler, {
// IMPORTANT: dev middleware can't access config, so we should
// provide publicPath by ourselves
publicPath: webpackConf.output.publicPath,
// Quiet verbose output in console
quiet: true
}),
// bundler should be the same as above
webpackHotMiddleware(webpackBundler)`
];
}
}
return conf;
};
| const lit = require('fountain-generator').lit;
module.exports = function browsersyncConf(props) {
const conf = {
server: {
baseDir: []
}
};
if (props.dist) {
conf.server.baseDir.push(lit`conf.paths.dist`);
} else {
conf.server.baseDir.push(lit`conf.paths.tmp`);
if (props.modules === 'systemjs') {
conf.server.baseDir.push('.');
} else {
conf.server.baseDir.push(lit`conf.paths.src`);
}
if (props.modules === 'inject') {
conf.server.routes = {
'/bower_components': 'bower_components'
};
}
if (props.modules === 'systemjs') {
conf.server.routes = {
'/index.html': 'src/index.html'
};
conf.server.index = 'src/index.html';
}
if (props.webpackHotReload) {
conf.server.middleware = [
lit`webpackDevMiddleware(webpackBundler, {
// IMPORTANT: dev middleware can't access config, so we should
// provide publicPath by ourselves
publicPath: webpackConf.output.publicPath,
// Quiet verbose output in console
quiet: true
}),
// bundler should be the same as above
webpackHotMiddleware(webpackBundler)`
];
}
}
return conf;
};
|
Add typehints for ServiceRegistryInterface::all() calls | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Payment\Resolver;
use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Registry\PrioritizedServiceRegistryInterface;
/**
* @author Anna Walasek <[email protected]>
*/
class CompositeMethodsResolver implements MethodsResolverInterface
{
/**
* @var PrioritizedServiceRegistryInterface
*/
private $resolversRegistry;
/**
* @param PrioritizedServiceRegistryInterface $resolversRegistry
*/
public function __construct(PrioritizedServiceRegistryInterface $resolversRegistry)
{
$this->resolversRegistry = $resolversRegistry;
}
/**
* {@inheritdoc}
*/
public function getSupportedMethods(PaymentInterface $payment)
{
/** @var MethodsResolverInterface $resolver */
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($payment)) {
return $resolver->getSupportedMethods($payment);
}
}
return [];
}
/**
* {@inheritdoc}
*/
public function supports(PaymentInterface $payment)
{
/** @var MethodsResolverInterface $resolver */
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($payment)) {
return true;
}
}
return false;
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Payment\Resolver;
use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Registry\PrioritizedServiceRegistryInterface;
/**
* @author Anna Walasek <[email protected]>
*/
class CompositeMethodsResolver implements MethodsResolverInterface
{
/**
* @var PrioritizedServiceRegistryInterface
*/
private $resolversRegistry;
/**
* @param PrioritizedServiceRegistryInterface $resolversRegistry
*/
public function __construct(PrioritizedServiceRegistryInterface $resolversRegistry)
{
$this->resolversRegistry = $resolversRegistry;
}
/**
* {@inheritdoc}
*/
public function getSupportedMethods(PaymentInterface $payment)
{
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($payment)) {
return $resolver->getSupportedMethods($payment);
}
}
return [];
}
/**
* {@inheritdoc}
*/
public function supports(PaymentInterface $payment)
{
foreach ($this->resolversRegistry->all() as $resolver) {
if ($resolver->supports($payment)) {
return true;
}
}
return false;
}
}
|
Remove outdated column name from user table seeder | <?php namespace Flarum\Core\Seeders;
use Illuminate\Database\Seeder;
use Flarum\Core\Models\User;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::unguard();
$faker = \Faker\Factory::create();
for ($i = 0; $i < 100; $i++) {
$user = User::create([
'username' => $faker->userName,
'email' => $faker->safeEmail,
'is_activated' => true,
'password' => 'password',
'join_time' => $faker->dateTimeThisYear
]);
// Assign the users to the 'Member' group, and possibly some others.
$user->groups()->attach(3);
if (rand(1, 50) == 1) {
$user->groups()->attach(4);
}
if (rand(1, 20) == 1) {
$user->groups()->attach(5);
}
if (rand(1, 20) == 1) {
$user->groups()->attach(1);
}
}
}
}
| <?php namespace Flarum\Core\Seeders;
use Illuminate\Database\Seeder;
use Flarum\Core\Models\User;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::unguard();
$faker = \Faker\Factory::create();
for ($i = 0; $i < 100; $i++) {
$user = User::create([
'username' => $faker->userName,
'email' => $faker->safeEmail,
'is_confirmed' => true,
'is_activated' => true,
'password' => 'password',
'join_time' => $faker->dateTimeThisYear
]);
// Assign the users to the 'Member' group, and possibly some others.
$user->groups()->attach(3);
if (rand(1, 50) == 1) {
$user->groups()->attach(4);
}
if (rand(1, 20) == 1) {
$user->groups()->attach(5);
}
if (rand(1, 20) == 1) {
$user->groups()->attach(1);
}
}
}
}
|
Move eslint-disable no-undef to a global comment
Summary:
Switch the only `// eslint-disable no-undef` to defined the global instead so that the new babel-eslint-no-undef compile time check doesn't need to understand inline eslint comments.
Changelog: [Internal]
Reviewed By: cpojer
Differential Revision: D18644590
fbshipit-source-id: ac9c6da3a5e63b285b5e1dde210613b5d893641b | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const {Alert, Button, View} = require('react-native');
class XHRExampleAbortController extends React.Component<{...}, {...}> {
_timeout: any;
_submit(abortDelay) {
clearTimeout(this._timeout);
const abortController = new global.AbortController();
fetch('https://facebook.github.io/react-native/', {
signal: abortController.signal,
})
.then(res => res.text())
.then(res => Alert.alert(res))
.catch(err => Alert.alert(err.message));
this._timeout = setTimeout(() => {
abortController.abort();
}, abortDelay);
}
componentWillUnmount() {
clearTimeout(this._timeout);
}
render(): React.Node {
return (
<View>
<Button
title="Abort before response"
onPress={() => {
this._submit(0);
}}
/>
<Button
title="Abort after response"
onPress={() => {
this._submit(5000);
}}
/>
</View>
);
}
}
module.exports = XHRExampleAbortController;
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const {Alert, Button, View} = require('react-native');
class XHRExampleAbortController extends React.Component<{...}, {...}> {
_timeout: any;
_submit(abortDelay) {
clearTimeout(this._timeout);
// eslint-disable-next-line no-undef
const abortController = new AbortController();
fetch('https://facebook.github.io/react-native/', {
signal: abortController.signal,
})
.then(res => res.text())
.then(res => Alert.alert(res))
.catch(err => Alert.alert(err.message));
this._timeout = setTimeout(() => {
abortController.abort();
}, abortDelay);
}
componentWillUnmount() {
clearTimeout(this._timeout);
}
render(): React.Node {
return (
<View>
<Button
title="Abort before response"
onPress={() => {
this._submit(0);
}}
/>
<Button
title="Abort after response"
onPress={() => {
this._submit(5000);
}}
/>
</View>
);
}
}
module.exports = XHRExampleAbortController;
|
Use local date instead of a sql function (tests are in sqlite, base in mysql) | <?php
namespace App;
use App\Casts\EncryptedString;
use DateInterval;
use DateTime;
use DB;
use Illuminate\Database\Eloquent\Model;
class Draw extends Model
{
use HashId;
protected static $hashConnection = 'draw';
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'mail_title' => EncryptedString::class,
'mail_body' => EncryptedString::class,
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'expires_at',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['mail_title', 'mail_body', 'expires_at'];
public function save(array $options = [])
{
$this->expires_at = $this->expires_at ?: (new DateTime('now'))->add(new DateInterval('P7D'));
return parent::save($options);
}
public static function cleanup()
{
// Recap is sent 2 days after so remove everything 3 days after
self::where('expires_at', '<=', (new DateTime('now'))->add(new DateInterval('P3D')))->delete();
}
public function participants()
{
return $this->hasMany(Participant::class)->with('mail');
}
public function getOrganizerAttribute()
{
return $this->participants->first();
}
}
| <?php
namespace App;
use App\Casts\EncryptedString;
use DateInterval;
use DateTime;
use DB;
use Illuminate\Database\Eloquent\Model;
class Draw extends Model
{
use HashId;
protected static $hashConnection = 'draw';
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'mail_title' => EncryptedString::class,
'mail_body' => EncryptedString::class,
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'expires_at',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['mail_title', 'mail_body', 'expires_at'];
public function save(array $options = [])
{
$this->expires_at = $this->expires_at ?: (new DateTime('now'))->add(new DateInterval('P7D'));
return parent::save($options);
}
public static function cleanup()
{
// Recap is sent 2 days after so remove everything 3 days after
self::where('expires_at', '<=', DB::raw('DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY)'))->delete();
}
public function participants()
{
return $this->hasMany(Participant::class)->with('mail');
}
public function getOrganizerAttribute()
{
return $this->participants->first();
}
}
|
Add hide label back to columns component. | export default [
{
key: 'labelPosition',
ignore: true
},
{
key: 'placeholder',
ignore: true
},
{
key: 'description',
ignore: true
},
{
key: 'tooltip',
ignore: true
},
{
key: 'autofocus',
ignore: true
},
{
key: 'tabindex',
ignore: true
},
{
weight: 150,
type: 'datagrid',
input: true,
key: 'columns',
label: 'Column Properties',
addAnother: 'Add Column',
tooltip: 'The width, offset, push, and pull settings for each column.',
components: [
{
type: 'hidden',
key: 'components',
defaultValue: []
},
{
type: 'number',
key: 'width',
defaultValue: 6,
label: 'Width'
},
{
type: 'number',
key: 'offset',
defaultValue: 0,
label: 'Offset'
},
{
type: 'number',
key: 'push',
defaultValue: 0,
label: 'Push'
},
{
type: 'number',
key: 'pull',
defaultValue: 0,
label: 'Pull'
}
]
},
{
weight: 161,
type: 'checkbox',
label: 'Hide Column when Children Hidden',
key: 'hideOnChildrenHidden',
tooltip: 'Check this if you would like to hide any column when the children within that column are also hidden',
input: true
}
];
| export default [
{
key: 'labelPosition',
ignore: true
},
{
key: 'placeholder',
ignore: true
},
{
key: 'description',
ignore: true
},
{
key: 'tooltip',
ignore: true
},
{
key: 'hideLabel',
ignore: true
},
{
key: 'autofocus',
ignore: true
},
{
key: 'tabindex',
ignore: true
},
{
weight: 150,
type: 'datagrid',
input: true,
key: 'columns',
label: 'Column Properties',
addAnother: 'Add Column',
tooltip: 'The width, offset, push, and pull settings for each column.',
components: [
{
type: 'hidden',
key: 'components',
defaultValue: []
},
{
type: 'number',
key: 'width',
defaultValue: 6,
label: 'Width'
},
{
type: 'number',
key: 'offset',
defaultValue: 0,
label: 'Offset'
},
{
type: 'number',
key: 'push',
defaultValue: 0,
label: 'Push'
},
{
type: 'number',
key: 'pull',
defaultValue: 0,
label: 'Pull'
}
]
},
{
weight: 161,
type: 'checkbox',
label: 'Hide Column when Children Hidden',
key: 'hideOnChildrenHidden',
tooltip: 'Check this if you would like to hide any column when the children within that column are also hidden',
input: true
}
];
|
Undo change when merged to switch_to_vue | (function () {
require.config({
baseUrl: "../remoteappmanager/static/js/",
paths: {
components: '../components',
jquery: '../components/jquery/jquery.min',
bootstrap: '../components/bootstrap/js/bootstrap.min',
moment: "../components/moment/moment",
"jsapi/v1/resources": "../../../jstests/tests/home/mock_jsapi",
underscore: "../components/underscore/underscore-min"
},
shim: {
bootstrap: {
deps: ["jquery"],
exports: "bootstrap"
}
}
});
require([
"tests/home/test_configurables.js",
"tests/home/test_models.js",
"tests/home/test_application_list_view.js",
"tests/home/test_application_view.js",
"tests/test_utils.js",
"tests/test_analytics.js"
], function() {
window.apidata = {
base_url: "/",
prefix: "/"
};
QUnit.load();
QUnit.start();
});
}());
| (function () {
require.config({
baseUrl: "../remoteappmanager/static/js/",
paths: {
components: '../components',
jquery: '../components/jquery/jquery.min',
bootstrap: '../components/bootstrap/js/bootstrap.min',
moment: "../components/moment/moment",
"jsapi/v1/resources": "../../../jstests/tests/home/mock_jsapi",
handlebars: "../components/handlebars/handlebars.amd.min",
underscore: "../components/underscore/underscore-min"
},
shim: {
bootstrap: {
deps: ["jquery"],
exports: "bootstrap"
}
}
});
require([
"tests/home/test_configurables.js",
"tests/home/test_models.js",
"tests/home/test_application_list_view.js",
"tests/home/test_application_view.js",
"tests/test_utils.js",
"tests/test_analytics.js"
], function() {
window.apidata = {
base_url: "/",
prefix: "/"
};
QUnit.load();
QUnit.start();
});
}());
|
Add comments and cleanup syntax | þ.extend('CHAINABLES', {
//Add a single or an array of classes to this.nodes
addClass: function (values) {
var i, þnodes = this;
if (typeof values === "string") values = [values];
return this.each(function (nodeIndex) {
//each node
for (i = 0; i < values.length; i++) {
//each value
if (!þnodes.hasClass(values[i], nodeIndex)) {
if (this.className)
this.className = this.className + ' ' + values[i];
else
this.className = values[i];
}
}
}, true);
},
//Remove a single or an array of classes from this.nodes
removeClass: function (values) {
var i;
if (typeof values === "string") values = [values];
return this.each(function (nodeIndex) {
for (i = 0; i < values.length; i++) {
var classNames = this.className.split(' ');
var position = classNames.indexOf(values[i]);
if (position >= 0) {
classNames.splice(position, 1); //Deleted it from array
this.className = classNames.join(' ');//Join remaining
}
}
}, true);
},
});
| þ.extend('CHAINABLES', {
addClass: function (values) {
var i, þnodes = this;
if (typeof values === "string") values = [values];
return this.each(function (nodeIndex) {
//each node
for (i = 0; i < values.length; i++) {
//each value
if (!þnodes.hasClass(values[i], nodeIndex)) {
if (this.className)
this.className = this.className + ' ' + values[i];
else
this.className = values[i];
}
}
}, true);
},
removeClass: function (values) {
var i;
if (typeof values === "string") values = [values];
return this.each(function (nodeIndex) {
for (i = 0; i < values.length; i++) {
//
var classNames = this.className.split(' ');
var position = classNames.indexOf(values[i]);
if (position >= 0) {
classNames.splice(position, 1); //Deleted it from array
this.className = classNames.join(' ');//Join remaining
}
}
}, true);
},
});
|
Update dependencies to ones compatible with Python 3. | from setuptools import setup, find_packages
setup(name='googleanalytics',
description='A wrapper for the Google Analytics API.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='[email protected]',
url='https://github.com/debrouwere/google-analytics/',
download_url='http://www.github.com/debrouwere/google-analytics/tarball/master',
version='0.14.2',
license='ISC',
packages=find_packages(),
keywords='data analytics api wrapper google',
scripts=[
'bin/googleanalytics'
],
install_requires=[
'oauth2client>=1.4.6',
'google-api-python-client==1.4',
'python-dateutil==1.5',
'addressable>=1.4',
'inspect-it>=0.2',
'flask==0.10',
'keyring==5',
'click==3.3',
'pyyaml>=3',
],
test_suite='googleanalytics.tests',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Information Analysis',
],
) | from setuptools import setup, find_packages
setup(name='googleanalytics',
description='A wrapper for the Google Analytics API.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='[email protected]',
url='https://github.com/debrouwere/google-analytics/',
download_url='http://www.github.com/debrouwere/google-analytics/tarball/master',
version='0.14.2',
license='ISC',
packages=find_packages(),
keywords='data analytics api wrapper google',
scripts=[
'bin/googleanalytics'
],
install_requires=[
'oauth2client==1.3',
'google-api-python-client==1.3',
'python-dateutil==1.5',
'addressable>=1.3',
'inspect-it>=0.2',
'flask==0.10',
'keyring==4',
'click==3.3',
'pyyaml>=3',
],
test_suite='googleanalytics.tests',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Information Analysis',
],
) |
Add event automation for on prefixes. | function createElement (el) {
const realNode = document.createElement(el.tagName);
if (el.attributes) {
for (let a = 0; a < el.attributes.length; a++) {
const attr = el.attributes[a];
const name = attr.name;
const value = attr.value;
if (!value) {
continue;
}
if (name === 'content') {
if (Array.isArray(value)) {
value.forEach(ch => realNode.appendChild(render(ch)));
} else {
realNode.appendChild(render(value));
}
} else if (name.indexOf('on') === 0) {
realNode.addEventListener(name.substring(2).toLowerCase(), value);
} else {
realNode.setAttribute(name, value);
}
}
}
if (el.childNodes) {
const frag = document.createDocumentFragment();
for (let a = 0; a < el.childNodes.length; a++) {
const ch = el.childNodes[a];
if (ch) {
frag.appendChild(render(ch));
}
}
if (realNode.hasOwnProperty('content')) {
realNode.content = frag;
} else {
realNode.appendChild(frag);
}
}
return realNode;
}
function createText (el) {
return document.createTextNode(el.textContent);
}
export default function render (el) {
if (el instanceof Node) {
return el;
}
const realNode = el.tagName ? createElement(el) : createText(el);
return el.__realNode = realNode;
}
| function createElement (el) {
const realNode = document.createElement(el.tagName);
if (el.attributes) {
for (let a = 0; a < el.attributes.length; a++) {
const attr = el.attributes[a];
const name = attr.name;
const value = attr.value;
if (!value) {
continue;
}
if (name === 'content') {
if (Array.isArray(value)) {
value.forEach(ch => realNode.appendChild(render(ch)));
} else {
realNode.appendChild(render(value));
}
} else {
realNode.setAttribute(name, value);
}
}
}
if (el.childNodes) {
const frag = document.createDocumentFragment();
for (let a = 0; a < el.childNodes.length; a++) {
const ch = el.childNodes[a];
if (ch) {
frag.appendChild(render(ch));
}
}
if (realNode.hasOwnProperty('content')) {
realNode.content = frag;
} else {
realNode.appendChild(frag);
}
}
return realNode;
}
function createText (el) {
return document.createTextNode(el.textContent);
}
export default function render (el) {
if (el instanceof Node) {
return el;
}
const realNode = el.tagName ? createElement(el) : createText(el);
return el.__realNode = realNode;
}
|
Embed translations in client for production | var hackProviders = {}
require('../app')
.config(/* @ngInject */function (nyaBsConfigProvider) {
// dummy hack to allow runtime update of the translation matrix
hackProviders.nyaBsConfigProvider = nyaBsConfigProvider
})
.config(/* @ngInject */function ($translateProvider, ENDPOINT_URL) {
if (process.env.NODE_ENV === 'production') {
$translateProvider.translations('en', require('../../../i18n/en.json'))
$translateProvider.translations('bg', require('../../../i18n/bg.json'))
} else {
$translateProvider.useUrlLoader(ENDPOINT_URL + '/i18n')
}
$translateProvider
.registerAvailableLanguageKeys([ 'en', 'bg' ], {
'en_*': 'en',
'bg_*': 'bg',
'*': 'en'
})
.determinePreferredLanguage()
.preferredLanguage('bg')
})
.run(/* @ngInject */function ($translate, $rootScope) {
function updateLang (language) {
$rootScope.localeLanguage = $rootScope.$language = $translate.$language = language
hackProviders.nyaBsConfigProvider.setLocalizedText(language, {
defaultNoneSelection: $translate.instant('MULTIPLE_CHOICE_DEFAULT_NONE_SELECTION'),
noSearchResults: $translate.instant('MULTIPLE_CHOICE_NO_SEARCH_RESULTS'),
numberItemSelected: $translate('MULTIPLE_CHOICE_NUMBER_ITEM_SELECTED')
})
hackProviders.nyaBsConfigProvider.useLocale(language)
}
updateLang($translate.proposedLanguage())
$rootScope.$on('$translateChangeSuccess', function (e, params) { updateLang(params.language) })
})
.config(/* @ngInject */function ($httpProvider) {
$httpProvider.interceptors.push('languageInterceptor')
})
| var hackProviders = {}
require('../app')
.config(/* @ngInject */function (nyaBsConfigProvider) {
// dummy hack to allow runtime update of the translation matrix
hackProviders.nyaBsConfigProvider = nyaBsConfigProvider
})
.config(/* @ngInject */function ($translateProvider, ENDPOINT_URL) {
$translateProvider
.useUrlLoader(ENDPOINT_URL + '/i18n')
.registerAvailableLanguageKeys([ 'en', 'bg' ], {
'en_*': 'en',
'bg_*': 'bg',
'*': 'en'
})
.determinePreferredLanguage()
.preferredLanguage('bg')
})
.run(/* @ngInject */function ($translate, $rootScope) {
function updateLang (language) {
$rootScope.localeLanguage = $rootScope.$language = $translate.$language = language
hackProviders.nyaBsConfigProvider.setLocalizedText(language, {
defaultNoneSelection: $translate.instant('MULTIPLE_CHOICE_DEFAULT_NONE_SELECTION'),
noSearchResults: $translate.instant('MULTIPLE_CHOICE_NO_SEARCH_RESULTS'),
numberItemSelected: $translate('MULTIPLE_CHOICE_NUMBER_ITEM_SELECTED')
})
hackProviders.nyaBsConfigProvider.useLocale(language)
}
updateLang($translate.proposedLanguage())
$rootScope.$on('$translateChangeSuccess', function (e, params) { updateLang(params.language) })
})
.config(/* @ngInject */function ($httpProvider) {
$httpProvider.interceptors.push('languageInterceptor')
})
|
Make sure arrow popups don't overflow to the left | (function($){
$.fn.arrowPopup = function(popupSelector, arrowDirection) {
var popup = $(popupSelector);
var offset = $(this).offset();
arrowDirection = arrowDirection || 'up';
var left = 0;
var top = 0;
popup.removeClass('point-up').removeClass('point-left');
switch (arrowDirection) {
case 'up':
popup.addClass('point-up');
left = offset.left + ($(this).width()/2) - (popup.width()/2);
top = offset.top + $(this).height() + 15;
break;
case 'left':
popup.addClass('point-left');
left = 230;
top = offset.top + ($(this).height()/2) - (popup.height()/2);
break;
}
// Make sure the popup doesn't overflow if the window is too narrow
var popupRightSide = left + popup.width();
var windowRightSide = $(window).width() - 25; // assuming scrollbar takes up 25px;
if (popupRightSide > windowRightSide) {
left -= (popupRightSide - windowRightSide);
}
if (left < 0) {
left = 0;
}
// Display a blocker div that removes the popup when clicked
$('<div id="arrow-popup-blocker"></div>').mousedown(function(event) {
$(this).remove();
popup.hide();
event.stopPropagation();
}).appendTo('body');
popup.css({
top: top,
left: left
}).show();
return this;
};
}(jQuery));
| (function($){
$.fn.arrowPopup = function(popupSelector, arrowDirection) {
var popup = $(popupSelector);
var offset = $(this).offset();
arrowDirection = arrowDirection || 'up';
var left = 0;
var top = 0;
popup.removeClass('point-up').removeClass('point-left');
switch (arrowDirection) {
case 'up':
popup.addClass('point-up');
left = offset.left + ($(this).width()/2) - (popup.width()/2);
top = offset.top + $(this).height() + 15;
break;
case 'left':
popup.addClass('point-left');
left = 230;
top = offset.top + ($(this).height()/2) - (popup.height()/2);
break;
}
// Make sure the popup doesn't overflow if the window is too narrow
var popupRightSide = left + popup.width();
var windowRightSide = $(window).width() - 25; // assuming scrollbar takes up 25px;
if (popupRightSide > windowRightSide) {
left -= (popupRightSide - windowRightSide);
}
// Display a blocker div that removes the popup when clicked
$('<div id="arrow-popup-blocker"></div>').mousedown(function(event) {
$(this).remove();
popup.hide();
event.stopPropagation();
}).appendTo('body');
popup.css({
top: top,
left: left
}).show();
return this;
};
}(jQuery));
|
Make the initialization wait optional | # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
'''
'''
if not isinstance(security_groups, list):
security_groups = [security_groups]
ec2 = boto.ec2.connect_to_region(region)
reserve = ec2.run_instances(image_id, key_name=key_name,
instance_type=instance_type,
security_groups=security_groups,
user_data=user_data)
inst = reserve.instances[0]
while inst.state == u'pending':
time.sleep(10)
inst.update()
# Wait for the status checks first
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
if initial_check:
check_stat = "Status:initializing"
while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
time.sleep(10)
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
return inst
# ec2.get_instance_attribute('i-336b69f6', 'instanceType')
| # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None):
'''
'''
if not isinstance(security_groups, list):
security_groups = [security_groups]
ec2 = boto.ec2.connect_to_region(region)
reserve = ec2.run_instances(image_id, key_name=key_name,
instance_type=instance_type,
security_groups=security_groups,
user_data=user_data)
inst = reserve.instances[0]
while inst.state == u'pending':
time.sleep(10)
inst.update()
# Wait for the status checks first
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
check_stat = "Status:initializing"
while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
time.sleep(10)
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
return inst
# ec2.get_instance_attribute('i-336b69f6', 'instanceType')
|
Use aero info instead for caching info
Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later. | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
def search(self, query):
response = self.command(['search', query])[0]
if 'No formula found' not in response and 'Error:' not in response:
return dict([(
self.package_name(line),
self.search_info(self.package_name(line))
) for line in response.splitlines() if line])
return {}
def search_info(self, query):
response = self._execute_command('aero', ['info', query], False)[0]
from re import split
lines = response.splitlines()
idx = lines.index(' ________________________________________ __________________________________________________ ')
return '\n'.join([''.join(split('\x1b.*?m', l)).replace(' : ', '').strip() for l in response.splitlines()[idx+1:idx+4]])
def info(self, query):
if '/' in query:
self.command(['tap', '/'.join(query.split('/')[:-1])])
response = self.command(['info', query])[0]
if 'Error:' not in response:
response = response.replace(query + ': ', 'version: ')
return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line]
return [['No info available']]
def install(self, query):
self.shell(['install', query])
return {}
| # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
def search(self, query):
response = self.command(['search', query])[0]
if 'No formula found' not in response and 'Error:' not in response:
return dict([(
self.package_name(line),
'\n'.join(map(
lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1],
self.search_info(line)
))
) for line in response.splitlines() if line])
return {}
def search_info(self, query):
info = self.info(query)
return filter(
None,
[
info[0],
info[1] if len(info) > 1 else None,
info[2] if len(info) > 2 else None,
]
)
def info(self, query):
if '/' in query:
self.command(['tap', '/'.join(query.split('/')[:-1])])
response = self.command(['info', query])[0]
if 'Error:' not in response:
response = response.replace(query + ': ', 'version: ')
return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line]
return [['No info available']]
def install(self, query):
self.shell(['install', query])
return {}
|
Refactor args in manage task | # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django.core.management.base import BaseCommand
from cla_eventlog.models import Log
from cla_provider.models import Feedback
from complaints.models import Complaint
from diagnosis.models import DiagnosisTraversal
from legalaid.models import (
Case, EligibilityCheck, CaseNotesHistory, Person, Income, Savings,
Deductions, PersonalDetails, ThirdPartyDetails, AdaptationDetails,
CaseKnowledgebaseAssignment, EODDetails, EODDetailsCategory, Property
)
from timer.models import Timer
from ...qs_to_file import QuerysetToFile
MODELS = [
Deductions,
Income,
Savings,
Person,
AdaptationDetails,
PersonalDetails,
ThirdPartyDetails,
EligibilityCheck,
Property,
DiagnosisTraversal,
Case,
EODDetails,
EODDetailsCategory,
Complaint,
CaseKnowledgebaseAssignment,
Timer,
Feedback,
CaseNotesHistory,
Log,
LogEntry,
]
class Command(BaseCommand):
help = 'Attempts to re-load data that was deleted in the housekeeping'
def add_arguments(self, parser):
parser.add_argument('directory', nargs=1)
def handle(self, *args, **options):
path = os.path.join(settings.TEMP_DIR, args[0])
filewriter = QuerysetToFile(path)
for model in MODELS:
self.stdout.write(model.__name__)
filewriter.load(model)
| # -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django.core.management.base import BaseCommand
from cla_eventlog.models import Log
from cla_provider.models import Feedback
from complaints.models import Complaint
from diagnosis.models import DiagnosisTraversal
from legalaid.models import (
Case, EligibilityCheck, CaseNotesHistory, Person, Income, Savings,
Deductions, PersonalDetails, ThirdPartyDetails, AdaptationDetails,
CaseKnowledgebaseAssignment, EODDetails, EODDetailsCategory, Property
)
from timer.models import Timer
from ...qs_to_file import QuerysetToFile
MODELS = [
Deductions,
Income,
Savings,
Person,
AdaptationDetails,
PersonalDetails,
ThirdPartyDetails,
EligibilityCheck,
Property,
DiagnosisTraversal,
Case,
EODDetails,
EODDetailsCategory,
Complaint,
CaseKnowledgebaseAssignment,
Timer,
Feedback,
CaseNotesHistory,
Log,
LogEntry,
]
class Command(BaseCommand):
help = 'Attempts to re-load data that was deleted in the housekeeping'
def add_arguments(self, parser):
parser.add_argument('directory', nargs=1, type=str)
def handle(self, *args, **options):
d = args[0]
path = os.path.join(settings.TEMP_DIR, d)
filewriter = QuerysetToFile(path)
for model in MODELS:
self.stdout.write(model.__name__)
filewriter.load(model)
|
Add log when the app fail to get the token from the server | package br.com.alura.agenda.firebase;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import br.com.alura.agenda.retrofit.RetrofitInicializador;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AgendaInstanceIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("token firebase", "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
enviaTokenParaServidor(refreshedToken);
}
private void enviaTokenParaServidor(final String token) {
Call<Void> call = new RetrofitInicializador().getDispositivoService().enviaToken(token);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
Log.i("token enviado", token);
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
Log.e("token falhou", t.getMessage());
}
});
}
}
| package br.com.alura.agenda.firebase;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import br.com.alura.agenda.retrofit.RetrofitInicializador;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AgendaInstanceIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("token firebase", "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
enviaTokenParaServidor(refreshedToken);
}
private void enviaTokenParaServidor(final String token) {
Call<Void> call = new RetrofitInicializador().getDispositivoService().enviaToken(token);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
Log.i("token enviado", token);
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
}
}
|
Handle exceptions when attempting to open zip file | var q = require("q");
var mammoth = require("./");
exports.Converter = mammoth.Converter;
exports.fileInput = fileInput;
function fileInput(inputElement, callback) {
var converter = new mammoth.Converter(mammoth.standardOptions);
function handleFileSelect(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(loadEvent) {
var arrayBuffer = loadEvent.target.result;
try {
converter.convertToHtml({file: openFile(arrayBuffer)})
.then(callback, function(error) {
callback({error: error});
})
.done();
} catch (error) {
callback({error: error});
}
};
reader.readAsArrayBuffer(file);
}
inputElement.addEventListener('change', handleFileSelect, false);
}
function openFile(arrayBuffer) {
var zipFile = new JSZip(arrayBuffer);
function exists(name) {
return zipFile.file(name) !== null;
}
function read(name, encoding) {
var array = zipFile.file(name).asUint8Array();
var buffer = new Buffer(array);
if (encoding) {
return q.when(buffer.toString(encoding));
} else {
return q.when(buffer);
}
}
return {
exists: exists,
read: read
};
}
| var q = require("q");
var mammoth = require("./");
exports.Converter = mammoth.Converter;
exports.fileInput = fileInput;
function fileInput(inputElement, callback) {
var converter = new mammoth.Converter(mammoth.standardOptions);
function handleFileSelect(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(loadEvent) {
var arrayBuffer = loadEvent.target.result;
converter.convertToHtml({file: openFile(arrayBuffer)})
.then(callback, function(error) {
callback({error: error});
})
.done();
};
reader.readAsArrayBuffer(file);
}
inputElement.addEventListener('change', handleFileSelect, false);
}
function openFile(arrayBuffer) {
var zipFile = new JSZip(arrayBuffer);
function exists(name) {
return zipFile.file(name) !== null;
}
function read(name, encoding) {
var array = zipFile.file(name).asUint8Array();
var buffer = new Buffer(array);
if (encoding) {
return q.when(buffer.toString(encoding));
} else {
return q.when(buffer);
}
}
return {
exists: exists,
read: read
};
}
|
Clean up duplicate code in controllers | package org.apereo.cas.web.report;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;
import java.util.Map;
/**
* This is {@link ControllerUtils}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
final class ControllerUtils {
private ControllerUtils() {
}
/**
* Configure model map for config server cloud bus endpoints.
*
* @param busProperties the bus properties
* @param configServerProperties the config server properties
* @param path the path
* @param model the model
*/
public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
final ConfigServerProperties configServerProperties,
final String path,
final Map model) {
if (busProperties != null && busProperties.isEnabled()) {
model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
model.put("refreshMethod", "GET");
} else {
model.put("refreshEndpoint", path + "/status/refresh");
model.put("refreshMethod", "POST");
}
}
}
| package org.apereo.cas.web.report;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;
import java.util.Map;
/**
* This is {@link ControllerUtils}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
public final class ControllerUtils {
private ControllerUtils() {
}
/**
* Configure model map for config server cloud bus endpoints.
*
* @param busProperties the bus properties
* @param configServerProperties the config server properties
* @param path the path
* @param model the model
*/
public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
final ConfigServerProperties configServerProperties,
final String path,
final Map model) {
if (busProperties != null && busProperties.isEnabled()) {
model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
model.put("refreshMethod", "GET");
} else {
model.put("refreshEndpoint", path + "/status/refresh");
model.put("refreshMethod", "POST");
}
}
}
|
Use radio buttons for the style and number of answers. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models
@admin.register(models.Question)
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['title']}),
(_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}),
(_('Secondary image or video'), {
'fields': ['secondary_image', 'secondary_video_url'],
'classes': ['collapse'],
'description': _(
'Choose either a video or image to include on the first page of the question, '
'where students select concept tags. This is only used if you want the question '
'to be hidden when students select concept tags; instead, a preliminary video or '
'image can be displayed. The main question image will be displayed on all '
'subsequent pages.'
),
}),
(_('Answers'), {'fields': [
'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer'
]}),
(None, {'fields': ['example_rationale']}),
]
radio_fields = {'answer_style': admin.HORIZONTAL, 'answer_num_choices': admin.HORIZONTAL}
@admin.register(models.Assignment)
class AssignmentAdmin(admin.ModelAdmin):
filter_horizontal = ['questions']
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models
@admin.register(models.Question)
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['title']}),
(_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}),
(_('Secondary image or video'), {
'fields': ['secondary_image', 'secondary_video_url'],
'classes': ['collapse'],
'description': _(
'Choose either a video or image to include on the first page of the question, '
'where students select concept tags. This is only used if you want the question '
'to be hidden when students select concept tags; instead, a preliminary video or '
'image can be displayed. The main question image will be displayed on all '
'subsequent pages.'
),
}),
(_('Answers'), {'fields': [
'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer'
]}),
(None, {'fields': ['example_rationale']}),
]
@admin.register(models.Assignment)
class AssignmentAdmin(admin.ModelAdmin):
filter_horizontal = ['questions']
|
Update messaging in the uploader form element | // @flow
import * as React from 'react';
import { Row, Col } from 'react-bootstrap';
import Box from '../../../components/box';
class Files extends React.PureComponent<any, any> {
constructor() {
super();
(this: any).fileUpload = undefined;
}
render() {
const { files, onChange } = this.props;
return (
<div>
<Box title="Scanned Forms" bsStyle="primary">
{files &&
files.map(file => (
<div key={`file-${file.filename}`}>
<a href={file.url} download>{file.filename}</a>
</div>
))}
<Row>
<Col xs={12}>
<p>
Save as Draft before uploading form.
</p>
<p class="text-danger">
Reminder: Nominations are not eligible for approval WITHOUT uploaded form.
</p>
</Col>
</Row>
{/* Re-used this box in ShowHousehold */}
{onChange &&
<Row>
<Col xs={12}>
<input
id="formControlsFile"
onChange={() => onChange(this.fileUpload.files)}
type="file"
label="File"
ref={ref => (this.fileUpload = ref)}
/>
</Col>
</Row>
}
</Box>
</div>
);
}
}
export default Files;
| // @flow
import * as React from 'react';
import { Row, Col } from 'react-bootstrap';
import Box from '../../../components/box';
class Files extends React.PureComponent<any, any> {
constructor() {
super();
(this: any).fileUpload = undefined;
}
render() {
const { files, onChange } = this.props;
return (
<div>
<Box title="Scanned Forms" bsStyle="primary">
{files &&
files.map(file => (
<div key={`file-${file.filename}`}>
<a href={file.url} download>{file.filename}</a>
</div>
))}
{/* Re-used this box in ShowHousehold */}
{onChange &&
<Row>
<Col xs={12}>
<input
id="formControlsFile"
onChange={() => onChange(this.fileUpload.files)}
type="file"
label="File"
ref={ref => (this.fileUpload = ref)}
/>
</Col>
</Row>
}
</Box>
</div>
);
}
}
export default Files;
|
Use `username` instead of `redditor` in templates | import praw
import humanize
from datetime import datetime
from flask import Flask
from flask import request, render_template
from prawoauth2 import PrawOAuth2Mini
from settings import (app_key, app_secret, access_token, refresh_token,
user_agent, scopes)
reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client, app_key=app_key,
app_secret=app_secret,
access_token=access_token,
refresh_token=refresh_token, scopes=scopes)
app = Flask(__name__)
def get_cake_day(username):
redditor = reddit_client.get_redditor(username)
try:
created_on = datetime.utcfromtimestamp(redditor.created_utc)
except praw.errors.NotFound:
return False
oauth_helper.refresh()
return(humanize.naturalday(created_on))
@app.route('/')
def index():
error_message = 'Redditor does not exist or Shadowbanned'
username = request.values.get('username')
if not username:
return render_template('index.html')
cakeday = get_cake_day(username)
if cakeday:
return render_template('result.html', username=username,
cakeday=cakeday)
return render_template('index.html', error_message=error_message)
if __name__ == '__main__':
app.run(debug=True)
| import praw
import humanize
from datetime import datetime
from flask import Flask
from flask import request, render_template
from prawoauth2 import PrawOAuth2Mini
from settings import (app_key, app_secret, access_token, refresh_token,
user_agent, scopes)
reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client, app_key=app_key,
app_secret=app_secret,
access_token=access_token,
refresh_token=refresh_token, scopes=scopes)
app = Flask(__name__)
def get_cake_day(username):
redditor = reddit_client.get_redditor(username)
try:
created_on = datetime.utcfromtimestamp(redditor.created_utc)
except praw.errors.NotFound:
return False
oauth_helper.refresh()
return(humanize.naturalday(created_on))
@app.route('/')
def index():
error_message = 'Redditor does not exist or Shadowbanned'
username = request.values.get('username')
if not username:
return render_template('index.html')
cakeday = get_cake_day(username)
if cakeday:
return render_template('result.html', redditor=username,
cakeday=cakeday)
return render_template('index.html', error_message=error_message)
if __name__ == '__main__':
app.run(debug=True)
|
Set null default value to max
This avoid this error:
Type error: Too few arguments to function Avanzu\AdminThemeBundle\Event\NotificationListEvent::__construct(), 0 passed in /var/www/html/cti/vendor/avanzu/admin-theme-bundle/Controller/NavbarController.php on line 39 and exactly 1 expected | <?php
/**
* NotificationListEvent.php
* avanzu-admin
* Date: 23.02.14
*/
namespace Avanzu\AdminThemeBundle\Event;
use Avanzu\AdminThemeBundle\Model\NotificationInterface;
/**
* Class NotificationListEvent
*
* @package Avanzu\AdminThemeBundle\Event
*/
class NotificationListEvent extends ThemeEvent
{
/**
* @var array
*/
protected $notifications = [];
protected $total = 0;
protected $max = null;
/**
* NotificationListEvent constructor.
*
* @param null $max
*/
public function __construct($max = null)
{
$this->max = $max;
}
/**
* @return null
*/
public function getMax()
{
return $this->max;
}
/**
* @return array
*/
public function getNotifications()
{
return $this->notifications;
}
/**
* @param NotificationInterface $notificationInterface
*
* @return $this
*/
public function addNotification(NotificationInterface $notificationInterface)
{
$this->notifications[] = $notificationInterface;
return $this;
}
/**
* @param int $total
*/
public function setTotal($total)
{
$this->total = $total;
}
/**
* @return int
*/
public function getTotal()
{
return $this->total == 0 ? count($this->notifications) : $this->total;
}
}
| <?php
/**
* NotificationListEvent.php
* avanzu-admin
* Date: 23.02.14
*/
namespace Avanzu\AdminThemeBundle\Event;
use Avanzu\AdminThemeBundle\Model\NotificationInterface;
/**
* Class NotificationListEvent
*
* @package Avanzu\AdminThemeBundle\Event
*/
class NotificationListEvent extends ThemeEvent
{
/**
* @var array
*/
protected $notifications = [];
protected $total = 0;
protected $max = null;
/**
* NotificationListEvent constructor.
*
* @param null $max
*/
public function __construct($max)
{
$this->max = $max;
}
/**
* @return null
*/
public function getMax()
{
return $this->max;
}
/**
* @return array
*/
public function getNotifications()
{
return $this->notifications;
}
/**
* @param NotificationInterface $notificationInterface
*
* @return $this
*/
public function addNotification(NotificationInterface $notificationInterface)
{
$this->notifications[] = $notificationInterface;
return $this;
}
/**
* @param int $total
*/
public function setTotal($total)
{
$this->total = $total;
}
/**
* @return int
*/
public function getTotal()
{
return $this->total == 0 ? count($this->notifications) : $this->total;
}
}
|
Format loyalty number when shown as name in search | <?
include '../scat.php';
include '../lib/person.php';
$criteria= array();
$term= $_REQUEST['term'];
$terms= preg_split('/\s+/', $term);
foreach ($terms as $term) {
$term= $db->real_escape_string($term);
$criteria[]= "(person.name LIKE '%$term%'
OR person.company LIKE '%$term%'
OR person.email LIKE '%$term%'
OR person.loyalty_number LIKE '%$term%'
OR person.phone LIKE '%$term%')";
}
if (!$_REQUEST['all'])
$criteria[]= 'active';
if (($type= $_REQUEST['role'])) {
$criteria[]= "person.role = '" . $db->escape($type) . "'";
}
if (empty($criteria)) {
$criteria= '1=1';
} else {
$criteria= join(' AND ', $criteria);
}
$q= "SELECT id,
CONCAT(IFNULL(name, ''),
IF(name != '' AND company != '', ' / ', ''),
IFNULL(company, ''))
AS value,
loyalty_number
FROM person
WHERE $criteria
ORDER BY value";
$r= $db->query($q)
or die_query($db, $q);
$list= array();
while ($row= $r->fetch_assoc()) {
if (!$row['value']) $row['value']= format_phone($row['loyalty_number']);
$list[]= $row;
}
echo jsonp($list);
| <?
include '../scat.php';
$criteria= array();
$term= $_REQUEST['term'];
$terms= preg_split('/\s+/', $term);
foreach ($terms as $term) {
$term= $db->real_escape_string($term);
$criteria[]= "(person.name LIKE '%$term%'
OR person.company LIKE '%$term%'
OR person.email LIKE '%$term%'
OR person.loyalty_number LIKE '%$term%'
OR person.phone LIKE '%$term%')";
}
if (!$_REQUEST['all'])
$criteria[]= 'active';
if (($type= $_REQUEST['role'])) {
$criteria[]= "person.role = '" . $db->escape($type) . "'";
}
if (empty($criteria)) {
$criteria= '1=1';
} else {
$criteria= join(' AND ', $criteria);
}
$q= "SELECT id,
CONCAT(IFNULL(name, ''),
IF(name != '' AND company != '', ' / ', ''),
IFNULL(company, ''))
AS value,
loyalty_number
FROM person
WHERE $criteria
ORDER BY value";
$r= $db->query($q)
or die_query($db, $q);
$list= array();
while ($row= $r->fetch_assoc()) {
if (!$row['value']) $row['value']= $row['loyalty_number'];
$list[]= $row;
}
echo jsonp($list);
|
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;
}
}
|
Save timer instances to internal cache obj | var Events = {
scrollTimer: null,
stopTimer: null,
scroll: function (ev, me) {
var cache = me.cache,
now = getTime();
if(me.disableScrollEv) { return; }
if (!G.pauseCheck) {
me.fireCustomEvent('scrollstart');
}
G.pauseCheck = true;
if( !cache.now || now > cache.now + GS.scrollMinUpdateInterval ) {
cache.now = now;
clearTimeout(cache.timerScroll);
cache.timerScroll = setTimeout(function () {
_invoke(me.scrollbars, 'update');
}, GS.scrollMinUpdateInterval);
clearTimeout(cache.timerStop);
cache.timerStop = setTimeout(function () {
Events.scrollStop(me);
}, me.settings.scrollStopDelay);
}
},
touchstart: function (ev, me) {
G.pauseCheck = false;
if(me.settings.fixTouchPageBounce) {
_invoke(me.scrollbars, 'update', [true]);
}
},
touchend: function (ev, me) {
// prevents touchmove generate scroll event to call
// scrollstop while the page is still momentum scrolling
clearTimeout(me.cache.timerStop);
},
scrollStop: function (me) {
// update position, cache and detect edge
// _invoke(me.scrollbars, 'update');
// fire custom event
me.fireCustomEvent('scrollstop');
// restore check loop
G.pauseCheck = false;
}
};
| var Events = {
scrollTimer: null,
stopTimer: null,
scroll: function (ev, me) {
var cache = me.cache,
now = getTime();
if(me.disableScrollEv) { return; }
if (!G.pauseCheck) {
me.fireCustomEvent('scrollstart');
}
G.pauseCheck = true;
if( !cache.now || now > cache.now + GS.scrollMinUpdateInterval ) {
cache.now = now;
clearTimeout(me.timerScroll);
me.timerScroll = setTimeout(function () {
_invoke(me.scrollbars, 'update');
}, GS.scrollMinUpdateInterval);
clearTimeout(me.timerStop);
me.timerStop = setTimeout(function () {
Events.scrollStop(me);
}, me.settings.scrollStopDelay);
}
},
touchstart: function (ev, me) {
G.pauseCheck = false;
if(me.settings.fixTouchPageBounce) {
_invoke(me.scrollbars, 'update', [true]);
}
},
touchend: function (ev, me) {
// prevents touchmove generate scroll event to call
// scrollstop while the page is still momentum scrolling
clearTimeout(me.timerStop);
},
scrollStop: function (me) {
// update position, cache and detect edge
// _invoke(me.scrollbars, 'update');
// fire custom event
me.fireCustomEvent('scrollstop');
// restore check loop
G.pauseCheck = false;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.