text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change COLOR_NAME const to PRIMARY_COLORS | import { StyleSheet } from 'react-native';
import { typography, color } from 'react-native-material-design-styles';
/**
* Paper style color
* @type {object}
*/
export const COLOR = color;
/**
* Paper style typography
* @type {object}
*/
export const TYPO = typography;
/**
* Primary color name
* @type {string}
*/
export const PRIMARY = 'paperBlue';
/**
* Paper style color names
* @type {string[]}
*/
export const PRIMARY_COLORS = ['googleBlue', 'googleGreen', 'googleGrey', 'googleRed', 'googleYellow', 'paperAmber',
'paperBlue', 'paperBlueGrey', 'paperBrown', 'paperCyan', 'paperDeepOrange', 'paperDeepPurple', 'paperGreen',
'paperGrey', 'paperIndigo', 'paperLightBlue', 'paperLightGreen', 'paperLime', 'paperOrange', 'paperPink',
'paperPurple', 'paperRed', 'paperTeal', 'paperYellow'];
/**
* Themes
* @type {string[]}
*/
export const THEME_NAME = ['light', 'dark'];
| import { typography, color } from 'react-native-material-design-styles';
/**
* Paper style color
* @type {object}
*/
export const COLOR = color;
/**
* Paper style typography
* @type {object}
*/
export const TYPO = typography;
/**
* Primary color name
* @type {string}
*/
export const PRIMARY = 'paperBlue';
/**
* Paper style color names
* @type {string[]}
*/
export const COLOR_NAME = ['googleBlue', 'googleGreen', 'googleGrey', 'googleRed', 'googleYellow', 'paperAmber',
'paperBlue', 'paperBlueGrey', 'paperBrown', 'paperCyan', 'paperDeepOrange', 'paperDeepPurple', 'paperGreen',
'paperGrey', 'paperIndigo', 'paperLightBlue', 'paperLightGreen', 'paperLime', 'paperOrange', 'paperPink',
'paperPurple', 'paperRed', 'paperTeal', 'paperYellow'];
/**
* Themes
* @type {string[]}
*/
export const THEME_NAME = ['light', 'dark'];
|
Fix for broken config file publication
Fixed a broken link: to enable publication of the configuration (`config/api-tester.php`) through the existing `php artisan vendor:publish --provider="Asvae\ApiTester\ServiceProvider"` artisan command. | <?php
namespace Asvae\ApiTester;
use Asvae\ApiTester\Contracts\RouteRepositoryInterface;
use Asvae\ApiTester\Providers\RouteServiceProvider;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
public function register()
{
$this->app->register(RouteServiceProvider::class);
$this->mergeConfigFrom(__DIR__.'/../config/api-tester.php',
'api-tester');
$this->app->bind(RouteRepositoryInterface::class,
config('api-tester.repository'));
}
public function boot()
{
$this->publishes([
__DIR__.'/../config/api-tester.php' => config_path('api-tester.php'),
], 'config');
}
}
| <?php
namespace Asvae\ApiTester;
use Asvae\ApiTester\Contracts\RouteRepositoryInterface;
use Asvae\ApiTester\Providers\RouteServiceProvider;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
public function register()
{
$this->app->register(RouteServiceProvider::class);
$this->mergeConfigFrom(__DIR__.'/../config/api-tester.php',
'api-tester');
$this->app->bind(RouteRepositoryInterface::class,
config('api-tester.repository'));
}
public function boot()
{
$this->publishes([
__DIR__.'/config/api-tester.php' => config_path('api-tester.php'),
], 'config');
}
}
|
Remove array of illegal key chars
Should have been done in 4c138b23602edc8db5a2dbc89b86db54fe3a6e0d | 'use strict'
import validateKey from 'firebase-validate-key'
import extend from 'xtend'
import find from 'babel-runtime/core-js/array/find'
export default function valueToFirebase (value) {
if (typeof value === 'undefined') {
throw new Error('Firebase cannot accept undefined values')
}
if (typeof value === 'function') {
throw new Error(`Firebase cannot accept function values: ${value.toString()}`)
}
if (value instanceof Date || value instanceof RegExp || value === null) {
return null
}
if (typeof value === 'object') {
if (Array.isArray(value)) {
if (!value.length) return null
value = extend({}, value)
}
const keys = Object.keys(value)
if (!keys.length) return null
keys.forEach(validateKey)
}
return value
}
| 'use strict'
import validateKey from 'firebase-validate-key'
import extend from 'xtend'
import find from 'babel-runtime/core-js/array/find'
const illegal = ['.', '$', '#', '[', ']', '/']
export default function valueToFirebase (value) {
if (typeof value === 'undefined') {
throw new Error('Firebase cannot accept undefined values')
}
if (typeof value === 'function') {
throw new Error(`Firebase cannot accept function values: ${value.toString()}`)
}
if (value instanceof Date || value instanceof RegExp || value === null) {
return null
}
if (typeof value === 'object') {
if (Array.isArray(value)) {
if (!value.length) return null
value = extend({}, value)
}
const keys = Object.keys(value)
if (!keys.length) return null
keys.forEach(validateKey)
}
return value
}
|
mypy: Add imports needed for new migration. | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from __future__ import unicode_literals
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None
Realm = apps.get_model('zerver', 'Realm')
if Realm.objects.count() != 2:
return
zulip_realm = Realm.objects.get(string_id="zulip")
try:
user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]
except Realm.DoesNotExist:
return
user_realm.string_id = ""
user_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0107_multiuseinvite'),
]
operations = [
migrations.RunPython(fix_realm_string_ids,
reverse_code=migrations.RunPython.noop),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from __future__ import unicode_literals
from django.db import migrations
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None
Realm = apps.get_model('zerver', 'Realm')
if Realm.objects.count() != 2:
return
zulip_realm = Realm.objects.get(string_id="zulip")
try:
user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]
except Realm.DoesNotExist:
return
user_realm.string_id = ""
user_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0107_multiuseinvite'),
]
operations = [
migrations.RunPython(fix_realm_string_ids,
reverse_code=migrations.RunPython.noop),
]
|
Change yosay end message color | var generators = require('yeoman-generator');
var inquirer = require("inquirer");
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = generators.Base.extend({
initializing: function() {
this.store = {
"bower-dependencies": []
}
},
writing: function() {
this.template('_bower.json', 'bower.json');
this.template('_package.json', 'package.json');
this.template('_gulpfile.js', 'gulpfile.js');
this.template('_.gitignore', '.gitignore');
},
install: function() {
this.installDependencies();
},
end: function() {
this.log(yosay('Almost done! ' + chalk.green('running default gulp task')));
this.spawnCommand('node_modules/gulp/bin/gulp.js');
}
});
| var generators = require('yeoman-generator');
var inquirer = require("inquirer");
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = generators.Base.extend({
initializing: function() {
this.store = {
"bower-dependencies": []
}
},
writing: function() {
this.template('_bower.json', 'bower.json');
this.template('_package.json', 'package.json');
this.template('_gulpfile.js', 'gulpfile.js');
this.template('_.gitignore', '.gitignore');
},
install: function() {
this.installDependencies();
},
end: function() {
this.log(yosay('Almost done! ' + chalk.red('running default gulp task')));
this.spawnCommand('node_modules/gulp/bin/gulp.js');
}
});
|
Add basic AI functionality to follow the ball | import Player from 'props/player';
import Ball from 'props/ball';
import Net from 'props/net';
import canvas from 'canvas';
import mouse from 'lib/mouse';
import events from 'lib/events';
import collision from 'lib/collision';
export default class Game {
constructor() {
canvas.clear();
this.players = [
new Player(),
new Player(),
];
this.score = [0, 0];
this.net = new Net();
this.ball = new Ball();
this.newRound();
mouse.onMove((x, y) => this.players[0].moveTo(y));
}
endRound() {
this.score[0] += 1;
console.log('this.score', this.score);
}
newRound() {
canvas.clear();
this.players[0].spawn(5, 50);
this.players[1].spawn(canvas.width - 15, 50);
this.net.spawn();
this.ball.spawn();
this.ball.fire();
var subscription = events.subscribe('ballMove', (ball) => {
// Move AI to follow ball. A bit of calculation required to alway keep in center.
this.players[1].moveTo(ball.y - ((this.players[1].height / 2) - (ball.height / 2)));
if(collision.isColliding(ball, this.players[0])) {
console.log('collision detected');
}
if (collision.isOutOfBounds(ball)) {
this.endRound();
}
});
}
}
| import Player from 'props/player';
import Ball from 'props/ball';
import Net from 'props/net';
import canvas from 'canvas';
import mouse from 'lib/mouse';
import events from 'lib/events';
import collision from 'lib/collision';
export default class Game {
constructor() {
canvas.clear();
this.players = [
new Player(),
new Player(),
];
this.score = [0, 0];
this.net = new Net();
this.ball = new Ball();
this.newRound();
mouse.onMove((x, y) => this.players[0].moveTo(y));
}
endRound() {
this.score[0] += 1;
console.log('this.score', this.score);
}
newRound() {
canvas.clear();
this.players[0].spawn(5, 50);
this.players[1].spawn(canvas.width - 15, 50);
this.net.spawn();
this.ball.spawn();
this.ball.fire();
var subscription = events.subscribe('ballMove', (ball) => {
if(collision.isColliding(ball, this.players[0])) {
console.log('collision detected');
}
if (collision.isOutOfBounds(ball)) {
this.endRound();
}
});
}
}
|
Send state + props to the client | // Dependencies
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
// Components
import Home from '../src/pages/home';
// Stores
import AppStore from '../src/stores/store';
const router = express.Router();
// Home route
router.get('/', (req, res) => {
var locals = {
app: ReactDOMServer.renderToString(<Home name='User' counter={0} />),
componentContext: AppStore.getStore()
};
res.render('home', locals);
});
// Name route
router.get('/:name', (req, res) => {
var locals = {
app: ReactDOMServer.renderToString(<Home name={req.params.name} counter={0} />),
componentContext: AppStore.getStore()
};
res.render('home', locals);
});
// Name + counter route
router.get('/:name/:counter', (req, res) => {
var locals = {
app: ReactDOMServer.renderToString(<Home name={req.params.name} counter={req.params.counter} />),
componentContext: AppStore.getStore()
};
res.render('home', locals);
});
export default router;
| // Dependencies
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
// Components
import Home from '../src/pages/home';
// Stores
import AppStore from '../src/stores/store';
const router = express.Router();
// Home route
router.get('/', (req, res) => {
var locals = {
app: ReactDOMServer.renderToString(<Home name='User' counter={0} />),
componentContext: AppStore.getState()
};
res.render('home', locals);
});
// Name route
router.get('/:name', (req, res) => {
var locals = {
app: ReactDOMServer.renderToString(<Home name={req.params.name} counter={0} />),
componentContext: AppStore.getState()
};
res.render('home', locals);
});
// Name + counter route
router.get('/:name/:counter', (req, res) => {
var locals = {
app: ReactDOMServer.renderToString(<Home name={req.params.name} counter={req.params.counter} />),
componentContext: AppStore.getState()
};
res.render('home', locals);
});
export default router;
|
Set $initialized flag after initialization in EmailTemplateEngine | <?php
namespace wcf\system\template;
use wcf\system\WCF;
/**
* Loads and displays templates in emails.
*
* @author Tim Duesterhus
* @copyright 2001-2016 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Template
*/
class EmailTemplateEngine extends TemplateEngine {
/**
* @inheritDoc
*/
protected $environment = 'email';
/**
* @inheritDoc
*/
public function getTemplateGroupID() {
static $initialized = false;
if (!$initialized) {
$sql = "SELECT templateGroupID
FROM wcf".WCF_N."_template_group
WHERE templateGroupFolderName = ?";
$statement = WCF::getDB()->prepareStatement($sql);
$statement->execute(['_wcf_email/']);
parent::setTemplateGroupID($statement->fetchSingleColumn());
$initialized = true;
}
return parent::getTemplateGroupID();
}
/**
* This method always throws, because changing the template group is not supported.
*
* @param integer $templateGroupID
* @throws \BadMethodCallException
*/
public function setTemplateGroupID($templateGroupID) {
throw new \BadMethodCallException("You may not change the template group of the email template engine");
}
}
| <?php
namespace wcf\system\template;
use wcf\system\WCF;
/**
* Loads and displays templates in emails.
*
* @author Tim Duesterhus
* @copyright 2001-2016 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Template
*/
class EmailTemplateEngine extends TemplateEngine {
/**
* @inheritDoc
*/
protected $environment = 'email';
/**
* @inheritDoc
*/
public function getTemplateGroupID() {
static $initialized = false;
if (!$initialized) {
$sql = "SELECT templateGroupID
FROM wcf".WCF_N."_template_group
WHERE templateGroupFolderName = ?";
$statement = WCF::getDB()->prepareStatement($sql);
$statement->execute(['_wcf_email/']);
parent::setTemplateGroupID($statement->fetchSingleColumn());
}
return parent::getTemplateGroupID();
}
/**
* This method always throws, because changing the template group is not supported.
*
* @param integer $templateGroupID
* @throws \BadMethodCallException
*/
public function setTemplateGroupID($templateGroupID) {
throw new \BadMethodCallException("You may not change the template group of the email template engine");
}
}
|
Use MediaSource.isTypeSupported as a decoding info fallback. | /**
* Returns decoding info for a given media configuration.
*
* @param {MediaDecodingConfiguration} configuration Media configuration.
* @returns {Promise<MediaCapabilitiesInfo>} Media decoding information.
*/
export default async function getDecodingInfo(configuration) {
if (navigator.mediaCapabilities) {
return navigator.mediaCapabilities.decodingInfo(configuration);
}
// If we can't use the Media Capabilities API, try using `MediaSource.isTypeSupported`.
if (MediaSource && MediaSource.isTypeSupported) {
const contentType = configuration.video?.contentType || configuration.audio?.contentType;
return {
supported: MediaSource.isTypeSupported(contentType),
smooth: false,
powerEfficient: false,
};
}
// Very unlikely any agent would reach this point, but
// if all fails, pretend we support the source.
return {
supported: true,
smooth: false,
powerEfficient: false,
};
}
| /**
* Returns decoding info for a given media configuration.
*
* @param {MediaDecodingConfiguration} configuration Media configuration.
* @returns {Promise<MediaCapabilitiesInfo>} Media decoding information.
*/
export default async function getDecodingInfo(configuration) {
if (navigator.mediaCapabilities) {
return navigator.mediaCapabilities.decodingInfo(configuration);
}
// If we can't use the Media Capabilities API, try using `canPlayType`.
try {
const videoEl = document.createElement('video');
const typeString = configuration.audio.contentType || configuration.video.contentType;
const canPlay = videoEl.canPlayType(typeString);
return {
supported: canPlay === 'probably' || canPlay === 'maybe',
smooth: false,
powerEfficient: false,
};
} catch (error) {
// Fail quietly.
}
// Very unlikely any agent would reach this point, but
// if all fails, pretend we support the source.
return {
supported: true,
smooth: false,
powerEfficient: false,
};
}
|
Add checking flag to RelatedResource model | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var ORIGIN_TYPES = [
'srv:coupledResource',
'gmd:onLine'
];
var RESOURCE_TYPES = [
'feature-type',
'link',
'atom-feed'
];
var RelatedResourceSchema = new Schema({
type: { type: String, required: true, index: true, enum: RESOURCE_TYPES },
updatedAt: { type: Date, required: true, index: true },
checking: { type: Boolean, index: true, sparse: true },
name: { type: String },
/* Origin */
originType: { type: String, enum: ORIGIN_TYPES, required: true, index: true },
originId: { type: ObjectId, required: true, index: true },
originCatalog: { type: ObjectId, ref: 'Service', index: true, sparse: true },
/* Record */
record: { type: String, required: true, index: true },
/* FeatureType */
featureType: {
candidateName: { type: String },
candidateLocation: { type: String },
matchingName: { type: String, index: true, sparse: true },
matchingService: { type: ObjectId, index: true, sparse: true }
}
});
/*
** Statics
*/
RelatedResourceSchema.statics = {
markAsChecking: function (query, done) {
this.update(query, { $set: { checking: true } }, { multi: true }, done);
}
};
mongoose.model('RelatedResource', RelatedResourceSchema);
| var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var ORIGIN_TYPES = [
'srv:coupledResource',
'gmd:onLine'
];
var RESOURCE_TYPES = [
'feature-type',
'link',
'atom-feed'
];
var RelatedResourceSchema = new Schema({
type: { type: String, required: true, index: true, enum: RESOURCE_TYPES },
updatedAt: { type: Date, required: true, index: true },
// touchedAt: { type: Date, required: true },
name: { type: String },
/* Origin */
originType: { type: String, enum: ORIGIN_TYPES, required: true, index: true },
originId: { type: ObjectId, required: true, index: true },
originCatalog: { type: ObjectId, ref: 'Service', index: true, sparse: true },
/* Record */
record: { type: String, required: true, index: true },
/* FeatureType */
featureType: {
candidateName: { type: String },
candidateLocation: { type: String },
matchingName: { type: String, index: true, sparse: true },
matchingService: { type: ObjectId, index: true, sparse: true }
}
/* */
});
mongoose.model('RelatedResource', RelatedResourceSchema);
|
Return proper customerReference & cardReference | <?php
namespace Omnipay\Stripe\Message;
use Omnipay\Common\Message\AbstractResponse;
/**
* Stripe Response
*/
class Response extends AbstractResponse
{
public function isSuccessful()
{
return !isset($this->data['error']);
}
public function getTransactionReference()
{
if (isset($this->data['object']) && 'charge' === $this->data['object']) {
return $this->data['id'];
}
}
public function getCardReference()
{
if (isset($this->data['object']) && ('card' === $this->data['object'] || 'customer' === $this->data['object']) ) {
return $this->data['id'];
}
}
public function getCustomerReference()
{
if (isset($this->data['object']) && 'customer' === $this->data['object']) {
return $this->data['id'];
}
}
public function getMessage()
{
if (!$this->isSuccessful()) {
return $this->data['error']['message'];
}
}
}
| <?php
namespace Omnipay\Stripe\Message;
use Omnipay\Common\Message\AbstractResponse;
/**
* Stripe Response
*/
class Response extends AbstractResponse
{
public function isSuccessful()
{
return !isset($this->data['error']);
}
public function getTransactionReference()
{
if (isset($this->data['object']) && 'charge' === $this->data['object']) {
return $this->data['id'];
}
}
public function getCardReference()
{
if (isset($this->data['object']) && 'customer' === $this->data['object']) {
return $this->data['id'];
}
}
public function getMessage()
{
if (!$this->isSuccessful()) {
return $this->data['error']['message'];
}
}
}
|
Fix modules_extra action for widget recent posts | <?php
namespace Backend\Modules\MiniBlog\Installer;
use Backend\Core\Installer\ModuleInstaller;
/**
* This action will install the mini blog module.
*
* @author Lander Vanderstraeten <lander.vanderstraeten@wijs.be>
*/
class Installer extends ModuleInstaller
{
/**
* Install the module
*/
public function install()
{
$this->importSQL(dirname(__FILE__) . '/Data/install.sql');
$this->addModule('MiniBlog');
$this->importLocale(dirname(__FILE__) . '/Data/locale.xml');
$this->makeSearchable('MiniBlog');
$this->setModuleRights(1, 'MiniBlog');
$this->setActionRights(1, 'MiniBlog', 'Index');
$this->setActionRights(1, 'MiniBlog', 'Add');
$this->setActionRights(1, 'MiniBlog', 'Edit');
$this->setActionRights(1, 'MiniBlog', 'Delete');
$this->insertExtra('MiniBlog', 'block', 'MiniBlog');
$this->insertExtra('MiniBlog', 'widget', 'RecentPosts', 'recentposts');
$navigationModulesId = $this->setNavigation(null, 'Modules');
$this->setNavigation($navigationModulesId, 'MiniBlog', 'MiniBlog/Index', array('MiniBlog/Add', 'MiniBlog/Edit'));
}
}
| <?php
namespace Backend\Modules\MiniBlog\Installer;
use Backend\Core\Installer\ModuleInstaller;
/**
* This action will install the mini blog module.
*
* @author Lander Vanderstraeten <lander.vanderstraeten@wijs.be>
*/
class Installer extends ModuleInstaller
{
/**
* Install the module
*/
public function install()
{
$this->importSQL(dirname(__FILE__) . '/Data/install.sql');
$this->addModule('MiniBlog');
$this->importLocale(dirname(__FILE__) . '/Data/locale.xml');
$this->makeSearchable('MiniBlog');
$this->setModuleRights(1, 'MiniBlog');
$this->setActionRights(1, 'MiniBlog', 'Index');
$this->setActionRights(1, 'MiniBlog', 'Add');
$this->setActionRights(1, 'MiniBlog', 'Edit');
$this->setActionRights(1, 'MiniBlog', 'Delete');
$this->insertExtra('MiniBlog', 'block', 'MiniBlog');
$this->insertExtra('MiniBlog', 'widget', 'RecentPosts', 'recent_posts');
$navigationModulesId = $this->setNavigation(null, 'Modules');
$this->setNavigation($navigationModulesId, 'MiniBlog', 'MiniBlog/Index', array('MiniBlog/Add', 'MiniBlog/Edit'));
}
}
|
Correct way to fallback when decodingInfo() throws. | /**
* Returns decoding info for a given media configuration.
*
* @param {MediaDecodingConfiguration} mediaConfig Media configuration.
* @returns {Promise<MediaCapabilitiesInfo>} Media decoding information.
*/
export default async function getDecodingInfo(mediaConfig) {
const promise = new Promise((resolve, reject) => {
if (!('mediaCapabilities' in navigator)) {
return reject('MediaCapabilities API not available');
}
if (!('decodingInfo' in navigator.mediaCapabilities)) {
return reject('Decoding Info not available');
}
// eslint-disable-next-line compat/compat
return resolve(navigator.mediaCapabilities.decodingInfo(mediaConfig));
});
return promise.catch(() => {
const fallbackResult = {
supported: false,
smooth: false, // always false
powerEfficient: false, // always false
};
if ('video' in mediaConfig) {
fallbackResult.supported = MediaSource.isTypeSupported(mediaConfig.video.contentType);
if (!fallbackResult.supported) {
return fallbackResult;
}
}
if ('audio' in mediaConfig) {
fallbackResult.supported = MediaSource.isTypeSupported(mediaConfig.audio.contentType);
}
return fallbackResult;
});
}
| /**
* Returns decoding info for a given media configuration.
*
* @param {MediaDecodingConfiguration} configuration Media configuration.
* @returns {Promise<MediaCapabilitiesInfo>} Media decoding information.
*/
export default async function getDecodingInfo(configuration) {
if (navigator.mediaCapabilities) {
return navigator.mediaCapabilities.decodingInfo(configuration);
}
// If we can't use the Media Capabilities API, try using `MediaSource.isTypeSupported`.
if (MediaSource && MediaSource.isTypeSupported) {
const contentType = configuration.video?.contentType || configuration.audio?.contentType;
return {
supported: MediaSource.isTypeSupported(contentType),
smooth: false,
powerEfficient: false,
};
}
// Very unlikely any agent would reach this point, but
// if all fails, pretend we support the source.
return {
supported: true,
smooth: false,
powerEfficient: false,
};
}
|
Add test for SliceTiming negative value detection | var assert = require('assert');
var validate = require('../index');
describe('JSON', function(){
var file = {
name: 'task-rest_bold.json',
relativePath: '/task-rest_bold.json'
};
it('should catch missing closing brackets', function(){
validate.JSON(file, '{', function (issues) {
assert(issues && issues.length > 0);
});
});
it('sidecars should have key/value pair for "RepetitionTime" expressed in seconds', function(){
var jsonObj = '{"RepetitionTime": 1.2, "echo_time": 0.005, "flip_angle": 90, "TaskName": "Rest"}';
validate.JSON(file, jsonObj, function (issues) {
assert(issues.length === 0);
});
var jsonObjInval = '{"RepetitionTime": 1200, "echo_time": 0.005, "flip_angle": 90, "TaskName": "Rest"}';
validate.JSON(file, jsonObjInval, function (issues) {
assert(issues && issues.length === 1);
});
});
it('should detect negative value for SliceTiming', function(){
var jsonObj = '{"SliceTiming": [-1.0, 0.0, 1.0]}';
validate.JSON(file, jsonObj, function (issues) {
assert(issues.length === 1 && issues[0].code == 55);
});
});
});
| var assert = require('assert');
var validate = require('../index');
describe('JSON', function(){
var file = {
name: 'task-rest_bold.json',
relativePath: '/task-rest_bold.json'
};
it('should catch missing closing brackets', function(){
validate.JSON(file, '{', function (issues) {
assert(issues && issues.length > 0);
});
});
it('sidecars should have key/value pair for "RepetitionTime" expressed in seconds', function(){
var jsonObj = '{"RepetitionTime": 1.2, "echo_time": 0.005, "flip_angle": 90, "TaskName": "Rest"}';
validate.JSON(file, jsonObj, function (issues) {
assert(issues.length === 0);
});
var jsonObjInval = '{"RepetitionTime": 1200, "echo_time": 0.005, "flip_angle": 90, "TaskName": "Rest"}';
validate.JSON(file, jsonObjInval, function (issues) {
assert(issues && issues.length === 1);
});
});
});
|
Add onReset() to clear collections | Donations.App = Space.Application.define('Donations.App', {
configuration: {
appId: 'Donations.App'
},
requiredModules: [
'Space.accounts',
'Space.accountsUi',
'Donations.domain'
],
singletons: [
// APIS
'Donations.OrgRegistrationApi',
'Donations.OrgApi',
'Donations.AppealsApi',
// PROJECTIONS
'Donations.OrgRegistrationsProjection',
'Donations.OrgProjection',
'Donations.AppealsProjection',
// PUBLICATIONS
'Donations.OrgPublication',
'Donations.AppealsPublication'
],
onInitialize() {
this.injector.map('Donations.Organizations').asStaticValue();
this.injector.map('Donations.Appeals').asStaticValue();
},
onReset() {
this.injector.get('Donations.Organizations').remove({});
this.injector.get('Donations.Appeals').remove({});
}
});
| Donations.App = Space.Application.define('Donations.App', {
configuration: {
appId: 'Donations.App'
},
requiredModules: [
'Space.accounts',
'Space.accountsUi',
'Donations.domain'
],
singletons: [
// APIS
'Donations.OrgRegistrationApi',
'Donations.OrgApi',
'Donations.AppealsApi',
// PROJECTIONS
'Donations.OrgRegistrationsProjection',
'Donations.OrgProjection',
'Donations.AppealsProjection',
// PUBLICATIONS
'Donations.OrgPublication',
'Donations.AppealsPublication'
],
onInitialize() {
this.injector.map('Donations.Organizations').asStaticValue();
this.injector.map('Donations.Appeals').asStaticValue();
}
});
|
Remove lint task from prod | /* eslint-disable */
const gulp = require('gulp');
const tasks = require('strt-gulptasks')({
source: 'src',
output: 'public/dist',
scripts: {
publicPath: '/dist/scripts',
},
serve: {
server: 'public',
files: ['public/*.html'],
}
});
gulp.task('default', gulp.series(
tasks.clean,
gulp.parallel(
tasks.styles,
tasks.images,
tasks.files,
tasks.icons,
tasks.scripts
),
tasks.serve
));
gulp.task('production', gulp.series(
function setProdEnv(done) {
process.env.NODE_ENV = 'production';
done();
},
tasks.clean,
gulp.parallel(
tasks.styles,
tasks.images,
tasks.files,
tasks.icons,
tasks.scripts
)
));
| /* eslint-disable */
const gulp = require('gulp');
const tasks = require('strt-gulptasks')({
source: 'src',
output: 'public/dist',
scripts: {
publicPath: '/dist/scripts',
},
serve: {
server: 'public',
files: ['public/*.html'],
}
});
gulp.task('default', gulp.series(
tasks.clean,
gulp.parallel(
tasks.styles,
tasks.images,
tasks.files,
tasks.icons,
tasks.scripts
),
tasks.serve
));
gulp.task('production', gulp.series(
function setProdEnv(done) {
process.env.NODE_ENV = 'production';
done();
},
tasks.lint,
tasks.clean,
gulp.parallel(
tasks.styles,
tasks.images,
tasks.files,
tasks.icons,
tasks.scripts
)
));
|
Add --out option to generate graph at specific location instead of interactive display | #!/usr/bin/python
import argparse
import matplotlib.pyplot as plt
from pylab import *
from osta.osta import *
############
### MAIN ###
############
parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)
parser.add_argument(
'--select',
help = "Select the full name of a stat to graph (e.g. \"scene.Keynote 1.RootAgents\")")
parser.add_argument(
'--out',
help = "Path to output the graph rather the interactively display. Filename extension determines graphics type (e.g. \"graph.jpg\")",
)
parser.add_argument(
'statsLogPath',
help = "Path to the stats log file.",
metavar = "stats-log-path")
opts = parser.parse_args()
data = Osta.parse(opts.statsLogPath)
# TODO: We will move this kind of check inside Osta shortly
(category, container, name) = opts.select.split(".")
if (category in data and container in data[category] and name in data[category][container]):
plt.plot(data[category][container][name]['abs']['values'])
plt.ylabel(opts.select)
if 'out' in opts:
savefig(opts.out)
else:
plt.show()
else:
print "No such stat as %s" % (opts.select) | #!/usr/bin/python
import argparse
import matplotlib.pyplot as plt
from osta.osta import *
############
### MAIN ###
############
parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)
parser.add_argument(
'--select',
help = "Select the full name of a stat to graph (e.g. \"scene.Keynote 1.RootAgents\")")
parser.add_argument(
'statsLogPath',
help = "Path to the stats log file.",
metavar = "stats-log-path")
opts = parser.parse_args()
data = Osta.parse(opts.statsLogPath)
# TODO: We will move this kind of check inside Osta shortly
(category, container, name) = opts.select.split(".")
if (category in data and container in data[category] and name in data[category][container]):
plt.plot(data[category][container][name]['abs']['values'])
plt.ylabel(opts.select)
plt.show()
else:
print "No such stat as %s" % (opts.select) |
Split methods for connecting as student or teacher. | module.exports = function(options) {
var url = options.url;
var faye = require('faye');
var teacher = new faye.Client(url);
var student = new faye.Client(url);
teacher.bind('transport:down', function() {
console.log('Disconnected.');
});
teacher.bind('transport:up', function() {
console.log('Connected.');
});
//teacher
//connect
//wait for students to pop in the queue
//grab a student
//go into a private channel
//send messages
//leave
teacher.publish('/presence/connect/teacher', {
userId: 1,
role: 'teacher'
});
//student
//connect
//wait for teacher to grab student
//go into a private channel
//send messages
//leave
student.publish('/presence/connect/student', {
userId: 100,
role: 'student'
});
teacher.subscribe('/presence/status', function(data) {
console.log('teacher', data);
});
student.subscribe('/presence/status', function(data) {
console.log('student', data);
});
}
| module.exports = function(options) {
var url = options.url;
var faye = require('faye');
var teacher = new faye.Client(url);
var student = new faye.Client(url);
teacher.bind('transport:down', function() {
console.log('Disconnected.');
});
teacher.bind('transport:up', function() {
console.log('Connected.');
});
//teacher
//connect
//wait for students to pop in the queue
//grab a student
//go into a private channel
//send messages
//leave
teacher.publish('/presence/connect', {
userId: 1,
role: 'teacher'
});
//student
//connect
//wait for teacher to grab student
//go into a private channel
//send messages
//leave
student.publish('/presence/connect', {
userId: 100,
role: 'student'
});
teacher.subscribe('/presence/status', function(data) {
console.log('teacher', data);
});
student.subscribe('/presence/status', function(data) {
console.log('student', data);
});
}
|
Update import path for vfs package
It's now hosted at GitHub | // Package buildfs allows plugging a VFS into a go/build.Context.
package buildfs
import (
"go/build"
"io"
"path"
"path/filepath"
"strings"
"github.com/rainycape/vfs"
)
const (
separator = "/"
)
// Setup configures a *build.Context to use the given VFS
// as its filesystem.
func Setup(ctx *build.Context, fs vfs.VFS) {
ctx.JoinPath = path.Join
ctx.SplitPathList = filepath.SplitList
ctx.IsAbsPath = func(p string) bool {
return p != "" && p[0] == '/'
}
ctx.IsDir = func(p string) bool {
stat, err := fs.Stat(p)
return err == nil && stat.IsDir()
}
ctx.HasSubdir = func(root, dir string) (string, bool) {
root = path.Clean(root)
if !strings.HasSuffix(root, separator) {
root += separator
}
dir = path.Clean(dir)
if !strings.HasPrefix(dir, root) {
return "", false
}
return dir[len(root):], true
}
ctx.ReadDir = fs.ReadDir
ctx.OpenFile = func(p string) (io.ReadCloser, error) {
return fs.Open(p)
}
}
| // Package buildfs allows plugging a VFS into a go/build.Context.
package buildfs
import (
"go/build"
"io"
"path"
"path/filepath"
"strings"
"vfs"
)
const (
separator = "/"
)
// Setup configures a *build.Context to use the given VFS
// as its filesystem.
func Setup(ctx *build.Context, fs vfs.VFS) {
ctx.JoinPath = path.Join
ctx.SplitPathList = filepath.SplitList
ctx.IsAbsPath = func(p string) bool {
return p != "" && p[0] == '/'
}
ctx.IsDir = func(p string) bool {
stat, err := fs.Stat(p)
return err == nil && stat.IsDir()
}
ctx.HasSubdir = func(root, dir string) (string, bool) {
root = path.Clean(root)
if !strings.HasSuffix(root, separator) {
root += separator
}
dir = path.Clean(dir)
if !strings.HasPrefix(dir, root) {
return "", false
}
return dir[len(root):], true
}
ctx.ReadDir = fs.ReadDir
ctx.OpenFile = func(p string) (io.ReadCloser, error) {
return fs.Open(p)
}
}
|
Make sure to use the Pyramid transaction manager | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
# Include the transaction manager
config.include('pyramid_tm')
config.add_static_view('static', 'static', cache_max_age=3600)
| import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
|
Add requests module in the dependencies | from setuptools import setup
exec([l for l in open("flask_mwoauth/__init__.py")
if l.startswith('__version__')][0])
setup(name='flask-mwoauth',
version=__version__,
description='Flask blueprint to connect to a MediaWiki OAuth server',
url='http://github.com/valhallasw/flask-mwoauth',
author='Merlijn van Deen',
author_email='valhallasw@arctus.nl',
license='MIT',
packages=['flask_mwoauth'],
install_requires=['flask-oauth', 'requests>=2.0.1'],
zip_safe=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules"]
)
| from setuptools import setup
exec([l for l in open("flask_mwoauth/__init__.py") if l.startswith('__version__')][0])
setup(name='flask-mwoauth',
version=__version__,
description='Flask blueprint to connect to a MediaWiki OAuth server',
url='http://github.com/valhallasw/flask-mwoauth',
author='Merlijn van Deen',
author_email='valhallasw@arctus.nl',
license='MIT',
packages=['flask_mwoauth'],
install_requires=['flask-oauth'],
zip_safe=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
]
)
|
Include position option for tooltip | <?php
/*
* This file is part of the Panda framework Ui component.
*
* (c) Ioannis Papikas <papikas.ioan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Panda\Ui\Helpers;
use DOMNode;
use Panda\Ui\Contracts\Handlers\HTMLHandlerInterface;
/**
* Class TooltipHelper
*
* @package Panda\Ui\Helpers
*
* @version 0.1
*/
class TooltipHelper
{
/**
* Set tooltip handler attribute
*
* @param HTMLHandlerInterface $HTMLHandler
* @param DOMNode $HTMLElement
* @param string $content
* @param int $delay
* @param string $position
*/
public static function set(HTMLHandlerInterface $HTMLHandler, DOMNode $HTMLElement, $content, $delay = 0, $position = '')
{
// Set tooltip attribute array
$tooltip = [
'content' => $content,
'delay' => $delay,
'position' => $position
];
$HTMLHandler->data($HTMLElement, 'ui-tooltip', $tooltip);
}
}
| <?php
/*
* This file is part of the Panda framework Ui component.
*
* (c) Ioannis Papikas <papikas.ioan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Panda\Ui\Helpers;
use DOMNode;
use Panda\Ui\Contracts\Handlers\HTMLHandlerInterface;
/**
* Class TooltipHelper
*
* @package Panda\Ui\Helpers
*
* @version 0.1
*/
class TooltipHelper
{
/**
* Set tooltip handler attribute
*
* @param HTMLHandlerInterface $HTMLHandler
* @param DOMNode $HTMLElement
* @param string $content
* @param int $delay
*/
public static function set(HTMLHandlerInterface $HTMLHandler, DOMNode $HTMLElement, $content, $delay = 0)
{
// Set tooltip attribute array
$tooltip = [];
$tooltip['content'] = $content;
$tooltip['delay'] = $delay;
$HTMLHandler->data($HTMLElement, 'ui-tooltip', $tooltip);
}
}
|
Make test config consistent with original config |
package seedu.gtd.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.gtd.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Tary\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/tasklist.xml\n" +
"Task List name : MyTaskList";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
package seedu.gtd.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.gtd.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : TaryTest\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/tasklist.xml\n" +
"Task List name : MyTaskList";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
Fix bug, name of config param | <?php
/**
* PaymentCoreBundle for Symfony2
*
* This Bundle is part of Symfony2 Payment Suite
*
* @author Marc Morera <yuhu@mmoreram.com>
* @package PaymentCoreBundle
*
* Marc Morera 2013
*/
namespace Mmoreram\PaymentCoreBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class PaymentCoreExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('payment.default.currency', $config['default_currency']);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('parameters.yml');
$loader->load('services.yml');
$loader->load('twig.yml');
}
}
| <?php
/**
* PaymentCoreBundle for Symfony2
*
* This Bundle is part of Symfony2 Payment Suite
*
* @author Marc Morera <yuhu@mmoreram.com>
* @package PaymentCoreBundle
*
* Marc Morera 2013
*/
namespace Mmoreram\PaymentCoreBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class PaymentCoreExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('payment.default.currency', $config['currency']);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('parameters.yml');
$loader->load('services.yml');
$loader->load('twig.yml');
}
}
|
Use an arrow function instead | var React = require( "react" );
var MorningScreen = require( "./morning-screen" );
var PlayScreen = require( "./play-screen" );
module.exports = React.createClass({
displayName: "RepubliaTimes",
getInitialState() {
return {
day: 1,
screen: "morning"
};
},
changeToScreen( newScreen ) {
this.setState({
screen: newScreen
});
},
renderMorningScreen() {
return <MorningScreen
day={this.state.day}
onContinue={() => this.changeToScreen( "play" )} />;
},
renderPlayScreen() {
return <PlayScreen day={this.state.day} />;
},
render() {
var screen = this.state.screen;
var screenRenderFunction = {
morning: this.renderMorningScreen,
play: this.renderPlayScreen
}[ screen ];
if ( screenRenderFunction === undefined ) {
throw new Error( "Invalid screen '" + screen +"'" );
}
return screenRenderFunction();
}
});
| var React = require( "react" );
var MorningScreen = require( "./morning-screen" );
var PlayScreen = require( "./play-screen" );
module.exports = React.createClass({
displayName: "RepubliaTimes",
getInitialState() {
return {
day: 1,
screen: "morning"
};
},
changeToScreen( newScreen ) {
this.setState({
screen: newScreen
});
},
renderMorningScreen() {
return <MorningScreen
day={this.state.day}
onContinue={this.changeToScreen.bind( null, "play" )} />;
},
renderPlayScreen() {
return <PlayScreen day={this.state.day} />;
},
render() {
var screen = this.state.screen;
var screenRenderFunction = {
morning: this.renderMorningScreen,
play: this.renderPlayScreen
}[ screen ];
if ( screenRenderFunction === undefined ) {
throw new Error( "Invalid screen '" + screen +"'" );
}
return screenRenderFunction();
}
});
|
Make copy of reference image with same name modification as the rest of the images | from image import ImageWithWCS
import numpy as np
from os import path
def shift_images(files, source_dir, output_file='_shifted'):
"""Align images based on astrometry."""
ref = files[0] # TODO: make reference image an input
ref_im = ImageWithWCS(path.join(source_dir, ref))
ref_pix = np.int32(np.array(ref_im.data.shape) / 2)
ref_ra_dec = ref_im.wcs_pix2sky(ref_pix)
base, ext = path.splitext(files[0])
ref_im.save(path.join(source_dir, base + output_file + ext))
for fil in files[1:]:
img = ImageWithWCS(path.join(source_dir, fil))
ra_dec_pix = img.wcs_sky2pix(ref_ra_dec)
shift = ref_pix - np.int32(ra_dec_pix)
print shift
img.shift(shift, in_place=True)
base, ext = path.splitext(fil)
img.save(path.join(source_dir, base + output_file + ext))
| from image import ImageWithWCS
import numpy as np
from os import path
def shift_images(files, source_dir, output_file='_shifted'):
"""Align images based on astrometry."""
ref = files[0] # TODO: make reference image an input
ref_im = ImageWithWCS(path.join(source_dir, ref))
ref_pix = np.int32(np.array(ref_im.data.shape) / 2)
ref_ra_dec = ref_im.wcs_pix2sky(ref_pix)
for fil in files[1:]:
img = ImageWithWCS(path.join(source_dir, fil))
ra_dec_pix = img.wcs_sky2pix(ref_ra_dec)
shift = ref_pix - np.int32(ra_dec_pix)
print shift
img.shift(shift, in_place=True)
base, ext = path.splitext(fil)
img.save(path.join(source_dir, base + output_file + ext))
|
Fix when default controller is loaded. | <?php
namespace Thulium;
use Thulium\Utilities\Strings;
class ControllerResolver
{
function __construct()
{
$globalConfig = Config::load()->getConfig('global');
$this->_defaultController = $globalConfig['controller'];
$this->_uri = new Uri();
}
public function getCurrentController()
{
$controllerName = $this->_uri->getController();
$controller = $controllerName ? "\\Controller\\" . $controllerName . "Controller" : "\\Controller\\" . Strings::underscoreToCamelCase($this->_defaultController) . "Controller";
$controllerCustom = $controllerName ? "\\Controller\\" . $controllerName . "ControllerCustom" : null;
$this->_validateControllerExists($controller, $controllerCustom);
return class_exists($controllerCustom) ? new $controllerCustom() : new $controller();
}
private function _validateControllerExists($controller, $controllerCustom)
{
if (!class_exists($controllerCustom) && !class_exists($controller)) {
throw new FrontControllerException('Controller does not exist: ' . $controller);
}
}
} | <?php
namespace Thulium;
class ControllerResolver
{
function __construct()
{
$globalConfig = Config::load()->getConfig('global');
$this->_defaultController = $globalConfig['controller'];
$this->_uri = new Uri();
}
public function getCurrentController()
{
$controllerName = $this->_uri->getController();
$controller = $controllerName ? "\Controller\\" . $controllerName . "Controller" : "\Controller\\" . ucfirst($this->_defaultController) . "Controller";
$controllerCustom = $controllerName ? "\Controller\\" . $controllerName . "ControllerCustom" : null;
$this->_validateControllerExists($controller, $controllerCustom);
return class_exists($controllerCustom) ? new $controllerCustom() : new $controller();
}
private function _validateControllerExists($controller, $controllerCustom)
{
if (!class_exists($controllerCustom) && !class_exists($controller)) {
throw new FrontControllerException('Controller does not exist: ' . $controller);
}
}
} |
Add some initial information in command line | // gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package main
import (
"fmt"
"net/http"
"os"
"path"
"github.com/golang/gddo/database"
"github.com/gregjones/httpcache"
"github.com/gregjones/httpcache/diskcache"
"github.com/rafaeljusto/gddoexp"
)
func main() {
// add cache to avoid to repeated requests to Github
gddoexp.HTTPClient = &http.Client{
Transport: httpcache.NewTransport(
diskcache.New(path.Join(os.Getenv("HOME"), ".gddoexp")),
),
}
db, err := database.New()
if err != nil {
fmt.Println("error connecting to database:", err)
return
}
pkgs, err := db.AllPackages()
if err != nil {
fmt.Println("error retrieving all packages:", err)
return
}
fmt.Printf("%d packages will be analyzed\n", len(pkgs))
for response := range gddoexp.ShouldArchivePackages(pkgs, db) {
if response.Error != nil {
fmt.Println(err)
} else if response.Archive {
fmt.Printf("package “%s” should be archived\n", response.Path)
}
}
}
| // gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package main
import (
"fmt"
"net/http"
"os"
"path"
"github.com/golang/gddo/database"
"github.com/gregjones/httpcache"
"github.com/gregjones/httpcache/diskcache"
"github.com/rafaeljusto/gddoexp"
)
func main() {
// add cache to avoid to repeated requests to Github
gddoexp.HTTPClient = &http.Client{
Transport: httpcache.NewTransport(
diskcache.New(path.Join(os.Getenv("HOME"), ".gddoexp")),
),
}
db, err := database.New()
if err != nil {
fmt.Println("error connecting to database:", err)
return
}
pkgs, err := db.AllPackages()
if err != nil {
fmt.Println("error retrieving all packages:", err)
return
}
for response := range gddoexp.ShouldArchivePackages(pkgs, db) {
if response.Error != nil {
fmt.Println(err)
} else if response.Archive {
fmt.Printf("package “%s” should be archived\n", response.Path)
}
}
}
|
Remove database initialization via application. | /*
* Copyright 2012 Artur Dryomov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.ming13.gambit;
import android.app.Application;
import com.bugsense.trace.BugSenseHandler;
public class GambitApplication extends Application
{
@Override
public void onCreate() {
super.onCreate();
setUpBugsense();
}
private void setUpBugsense() {
if (BuildConfig.DEBUG) {
return;
}
BugSenseHandler.initAndStartSession(this, getBugsenseProjectKey());
}
private String getBugsenseProjectKey() {
return getString(R.string.key_bugsense_project);
}
}
| /*
* Copyright 2012 Artur Dryomov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.ming13.gambit;
import android.app.Application;
import com.bugsense.trace.BugSenseHandler;
import ru.ming13.gambit.local.DbProvider;
public class GambitApplication extends Application
{
@Override
public void onCreate() {
super.onCreate();
setUpDatabase();
setUpBugsense();
}
private void setUpDatabase() {
DbProvider.getInstance(this);
}
private void setUpBugsense() {
if (BuildConfig.DEBUG) {
return;
}
BugSenseHandler.initAndStartSession(this, getBugsenseProjectKey());
}
private String getBugsenseProjectKey() {
return getString(R.string.key_bugsense_project);
}
}
|
Make rules and resolvedRules for new category
This adds in the appropriate data structure to the
category model. | function panel() {
return {
restrict: 'E',
scope: {
category: '='
},
templateUrl: 'category.edit.html',
controller: 'CategoryCtrl'
};
}
module.exports.panel = panel;
function controller($scope, cs, rs, $q) {
$scope.deleteCategory = function(category) {
return cs.deleteCategory(category).then(function() {
console.log('deleting category ', category);
});
};
$scope.editCategory = function(category) {
console.log(category);
};
$scope.newRule = function(category) {
$scope.showNewRuleModal = true;
};
$scope.showDeleteCategory = function() {
$scope.showDeleteCategoryModal = true;
};
$scope.saveRule = function(category, rule) {
var d = $q.defer();
rs.saveRule(rule).then(function(ruleId) {
if (!category.rules) {
category.rules = {};
}
category.rules[ruleId] = true;
cs.updateCategory(category).then(function() {
if (!category.resolvedRules) {
category.resolvedRules = [];
}
category.resolvedRules.push(rule);
$scope.category = category;
d.resolve();
} ,d.reject);
}, d.reject);
return d.promise;
};
}
module.exports.controller = ['$scope', 'CategoryService', 'RuleService', '$q', controller];
| function panel() {
return {
restrict: 'E',
scope: {
category: '='
},
templateUrl: 'category.edit.html',
controller: 'CategoryCtrl'
};
}
module.exports.panel = panel;
function controller($scope, cs, rs, $q) {
$scope.deleteCategory = function(category) {
return cs.deleteCategory(category).then(function() {
console.log('deleting category ', category);
});
};
$scope.editCategory = function(category) {
console.log(category);
};
$scope.newRule = function(category) {
$scope.showNewRuleModal = true;
};
$scope.showDeleteCategory = function() {
$scope.showDeleteCategoryModal = true;
};
$scope.saveRule = function(category, rule) {
var d = $q.defer();
rs.saveRule(rule).then(function(ruleId) {
category.rules[ruleId] = true;
cs.updateCategory(category).then(function() {
category.resolvedRules.push(rule);
$scope.category = category;
d.resolve();
} ,d.reject);
}, d.reject);
return d.promise;
};
}
module.exports.controller = ['$scope', 'CategoryService', 'RuleService', '$q', controller];
|
Add default check type in integration
Fixes broken unit tests from commit bfdda34. | /*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2008 All Rights Reserved.
*/
package org.dita.dost.platform;
import org.dita.dost.util.StringUtils;
/**
* CheckTranstypeAction class.
*
*/
final class CheckTranstypeAction extends ImportAction {
/**
* Get result.
* @return result
*/
@Override
public String getResult() {
final StringBuilder retBuf = new StringBuilder();
final String property = paramTable.containsKey("property") ? paramTable.get("property") : "transtype";
for (final String value: valueSet) {
retBuf.append("<not><equals arg1=\"${")
.append(StringUtils.escapeXML(property))
.append("}\" arg2=\"")
.append(StringUtils.escapeXML(value))
.append("\" casesensitive=\"false\"/></not>");
}
return retBuf.toString();
}
}
| /*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2008 All Rights Reserved.
*/
package org.dita.dost.platform;
import org.dita.dost.util.StringUtils;
/**
* CheckTranstypeAction class.
*
*/
final class CheckTranstypeAction extends ImportAction {
/**
* Get result.
* @return result
*/
@Override
public String getResult() {
final StringBuilder retBuf = new StringBuilder();
final String property = paramTable.get("property");
for (final String value: valueSet) {
retBuf.append("<not><equals arg1=\"${")
.append(StringUtils.escapeXML(property))
.append("}\" arg2=\"")
.append(StringUtils.escapeXML(value))
.append("\" casesensitive=\"false\"/></not>");
}
return retBuf.toString();
}
}
|
Add part loading command on profile instead of session | #import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = folder #os.path.join(profile.getDestinationPath(), folder)
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
profile.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
| #import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = folder #os.path.join(profile.getDestinationPath(), folder)
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
session.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
|
Change dependency from PyODE to bindings included with ODE source. | import os
import setuptools
setuptools.setup(
name='lmj.sim',
version='0.0.2',
namespace_packages=['lmj'],
packages=setuptools.find_packages(),
author='Leif Johnson',
author_email='leif@leifjohnson.net',
description='Yet another OpenGL-with-physics simulation framework',
long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.md')).read(),
license='MIT',
url='http://github.com/lmjohns3/py-sim/',
keywords=('simulation '
'physics '
'ode '
'visualization '
),
install_requires=['lmj.cli', 'numpy', 'glumpy', 'PyOpenGL', 'Open-Dynamics-Engine'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
| import os
import setuptools
setuptools.setup(
name='lmj.sim',
version='0.0.2',
namespace_packages=['lmj'],
packages=setuptools.find_packages(),
author='Leif Johnson',
author_email='leif@leifjohnson.net',
description='Yet another OpenGL-with-physics simulation framework',
long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.md')).read(),
license='MIT',
url='http://github.com/lmjohns3/py-sim/',
keywords=('simulation '
'physics '
'ode '
'visualization '
),
install_requires=['lmj.cli', 'numpy', 'glumpy', 'PyOpenGL', 'PyODE'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
|
Add new latest interaction date sort option | const companySortForm = {
method: 'get',
class: 'c-collection__sort-form js-AutoSubmit',
hideFormActions: true,
hiddenFields: { custom: true },
children: [
{
macroName: 'MultipleChoiceField',
label: 'Sort by',
name: 'sortby',
modifier: ['small', 'inline', 'light'],
inputClass: 'js-MirrorValue',
inputData: {
'target-selector': '.c-collection-filters input[name="sortby"]',
},
options: [
{ value: 'modified_on:desc', label: 'Recently updated' },
{ value: 'modified_on:asc', label: 'Least recently updated' },
{ value: 'name:asc', label: 'Company name: A-Z' },
{ value: 'latest_interaction_date:desc', label: 'Lastest interaction date' },
],
},
],
}
module.exports = companySortForm
| const companySortForm = {
method: 'get',
class: 'c-collection__sort-form js-AutoSubmit',
hideFormActions: true,
hiddenFields: { custom: true },
children: [
{
macroName: 'MultipleChoiceField',
label: 'Sort by',
name: 'sortby',
modifier: ['small', 'inline', 'light'],
inputClass: 'js-MirrorValue',
inputData: {
'target-selector': '.c-collection-filters input[name="sortby"]',
},
options: [
{ value: 'modified_on:desc', label: 'Recently updated' },
{ value: 'modified_on:asc', label: 'Least recently updated' },
{ value: 'name:asc', label: 'Company name: A-Z' },
],
},
],
}
module.exports = companySortForm
|
Add gossip padding for 1.1
This puts us at 5 new states for trunk, and thus no more can be added or
we exceed the previous padding. | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.gms;
public enum ApplicationState
{
STATUS,
LOAD,
SCHEMA,
DC,
RACK,
RELEASE_VERSION,
REMOVAL_COORDINATOR,
X_11_PADDING, // padding specifically for 1.1
INTERNAL_IP,
RPC_ADDRESS,
SEVERITY,
NET_VERSION,
// pad to allow adding new states to existing cluster
X1,
X2,
X3,
X4,
X5,
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.gms;
public enum ApplicationState
{
STATUS,
LOAD,
SCHEMA,
DC,
RACK,
RELEASE_VERSION,
REMOVAL_COORDINATOR,
INTERNAL_IP,
RPC_ADDRESS,
SEVERITY,
NET_VERSION,
// pad to allow adding new states to existing cluster
X1,
X2,
X3,
X4,
X5,
}
|
Fix config and data load | $(document).ready(function() {
// read manifest
$.get('manifest.json', function(manifest) {
window.config = {};
var properties = manifest.properties;
properties.forEach(function(p) {
window.config[p.name] = p.value;
});
// load HTML and append to body canvas
var document_html = manifest.html[0],
document_css = manifest.stylesheet[0],
document_js = manifest.javascript[0],
document_data = manifest.data[0]
$.get(document_html, function(html) {
$('#canvas').append(html);
$.get(document_data, function(data) {
window.data = data;
// load CSS
var css = $('<link rel="stylesheet" type="text/css" href="' + document_css + '" />');
$('body').append(css);
// load Javascript
var script = $('<script type="text/javascript" src="' + document_js +'"></script>');
$('body').append(script);
})
});
});
});
| $(document).ready(function() {
// read manifest
$.get('manifest.json', function(manifest) {
window.config = manifest.properties;
// load HTML and append to body canvas
var document_html = manifest.html[0],
document_css = manifest.stylesheet[0],
document_js = manifest.javascript[0],
document_data = manifest.data[0]
$.get(document_html, function(html) {
$('#canvas').append(html);
$.get(document_data, function(data) {
// load CSS
var css = $('<link rel="stylesheet" type="text/css" href="' + document_css + '" />');
$('body').append(css);
// load Javascript
var script = $('<script type="text/javascript" src="' + document_js +'"></script>');
$('body').append(script);
})
});
});
}); |
[Runtime] Fix passing $debug parameter to `ErrorHandler` | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Runtime\Internal;
use Symfony\Component\ErrorHandler\BufferingLogger;
use Symfony\Component\ErrorHandler\DebugClassLoader;
use Symfony\Component\ErrorHandler\ErrorHandler;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class SymfonyErrorHandler
{
public static function register(bool $debug): void
{
BasicErrorHandler::register($debug);
if (class_exists(ErrorHandler::class)) {
DebugClassLoader::enable();
restore_error_handler();
ErrorHandler::register(new ErrorHandler(new BufferingLogger(), $debug));
}
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Runtime\Internal;
use Symfony\Component\ErrorHandler\BufferingLogger;
use Symfony\Component\ErrorHandler\DebugClassLoader;
use Symfony\Component\ErrorHandler\ErrorHandler;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class SymfonyErrorHandler
{
public static function register(bool $debug): void
{
BasicErrorHandler::register($debug);
if (class_exists(ErrorHandler::class)) {
DebugClassLoader::enable();
restore_error_handler();
ErrorHandler::register(new ErrorHandler(new BufferingLogger(), true));
}
}
}
|
Fix assertion for new db structure | <?php
namespace Tests\AppBundle\Command;
use AppBundle\Command\ListUserCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
class ListUserCommandTest extends KernelTestCase
{
public function testExecute()
{
self::bootKernel();
$application = new Application(self::$kernel);
$application->add(new ListUserCommand());
$command = $application->find('app:list-user');
$commandTester = new CommandTester($command);
$commandTester->execute(array(
'command' => $command->getName(),
));
// the output of the command in the console
$output = $commandTester->getDisplay();
$this->assertContains('firstName', $output);
}
} | <?php
namespace Tests\AppBundle\Command;
use AppBundle\Command\ListUserCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
class ListUserCommandTest extends KernelTestCase
{
public function testExecute()
{
self::bootKernel();
$application = new Application(self::$kernel);
$application->add(new ListUserCommand());
$command = $application->find('app:list-user');
$commandTester = new CommandTester($command);
$commandTester->execute(array(
'command' => $command->getName(),
));
// the output of the command in the console
$output = $commandTester->getDisplay();
$this->assertContains('iucn_redlist_api', $output);
}
} |
Use vanilla includes function. Correct capitalisation. | /**
* Utility function to check whether or not a view-context is a site kit view.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
/**
* Internal dependencies
*/
import { SITE_KIT_VIEW_CONTEXTS } from '../googlesitekit/constants';
/**
* Checks whether or not the current viewContext is a Site Kit screen.
*
* @since n.e.x.t
*
* @param {string} viewContext The view-context.
* @return {boolean} TRUE if the passed view-context is a site kit view; otherwise FALSE.
*/
const isSiteKitScreen = ( viewContext ) =>
SITE_KIT_VIEW_CONTEXTS.includes( viewContext );
export default isSiteKitScreen;
| /**
* Utility function to check whether or not a view-context is a site kit view.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
/**
* External dependencies
*/
import includes from 'lodash/includes';
/**
* Internal dependencies
*/
import { SITE_KIT_VIEW_CONTEXTS } from '../googlesitekit/constants';
/**
* Checks whether or not the current viewContext is a Site Kit screen.
*
* @since n.e.x.t
*
* @param {string} viewContext THe view-context.
* @return {boolean} TRUE if the passed view-context is a site kit view; otherwise FALSE.
*/
const isSiteKitScreen = ( viewContext ) =>
includes( SITE_KIT_VIEW_CONTEXTS, viewContext );
export default isSiteKitScreen;
|
[FIX] Correct (if unused) param for a Smarty function
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@20807 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
/*
* $Id: function.toolbars.php 20665 2009-08-07 15:13:18Z jonnybradley $
*
* Smarty plugin to display content only to some groups
*/
function smarty_function_toolbars($params, &$smarty)
{
if( ! isset( $params['section'] ) ) {
global $section;
if( ! empty($section) )
$params['section'] = $section;
else
$params['section'] = 'global';
}
if( isset( $params['comments'] ) && $params['comments'] == 'y' ) {
$comments = true;
} else {
$comments = false;
}
if( ! isset( $params['area_name'] ) ) {
$params['area_name'] = 'wikiedit';
}
include_once( 'lib/toolbars/toolbarslib.php' );
$list = ToolbarsList::fromPreference( $params['section'] . ($comments ? '_comments' : '') );
return $list->getWikiHtml( $params['area_name'] );
}
| <?php
/*
* $Id: function.toolbars.php 20665 2009-08-07 15:13:18Z jonnybradley $
*
* Smarty plugin to display content only to some groups
*/
function smarty_function_toolbars($params, $content)
{
if( ! isset( $params['section'] ) ) {
global $section;
if( ! empty($section) )
$params['section'] = $section;
else
$params['section'] = 'global';
}
if( isset( $params['comments'] ) && $params['comments'] == 'y' ) {
$comments = true;
} else {
$comments = false;
}
if( ! isset( $params['area_name'] ) ) {
$params['area_name'] = 'wikiedit';
}
include_once( 'lib/toolbars/toolbarslib.php' );
$list = ToolbarsList::fromPreference( $params['section'] . ($comments ? '_comments' : '') );
return $list->getWikiHtml( $params['area_name'] );
}
|
Add 'enabled' argument to FieldEnabled to test negative values | # -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
| # -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
def FieldEnabled(field):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled()
else:
return field.IsEnabled()
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
Use tms: protocol; error handling | var tilelive = require("tilelive");
require("./").registerProtocols(tilelive); // Register tms protocol
require("mbtiles").registerProtocols(tilelive); // Register mbtiles protocol
// A tms url starts with "tms:", followed by an URL template, which must contain {z} {x} and {y} placeholders
var src = "tms:http://localhost:8080/geoserver/gwc/service/tms/1.0.0/osm@EPSG%3A900913@png8/{z}/{x}/{y}.png";
var dst = "mbtiles://./osm.mbtiles";
// Indicate zoom levels and bbox in geographic coordinates [xmin, ymin, xmax, ymax]
var options = {
minzoom: 0,
maxzoom: 16,
bounds: [1.8959314626397201, 41.24712051859019, 2.3140591893595457, 41.53442029978945],
progress: function report(stats, p) {
// Write a progress indication
process.stdout.write("\r" + (p.percentage).toFixed(1) + " % - ETA " + p.eta % 60 + " s ");
if (p.percentage == 100) process.stdout.write("\r\nDone!\r\n");
}
};
// Run!
tilelive.copy(src, dst, options, function(error) {
// Handle errors
if (error) console.error(error);
});
| /*jslint node: true */
"use strict";
var tilelive = require("tilelive");
require("./").registerProtocols(tilelive);
require("mbtiles").registerProtocols(tilelive);
var src = "http://localhost:8080/geoserver/gwc/service/tms/1.0.0/osm@EPSG%3A900913@png8/{z}/{x}/{y}.png";
var dst = "mbtiles://./osm.mbtiles";
var options = {
minzoom: 0,
maxzoom: 16,
bounds: [1.8959314626397201, 41.24712051859019, 2.3140591893595457, 41.53442029978945],
progress: function report(stats, p) {
process.stdout.write("\r" + (p.percentage).toFixed(1) + " % - ETA " + p.eta % 60 + " s ");
if (p.percentage == 100) process.stdout.write("\r\nDone!\r\n");
}
};
tilelive.copy(src, dst, options);
|
Split out createDeviceTokens() method for readability | 'use strict';
var apn = require('apn');
var _ = require('lodash');
function createDeviceTokens(token) {
if(!token || _.isEmpty(token)){
throw new Error('Device token is required');
}
// Array of tokens
if(_.isArray(token)){
return token.map(function(token) {
return new apn.Device(token);
});
}
// Simple length validation for the token length
if(token.length !== 64){
throw new Error('Device token should be 64 characters');
}
return new apn.Device(token);
}
module.exports = function(message, options, callback){
var defaultOptions = {
cert: 'cert.pem',
key: 'key.pem',
fastMode: true,
production: true,
connectionTimeout: 1000
};
options = _.defaults(options, defaultOptions);
callback = callback || _.noop;
var device = createDeviceTokens(options.token);
var connection = new apn.Connection(options);
var notification = new apn.Notification();
notification.alert = message || 'Hello world!';
notification.badge = options.badge || 0;
notification.sound = options.sound || 'ping.aiff';
notification.payload = options.payload || {};
notification.expiry = options.expiry || Math.floor(Date.now() / 1000) + 3600;
connection.pushNotification(notification, device);
return callback(connection);
};
| 'use strict';
var apn = require('apn');
var _ = require('lodash');
module.exports = function(message, options, callback){
var defaultOptions = {
cert: 'cert.pem',
key: 'key.pem',
fastMode: true,
production: true,
connectionTimeout: 1000
};
options = _.defaults(options, defaultOptions);
callback = callback || _.noop;
if(_.isEmpty(options.token)){
throw new Error('Device token is required');
}
var device;
if(_.isArray(options.token)){
device = options.token.map(function(token) {
return new apn.Device(token);
});
} else {
if(options.token.length !== 64){
throw new Error('Device token should be 64 characters');
}
device = new apn.Device(options.token);
}
var connection = new apn.Connection(options);
var notification = new apn.Notification();
notification.alert = message || 'Hello world!';
notification.badge = options.badge || 0;
notification.sound = options.sound || 'ping.aiff';
notification.payload = options.payload || {};
notification.expiry = options.expiry || Math.floor(Date.now() / 1000) + 3600;
connection.pushNotification(notification, device);
return callback(connection);
};
|
Update subject value (Use app.name) | <?php
namespace Webup\LaravelHelium\Contact\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ContactMessage extends Mailable
{
use Queueable, SerializesModels;
private $contact;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($contact)
{
$this->contact = $contact;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('['.config('app.name').'] Contact')
->text('helium::emails.contact-message')
->with(['contact' => $this->contact]);
}
}
| <?php
namespace Webup\LaravelHelium\Contact\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ContactMessage extends Mailable
{
use Queueable, SerializesModels;
private $contact;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($contact)
{
$this->contact = $contact;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('[Site] contact')
->text('helium::emails.contact-message')
->with(['contact' => $this->contact]);
}
}
|
Check if FormData is present | /**
* Sends a JSON-LD request to the API.
*
* @param {string} url
* @param {object} options
* @return {Promise.<object>} An object with a response key (the original HTTP response) and an optional body key (the parsed JSON-LD body)
*/
export default function fetchJsonLd(url, options = {}) {
const jsonLdMimeType = 'application/ld+json';
if ('undefined' === typeof options.headers) {
options.headers = new Headers();
}
if (null === options.headers.get('Accept')) {
options.headers.set('Accept', jsonLdMimeType);
}
if ('undefined' !== options.body && !(typeof FormData !== 'undefined' && options.body instanceof FormData) && null === options.headers.get('Content-Type')) {
options.headers.set('Content-Type', jsonLdMimeType);
}
return fetch(url, options)
.then(response => {
if (!response.headers.has('Content-Type') || !response.headers.get('Content-Type').includes(jsonLdMimeType)) {
return {response: response};
}
return response.json().then(body => { return { response, body }});
});
}
| /**
* Sends a JSON-LD request to the API.
*
* @param {string} url
* @param {object} options
* @return {Promise.<object>} An object with a response key (the original HTTP response) and an optional body key (the parsed JSON-LD body)
*/
export default function fetchJsonLd(url, options = {}) {
const jsonLdMimeType = 'application/ld+json';
if ('undefined' === typeof options.headers) {
options.headers = new Headers();
}
if (null === options.headers.get('Accept')) {
options.headers.set('Accept', jsonLdMimeType);
}
if ('undefined' !== options.body && !(options.body instanceof FormData) && null === options.headers.get('Content-Type')) {
options.headers.set('Content-Type', jsonLdMimeType);
}
return fetch(url, options)
.then(response => {
if (!response.headers.has('Content-Type') || !response.headers.get('Content-Type').includes(jsonLdMimeType)) {
return {response: response};
}
return response.json().then(body => { return { response, body }});
});
}
|
Change version string to "0.05.0".
This is a medium-ish change because we kind of break compatibility with
older sites. | from distutils.core import setup
setup(
name = "Cytoplasm",
version = "0.05.0",
author = "startling",
author_email = "tdixon51793@gmail.com",
url = "http://cytoplasm.somethingsido.com",
keywords = ["blogging", "site compiler", "blog compiler"],
description = "A static, blog-aware website generator written in python.",
packages = ['cytoplasm'],
scripts = ['scripts/cytoplasm'],
install_requires = ['Mako'],
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Internet :: WWW/HTTP :: Site Management",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary",
]
)
| from distutils.core import setup
setup(
name = "Cytoplasm",
version = "0.04.5",
author = "startling",
author_email = "tdixon51793@gmail.com",
url = "http://cytoplasm.somethingsido.com",
keywords = ["blogging", "site compiler", "blog compiler"],
description = "A static, blog-aware website generator written in python.",
packages = ['cytoplasm'],
scripts = ['scripts/cytoplasm'],
install_requires = ['Mako'],
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Internet :: WWW/HTTP :: Site Management",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary",
]
)
|
Add "disabled" class binding to checkbox's div | import Ember from 'ember';
import TooltipEnabled from '../mixins/sl-tooltip-enabled';
/**
* @module components
* @class sl-checkbox
*/
export default Ember.Component.extend( TooltipEnabled, {
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
// Attributes
/**
* Attribute bindings for containing div
*
* @property {Ember.Array} attributeBindings
*/
attributeBindings: [ 'checked', 'disabled' ],
/**
* Class names for containing div
*
* @property {Ember.Array} classNames
*/
classNames: [ 'checkbox', 'form-group', 'sl-checkbox' ],
/**
* Bindings for the base component class
*
* @property {Ember.Array} classNameBindings
*/
classNameBindings: [ 'disabled' ]
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
// Events
// -------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------
// Observers
// -------------------------------------------------------------------------
// Methods
});
| import Ember from 'ember';
import TooltipEnabled from '../mixins/sl-tooltip-enabled';
/**
* @module components
* @class sl-checkbox
*/
export default Ember.Component.extend( TooltipEnabled, {
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
// Attributes
/**
* Attribute bindings for containing div
*
* @property {Ember.Array} attributeBindings
*/
attributeBindings: [ 'checked', 'disabled' ],
/**
* Class names for containing div
*
* @property {Ember.Array} classNames
*/
classNames: [ 'checkbox', 'form-group', 'sl-checkbox' ]
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
// Events
// -------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------
// Observers
// -------------------------------------------------------------------------
// Methods
});
|
Add fe80::1 to list of loopback addresses.
On my Mac, my loopback interface is configured (via `/etc/hosts`, out of the box) to have both a link-local and a node-local loopback address, with the link-local address taking precedence:
```
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
inet 127.0.0.1 netmask 0xff000000
inet6 ::1 prefixlen 128
```
That obviously results in a `REMOTE_ADDR` of "fe80::1" rather than just "::1". | <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array(
'127.0.0.1',
'fe80::1',
'::1',
))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array(
'127.0.0.1',
'::1',
))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Refactor children initialisation in constructor | <?php
namespace Symfony\Cmf\Bundle\BlockBundle\Document;
use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
use Doctrine\ODM\PHPCR\ChildrenCollection;
use Doctrine\Common\Collections\ArrayCollection;
use Sonata\BlockBundle\Model\BlockInterface;
/**
* Block that contains other blocks ...
*
* @PHPCRODM\Document(referenceable=true)
*/
class ContainerBlock extends BaseBlock
{
/** @PHPCRODM\Children */
protected $children;
public function __construct($name = null)
{
$this->setName($name);
$this->children = new ArrayCollection();
}
/**
* {@inheritdoc}
*/
public function getType()
{
return 'symfony_cmf.block.container';
}
public function getChildren()
{
return $this->children;
}
public function setChildren(ChildrenCollection $children)
{
return $this->children = $children;
}
/**
* Add a child to this container
*
* @param BlockInterface $child
* @param string $key OPTIONAL
* @return boolean
*/
public function addChild(BlockInterface $child, $key = null)
{
if ($key != null) {
return $this->children->set($key, $child);
}
return $this->children->add($child);
}
}
| <?php
namespace Symfony\Cmf\Bundle\BlockBundle\Document;
use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
use Doctrine\ODM\PHPCR\ChildrenCollection;
use Doctrine\Common\Collections\ArrayCollection;
use Sonata\BlockBundle\Model\BlockInterface;
/**
* Block that contains other blocks ...
*
* @PHPCRODM\Document(referenceable=true)
*/
class ContainerBlock extends BaseBlock
{
/** @PHPCRODM\Children */
protected $children;
public function getType()
{
return 'symfony_cmf.block.container';
}
public function getChildren()
{
return $this->children;
}
public function setChildren(ChildrenCollection $children)
{
return $this->children = $children;
}
/**
* Add a child to this container
*
* @param BlockInterface $child
* @param string $key OPTIONAL
* @return boolean
*/
public function addChild(BlockInterface $child, $key = null)
{
if (null === $this->children) {
$this->children = new ArrayCollection();
}
if ($key != null) {
return $this->children->set($key, $child);
}
return $this->children->add($child);
}
}
|
Update according to latest odlclient | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hp.com>
#
# 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 requests
from django.conf import settings
from odlclient.v2 import client as odl_client
def get_client(request):
session = requests.Session()
session.cookies.update({
'JSESSIONID': request.user.jsessionid,
'JSESSIONIDSSO': request.user.jsessionidsso
})
http = odl_client.HTTPClient(request.user.controller, http=session,
debug=settings.DEBUG)
client = odl_client.Client(http)
return client
| # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hp.com>
#
# 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 requests
from django.conf import settings
from odlclient.v2 import client as odl_client
def get_client(request):
session = requests.Session()
session.cookies.update({
'JSESSIONID': request.user.jsessionid,
'JSESSIONIDSSO': request.user.jsessionidsso
})
url = request.user.controller + '/controller/nb/v2'
http = odl_client.HTTPClient(url, http=session, debug=settings.DEBUG)
client = odl_client.Client(http)
return client
|
Remove max_length from TextFields and replace short text fields with CharFields | """Social auth models"""
from django.db import models
from django.contrib.auth.models import User
class UserSocialAuth(models.Model):
"""Social Auth association model"""
user = models.ForeignKey(User, related_name='social_auth')
provider = models.CharField(max_length=32)
uid = models.TextField()
class Meta:
"""Meta data"""
unique_together = ('provider', 'uid')
class Nonce(models.Model):
"""One use numbers"""
server_url = models.TextField()
timestamp = models.IntegerField()
salt = models.CharField(max_length=40)
class Association(models.Model):
"""OpenId account association"""
server_url = models.TextField()
handle = models.CharField(max_length=255)
secret = models.CharField(max_length=255) # Stored base64 encoded
issued = models.IntegerField()
lifetime = models.IntegerField()
assoc_type = models.CharField(max_length=64)
| """Social auth models"""
from django.db import models
from django.contrib.auth.models import User
class UserSocialAuth(models.Model):
"""Social Auth association model"""
user = models.ForeignKey(User, related_name='social_auth')
provider = models.CharField(max_length=32)
uid = models.TextField()
class Meta:
"""Meta data"""
unique_together = ('provider', 'uid')
class Nonce(models.Model):
"""One use numbers"""
server_url = models.TextField()
timestamp = models.IntegerField()
salt = models.CharField(max_length=40)
class Association(models.Model):
"""OpenId account association"""
server_url = models.TextField(max_length=2047)
handle = models.CharField(max_length=255)
secret = models.TextField(max_length=255) # Stored base64 encoded
issued = models.IntegerField()
lifetime = models.IntegerField()
assoc_type = models.TextField(max_length=64)
|
Update sqlalchemy command configuration example | import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# [from aiopg.sa import create_engine]
# sqlalchemy.configure_manager(manager, app, Base,
# settings.DATABASE_USERNAME,
# settings.DATABASE_PASSWORD,
# settings.DATABASE_NAME,
# settings.DATABASE_HOST,
# settings.DATABASE_PORT[,
# create_engine])
if __name__ == "__main__":
manager.run()
| import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# sqlalchemy.configure_manager(manager, app, Base,
# settings.DATABASE_USERNAME,
# settings.DATABASE_NAME,
# settings.DATABASE_HOST,
# settings.DATABASE_PASSWORD)
if __name__ == "__main__":
manager.run()
|
Fix service provider class name | <?php namespace GeneaLabs\LaravelGovernor\Console\Commands;
use GeneaLabs\LaravelGovernor\Providers\Service as LaravelGovernorService;
use Illuminate\Console\Command;
class Publish extends Command
{
protected $signature = 'governor:publish {--assets} {--config} {--views}';
protected $description = 'Publish various assets of the Laravel Casts package.';
public function handle()
{
if ($this->option('assets')) {
$this->call('casts:publish', ['--assets' => true]);
}
if ($this->option('config')) {
$this->call('vendor:publish', [
'--provider' => LaravelGovernorService::class,
'--tag' => ['config'],
'--force' => true,
]);
}
if ($this->option('views')) {
$this->call('vendor:publish', [
'--provider' => LaravelGovernorService::class,
'--tag' => ['views'],
'--force' => true,
]);
}
}
}
| <?php namespace GeneaLabs\LaravelGovernor\Console\Commands;
use GeneaLabs\LaravelGovernor\Providers\LaravelGovernorService;
use Illuminate\Console\Command;
class Publish extends Command
{
protected $signature = 'governor:publish {--assets} {--config} {--views}';
protected $description = 'Publish various assets of the Laravel Casts package.';
public function handle()
{
if ($this->option('assets')) {
$this->call('casts:publish', ['--assets' => true]);
}
if ($this->option('config')) {
$this->call('vendor:publish', [
'--provider' => LaravelGovernorService::class,
'--tag' => ['config'],
'--force' => true,
]);
}
if ($this->option('views')) {
$this->call('vendor:publish', [
'--provider' => LaravelGovernorService::class,
'--tag' => ['views'],
'--force' => true,
]);
}
}
}
|
Bring your own buffer for leb128 | const continuationBit = 1 << 7;
const lowBitsMask = ~continuationBit & 0xff;
/**
* Consume a readable stream of unsigned LEB128 encoded bytes, writing the
* results into the provided buffer
*
* @template {ArrayBufferView} T
* @param {ReadableStream<Uint8Array>} stream A stream of concatenated unsigned
* LEB128 encoded values
* @param {T} buffer An ArrayBuffer view to write the decoded values to
* @returns {T} the passed in `buffer`
*/
export async function decompress(stream, buffer) {
const reader = stream.getReader();
let index = 0;
let result = 0;
let shift = 0;
while (true) {
const { done, value } = await reader.read();
if (done) {
return buffer;
}
for (const byte of value) {
result |= (byte & lowBitsMask) << shift;
if ((byte & continuationBit) === 0) {
buffer[index++] = result;
result = shift = 0;
continue;
}
shift += 7;
}
}
}
| const continuationBit = 1 << 7;
const lowBitsMask = ~continuationBit & 0xff;
/**
* @template {ArrayBufferView} T
*
* @param {ReadableStream<Uint8Array>} stream
* @param {number} length of the returned ArrayBufferView
* @param {new (length: number) => T} Type
*
* @returns {T}
*/
export async function decompress(stream, length, Type) {
const reader = stream.getReader();
const output = new Type(length);
let outIndex = 0;
let result = 0;
let shift = 0;
while (true) {
const { done, value } = await reader.read();
if (done) {
return output;
}
for (const byte of value) {
result |= (byte & lowBitsMask) << shift;
if ((byte & continuationBit) === 0) {
output[outIndex++] = result;
result = shift = 0;
continue;
}
shift += 7;
}
}
}
|
Revert "Revert "removing data binding warnings""
This reverts commit 0d441ece80c6e8dbb7b9045a9e2a48d2af0ea992. | package com.prateekj.snooper.infra;
import android.databinding.BindingAdapter;
import android.support.v7.widget.RecyclerView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class CustomBindings {
@BindingAdapter("adapter")
public static void setAdapter(RecyclerView recyclerView, RecyclerView.Adapter adapter) {
recyclerView.setAdapter(adapter);
}
@BindingAdapter("listAdapter")
public static void setListAdapter(ListView listView, BaseAdapter adapter) {
listView.setAdapter(adapter);
}
@BindingAdapter("itemDecoration")
public static void setItemDecoration(RecyclerView recyclerView, RecyclerView.ItemDecoration itemDecoration) {
recyclerView.addItemDecoration(itemDecoration);
}
@BindingAdapter({"textColor"})
public static void setTextColor(TextView view, int color) {
if (color != 0) {
view.setTextColor(view.getResources().getColor(color));
}
}
}
| package com.prateekj.snooper.infra;
import android.databinding.BindingAdapter;
import android.support.v7.widget.RecyclerView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class CustomBindings {
@BindingAdapter("app:adapter")
public static void setAdapter(RecyclerView recyclerView, RecyclerView.Adapter adapter) {
recyclerView.setAdapter(adapter);
}
@BindingAdapter("app:listAdapter")
public static void setListAdapter(ListView listView, BaseAdapter adapter) {
listView.setAdapter(adapter);
}
@BindingAdapter("app:itemDecoration")
public static void setItemDecoration(RecyclerView recyclerView, RecyclerView.ItemDecoration itemDecoration) {
recyclerView.addItemDecoration(itemDecoration);
}
@BindingAdapter({"textColor"})
public static void setTextColor(TextView view, int color) {
if (color != 0) {
view.setTextColor(view.getResources().getColor(color));
}
}
}
|
Remove set comprehension to support python 2.6 | from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
from six import string_types
class SentenceValidator(Validator):
"""
Validate input only when it appears in this list of sentences.
:param sentences: List of sentences.
:param ignore_case: If True, case-insensitive comparisons.
"""
def __init__(self, sentences, ignore_case=False, error_message='Invalid input', move_cursor_to_end=False):
assert all(isinstance(s, string_types) for s in sentences)
assert isinstance(ignore_case, bool)
assert isinstance(error_message, string_types)
self.sentences = list(sentences)
self.ignore_case = ignore_case
self.error_message = error_message
self.move_cursor_to_end = move_cursor_to_end
if ignore_case:
self.sentences = set([s.lower() for s in self.sentences])
def validate(self, document):
if document.text not in self.sentences:
if self.move_cursor_to_end:
index = len(document.text)
else:
index = 0
raise ValidationError(cursor_position=index,
message=self.error_message)
| from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
from six import string_types
class SentenceValidator(Validator):
"""
Validate input only when it appears in this list of sentences.
:param sentences: List of sentences.
:param ignore_case: If True, case-insensitive comparisons.
"""
def __init__(self, sentences, ignore_case=False, error_message='Invalid input', move_cursor_to_end=False):
assert all(isinstance(s, string_types) for s in sentences)
assert isinstance(ignore_case, bool)
assert isinstance(error_message, string_types)
self.sentences = list(sentences)
self.ignore_case = ignore_case
self.error_message = error_message
self.move_cursor_to_end = move_cursor_to_end
if ignore_case:
self.sentences = {s.lower() for s in self.sentences}
def validate(self, document):
if document.text not in self.sentences:
if self.move_cursor_to_end:
index = len(document.text)
else:
index = 0
raise ValidationError(cursor_position=index,
message=self.error_message)
|
Add a test for stringLength. | package gtf
import (
"testing"
"bytes"
"html/template"
)
func AssertEqual(t *testing.T, buffer *bytes.Buffer, testString string) {
if buffer.String() != testString {
t.Error()
}
buffer.Reset()
}
func ParseTest(buffer *bytes.Buffer, body string) {
tpl := template.New("test").Funcs(GtfFuncMap)
tpl.Parse(body)
tpl.Execute(buffer, "")
}
func TestGtfFuncMap(t *testing.T) {
var buffer bytes.Buffer
ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringReplace \" \" }}")
AssertEqual(t, &buffer, "TheGoProgrammingLanguage")
ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringDefault \"default value\" }}")
AssertEqual(t, &buffer, "The Go Programming Language")
ParseTest(&buffer, "{{ \"\" | stringDefault \"default value\" }}")
AssertEqual(t, &buffer, "default value")
ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringLength }}")
AssertEqual(t, &buffer, "27")
ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringLower }}")
AssertEqual(t, &buffer, "the go programming language")
} | package gtf
import (
"testing"
"bytes"
"html/template"
)
func AssertEqual(t *testing.T, buffer *bytes.Buffer, testString string) {
if buffer.String() != testString {
t.Error()
}
buffer.Reset()
}
func ParseTest(buffer *bytes.Buffer, body string) {
tpl := template.New("test").Funcs(GtfFuncMap)
tpl.Parse(body)
tpl.Execute(buffer, "")
}
func TestGtfFuncMap(t *testing.T) {
var buffer bytes.Buffer
ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringReplace \" \" }}")
AssertEqual(t, &buffer, "TheGoProgrammingLanguage")
ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringDefault \"default value\" }}")
AssertEqual(t, &buffer, "The Go Programming Language")
ParseTest(&buffer, "{{ \"\" | stringDefault \"default value\" }}")
AssertEqual(t, &buffer, "default value")
ParseTest(&buffer, "{{ \"The Go Programming Language\" | stringLower }}")
AssertEqual(t, &buffer, "the go programming language")
} |
Define a custom related_name in UserSettings->User relation | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.utils.compat.dj import force_unicode, python_2_unicode_compatible
@python_2_unicode_compatible
class UserSettings(models.Model):
user = models.ForeignKey(User, editable=False, related_name='djangocms_usersettings')
language = models.CharField(_("Language"), max_length=10, choices=settings.LANGUAGES,
help_text=_("The language for the admin interface and toolbar"))
clipboard = models.ForeignKey('cms.Placeholder', blank=True, null=True, editable=False)
class Meta:
verbose_name = _('user setting')
verbose_name_plural = _('user settings')
app_label = 'cms'
def __str__(self):
return force_unicode(self.user)
| # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.utils.compat.dj import force_unicode, python_2_unicode_compatible
@python_2_unicode_compatible
class UserSettings(models.Model):
user = models.ForeignKey(User, editable=False)
language = models.CharField(_("Language"), max_length=10, choices=settings.LANGUAGES,
help_text=_("The language for the admin interface and toolbar"))
clipboard = models.ForeignKey('cms.Placeholder', blank=True, null=True, editable=False)
class Meta:
verbose_name = _('user setting')
verbose_name_plural = _('user settings')
app_label = 'cms'
def __str__(self):
return force_unicode(self.user)
|
Support hiding note and notebook template notes | #
# Copyright (c) 2009 Brad Taylor <brad@getcoded.net>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from django.db import models
class NoteManager(models.Manager):
def user_viewable(self, request_user, author, templates=False):
notes = self.filter(author=author)
if request_user != author:
# Public notes only
notes = notes.filter(permissions=1)
if not templates:
notes = notes.exclude(tags__name="system:template")
return notes
| #
# Copyright (c) 2009 Brad Taylor <brad@getcoded.net>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from django.db import models
class NoteManager(models.Manager):
def user_viewable(self, request_user, author):
notes = self.filter(author=author)
if request_user != author:
# Public notes only
notes = notes.filter(permissions=1)
return notes
|
Fix "class not found" bug when removing puzzle from composer | <?php
/**
* @package Puzzle-DI
* @copyright Copyright © 2015 Danny Smart
*/
namespace Lexide\PuzzleDI\Plugin;
use Composer\Composer;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Script\Event;
use Composer\Script\ScriptEvents;
use Lexide\PuzzleDI\Controller\ScriptController;
class PuzzlePlugin implements PluginInterface, EventSubscriberInterface
{
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return [
ScriptEvents::POST_INSTALL_CMD => ['runPlugin'],
ScriptEvents::POST_UPDATE_CMD => ['runPlugin']
];
}
/**
* {@inheritDoc}
*/
public function activate(Composer $composer, IOInterface $io)
{
// move along, nothing to see here
}
/**
* @param Event $event
*/
public function runPlugin(Event $event)
{
// If puzzle has been removed in this update, the script controller may no longer exist
if (!class_exists("\\Lexide\\PuzzleDI\\Controller\\ScriptController")) {
return;
}
$controller = new ScriptController();
$controller->compileConfigList($event);
}
}
| <?php
/**
* @package Puzzle-DI
* @copyright Copyright © 2015 Danny Smart
*/
namespace Lexide\PuzzleDI\Plugin;
use Composer\Composer;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Script\Event;
use Composer\Script\ScriptEvents;
use Lexide\PuzzleDI\Controller\ScriptController;
class PuzzlePlugin implements PluginInterface, EventSubscriberInterface
{
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return [
ScriptEvents::POST_INSTALL_CMD => ['runPlugin'],
ScriptEvents::POST_UPDATE_CMD => ['runPlugin']
];
}
/**
* {@inheritDoc}
*/
public function activate(Composer $composer, IOInterface $io)
{
// move along, nothing to see here
}
/**
* @param Event $event
*/
public function runPlugin(Event $event)
{
$controller = new ScriptController();
$controller->compileConfigList($event);
}
}
|
Remove throws exception on main() | package com.redpois0n.gitj;
import java.io.File;
import javax.swing.UIManager;
import com.redpois0n.git.Repository;
import com.redpois0n.gitj.ui.MainFrame;
public class Main {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MainFrame frame = new MainFrame();
frame.setVisible(true);
if (argsContains("--debug", args)) {
File dir = new File(System.getProperty("user.dir"));
Repository repository = new Repository(dir);
frame.loadRepository(repository);
frame.addBookmark(repository);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static boolean argsContains(String s, String[] args) {
for (String arg : args) {
if (arg.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
public static void displayError(Exception e) {
}
public static void print(String s) {
System.out.println(s);
}
}
| package com.redpois0n.gitj;
import java.io.File;
import javax.swing.UIManager;
import com.redpois0n.git.Repository;
import com.redpois0n.gitj.ui.MainFrame;
public class Main {
public static void main(String[] args) throws Exception {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MainFrame frame = new MainFrame();
frame.setVisible(true);
if (argsContains("--debug", args)) {
File dir = new File(System.getProperty("user.dir"));
Repository repository = new Repository(dir);
frame.loadRepository(repository);
frame.addBookmark(repository);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static boolean argsContains(String s, String[] args) {
for (String arg : args) {
if (arg.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
public static void displayError(Exception e) {
}
public static void print(String s) {
System.out.println(s);
}
}
|
Fix apple touch icon path | <?php
/*
* Layout variables
*/
//
// Meta
//
$doctype = '<!DOCTYPE html>';
$encoding = 'utf-8';
$site = 'Site';
$title_divider = '·';
// Include page title if set
if (!empty($title)) {
$title = "$title $title_divider $site";
}
else {
$title = $site;
}
$author = 'Mr. Ghost';
$description = "Personal site of $author.";
$keywords = 'site, website, ghost';
$robots = 'noodp,noydir';
$viewport = 'width=device-width, initial-scale=1';
$stylesheet = ASSETS . '/css/main.css';
$favicon = '/favicon.ico';
$apple_touch_icon = ASSETS . '/img/apple-touch-icon.png';
//
// Copyright
//
$cpowner = $author;
$cpyear = 2013;
$copyright = '© ' . $cpyear . (($cpyear != date('Y')) ? '-' . date('Y') :
'') . ' ' . $cpowner; | <?php
/*
* Layout variables
*/
//
// Meta
//
$doctype = '<!DOCTYPE html>';
$encoding = 'utf-8';
$site = 'Site';
$title_divider = '·';
// Include page title if set
if (!empty($title)) {
$title = "$title $title_divider $site";
}
else {
$title = $site;
}
$author = 'Mr. Ghost';
$description = "Personal site of $author.";
$keywords = 'site, website, ghost';
$robots = 'noodp,noydir';
$viewport = 'width=device-width, initial-scale=1';
$stylesheet = ASSETS . '/css/main.css';
$favicon = '/favicon.ico';
$apple_touch_icon = '/apple-touch-icon.png';
//
// Copyright
//
$cpowner = $author;
$cpyear = 2013;
$copyright = '© ' . $cpyear . (($cpyear != date('Y')) ? '-' . date('Y') :
'') . ' ' . $cpowner; |
Remove print in unit test | import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
self.assertEqual(2000, cst.year)
self.assertEqual(1, cst.month)
self.assertEqual(2, cst.day)
self.assertEqual(11, cst.hour)
self.assertEqual(4, cst.minute)
self.assertEqual(0, cst.second)
self.assertEqual(0, cst.microsecond)
if __name__ == '__main__':
unittest.main()
| import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
print('xxx', utc, cst)
self.assertEqual(2000, cst.year)
self.assertEqual(1, cst.month)
self.assertEqual(2, cst.day)
self.assertEqual(11, cst.hour)
self.assertEqual(4, cst.minute)
self.assertEqual(0, cst.second)
self.assertEqual(0, cst.microsecond)
if __name__ == '__main__':
unittest.main()
|
Add missing project URL to the project meta | import setuptools
def content_of(fpath):
with open(fpath, 'r') as fd:
return fd.read()
setuptools.setup(
name='tox-battery',
description='Additional functionality for tox',
long_description=content_of("README.rst"),
license='http://opensource.org/licenses/MIT',
version='0.0.1',
author='Volodymyr Vitvitskyi',
author_email='contact.volodymyr@gmail.com',
url='https://github.com/signalpillar/tox-battery',
packages=setuptools.find_packages(),
entry_points={'tox': [
'toxbat-requirements = toxbat.requirements',
]},
install_requires=['tox',],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 3'],
)
| import setuptools
def content_of(fpath):
with open(fpath, 'r') as fd:
return fd.read()
setuptools.setup(
name='tox-battery',
description='Additional functionality for tox',
long_description=content_of("README.rst"),
license='http://opensource.org/licenses/MIT',
version='0.0.1',
author='Volodymyr Vitvitskyi',
author_email='contact.volodymyr@gmail.com',
packages=setuptools.find_packages(),
entry_points={'tox': [
'toxbat-requirements = toxbat.requirements',
]},
install_requires=['tox',],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 3'],
)
|
Fix for repository query() response returning model class | <?php
namespace Czim\CmsModels\Repositories;
use Czim\CmsModels\Contracts\Repositories\ModelRepositoryInterface;
use Czim\Repository\ExtendedRepository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
class ModelRepository extends ExtendedRepository implements ModelRepositoryInterface
{
/**
* @var string
*/
protected $modelClass;
/**
* @param string $modelClass
*/
public function __construct($modelClass = null)
{
$this->modelClass = $modelClass;
parent::__construct(app(Application::class), new Collection);
}
/**
* @return string
*/
public function model()
{
return $this->modelClass;
}
/**
* @return \Illuminate\Database\Eloquent\Builder
*/
public function query()
{
$query = parent::query();
if ($query instanceof Model) {
$query = $query->query();
}
return $query;
}
}
| <?php
namespace Czim\CmsModels\Repositories;
use Czim\CmsModels\Contracts\Repositories\ModelRepositoryInterface;
use Czim\Repository\ExtendedRepository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Collection;
class ModelRepository extends ExtendedRepository implements ModelRepositoryInterface
{
/**
* @var string
*/
protected $modelClass;
/**
* @param string $modelClass
*/
public function __construct($modelClass = null)
{
$this->modelClass = $modelClass;
parent::__construct(app(Application::class), new Collection);
}
/**
* @return string
*/
public function model()
{
return $this->modelClass;
}
}
|
Check bootdir async and fix static path |
var Router = require('routes');
var router = new Router();
var st = require('st');
var fs = require('fs');
var mount = st({
path: __dirname + '/../static/', // resolved against the process cwd
url: 'boot/', // defaults to '/'
// indexing options
index: 'index', // auto-index, the default
dot: false // default: return 403 for any url with a dot-file part
});
router.addRoute('/chain', function(req, res, params, splats) {
console.log("Got a CHAIN request");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("#!ipxe\n\necho Attempting to boot into the chain... \nchain http://${next-server}/boot/${mac}\n");
});
router.addRoute('/boot/:macaddr', function boot(req, res, params, splats) {
console.log("Got a BOOT request");
console.log("Just got word that "+params.params.macaddr+" just booted");
fs.stat(__dirname + '/../static/' + params.params.macaddr, function(err,stat){
if(stat && stat.isDirectory()){
mount(req, res);
} else {
req.url = '/boot/default';
mount(req, res);
}
})
});
module.exports = router;
|
var Router = require('routes');
var router = new Router();
var st = require('st');
var fs = require('fs');
var mount = st({
path: __dirname + '/static/', // resolved against the process cwd
url: 'boot/', // defaults to '/'
// indexing options
index: 'index', // auto-index, the default
dot: false // default: return 403 for any url with a dot-file part
});
router.addRoute('/chain', function(req, res, params, splats) {
console.log("Got a CHAIN request");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("#!ipxe\n\necho Attempting to boot into the chain... \nchain http://${next-server}/boot/${mac}\n");
});
router.addRoute('/boot/:macaddr', function boot(req, res, params, splats) {
console.log("Got a BOOT request");
console.log("Just got word that "+params.params.macaddr+" just booted");
try {
var stat = fs.statSync(__dirname + '/static/' + params.params.macaddr);
} catch (error){
if(error.code != 'ENOENT')
throw error;
}
if(stat && stat.isDirectory()){
mount(req, res);
} else {
req.url = '/boot/default';
mount(req, res);
}
});
module.exports = router;
|
Fix woocommerce-variation-price may not exists
Related 034e1fac038566cdc69d8f50b210e44ed8211d9d | <?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/** @var WC_Aplazame $aplazame */
global $aplazame;
if ( ! $aplazame->enabled ) {
return;
}
/** @var WC_Product $product */
global $product;
switch ( $product->get_type() ) {
case 'variable':
$price_selector = '#main [itemtype="http://schema.org/Product"] .single_variation_wrap .amount';
$price = '';
break;
default:
$price_selector = '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount';
$price = Aplazame_Filters::decimals( $product->get_price() );
}
?>
<div
data-aplazame-simulator=""
data-view="product"
data-price='<?php echo $price_selector; ?>'
data-currency="<?php echo get_woocommerce_currency(); ?>"
data-stock="<?php echo $product->is_in_stock() ? 'true' : 'false'; ?>">
</div>
| <?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/** @var WC_Aplazame $aplazame */
global $aplazame;
if ( ! $aplazame->enabled ) {
return;
}
/** @var WC_Product $product */
global $product;
switch ( $product->get_type() ) {
case 'variable':
$price_selector = '#main [itemtype="http://schema.org/Product"] .woocommerce-variation-price .amount';
$price = '';
break;
default:
$price_selector = '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount';
$price = Aplazame_Filters::decimals( $product->get_price() );
}
?>
<div
data-aplazame-simulator=""
data-view="product"
data-price='<?php echo $price_selector; ?>'
data-currency="<?php echo get_woocommerce_currency(); ?>"
data-stock="<?php echo $product->is_in_stock() ? 'true' : 'false'; ?>">
</div>
|
Allow Canary ember try test run to fail | /*jshint node:true*/
module.exports = {
scenarios: [
{
name: 'default',
bower: {
dependencies: { }
}
},
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
}
},
{
name: 'ember-canary',
allowedToFail: true,
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
}
]
};
| /*jshint node:true*/
module.exports = {
scenarios: [
{
name: 'default',
bower: {
dependencies: { }
}
},
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
}
]
};
|
Fix expectation for number of traits | <?php
namespace Tests\AppBundle\API\Listing;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class TraitsTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$service = $this->webservice->factory('listing', 'traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => '')),
null
);
$expected = array(
array(
"name" => "Plant Habit",
"trait_type_id" => 1,
"frequency" => 48842
)
);
$this->assertEquals($expected, $results, 'Search without term and limit, result should be a list of all traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => 'SomethingThatWillNeverBeATraitType')),
null
);
$expected = array();
$this->assertEquals($expected, $results, 'Search term does not hit, result should be an empty array');
}
}
| <?php
namespace Tests\AppBundle\API\Listing;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class TraitsTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$service = $this->webservice->factory('listing', 'traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => '')),
null
);
$expected = array(
array(
"name" => "PlantHabit",
"trait_type_id" => 1,
"frequency" => 48916
)
);
$this->assertEquals($expected, $results, 'Search without term and limit, result should be a list of all traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => 'SomethingThatWillNeverBeATraitType')),
null
);
$expected = array();
$this->assertEquals($expected, $results, 'Search term does not hit, result should be an empty array');
}
}
|
Improve help docs for app server's command line parser. Dave. | """This module contains all the logic required to parse the app
server's command line."""
#-------------------------------------------------------------------------------
import re
import logging
import optparse
import clparserutil
#-------------------------------------------------------------------------------
class CommandLineParser(optparse.OptionParser):
def __init__(self):
optparse.OptionParser.__init__(
self,
"usage: %prog [options]",
option_class=clparserutil.Option)
self.add_option(
"--log",
action="store",
dest="logging_level",
default=logging.ERROR,
type="logginglevel",
help="logging level [DEBUG,INFO,WARNING,ERROR,CRITICAL,FATAL] - default = ERRROR" )
self.add_option(
"--port",
action="store",
dest="port",
default=8080,
type=int,
help="port - default = 8080" )
#------------------------------------------------------------------- End-of-File
| """This module contains all the logic required to parse the app
server's command line."""
#-------------------------------------------------------------------------------
import re
import logging
import optparse
import clparserutil
#-------------------------------------------------------------------------------
class CommandLineParser(optparse.OptionParser):
def __init__(self):
optparse.OptionParser.__init__(
self,
"usage: %prog [options]",
option_class=clparserutil.Option)
self.add_option(
"--log",
action="store",
dest="logging_level",
default=logging.ERROR,
type="logginglevel",
help="logging level [DEBUG,INFO,WARNING,ERROR,CRITICAL,FATAL] - default = ERRROR" )
self.add_option(
"--port",
action="store",
dest="port",
default=8080,
type=int,
help="port" )
#------------------------------------------------------------------- End-of-File
|
Make JSON parameter middleware a bit more generic | <?php namespace Flarum\Api\Middleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;
class ReadJsonParameters implements MiddlewareInterface
{
/**
* {@inheritdoc}
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
if (str_contains($request->getHeaderLine('content-type'), 'json')) {
$input = json_decode($request->getBody(), true);
foreach ($input as $name => $value) {
$request = $request->withAttribute($name, $value);
}
}
return $out ? $out($request, $response) : $response;
}
}
| <?php namespace Flarum\Api\Middleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;
class ReadJsonParameters implements MiddlewareInterface
{
/**
* {@inheritdoc}
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
if (str_contains($request->getHeaderLine('content-type'), 'application/vnd.api+json')) {
$input = json_decode($request->getBody(), true);
foreach ($input as $name => $value) {
$request = $request->withAttribute($name, $value);
}
}
return $out ? $out($request, $response) : $response;
}
}
|
Set celery task results to expire in 1h | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Celery configuration values."""
BROKER_URL = "redis://localhost"
BROKER_POOL_LIMIT = 20
BROKER_TRANSPORT_OPTIONS = {
"visibility_timeout": 60*60*6,
"fanout_prefix": True,
"fanout_patterns": True
}
# Use custom json encoder.
CELERY_ACCEPT_CONTENT = ["kjson"]
CELERY_RESULT_SERIALIZER = "kjson"
CELERY_TASK_SERIALIZER = "kjson"
CELERY_TASK_RESULT_EXPIRES = 3600
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# Use a different DB than the redis default one.
CELERY_RESULT_BACKEND = "redis://localhost/1"
| # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Celery configuration values."""
BROKER_URL = "redis://localhost"
BROKER_POOL_LIMIT = 20
BROKER_TRANSPORT_OPTIONS = {
"visibility_timeout": 60*60*6,
"fanout_prefix": True,
"fanout_patterns": True
}
# Use custom json encoder.
CELERY_ACCEPT_CONTENT = ["kjson"]
CELERY_RESULT_SERIALIZER = "kjson"
CELERY_TASK_SERIALIZER = "kjson"
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# Use a different DB than the redis default one.
CELERY_RESULT_BACKEND = "redis://localhost/1"
|
Append cause error message to our processing error message
git-svn-id: 36dcc065b18e9ace584b1c777eaeefb1d96b1ee8@485910 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.forrest.core.exception;
public class ProcessingException extends Exception {
/**
*
*/
private static final long serialVersionUID = -5175336575758457083L;
public ProcessingException(final String message, final Exception e) {
super(message, e);
}
public ProcessingException(String message) {
super(message);
}
@Override
public String getMessage() {
String msg = super.getMessage();
if (getCause() != null) {
msg = msg + " caused by " + getCause().getMessage();
}
return msg;
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.forrest.core.exception;
public class ProcessingException extends Exception {
/**
*
*/
private static final long serialVersionUID = -5175336575758457083L;
public ProcessingException(final String message, final Exception e) {
super(message, e);
}
public ProcessingException(String message) {
super(message);
}
}
|
Add `check` method to linters, that just checks without loading a file. | var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var busterPromise = require('buster-promise');
var checkedFile = require('./checked-file');
function check(file, fileName) {
var errors = this.linter.check(file, this.options) ? [] : this.linter.check.errors;
return checkedFile.create(fileName, errors);
}
function checkFile(promise, fileName, err, file) {
var checked = check.call(this, file, fileName);
this.emit('fileChecked', checked);
promise.resolve(checked.errors);
}
function loadAndCheckFile(fileName) {
var self = this;
var promise = busterPromise.create();
fs.readFile(fileName, 'utf-8', checkFile.bind(this, promise, fileName));
return promise;
}
function create(options) {
if (!options) { throw new TypeError('options is required (at least an empty object)'); }
return Object.create(this, {
options: { value: options },
linter: { value: { check: require('../vendor/jslint').JSLINT } }
});
}
module.exports = new EventEmitter();
module.exports.create = create;
module.exports.checkFile = loadAndCheckFile;
module.exports.check = check;
| var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var busterPromise = require('buster-promise');
var checkedFile = require('./checked-file');
function checkFile(promise, fileName, err, file) {
var errors = this.linter.check(file, this.options) ? [] : this.linter.check.errors;
this.emit('fileChecked', checkedFile.create(fileName, errors));
promise.resolve(errors);
}
function loadAndCheckFile(fileName) {
var self = this;
var promise = busterPromise.create();
fs.readFile(fileName, 'utf-8', checkFile.bind(this, promise, fileName));
return promise;
}
function create(options) {
if (!options) { throw new TypeError('options is required (at least an empty object)'); }
return Object.create(this, {
options: { value: options },
linter: { value: { check: require('../vendor/jslint').JSLINT } }
});
}
module.exports = new EventEmitter();
module.exports.create = create;
module.exports.checkFile = loadAndCheckFile; |
Fix `Error:` appearing in log console messages | 'use strict'
const { resolve } = require('path')
// Retrieve error message of a standard error
const getErrorMessage = function ({
error: { type, description, details },
message,
}) {
// Retrieve both the main message and the stack
const stack = getStack(description, details)
// Add error type to message
const errorMessage = stack ? `${type} - ${stack}` : type
// Add original event's message
const errorMessageA = message ? `${message}\n${errorMessage}` : errorMessage
return errorMessageA
}
const getStack = function (description, details = '') {
// Only include description if it's not already in the stack trace
const stack = !description || details.includes(description)
? details
: `${description}\n${details}`
// Remove `Error:` as it gets prepended to `error.stack` (i.e. `details`)
const stackA = stack.replace(/^[\w]*Error: /u, '')
// Shorten stack trace directory paths
const dirPrefixRegExp = new RegExp(ROOT_DIR, 'gu')
const stackB = stackA.replace(dirPrefixRegExp, '')
return stackB
}
const ROOT_DIR = resolve(__dirname, '../..')
module.exports = {
getErrorMessage,
}
| 'use strict'
const { resolve } = require('path')
// Retrieve error message of a standard error
const getErrorMessage = function ({
error: { type, description, details },
message,
}) {
// Retrieve both the main message and the stack
const stack = getStack(description, details)
// Add error type to message
const errorMessage = stack ? `${type} - ${stack}` : type
// Add original event's message
const errorMessageA = message ? `${message}\n${errorMessage}` : errorMessage
return errorMessageA
}
const getStack = function (description, details = '') {
// Only include description if it's not already in the stack trace
const stack = !description || details.indexOf(description) !== -1
? details
: `${description}\n${details}`
// Shorten stack trace directory paths
const dirPrefixRegExp = new RegExp(ROOT_DIR, 'gu')
const trimmedStack = stack.replace(dirPrefixRegExp, '')
return trimmedStack
}
const ROOT_DIR = resolve(__dirname, '../..')
module.exports = {
getErrorMessage,
}
|
4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
#
# License: Apache 2.0
#
# TODO: Create a menu for file selection
import sys
import os.path
filename = raw_input( 'Path and Filename to Documentation file: ' )
sys.stdout = open( filename, "w")
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
#
# License: Apache 2.0
#
# TODO: Create a menu for file selection
import ibmcnx.filehandle
import sys
emp1 = ibmcnx.filehandle.Ibmcnxfile()
sys.stdout = emp1.askFileParams()
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) |
Add a watch gulp function | const { src, dest, watch, series } = require("gulp");
const sass = require("gulp-sass");
const autoPrefixer = require("gulp-autoprefixer");
const htmlmin = require("gulp-htmlmin");
const prettify = require("gulp-jsbeautifier");
const prettier = require("gulp-prettier");
/// Transpile Sass files to CSS
function scss() {
return src("scss/main.scss")
.pipe(sass({ outputStyle: "expanded" }))
.pipe(autoPrefixer({ browsers: ["last 20 versions"] }))
.pipe(dest("themes/web1/source/css"));
}
/// Prettify HTML
function clean() {
return src(["./public**/*.html"])
.pipe(htmlmin({
collapseWhitespace: true,
customAttrCollapse: /content/
}))
.pipe(prettify())
.pipe(dest("./public"));
}
watch("scss/**/*", scss);
exports.scss = scss;
exports.clean = clean;
exports.default = watch;
| const { src, dest, watch, series } = require("gulp");
const sass = require("gulp-sass");
const autoPrefixer = require("gulp-autoprefixer");
const htmlmin = require("gulp-htmlmin");
const prettify = require("gulp-jsbeautifier");
const prettier = require("gulp-prettier");
/// Transpile Sass files to CSS
function scss() {
return src("scss/main.scss")
.pipe(sass({ outputStyle: "expanded" }))
.pipe(autoPrefixer({ browsers: ["last 20 versions"] }))
.pipe(dest("themes/web1/source/css"));
}
/// Prettify HTML
function clean() {
return src(["./public**/*.html"])
.pipe(htmlmin({
collapseWhitespace: true,
customAttrCollapse: /content/
}))
.pipe(prettify())
.pipe(dest("./public"));
}
watch("scss/**/*", { events: "all" }, function() {
scss();
})
exports.scss = scss;
exports.clean = clean;
exports.default = watch;
|
Add Format method to String
This is the Go version of PyString_Format, which is the C API version
of "format % args". | // Copyright 2011 Julian Phillips. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package py
// #include "utils.h"
// static inline int stringCheck(PyObject *o) { return PyString_Check(o); }
import "C"
import (
"os"
"unsafe"
)
type String struct {
BaseObject
}
func stringCheck(obj Object) bool {
return C.stringCheck(c(obj)) != 0
}
func newString(obj *C.PyObject) *String {
return (*String)(unsafe.Pointer(obj))
}
func String_FromString(s string) (*String, os.Error) {
cs := C.CString(s)
defer C.free(unsafe.Pointer(cs))
ret := C.PyString_FromString(cs)
if ret == nil {
return nil, exception()
}
return newString(ret), nil
}
func (s *String) String() string {
ret := C.PyString_AsString(c(s))
if ret == nil {
panic(exception())
}
return C.GoString(ret)
}
func (s *String) Format(args *Tuple) (*String, os.Error) {
ret := C.PyString_Format(c(s), c(args))
if ret == nil {
return nil, exception()
}
return newString(ret), nil
}
| // Copyright 2011 Julian Phillips. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package py
// #include "utils.h"
// static inline int stringCheck(PyObject *o) { return PyString_Check(o); }
import "C"
import (
"os"
"unsafe"
)
type String struct {
BaseObject
}
func stringCheck(obj Object) bool {
return C.stringCheck(c(obj)) != 0
}
func newString(obj *C.PyObject) *String {
return (*String)(unsafe.Pointer(obj))
}
func String_FromString(s string) (*String, os.Error) {
cs := C.CString(s)
defer C.free(unsafe.Pointer(cs))
ret := C.PyString_FromString(cs)
if ret == nil {
return nil, exception()
}
return newString(ret), nil
}
func (s *String) String() string {
ret := C.PyString_AsString(c(s))
if ret == nil {
panic(exception())
}
return C.GoString(ret)
}
|
Add the process exit handler to perform finalization process | 'use strict';
import 'source-map-support/register';
import http from 'http';
import express from 'express';
import RED from 'node-red';
// Exit handler
process.stdin.resume();
function exitHandler(err) {
if (err instanceof Error) {
console.log(err.stack);
process.exit(1);
} else if (isNaN(err)) {
process.exit();
} else {
process.exit(err);
}
}
process.on('exit', exitHandler);
process.on('SIGINT', exitHandler);
process.on('uncaughtException', exitHandler);
// Create an Express app
let app = express();
// Create a server
let server = http.createServer(app);
// Create the settings object - see default settings.js file for other options
let settings = {
verbose: true,
disableEditor: false,
httpAdminRoot: '/red',
httpNodeRoot: '/api',
userDir: (process.env.HOME || process.env.USERPROFILE) + '/.node-red',
functionGlobalContext: { } // enables global context
};
// Initialise the runtime with a server and settings
RED.init(server, settings);
// Add a simple route for static content served from 'public'
app.use('/', express.static('public'));
if (settings.httpAdminRoot) {
app.get('/', (_, res) => {
res.redirect(settings.httpAdminRoot);
});
}
// Serve the editor UI from /red
app.use(settings.httpAdminRoot, RED.httpAdmin);
// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot, RED.httpNode);
server.listen(8000);
// Start the runtime
RED.start();
| 'use strict';
import 'source-map-support/register';
import http from 'http';
import express from 'express';
import RED from 'node-red';
// Create an Express app
let app = express();
// Create a server
let server = http.createServer(app);
// Create the settings object - see default settings.js file for other options
let settings = {
verbose: true,
disableEditor: false,
httpAdminRoot: '/red',
httpNodeRoot: '/api',
userDir: (process.env.HOME || process.env.USERPROFILE) + '/.node-red',
functionGlobalContext: { } // enables global context
};
// Initialise the runtime with a server and settings
RED.init(server, settings);
// Add a simple route for static content served from 'public'
app.use('/', express.static('public'));
if (settings.httpAdminRoot) {
app.get('/', (_, res) => {
res.redirect(settings.httpAdminRoot);
});
}
// Serve the editor UI from /red
app.use(settings.httpAdminRoot, RED.httpAdmin);
// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot, RED.httpNode);
server.listen(8000);
// Start the runtime
RED.start();
|
Fix locale to get consistent results independent of browser locale
svn changeset:13060/svn branch:6.3 | package com.vaadin.tests.components.datefield;
import java.util.Date;
import java.util.Locale;
import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.DateField;
public class TestDatefieldYear extends TestBase {
@Override
protected String getDescription() {
return "A popup with resolution year or month should update the textfield when browsing. The value displayed in the textfield should always be the same as the popup shows.";
}
@Override
protected Integer getTicketNumber() {
return 2813;
}
@Override
protected void setup() {
DateField df = new DateField("Year", new Date(2009 - 1900, 4 - 1, 1));
df.setLocale(new Locale("en", "US"));
df.setResolution(DateField.RESOLUTION_YEAR);
df.setResolution(DateField.RESOLUTION_MONTH);
addComponent(df);
}
}
| package com.vaadin.tests.components.datefield;
import java.util.Date;
import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.DateField;
public class TestDatefieldYear extends TestBase {
@Override
protected String getDescription() {
return "A popup with resolution year or month should update the textfield when browsing. The value displayed in the textfield should always be the same as the popup shows.";
}
@Override
protected Integer getTicketNumber() {
return 2813;
}
@Override
protected void setup() {
DateField df = new DateField("Year", new Date(2009 - 1900, 4 - 1, 1));
df.setResolution(DateField.RESOLUTION_YEAR);
df.setResolution(DateField.RESOLUTION_MONTH);
addComponent(df);
}
}
|
Fix for package name differences | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Checks for optional dependencies using lazy import from
`PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_.
"""
import importlib
# This list is a duplicate of the dependencies in setup.cfg "all".
# Note that in some cases the package names are different from the
# pip-install name (e.g.k scikit-image -> skimage).
optional_deps = ['scipy', 'matplotlib', 'skimage', 'sklearn', 'gwcs']
deps = {key.upper(): key for key in optional_deps}
__all__ = [f'HAS_{pkg}' for pkg in deps]
def __getattr__(name):
if name in __all__:
try:
importlib.import_module(deps[name[4:]])
except (ImportError, ModuleNotFoundError):
return False
return True
raise AttributeError(f'Module {__name__!r} has no attribute {name!r}.')
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Checks for optional dependencies using lazy import from
`PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_.
"""
import importlib
# This list is a duplicate of the dependencies in setup.cfg "all".
optional_deps = ['scipy', 'matplotlib', 'scikit-image', 'scikit-learn',
'gwcs']
deps = {key.upper(): key for key in optional_deps}
__all__ = [f'HAS_{pkg}' for pkg in deps]
def __getattr__(name):
if name in __all__:
try:
importlib.import_module(deps[name[4:]])
except (ImportError, ModuleNotFoundError):
return False
return True
raise AttributeError(f'Module {__name__!r} has no attribute {name!r}.')
|
Add check for disabled accounts. | package server
import (
"errors"
"net/http"
"github.com/flosch/pongo2"
"github.com/nathan-osman/informas/db"
)
// login presents the login form.
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
var (
username string
password string
)
if r.Method == http.MethodPost {
err := db.Transaction(func(t *db.Token) error {
username = r.Form.Get("username")
password = r.Form.Get("password")
u, err := db.FindUser(t, "Username", username)
if err != nil {
return errors.New("invalid username")
}
if err := u.Authenticate(password); err != nil {
return errors.New("invalid password")
}
if u.IsDisabled {
return errors.New("disabled account")
}
session, _ := s.sessions.Get(r, sessionName)
session.Values[sessionUserID] = u.ID
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
return nil
})
if err != nil {
s.addAlert(w, r, alertDanger, err.Error())
} else {
return
}
}
s.render(w, r, "login.html", pongo2.Context{
"username": username,
"password": password,
})
}
| package server
import (
"errors"
"net/http"
"github.com/flosch/pongo2"
"github.com/nathan-osman/informas/db"
)
// login presents the login form.
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
var (
username string
password string
)
if r.Method == http.MethodPost {
err := db.Transaction(func(t *db.Token) error {
username = r.Form.Get("username")
password = r.Form.Get("password")
u, err := db.FindUser(t, "Username", username)
if err != nil {
return errors.New("invalid username")
}
if err := u.Authenticate(password); err != nil {
return errors.New("invalid password")
}
session, _ := s.sessions.Get(r, sessionName)
session.Values[sessionUserID] = u.ID
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
return nil
})
if err != nil {
s.addAlert(w, r, alertDanger, err.Error())
} else {
return
}
}
s.render(w, r, "login.html", pongo2.Context{
"username": username,
"password": password,
})
}
|
Add Python-2.7 as a platform kitchen runs on | #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
import kitchen.release
setup(name='kitchen',
version=kitchen.release.__version__,
description=kitchen.release.DESCRIPTION,
author=kitchen.release.AUTHOR,
author_email=kitchen.release.EMAIL,
license=kitchen.release.LICENSE,
url=kitchen.release.URL,
download_url=kitchen.release.DOWNLOAD_URL,
keywords='Useful Small Code Snippets',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: General',
],
packages=find_packages(),
data_files = [],
)
| #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
import kitchen.release
setup(name='kitchen',
version=kitchen.release.__version__,
description=kitchen.release.DESCRIPTION,
author=kitchen.release.AUTHOR,
author_email=kitchen.release.EMAIL,
license=kitchen.release.LICENSE,
url=kitchen.release.URL,
download_url=kitchen.release.DOWNLOAD_URL,
keywords='Useful Small Code Snippets',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: General',
],
packages=find_packages(),
data_files = [],
)
|
Add maintainer: Piet Delport <pjdelport@gmail.com> | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-payfast',
version='0.3.dev',
author='Mikhail Korobov',
author_email='kmike84@gmail.com',
maintainer='Piet Delport',
maintainer_email='pjdelport@gmail.com',
packages=find_packages(exclude=['payfast_tests']),
url='http://bitbucket.org/kmike/django-payfast/',
download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz',
license = 'MIT license',
description = 'A pluggable Django application for integrating payfast.co.za payment system.',
long_description = open('README.rst').read().decode('utf8'),
classifiers=(
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-payfast',
version='0.3.dev',
author='Mikhail Korobov',
author_email='kmike84@gmail.com',
packages=find_packages(exclude=['payfast_tests']),
url='http://bitbucket.org/kmike/django-payfast/',
download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz',
license = 'MIT license',
description = 'A pluggable Django application for integrating payfast.co.za payment system.',
long_description = open('README.rst').read().decode('utf8'),
classifiers=(
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
|
[NG] Set max celery connections to 1. | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(32)
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL']
CELERY_RESULT_BACKEND = 'rpc'
REDIS_URL = os.environ['REDIS_URL']
CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com'
AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'
TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
USER_INFO = 'https://www.googleapis.com/userinfo/v2/me'
SCOPE = ['https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
REDIS_MAX_CONNECTIONS = 10
CELERY_MAX_CONNECTIONS = 1
class ProductionConfig(Config):
DEBUG = False
class StagingConfig(Config):
DEVELOPMENT = True
DEBUG = True
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
class TestingConfig(Config):
TESTING = True
| import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(32)
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL']
CELERY_RESULT_BACKEND = 'rpc'
REDIS_URL = os.environ['REDIS_URL']
CLIENT_ID = '690133088753-kk72josco183eb8smpq4dgkrqmd0eovm.apps.googleusercontent.com'
AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'
TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
USER_INFO = 'https://www.googleapis.com/userinfo/v2/me'
SCOPE = ['https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
REDIS_MAX_CONNECTIONS = 10
CELERY_MAX_CONNECTIONS = 10
class ProductionConfig(Config):
DEBUG = False
class StagingConfig(Config):
DEVELOPMENT = True
DEBUG = True
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
class TestingConfig(Config):
TESTING = True
|
Fix buildfailure by ignoring test on travis.
de.aikiit.fotorenamer.gui.ImageDirectorySelectorTest
performInit(de.aikiit.fotorenamer.gui.ImageDirectorySelectorTest) Time elapsed: 2.873 sec <<< ERROR!
java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
at de.aikiit.fotorenamer.gui.ImageDirectorySelectorTest.performInit(ImageDirectorySelectorTest.java:31) | /**
* Copyright 2011, Aiki IT, FotoRenamer
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.aikiit.fotorenamer.gui;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* Test directory selector.
*
* @author hirsch
* @version 2011-04-08, 00:22
*/
@Ignore("Not working on travis since no X11 present")
public class ImageDirectorySelectorTest {
@Test
public void performInit() {
assertNotNull(new ImageDirectorySelector(null));
}
}
| /**
* Copyright 2011, Aiki IT, FotoRenamer
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.aikiit.fotorenamer.gui;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* Test directory selector.
*
* @author hirsch
* @version 2011-04-08, 00:22
*/
public class ImageDirectorySelectorTest {
@Test
public void performInit() {
assertNotNull(new ImageDirectorySelector(null));
}
}
|
Make this package local because of IntelliJ suggestion. | package com.github.cstroe.sqs.www;
import com.github.cstroe.sqs.dao.NotebookDto;
import com.github.cstroe.sqs.model.Notebook;
import com.github.cstroe.sqs.model.Note;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class BaseActionBean implements ActionBean {
private ActionBeanContext context;
public void setContext(ActionBeanContext context) {
this.context = context;
}
public ActionBeanContext getContext() {
return context;
}
public List<Note> getRecentNotes() {
return new ArrayList<>();
}
public void recordError() {
// do some sort of error logging here
throw new RuntimeException("Error was encountered");
}
public List<Notebook> getGroups() {
List<Notebook> fakeNotebooks = new LinkedList<>();
fakeNotebooks.add(new NotebookDto(1, "Default"));
fakeNotebooks.add(new NotebookDto(1, "My Project"));
fakeNotebooks.add(new NotebookDto(1, "Random"));
return fakeNotebooks;
}
}
| package com.github.cstroe.sqs.www;
import com.github.cstroe.sqs.dao.NotebookDto;
import com.github.cstroe.sqs.model.Notebook;
import com.github.cstroe.sqs.model.Note;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class BaseActionBean implements ActionBean {
private ActionBeanContext context;
public void setContext(ActionBeanContext context) {
this.context = context;
}
public ActionBeanContext getContext() {
return context;
}
public List<Note> getRecentNotes() {
return new ArrayList<>();
}
public void recordError() {
// do some sort of error logging here
throw new RuntimeException("Error was encountered");
}
public List<Notebook> getGroups() {
List<Notebook> fakeNotebooks = new LinkedList<>();
fakeNotebooks.add(new NotebookDto(1, "Default"));
fakeNotebooks.add(new NotebookDto(1, "My Project"));
fakeNotebooks.add(new NotebookDto(1, "Random"));
return fakeNotebooks;
}
}
|
Update dev server to send requests to worker site. | const express = require('express');
const request = require('request');
const cookies = require('./cookie');
const app = express();
app.use('*', (req, res) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', 'true');
console.log(new Date(), ' -- Request Received:', req.originalUrl);
req.headers.cookie = cookies;
/**
* Credit to: https://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/
*/
const url = 'https://worker.mturk.com' + req.originalUrl;
req.pipe(request(url)).pipe(res);
});
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
| const express = require('express');
const request = require('request');
const cookies = require('./cookie');
const app = express();
app.use('*', (req, res) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', 'true');
console.log(new Date(), ' -- Request Received:', req.originalUrl);
req.headers.cookie = cookies;
/**
* Credit to: https://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/
*/
const url = 'http://www.mturk.com' + req.originalUrl;
req.pipe(request(url)).pipe(res);
});
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
|
Exclude AppCache js test on IE < 10 | ({
/**
* Verify the correct AppCache events are received and are in the right order, without an error event. This case
* covers when we have not seen the page before and must download resources.
*/
testAppCacheEvents: {
// AppCache not supported on IE < 10
browsers:["-IE7","-IE8","-IE9"],
test: function(component){
var appCacheEvents = $A.test.getAppCacheEvents();
var lastEvent = appCacheEvents.length - 1;
// Error event is always the last event in the sequence
$A.test.assertNotEquals("error", appCacheEvents[lastEvent], "AppCache returned with an error.");
// Verify we received the events in the right order
$A.test.assertEquals("checking", appCacheEvents[0], "AppCache should begin with checking event.");
$A.test.assertEquals("downloading", appCacheEvents[1], "AppCache did not start downloading resources.");
// A progress event is fired for each file that is successfully downloaded. Only check that at least one
// file has been downloaded then check that AppCache completed.
$A.test.assertEquals("progress", appCacheEvents[2], "No files successfully downloaded.");
$A.test.assertEquals("cached", appCacheEvents[lastEvent], "Cached event to signal all files downloaded never fired");
}
}
})
| ({
/**
* Verify the correct AppCache events are received and are in the right order, without an error event. This case
* covers when we have not seen the page before and must download resources.
*/
testAppCacheEvents: {
test: function(component){
var appCacheEvents = $A.test.getAppCacheEvents();
var lastEvent = appCacheEvents.length - 1;
// Error event is always the last event in the sequence
$A.test.assertNotEquals("error", appCacheEvents[lastEvent], "AppCache returned with an error.");
// Verify we received the events in the right order
$A.test.assertEquals("checking", appCacheEvents[0], "AppCache should begin with checking event.");
$A.test.assertEquals("downloading", appCacheEvents[1], "AppCache did not start downloading resources.");
// A progress event is fired for each file that is successfully downloaded. Only check that at least one
// file has been downloaded then check that AppCache completed.
$A.test.assertEquals("progress", appCacheEvents[2], "No files successfully downloaded.");
$A.test.assertEquals("cached", appCacheEvents[lastEvent], "Cached event to signal all files downloaded never fired");
}
}
})
|
Make this a subclass of Thread.
git-svn-id: fcb33a7ee5ec38b96370833547f088a4e742b712@969 c76caeb1-94fd-44dd-870f-0c9d92034fc1 | // Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* A special-purpose thread used by Resolvers (both SimpleResolver and
* ExtendedResolver) to perform asynchronous queries.
*
* @author Brian Wellington
*/
class ResolveThread extends Thread {
private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;
/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
ResolverListener listener)
{
this.res = res;
this.query = query;
this.id = id;
this.listener = listener;
}
/**
* Performs the query, and executes the callback.
*/
public void
run() {
try {
Message response = res.send(query);
listener.receiveMessage(id, response);
}
catch (Exception e) {
listener.handleException(id, e);
}
}
}
| // Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* A special-purpose thread used by Resolvers (both SimpleResolver and
* ExtendedResolver) to perform asynchronous queries.
*
* @author Brian Wellington
*/
class ResolveThread implements Runnable {
private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;
/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
ResolverListener listener)
{
this.res = res;
this.query = query;
this.id = id;
this.listener = listener;
}
/**
* Performs the query, and executes the callback.
*/
public void
run() {
try {
Message response = res.send(query);
listener.receiveMessage(id, response);
}
catch (Exception e) {
listener.handleException(id, e);
}
}
}
|
Revert "Bugfix: cross domain error"
This reverts commit 401624dfb2921995dd75e67b3cbfba9e181057f2. | <?php
/**
* Plugin Name: HD MAIL
* Description: This is a test for sending via ajax and wordpress wp-mail for the Happy-Dev website.
* Author: Jonathan BRALEY
* License: GPL2
*/
add_action("wp_ajax_send_HD_mail","HD_wp_ajax_send_mail");
add_action("wp_ajax_nopriv_send_HD_mail","HD_wp_ajax_send_mail");
function HD_wp_ajax_send_mail(){
if(isset($_POST["name"]) && isset($_POST["howru"]) && isset($_POST["request"]) && isset($_POST["contact"]) && isset($_POST["mails"]) && isset($_POST["action"])){
$message= "Bonjour Happy Dev,
".$_POST["name"]." cherche à vous contacter.
Lors de sa demande il allait : ".$_POST["howru"]."
Sujet de la demande:
".$_POST["request"]."
Vous pourrez le joindre de cette manière : ".$_POST["contact"]."
Bonne journée!";
$res = wp_mail($_POST["mails"],$_POST["name"]." cherche à vous contacter",$message);
echo res;
}else{
echo -1;
}
}
?> | <?php
/**
* Plugin Name: HD MAIL
* Description: This is a test for sending via ajax and wordpress wp-mail for the Happy-Dev website.
* Author: Jonathan BRALEY
* License: GPL2
*/
add_action("wp_ajax_send_HD_mail","HD_wp_ajax_send_mail");
add_action("wp_ajax_nopriv_send_HD_mail","HD_wp_ajax_send_mail");
add_action( 'init', 'allow_origin' );
function allow_origin() {
header("Access-Control-Allow-Origin: happy-dev.fr");
}
function HD_wp_ajax_send_mail(){
if(isset($_POST["name"]) && isset($_POST["howru"]) && isset($_POST["request"]) && isset($_POST["contact"]) && isset($_POST["mails"]) && isset($_POST["action"])){
$message= "Bonjour Happy Dev,
".$_POST["name"]." cherche à vous contacter.
Lors de sa demande il allait : ".$_POST["howru"]."
Sujet de la demande:
".$_POST["request"]."
Vous pourrez le joindre de cette manière : ".$_POST["contact"]."
Bonne journée!";
$res = wp_mail($_POST["mails"],$_POST["name"]." cherche à vous contacter",$message);
echo res;
}else{
echo -1;
}
}
?> |
Improve the formatting of the output to stdout. | package uk.ac.ebi.quickgo.indexer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Process to index all the information in Solr
*
* @author cbonill
*
*/
public class QuickGOIndexerProcess {
static ApplicationContext appContext;
static QuickGOIndexer quickGOIndexer;
/**
* We can use this method for indexing the data in Solr for the moment
*
* @param args
*/
public static void main(String[] args) {
appContext = new ClassPathXmlApplicationContext("common-beans.xml", "indexing-beans.xml", "query-beans.xml");
quickGOIndexer = (QuickGOIndexer) appContext.getBean("quickGOIndexer");
String start = DateFormat.getInstance().format(Calendar.getInstance().getTime());
System.out.println("================================================================");
System.out.println("STARTED: " + start);
System.out.println("================================================================");
quickGOIndexer.index();
System.out.println("================================================================");
System.out.println("DONE: " + DateFormat.getInstance().format(Calendar.getInstance().getTime()));
System.out.println("================================================================");
}
}
| package uk.ac.ebi.quickgo.indexer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Process to index all the information in Solr
*
* @author cbonill
*
*/
public class QuickGOIndexerProcess {
static ApplicationContext appContext;
static QuickGOIndexer quickGOIndexer;
/**
* We can use this method for indexing the data in Solr for the moment
*
* @param args
*/
public static void main(String[] args) {
appContext = new ClassPathXmlApplicationContext("common-beans.xml", "indexing-beans.xml", "query-beans.xml");
quickGOIndexer = (QuickGOIndexer) appContext.getBean("quickGOIndexer");
String start = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println("STARTED: " + start);
quickGOIndexer.index();
String end = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println("DONE: " + end);
}
}
|
Upgrade tangled 0.1a9 => 1.0a12 | from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.sqlalchemy',
version='1.0a6.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=PEP420PackageFinder.find(include=['tangled*']),
install_requires=[
'tangled>=1.0a12',
'SQLAlchemy',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.sqlalchemy',
version='1.0a6.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=PEP420PackageFinder.find(include=['tangled*']),
install_requires=[
'tangled>=0.1a9',
'SQLAlchemy',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Fix Iron Chests not loading | package xyz.brassgoggledcoders.opentransport.modules.ironchest;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import xyz.brassgoggledcoders.boilerplate.module.Module;
import xyz.brassgoggledcoders.boilerplate.module.ModuleBase;
import xyz.brassgoggledcoders.boilerplate.module.dependencies.IDependency;
import xyz.brassgoggledcoders.boilerplate.module.dependencies.ModDependency;
import xyz.brassgoggledcoders.opentransport.OpenTransport;
import xyz.brassgoggledcoders.opentransport.api.blockcontainers.IBlockContainer;
import java.util.List;
@Module(mod = OpenTransport.MODID)
public class IronChestModule extends ModuleBase {
public static IBlockContainer[] IRON_CHESTS;
@Override
public String getName() {
return "Iron Chest";
}
@Override
public List<IDependency> getDependencies(List<IDependency> dependencies) {
dependencies.add(new ModDependency("ironchest"));
return dependencies;
}
@Override
public void preInit(FMLPreInitializationEvent event) {
IronChestBlockContainers.preInit(event);
}
}
| package xyz.brassgoggledcoders.opentransport.modules.ironchest;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import xyz.brassgoggledcoders.boilerplate.module.Module;
import xyz.brassgoggledcoders.boilerplate.module.ModuleBase;
import xyz.brassgoggledcoders.boilerplate.module.dependencies.IDependency;
import xyz.brassgoggledcoders.boilerplate.module.dependencies.ModDependency;
import xyz.brassgoggledcoders.opentransport.OpenTransport;
import xyz.brassgoggledcoders.opentransport.api.blockcontainers.IBlockContainer;
import java.util.List;
@Module(mod = OpenTransport.MODID)
public class IronChestModule extends ModuleBase {
public static IBlockContainer[] IRON_CHESTS;
@Override
public String getName() {
return "Iron Chest";
}
@Override
public List<IDependency> getDependencies(List<IDependency> dependencies) {
dependencies.add(new ModDependency("IronChest"));
return dependencies;
}
@Override
public void preInit(FMLPreInitializationEvent event) {
IronChestBlockContainers.preInit(event);
}
}
|
Test that features stop sharding beyond Math.pow(2,20) when it becomes pointless. | var tape = require('tape');
var feature = require('../lib/util/feature.js');
tape('seek', function(assert) {
var shardString = JSON.stringify({
1: JSON.stringify({ id: 1 }),
2: JSON.stringify({ id: 2 }),
});
var shardBuffer = new Buffer(shardString);
assert.deepEqual(feature.seek(shardString, 3), false);
assert.deepEqual(feature.seek(shardString, 2), { id: 2 });
assert.deepEqual(feature.seek(shardBuffer, 3), false);
assert.deepEqual(feature.seek(shardBuffer, 2), { id: 2 });
assert.end();
});
tape('shard', function(assert) {
for (var level = 0; level < 7; level++) {
var shards = {};
for (var i = 0; i < Math.pow(2,20); i++) {
var shard = feature.shard(level, i);
shards[shard] = shards[shard] || 0;
shards[shard]++;
}
var expected = Math.min(Math.pow(2,20), Math.pow(16, level + 1));
assert.equal(Object.keys(shards).length, expected, 'shardlevel=' + level + ', shards=' + expected);
}
assert.end();
});
| var tape = require('tape');
var feature = require('../lib/util/feature.js');
tape('seek', function(assert) {
var shardString = JSON.stringify({
1: JSON.stringify({ id: 1 }),
2: JSON.stringify({ id: 2 }),
});
var shardBuffer = new Buffer(shardString);
assert.deepEqual(feature.seek(shardString, 3), false);
assert.deepEqual(feature.seek(shardString, 2), { id: 2 });
assert.deepEqual(feature.seek(shardBuffer, 3), false);
assert.deepEqual(feature.seek(shardBuffer, 2), { id: 2 });
assert.end();
});
tape('shard', function(assert) {
for (var level = 0; level < 5; level++) {
var shards = {};
for (var i = 0; i < Math.pow(2,20); i++) {
var shard = feature.shard(level, i);
shards[shard] = shards[shard] || 0;
shards[shard]++;
}
assert.equal(Object.keys(shards).length, Math.pow(16, level + 1), 'shardlevel=' + level + ', shards=' + Math.pow(16, level + 1));
}
assert.end();
});
|
Enforce InnoDB engine for users table
It's required for foreign key constraints by users_* tables | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
|
Test additional fields and display which entry is problematic. | <?php
class JsonTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider jsonFileProvider
*/
public function testJsonFile($file)
{
$filePath = __DIR__ . '/../data/' . $file;
$this->assertFileExists($filePath);
$data = json_decode(file_get_contents($filePath), true);
$this->assertEquals(JSON_ERROR_NONE, json_last_error());
$this->assertGreaterThan(0, count($data));
// Check data integrity.
$keys = [];
foreach ($data as $i => $entry) {
$this->assertArrayHasKey('key', $entry, 'Entry #'.$i);
$this->assertArrayHasKey('name', $entry, 'Entry '.$entry['key']);
$this->assertArrayHasKey('first_event', $entry, 'Entry '.$entry['key']);
$this->assertNotContains($entry['key'], $keys, 'Key must be unique within the file.');
$keys[] = $entry['key'];
}
}
public function jsonFileProvider()
{
return [
['user-groups.json'],
['conferences.json'],
];
}
}
| <?php
class JsonTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider jsonFileProvider
*/
public function testJsonFile($file)
{
$filePath = __DIR__ . '/../data/' . $file;
$this->assertFileExists($filePath);
$data = json_decode(file_get_contents($filePath), true);
$this->assertEquals(JSON_ERROR_NONE, json_last_error());
$this->assertGreaterThan(0, count($data));
// Check data integrity.
$keys = [];
foreach ($data as $entry) {
$this->assertArrayHasKey('key', $entry);
$this->assertArrayHasKey('name', $entry);
$this->assertNotContains($entry['key'], $keys, 'Key must be unique within the file.');
$keys[] = $entry['key'];
}
}
public function jsonFileProvider()
{
return [
['user-groups.json'],
['conferences.json'],
];
}
}
|
Set default values for `tags` and `availability` | from typing import NamedTuple, Sequence, Dict, Iterable, List
from datetime import datetime
class Slot(NamedTuple):
venue: str
starts_at: datetime
duration: int
capacity: int
session: str
class BaseEvent(NamedTuple):
name: str
duration: int
demand: int
tags: List[str]
unavailability: List
class Event(BaseEvent):
__slots__ = ()
def __new__(cls, name, duration, demand, tags=None, unavailability=None):
if tags is None:
tags = []
if unavailability is None:
unavailability = []
return super().__new__(
cls, name, duration, demand, tags, unavailability
)
class ScheduledItem(NamedTuple):
event: Event
slot: Slot
class ChangedEventScheduledItem(NamedTuple):
event: Event
old_slot: Slot = None
new_slot: Slot = None
class ChangedSlotScheduledItem(NamedTuple):
slot: Slot
old_event: Event = None
new_event: Event = None
class Shape(NamedTuple):
"""Represents the shape of a 2 dimensional array of events and slots"""
events: int
slots: int
class Constraint(NamedTuple):
label: str
condition: bool
| from typing import NamedTuple, Sequence, Dict, Iterable, List
from datetime import datetime
class Slot(NamedTuple):
venue: str
starts_at: datetime
duration: int
capacity: int
session: str
class Event(NamedTuple):
name: str
duration: int
demand: int
tags: List[str] = []
unavailability: List = []
class ScheduledItem(NamedTuple):
event: Event
slot: Slot
class ChangedEventScheduledItem(NamedTuple):
event: Event
old_slot: Slot = None
new_slot: Slot = None
class ChangedSlotScheduledItem(NamedTuple):
slot: Slot
old_event: Event = None
new_event: Event = None
class Shape(NamedTuple):
"""Represents the shape of a 2 dimensional array of events and slots"""
events: int
slots: int
class Constraint(NamedTuple):
label: str
condition: bool
|
Use a low cost in BCrypt test, improves test speed | <?php
/**
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Authentication\Tests\Password;
use Joomla\Authentication\Password\BCryptHandler;
use PHPUnit\Framework\TestCase;
/**
* Test class for \Joomla\Authentication\Password\BCryptHandler
*/
class BCryptHandlerTest extends TestCase
{
/**
* @testdox A password is hashed and validated
*
* @covers Joomla\Authentication\Password\BCryptHandler::hashPassword
* @covers Joomla\Authentication\Password\BCryptHandler::validatePassword
*/
public function testAPasswordIsHashedAndValidated()
{
$handler = new BCryptHandler;
$hash = $handler->hashPassword('password', array('cost' => 4));
$this->assertTrue($handler->validatePassword('password', $hash), 'The hashed password was not validated.');
}
}
| <?php
/**
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Authentication\Tests\Password;
use Joomla\Authentication\Password\BCryptHandler;
use PHPUnit\Framework\TestCase;
/**
* Test class for \Joomla\Authentication\Password\BCryptHandler
*/
class BCryptHandlerTest extends TestCase
{
/**
* @testdox A password is hashed and validated
*
* @covers Joomla\Authentication\Password\BCryptHandler::hashPassword
* @covers Joomla\Authentication\Password\BCryptHandler::validatePassword
*/
public function testAPasswordIsHashedAndValidated()
{
$handler = new BCryptHandler;
$hash = $handler->hashPassword('password');
$this->assertTrue($handler->validatePassword('password', $hash), 'The hashed password was not validated.');
}
}
|
Use env vars in example
Replace placeholders in example/index.js with the same env vars we
already use for tests. This makes it quicker to verify the example works
correctly. | // @flow
const ContactHub = require('contacthub-sdk-nodejs');
const ch = new ContactHub({
token: process.env.CONTACTHUB_TEST_TOKEN || '',
workspaceId: process.env.CONTACTHUB_TEST_WORKSPACE_ID || '',
nodeId: process.env.CONTACTHUB_TEST_NODE_ID || ''
});
const log = console.log; // eslint-disable-line no-console
ch.getCustomers({ sort: 'base.lastName' }).then(customers => {
log(`=== Retrieved ${customers.length} customers sorted by last name ===`);
customers.forEach(c => {
if (c.base && c.base.firstName && c.base.lastName) {
log(`${c.base.firstName} ${c.base.lastName}`);
}
});
log('\n');
});
const randomString = () => Math.random().toString(36).substr(2, 8);
const customer = {
base: {
firstName: randomString(),
contacts: {
email: `${randomString()}@example.com`
}
}
};
ch.addCustomer(customer).then(c => {
log('=== Created a new customer ===');
log(`Added with id ${c.id}`);
log('\n');
});
| // @flow
const ContactHub = require('contacthub-sdk-nodejs');
const ch = new ContactHub({
token: 'CONTACTHUB_API_TOKEN',
workspaceId: 'CONTACTHUB_WORKSPACE_ID',
nodeId: 'CONTACTHUB_NODE_ID'
});
const log = console.log; // eslint-disable-line no-console
ch.getCustomers({ sort: 'base.lastName' }).then(customers => {
log(`=== Retrieved ${customers.length} customers sorted by last name ===`);
customers.forEach(c => {
if (c.base && c.base.firstName && c.base.lastName) {
log(`${c.base.firstName} ${c.base.lastName}`);
}
});
log('\n');
});
const randomString = () => Math.random().toString(36).substr(2, 8);
const customer = {
base: {
firstName: randomString(),
contacts: {
email: `${randomString()}@example.com`
}
}
};
ch.addCustomer(customer).then(c => {
log('=== Created a new customer ===');
log(`Added with id ${c.id}`);
log('\n');
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.