text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix name of component input | 'use strict';
var noop = require('es5-ext/lib/Function/noop')
, d = require('es5-ext/lib/Object/descriptor')
, forEach = require('es5-ext/lib/Object/for-each')
, map = require('es5-ext/lib/Object/map')
, Base = require('dbjs').Base
, DOMInput = require('./_controls/input')
, Input;
module.exports = Input = function (rel, inputs, rels, dom) {
this.inputs = inputs;
this.relations = rels;
this.fnValue = rel._value;
this._name = rel._id_;
this.required = rel.__required.__value;
this.dom = dom;
this.onchange = this.onchange.bind(this);
forEach(this.inputs, function (input) {
input.on('change', this.onchange);
}, this);
this.onchange();
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
value: d.gs(function () {
return this.fnValue(map(this.inputs,
function (input) { return input.value; }));
}, noop)
});
Object.defineProperty(Base, 'DOMInputComponent', d(Input));
| 'use strict';
var noop = require('es5-ext/lib/Function/noop')
, d = require('es5-ext/lib/Object/descriptor')
, forEach = require('es5-ext/lib/Object/for-each')
, map = require('es5-ext/lib/Object/map')
, Base = require('dbjs').Base
, DOMInput = require('./_controls/input')
, Input;
module.exports = Input = function (rel, inputs, rels, dom) {
this.inputs = inputs;
this.relations = rels;
this.fnValue = rel._value;
this._name = rel.name;
this.required = rel.__required.__value;
this.dom = dom;
this.onchange = this.onchange.bind(this);
forEach(this.inputs, function (input) {
input.on('change', this.onchange);
}, this);
this.onchange();
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
value: d.gs(function () {
return this.fnValue(map(this.inputs,
function (input) { return input.value; }));
}, noop)
});
Object.defineProperty(Base, 'DOMInputComponent', d(Input));
|
Fix namespace in service provider | <?php
namespace AndrewNovikof\Objects;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
], 'config');
$this->publishes([
__DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
__DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
], 'objects');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../resources/config/objects.php',
'config'
);
}
}
| <?php
namespace AndrewNovikof\Objects\Traits;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
], 'config');
$this->publishes([
__DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
__DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
], 'objects');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../resources/config/objects.php',
'config'
);
}
}
|
Use the right float names for type shortcuts | from basetypes import *
from exttypes import *
from closuretypes import *
from ssatypes import *
from templatetypes import *
from typemapper import *
__all__ = minitypes.__all__ + [
'O', 'b1', 'i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',
'f4', 'f8', 'f16', 'c8', 'c16', 'c32', 'template',
]
#------------------------------------------------------------------------
# Utilities
#------------------------------------------------------------------------
def is_obj(type):
return type.is_object or type.is_array
def promote_closest(context, int_type, candidates):
"""
promote_closest(Py_ssize_t, [int_, long_, longlong]) -> longlong
"""
for candidate in candidates:
promoted = context.promote_types(int_type, candidate)
if promoted == candidate:
return candidate
return candidates[-1]
#------------------------------------------------------------------------
# Type shorthands
#------------------------------------------------------------------------
O = object_
b1 = bool_
i1 = int8
i2 = int16
i4 = int32
i8 = int64
u1 = uint8
u2 = uint16
u4 = uint32
u8 = uint64
f4 = float32
f8 = float64
f16 = float128
c8 = complex64
c16 = complex128
c32 = complex256
| from basetypes import *
from exttypes import *
from closuretypes import *
from ssatypes import *
from templatetypes import *
from typemapper import *
__all__ = minitypes.__all__ + [
'O', 'b1', 'i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',
'f4', 'f8', 'f16', 'c8', 'c16', 'c32', 'template',
]
#------------------------------------------------------------------------
# Utilities
#------------------------------------------------------------------------
def is_obj(type):
return type.is_object or type.is_array
def promote_closest(context, int_type, candidates):
"""
promote_closest(Py_ssize_t, [int_, long_, longlong]) -> longlong
"""
for candidate in candidates:
promoted = context.promote_types(int_type, candidate)
if promoted == candidate:
return candidate
return candidates[-1]
#------------------------------------------------------------------------
# Type shorthands
#------------------------------------------------------------------------
O = object_
b1 = bool_
i1 = int8
i2 = int16
i4 = int32
i8 = int64
u1 = uint8
u2 = uint16
u4 = uint32
u8 = uint64
f4 = float_
f8 = double
f16 = float128
c8 = complex64
c16 = complex128
c32 = complex256
|
Remove use of process from global | const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');
const resize = (proc, store) => {
const action = actions.resize({
rows: proc.stdout.rows,
columns: proc.stdout.columns
});
store.dispatch(action);
};
module.exports = (initialState, proc = process) => {
const store = configureStore(proc, initialState);
const onStateChange = draw(proc, store);
store.subscribe(onStateChange);
onStateChange();
proc.stdin.addListener('keypress', keys(store));
proc.stdout.addListener('resize', () => resize(proc, store));
resize(proc, store);
readline.emitKeypressEvents(proc.stdin);
proc.stdin.setRawMode(true);
}; | const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');
const resize = (proc, store) => {
const action = actions.resize({
rows: proc.stdout.rows,
columns: proc.stdout.columns
});
store.dispatch(action);
};
module.exports = (initialState, proc = process) => {
const store = configureStore(proc, initialState);
const onStateChange = draw(process, store);
store.subscribe(onStateChange);
onStateChange();
proc.stdin.addListener('keypress', keys(store));
proc.stdout.addListener('resize', () => resize(proc, store));
resize(proc, store);
readline.emitKeypressEvents(proc.stdin);
proc.stdin.setRawMode(true);
}; |
Use object instead of searching for the element | import Ember from 'ember';
import modalLayout from '../templates/components/modal-dialog';
export default Ember.Component.extend({
classNames: [ 'media' ],
classNameBindings: [ 'isOpen:open' ],
attributeBindings: [ 'id' ],
id: 'modal-dialog',
isOpen: function() {
return this.get( 'visibility' );
}.property( 'visibility' ),
expose: function() {
var appController = this.get( 'targetObject' ),
exposedName = 'modal-' + this.get( 'type' );
appController.set( exposedName, this );
}.on( 'init' ),
init: function() {
var store = this.get( 'targetObject.store' );
this._super();
this.set( 'model', store.findAll( 'file' ) );
},
actions: {
toggleModal: function() {
this.toggleProperty( 'visibility' );
$( document.body ).toggleClass( 'no-scroll' );
}
},
layout: modalLayout,
inModal: true
});
| import Ember from 'ember';
import modalLayout from '../templates/components/modal-dialog';
export default Ember.Component.extend({
classNames: [ 'media' ],
classNameBindings: [ 'isOpen:open' ],
attributeBindings: [ 'id' ],
id: 'modal-dialog',
isOpen: function() {
return this.get( 'visibility' );
}.property( 'visibility' ),
expose: function() {
var appController = this.get( 'targetObject' ),
exposedName = 'modal-' + this.get( 'type' );
appController.set( exposedName, this );
}.on( 'init' ),
init: function() {
var store = this.get( 'targetObject.store' );
this._super();
this.set( 'model', store.findAll( 'file' ) );
},
actions: {
toggleModal: function() {
this.toggleProperty( 'visibility' );
$( 'body' ).toggleClass( 'no-scroll' );
}
},
layout: modalLayout,
inModal: true
});
|
Throw exception when running scan/query and the cluster is empty. | /*
* Aerospike Client - Java Library
*
* Copyright 2013 by Aerospike, Inc. All rights reserved.
*
* Availability of this source code to partners and customers includes
* redistribution rights covered by individual contract. Please check your
* contract for exact rights and responsibilities.
*/
package com.aerospike.client.async;
import com.aerospike.client.AerospikeException;
import com.aerospike.client.ResultCode;
import com.aerospike.client.cluster.Node;
import com.aerospike.client.listener.RecordSequenceListener;
import com.aerospike.client.policy.ScanPolicy;
public final class AsyncScanExecutor extends AsyncMultiExecutor {
private final RecordSequenceListener listener;
public AsyncScanExecutor(
AsyncCluster cluster,
ScanPolicy policy,
RecordSequenceListener listener,
String namespace,
String setName,
String[] binNames
) throws AerospikeException {
this.listener = listener;
Node[] nodes = cluster.getNodes();
if (nodes.length == 0) {
throw new AerospikeException(ResultCode.SERVER_NOT_AVAILABLE, "Scan failed because cluster is empty.");
}
completedSize = nodes.length;
for (Node node : nodes) {
AsyncScan async = new AsyncScan(this, cluster, (AsyncNode)node, policy, listener, namespace, setName, binNames);
async.execute();
}
}
protected void onSuccess() {
listener.onSuccess();
}
protected void onFailure(AerospikeException ae) {
listener.onFailure(ae);
}
}
| /*
* Aerospike Client - Java Library
*
* Copyright 2013 by Aerospike, Inc. All rights reserved.
*
* Availability of this source code to partners and customers includes
* redistribution rights covered by individual contract. Please check your
* contract for exact rights and responsibilities.
*/
package com.aerospike.client.async;
import com.aerospike.client.AerospikeException;
import com.aerospike.client.cluster.Node;
import com.aerospike.client.listener.RecordSequenceListener;
import com.aerospike.client.policy.ScanPolicy;
public final class AsyncScanExecutor extends AsyncMultiExecutor {
private final RecordSequenceListener listener;
public AsyncScanExecutor(
AsyncCluster cluster,
ScanPolicy policy,
RecordSequenceListener listener,
String namespace,
String setName,
String[] binNames
) throws AerospikeException {
this.listener = listener;
Node[] nodes = cluster.getNodes();
completedSize = nodes.length;
for (Node node : nodes) {
AsyncScan async = new AsyncScan(this, cluster, (AsyncNode)node, policy, listener, namespace, setName, binNames);
async.execute();
}
}
protected void onSuccess() {
listener.onSuccess();
}
protected void onFailure(AerospikeException ae) {
listener.onFailure(ae);
}
}
|
Test both clone and init static methods. | /*
* git-exec - test script
*
* Copyright (c) 2013 Alex J Burke
* Licensed under the MIT license.
*/
// imports
var fs = require('fs');
// local imports
var Git = require('../lib/git-exec');
var rimraf = require('rimraf');
// constants
var TEST_REPO = 'test_repo';
// node <0.8 compat
var exists = fs.exists || require('path').exists;
module.exports = exports = {
tearDown: function (callback) {
rimraf(TEST_REPO, function() {
callback();
});
}
};
function checkRepoObject(test, repo) {
exists(TEST_REPO, function(doesExist) {
test.ok(doesExist, 'test repository was created');
test.ok(repo, 'repository object created');
test.ok(repo instanceof Git, 'repository object has correct type');
});
}
exports.testClone = function(test) {
var self = this;
Git.clone('.', TEST_REPO, function(repo) {
checkRepoObject(test, repo);
test.done();
});
};
exports.testInit = function(test) {
var self = this;
Git.init(TEST_REPO, null, function(repo) {
checkRepoObject(test, repo);
test.done();
});
};
| /*
* git-exec - test script
*
* Copyright (c) 2013 Alex J Burke
* Licensed under the MIT license.
*/
// imports
var fs = require('fs');
// local imports
var Git = require('../lib/git-exec');
var rimraf = require('rimraf');
// constants
var TEST_REPO = 'test_repo';
// node <0.8 compat
var exists = fs.exists || require('path').exists;
module.exports = exports = {
setUp: function (callback) {
var self = this;
Git.init(TEST_REPO, null, function(repo) {
self.repo = repo;
callback();
});
},
tearDown: function (callback) {
rimraf(TEST_REPO, function() {
callback();
});
}
};
exports.testInit = function(test) {
var self = this;
exists(TEST_REPO, function(doesExist) {
test.ok(doesExist, 'test repository was created');
test.ok(self.repo, 'repository object created');
test.ok(self.repo instanceof Git, 'repository object has correct type');
test.done();
});
};
|
Call personfinder module properly from a public channel | var Person = require('./person');
function incomingMessage(botId, message) {
return message.type === 'message' // check it's a message
&& Boolean(message.text) // check message has some content
&& Boolean(message.user) // check there is a user set
&& message.user !== botId; // check message is not from this bot
}
function directMessage(message) {
// check it's a direct message - direct message channels start with 'D'
return typeof message.channel === 'string' && message.channel[0] === 'D';
}
function channelMessageForMe(botId, message) {
return typeof message.channel === 'string' // check it's a string
&& message.channel[0] === 'C' // channel messages start with 'C'
&& message.text.startsWith('<@' + botId + '>'); // check it's for me
}
function createResponse(message, callback) {
var messageBody = message.text.replace(/^<@.+>:? /, '');
if (messageBody.startsWith('person')) {
var person = new Person(messageBody.substring(7));
person.getDetails(callback);
} else {
// if nothing else, just echo back the message
callback('Echo: ' + messageBody);
}
}
module.exports = {
incomingMessage: incomingMessage,
directMessage: directMessage,
channelMessageForMe: channelMessageForMe,
createResponse: createResponse
};
| var Person = require('./person');
function incomingMessage(botId, message) {
return message.type === 'message' // check it's a message
&& Boolean(message.text) // check message has some content
&& Boolean(message.user) // check there is a user set
&& message.user !== botId; // check message is not from this bot
}
function directMessage(message) {
// check it's a direct message - direct message channels start with 'D'
return typeof message.channel === 'string' && message.channel[0] === 'D';
}
function channelMessageForMe(botId, message) {
return typeof message.channel === 'string' // check it's a string
&& message.channel[0] === 'C' // channel messages start with 'C'
&& message.text.startsWith('<@' + botId + '>:'); // check it's for me
}
function createResponse(message, callback) {
if (message.text.startsWith('person')) {
var person = new Person(message.text.substring(7));
person.getDetails(callback);
} else {
// if nothing else, just echo back the message
callback('Echo: ' + message.text);
}
}
module.exports = {
incomingMessage: incomingMessage,
directMessage: directMessage,
channelMessageForMe: channelMessageForMe,
createResponse: createResponse
};
|
Use $timeout instead of setTimeout for better compatibility | /* global angular */
const MESSAGE_TIMEOUTS = {message: 7000, success: 6000, error: 14000};
angular.module('dappChess').controller('MessagesCtrl', function ($scope, $timeout) {
$scope.messages = [];
$scope.$on('message', function(event, message, type = message, topic = null) {
let id = Math.random();
if(topic) {
$scope.messages = $scope.messages.filter(function(message) {
if(topic === message.topic) {
return false;
}
return true;
});
}
if(type === 'success' || type === 'error') {
$timeout(function() {
$scope.messages = $scope.messages.filter(function(message) {
if(id === message.id) {
return false;
}
return true;
});
}, MESSAGE_TIMEOUTS[type]);
}
$scope.messages.push({
id: id,
message: message,
type: type,
topic: topic
});
});
});
| /* global angular */
const MESSAGE_TIMEOUTS = {message: 7000, success: 6000, error: 14000};
angular.module('dappChess').controller('MessagesCtrl', function ($scope) {
$scope.messages = [];
$scope.$on('message', function(event, message, type = message, topic = null) {
let id = Math.random();
if(topic) {
$scope.messages = $scope.messages.filter(function(message) {
if(topic === message.topic) {
return false;
}
return true;
});
}
if(type === 'success' || type === 'error') {
setTimeout(function() {
$scope.messages = $scope.messages.filter(function(message) {
if(id === message.id) {
return false;
}
return true;
});
$scope.$apply();
}, MESSAGE_TIMEOUTS[type]);
}
$scope.messages.push({
id: id,
message: message,
type: type,
topic: topic
});
});
});
|
Fix s3 bucket variable name bug | const express = require('express');
const aws = require('aws-sdk');
const app = express();
const port = process.env.PORT || 3000;
const S3_BUCKET = process.env.S3_BUCKET;
app.use(express.static('./public'));
app.listen(port);
console.log('listening on port', port);
app.get('/sign-s3', (req, res) => {
const s3 = new aws.S3();
const fileName = req.query['file-name'];
const fileType = req.query['file-type'];
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
console.log(s3Params)
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
console.log('error getting signed url: ', err);
return res.end();
}
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
res.send(returnData);
});
}) | const express = require('express');
const aws = require('aws-sdk');
const app = express();
const port = process.env.PORT || 3000;
const bucket = process.env.S3_BUCKET;
app.use(express.static('./public'));
app.listen(port);
console.log('listening on port', port);
app.get('/sign-s3', (req, res) => {
const s3 = new aws.S3();
const fileName = req.query['file-name'];
const fileType = req.query['file-type'];
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
console.log('error getting signed url: ', err);
return res.end();
}
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
res.send(returnData);
});
}) |
Fix broken Android back button | import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';
const PepperoniAppTemplate = React.createClass({
componentWillMount() {
BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
},
navigateBack() {
const navigationState = store.getState().get('navigationState');
const currentTab = navigationState.getIn(['routes', navigationState.get('index')]);
// if we are in the beginning of our tab stack
if (currentTab.get('index') === 0) {
// if we are not in the first tab, switch tab to the leftmost one
if (navigationState.get('index') !== 0) {
store.dispatch(NavigationStateActions.switchTab(0));
return true;
}
// otherwise let OS handle the back button action
return false;
}
store.dispatch(NavigationStateActions.popRoute());
return true;
},
render() {
return (
<Provider store={store}>
<AppViewContainer />
</Provider>
);
}
});
AppRegistry.registerComponent('PepperoniAppTemplate', () => PepperoniAppTemplate);
| import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';
const PepperoniAppTemplate = React.createClass({
componentWillMount() {
BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
},
navigateBack() {
const navigationState = store.getState().get('navigationState');
const currentTab = navigationState.getIn(['children', navigationState.get('index')]);
// if we are in the beginning of our tab stack
if (currentTab.get('index') === 0) {
// if we are not in the first tab, switch tab to the leftmost one
if (navigationState.get('index') !== 0) {
store.dispatch(NavigationStateActions.switchTab(0));
return true;
}
// otherwise let OS handle the back button action
return false;
}
store.dispatch(NavigationStateActions.popRoute());
return true;
},
render() {
return (
<Provider store={store}>
<AppViewContainer />
</Provider>
);
}
});
AppRegistry.registerComponent('PepperoniAppTemplate', () => PepperoniAppTemplate);
|
Set a timeout of 5 seconds | from setuptools import setup, find_packages
DESCRIPTION = "FFXI Linkshell Community Scraper"
with open('README.md') as f:
LONG_DESCRIPTION = f.read()
with open('requirements.txt') as f:
required = f.read().splitlines()
VERSION = '0.1.11'
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
setup(name='ffxiscraper',
version=VERSION,
packages=find_packages(),
install_requires=required,
scripts=['lscom'],
author='Stanislav Vishnevskiy',
author_email='vishnevskiy@gmail.com',
maintainer='Matthew Scragg',
maintainer_email='scragg@gmail.com',
url='https://github.com/scragg0x/FFXI-Scraper',
license='MIT',
include_package_data=True,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
#test_suite='tests',
) | from setuptools import setup, find_packages
DESCRIPTION = "FFXI Linkshell Community Scraper"
with open('README.md') as f:
LONG_DESCRIPTION = f.read()
with open('requirements.txt') as f:
required = f.read().splitlines()
VERSION = '0.1.10'
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
setup(name='ffxiscraper',
version=VERSION,
packages=find_packages(),
install_requires=required,
scripts=['lscom'],
author='Stanislav Vishnevskiy',
author_email='vishnevskiy@gmail.com',
maintainer='Matthew Scragg',
maintainer_email='scragg@gmail.com',
url='https://github.com/scragg0x/FFXI-Scraper',
license='MIT',
include_package_data=True,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
#test_suite='tests',
) |
Fix `bake all` ignores AppController::$theme | <?php
App::uses('AppShell', 'Console/Command');
App::uses('AppController', 'Controller');
class ThemeAppShell extends Shell
{
public function initialize() {
if ($this instanceof BakeShell || $this instanceof ThemeShell) {
$this->tasks['View'] = array(
'className' => 'Theme.ThemeView',
);
}
parent::initialize();
}
public function runCommand($command, $argv) {
if ($this instanceof BakeShell || $this instanceof ThemeShell) {
$theme = Configure::read('Theme.default');
if (!$theme) {
$class = Configure::read('Theme.defaultClass') ?: 'AppController';
$vars = get_class_vars($class);
if (isset($vars['theme'])) {
$theme = $vars['theme'];
}
}
if ($theme) {
array_splice($argv, 1, 0, array('--theme', $theme));
}
}
return parent::runCommand($command, $argv);
}
}
| <?php
App::uses('AppShell', 'Console/Command');
App::uses('AppController', 'Controller');
class ThemeAppShell extends Shell
{
public function initialize() {
if ($this instanceof BakeShell || $this instanceof ThemeShell) {
$this->tasks['View'] = array(
'className' => 'Theme.ThemeView',
);
}
parent::initialize();
}
public function runCommand($command, $argv) {
$auto = false;
if ($this instanceof ThemeShell) {
$auto = true;
} elseif ($this instanceof BakeShell) {
if ($argv && $this->hasTask($argv[0])) {
$auto = true;
}
}
if ($auto) {
$theme = Configure::read('Theme.default');
if (!$theme) {
$vars = get_class_vars('AppController');
if (isset($vars['theme'])) {
$theme = $vars['theme'];
}
}
if ($theme) {
array_splice($argv, 1, 0, array('--theme', $theme));
}
}
return parent::runCommand($command, $argv);
}
}
|
Clean up use of Symfony yaml dumper. | <?php
namespace Consolidation\OutputFormatters\Formatters;
use Symfony\Component\Yaml\Yaml;
use Consolidation\OutputFormatters\FormatterInterface;
use Symfony\Component\Console\Output\OutputInterface;
class YamlFormatter implements FormatterInterface
{
/**
* @inheritdoc
*/
public function write(OutputInterface $output, $data, $options = [])
{
// Set Yaml\Dumper's default indentation for nested nodes/collections to
// 2 spaces for consistency with Drupal coding standards.
$indent = 2;
// The level where you switch to inline YAML is set to PHP_INT_MAX to
// ensure this does not occur.
$output->writeln(Yaml::dump($data, PHP_INT_MAX, $indent, false, true));
}
}
| <?php
namespace Consolidation\OutputFormatters\Formatters;
use Symfony\Component\Yaml\Dumper;
use Consolidation\OutputFormatters\FormatterInterface;
use Symfony\Component\Console\Output\OutputInterface;
class YamlFormatter implements FormatterInterface
{
/**
* @inheritdoc
*/
public function write(OutputInterface $output, $data, $options = [])
{
$dumper = new Dumper();
// Set Yaml\Dumper's default indentation for nested nodes/collections to
// 2 spaces for consistency with Drupal coding standards.
$dumper->setIndentation(2);
// The level where you switch to inline YAML is set to PHP_INT_MAX to
// ensure this does not occur.
$output->writeln($dumper->dump($data, PHP_INT_MAX, null, null, true));
}
}
|
Fix typo in test ORC temp file name | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.orc;
import java.io.Closeable;
import java.io.File;
import static com.google.common.io.Files.createTempDir;
import static io.airlift.testing.FileUtils.deleteRecursively;
class TempFile
implements Closeable
{
private final File tempDir;
private final File file;
public TempFile()
{
tempDir = createTempDir();
tempDir.mkdirs();
file = new File(tempDir, "data.orc");
}
public File getFile()
{
return file;
}
@Override
public void close()
{
// hadoop creates crc files that must be deleted also, so just delete the whole directory
deleteRecursively(tempDir);
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.orc;
import java.io.Closeable;
import java.io.File;
import static com.google.common.io.Files.createTempDir;
import static io.airlift.testing.FileUtils.deleteRecursively;
class TempFile
implements Closeable
{
private final File tempDir;
private final File file;
public TempFile()
{
tempDir = createTempDir();
tempDir.mkdirs();
file = new File(tempDir, "data.rcfile");
}
public File getFile()
{
return file;
}
@Override
public void close()
{
// hadoop creates crc files that must be deleted also, so just delete the whole directory
deleteRecursively(tempDir);
}
}
|
Remove unrelated thing from migration | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-02 15:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0025_auto_20161219_0517'),
]
operations = [
migrations.CreateModel(
name='Collection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, verbose_name='name', unique=True,)),
('products', models.ManyToManyField(to='product.Product')),
],
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-02 15:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0025_auto_20161219_0517'),
]
operations = [
migrations.CreateModel(
name='Collection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, verbose_name='name', unique=True,)),
('products', models.ManyToManyField(to='product.Product')),
],
),
migrations.AlterField(
model_name='stocklocation',
name='name',
field=models.CharField(max_length=100, verbose_name='location'),
),
]
|
OAK-5793: Improve coverage for security code in oak-core
Missing license header
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1784852 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.jackrabbit.oak.spi.security.authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Created by angela on 28/02/17.
*/
class ThrowingCallbackHandler implements CallbackHandler {
private boolean throwIOException;
ThrowingCallbackHandler(boolean throwIOException) {
this.throwIOException = throwIOException;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (throwIOException) {
throw new IOException();
} else {
throw new UnsupportedCallbackException(new Callback() {
});
}
}
}
| package org.apache.jackrabbit.oak.spi.security.authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Created by angela on 28/02/17.
*/
class ThrowingCallbackHandler implements CallbackHandler {
private boolean throwIOException;
ThrowingCallbackHandler(boolean throwIOException) {
this.throwIOException = throwIOException;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (throwIOException) {
throw new IOException();
} else {
throw new UnsupportedCallbackException(new Callback() {
});
}
}
}
|
Fix message lost issue in samples | import threading
import sys
import nanomsg as nn
def ping(url, barrier):
with nn.Socket(protocol=nn.Protocol.NN_PUSH) as sock, sock.connect(url):
sock.send(b'Hello, World!')
# Shutdown the endpoint after the other side ack'ed; otherwise
# the message could be lost.
barrier.wait()
def pong(url, barrier):
with nn.Socket(protocol=nn.Protocol.NN_PULL) as sock, sock.bind(url):
message = sock.recv()
print(bytes(message.as_memoryview()).decode('ascii'))
barrier.wait()
def main():
barrier = threading.Barrier(2)
url = 'inproc://test'
print('Play ping-pong on %s' % url)
threads = [
threading.Thread(target=ping, args=(url, barrier)),
threading.Thread(target=pong, args=(url, barrier)),
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return 0
if __name__ == '__main__':
sys.exit(main())
| import os.path
import shutil
import tempfile
import threading
import sys
import nanomsg as nn
def ping(url, event):
with nn.Socket(protocol=nn.Protocol.NN_PUSH) as sock, sock.connect(url):
event.wait()
sock.send(b'Hello, World!')
def pong(url, event):
with nn.Socket(protocol=nn.Protocol.NN_PULL) as sock, sock.bind(url):
event.set()
message = sock.recv()
print(bytes(message.as_memoryview()).decode('ascii'))
def main():
path = tempfile.mkdtemp()
try:
event = threading.Event()
url = 'ipc://' + os.path.join(path, 'reqrep.ipc')
print('Play ping-pong on %s' % url)
threads = [
threading.Thread(target=ping, args=(url, event)),
threading.Thread(target=pong, args=(url, event)),
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
finally:
shutil.rmtree(path)
return 0
if __name__ == '__main__':
sys.exit(main())
|
Fix test to use ∞ | import {formatBytes, formatRPDuration} from 'utils/formatting';
describe('Formatting helpers', () => {
describe('formatBytes', () => {
it('returns null when passed a falsey value', () => {
const actual = formatBytes(null);
expect(actual).to.equal(null);
});
it('returns the correct value when passed 0', () => {
const actual = formatBytes(0);
expect(actual).to.equal('0 Bytes');
});
it('converts a raw byte value into it\'s most appropriate unit', () => {
expect(formatBytes(1000)).to.equal('1 KB');
expect(formatBytes(1000000)).to.equal('1 MB');
expect(formatBytes(1000000000)).to.equal('1 GB');
});
});
describe('formatRPDuration', () => {
it("returns 'infinite' for a retention policy with a value of '0'", () => {
const actual = formatRPDuration('0')
expect(actual).to.equal('∞');
});
it('correctly formats retention policy durations', () => {
expect(formatRPDuration('24h0m0s')).to.equal('24h');
expect(formatRPDuration('168h0m0s')).to.equal('7d');
expect(formatRPDuration('200h32m3s')).to.equal('8d8h32m3s');
});
});
});
| import {formatBytes, formatRPDuration} from 'utils/formatting';
describe('Formatting helpers', () => {
describe('formatBytes', () => {
it('returns null when passed a falsey value', () => {
const actual = formatBytes(null);
expect(actual).to.equal(null);
});
it('returns the correct value when passed 0', () => {
const actual = formatBytes(0);
expect(actual).to.equal('0 Bytes');
});
it('converts a raw byte value into it\'s most appropriate unit', () => {
expect(formatBytes(1000)).to.equal('1 KB');
expect(formatBytes(1000000)).to.equal('1 MB');
expect(formatBytes(1000000000)).to.equal('1 GB');
});
});
describe('formatRPDuration', () => {
it("returns 'infinite' for a retention policy with a value of '0'", () => {
const actual = formatRPDuration('0')
expect(actual).to.equal('infinite');
});
it('correctly formats retention policy durations', () => {
expect(formatRPDuration('24h0m0s')).to.equal('24h');
expect(formatRPDuration('168h0m0s')).to.equal('7d');
expect(formatRPDuration('200h32m3s')).to.equal('8d8h32m3s');
});
});
});
|
Use BOOLEAN as default H2 boolean type. | package it.unibz.inf.ontop.model.type.impl;
import com.google.common.collect.ImmutableMap;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.model.type.DBTermType;
import it.unibz.inf.ontop.model.type.TermType;
import it.unibz.inf.ontop.model.type.TypeFactory;
import java.util.Map;
public class H2SQLDBTypeFactory extends DefaultSQLDBTypeFactory {
@AssistedInject
private H2SQLDBTypeFactory(@Assisted TermType rootTermType, @Assisted TypeFactory typeFactory) {
super(createH2SQLTypeMap(rootTermType, typeFactory), createH2SQLCodeMap());
}
private static Map<String, DBTermType> createH2SQLTypeMap(TermType rootTermType, TypeFactory typeFactory) {
Map<String, DBTermType> map = createDefaultSQLTypeMap(rootTermType, typeFactory);
return map;
}
private static ImmutableMap<DefaultTypeCode, String> createH2SQLCodeMap() {
Map<DefaultTypeCode, String> map = createDefaultSQLCodeMap();
return ImmutableMap.copyOf(map);
}
}
| package it.unibz.inf.ontop.model.type.impl;
import com.google.common.collect.ImmutableMap;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.model.type.DBTermType;
import it.unibz.inf.ontop.model.type.TermType;
import it.unibz.inf.ontop.model.type.TypeFactory;
import java.util.Map;
public class H2SQLDBTypeFactory extends DefaultSQLDBTypeFactory {
private static final String BOOL_STR = "BOOL";
@AssistedInject
private H2SQLDBTypeFactory(@Assisted TermType rootTermType, @Assisted TypeFactory typeFactory) {
super(createH2SQLTypeMap(rootTermType, typeFactory), createH2SQLCodeMap());
}
private static Map<String, DBTermType> createH2SQLTypeMap(TermType rootTermType, TypeFactory typeFactory) {
Map<String, DBTermType> map = createDefaultSQLTypeMap(rootTermType, typeFactory);
// TODO: add the other alias BIT?
map.put(BOOL_STR, new BooleanDBTermType(BOOL_STR, rootTermType.getAncestry(), typeFactory.getXsdBooleanDatatype()));
return map;
}
private static ImmutableMap<DefaultTypeCode, String> createH2SQLCodeMap() {
Map<DefaultTypeCode, String> map = createDefaultSQLCodeMap();
map.put(DefaultTypeCode.BOOLEAN, BOOL_STR);
return ImmutableMap.copyOf(map);
}
}
|
Correct a typo in the service provider | <?php
namespace Chalcedonyt\COSProcessor\Providers;
use Illuminate\Support\ServiceProvider;
class COSProcessorServiceProvider extends ServiceProvider
{
protected $templates = [];
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$source_config = __DIR__ . '/../../config/cos_processor.php';
$this->publishes([
$source_config => base_path('config/cos_processor.php')
]);
// $this->loadViewsFrom(__DIR__ . '/../views', 'cos_processor');
}
/**
* Register any package services.
*
* @return void
*/
public function register()
{
$source_config = __DIR__ . '/../../config/cos_processor.php';
$this->mergeConfigFrom($source_config, 'cos_processor');
}
}
| <?php
namespace Chalcedonyt\COSProcessor\Providers;
use Illuminate\Support\ServiceProvider;
class COSProcessorServiceProvider extends ServiceProvider
{
protected $templates = [];
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$source_config = __DIR__ . '/../../config/cos_processor.php';
$this->publishes([
$source_config => base_path('config/cos_processor.php'),
__DIR__.'/../views/provider.php' => base_path('app/Providers/COSProcessorServiceProvider.php')
]);
// $this->loadViewsFrom(__DIR__ . '/../views', 'cos_processor');
}
/**
* Register any package services.
*
* @return void
*/
public function register()
{
$source_config = __DIR__ . '/../../config/cos_processor.php';
$this->mergeConfigFrom($source_config, 'cos_processor');
}
}
|
Switch to compose parsing from Docker context | package main
import (
"log"
"fmt"
"os"
"path"
"github.com/docker/libcompose/config"
"github.com/docker/libcompose/project"
)
func main() {
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
_, dir := path.Split(pwd)
project := project.NewProject(&project.Context{
ComposeFiles: []string{"docker-compose.yml"},
ProjectName: dir,
}, nil, &config.ParseOptions{})
if err := project.Parse(); err != nil {
log.Fatal(err)
}
for name, _ := range project.NetworkConfigs {
s := fmt.Sprintf("Network: %s", name)
fmt.Println(s)
}
}
| package main
import (
"log"
"fmt"
"os"
"path"
"golang.org/x/net/context"
"github.com/docker/libcompose/docker"
"github.com/docker/libcompose/docker/ctx"
"github.com/docker/libcompose/project"
"github.com/docker/libcompose/project/options"
)
func main() {
pwd, err := os.Getwd()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
_, dir := path.Split(pwd)
project, err := docker.NewProject(&ctx.Context{
Context: project.Context{
ComposeFiles: []string{"docker-compose.yml"},
ProjectName: dir,
},
}, nil)
if err != nil {
log.Fatal(err)
}
err = project.Up(context.Background(), options.Up{})
if err != nil {
log.Fatal(err)
}
}
|
Switch back the good agg version (instead of agg+) | # -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import re
import numpy as np
from glumpy import app, gl, data, svg, collections
from glumpy.transforms import Position, OrthographicProjection, PanZoom, Viewport
window = app.Window(800, 800, color=(1,1,1,1))
transform = PanZoom(OrthographicProjection(Position()))
@window.event
def on_draw(dt):
window.clear()
paths["antialias"] = -0.5
collections.Collection.draw(paths)
paths["antialias"] = +1.0
collections.Collection.draw(paths)
@window.event
def on_init():
gl.glEnable(gl.GL_DEPTH_TEST)
paths = collections.PathCollection("agg", transform=transform)
# paths["miter_limit"] = 4.0
paths["linewidth"] = 50.0
paths["color"] = 0.0,0.0,0.0,0.5
path = svg.Path("""M 300,400
c 0,100 200,-100 200,0
c 0,100 -200,-100 -200,0 z""")
vertices, closed = path.vertices[0]
paths.append(vertices, closed=closed)
window.attach(paths["transform"])
window.attach(paths["viewport"])
app.run()
| # -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import re
import numpy as np
from glumpy import app, gl, data, svg, collections
from glumpy.transforms import Position, OrthographicProjection, PanZoom, Viewport
window = app.Window(800, 800, color=(1,1,1,1))
transform = PanZoom(OrthographicProjection(Position()))
@window.event
def on_draw(dt):
window.clear()
paths["antialias"] = -0.5
collections.Collection.draw(paths)
paths["antialias"] = +1.0
collections.Collection.draw(paths)
@window.event
def on_init():
gl.glEnable(gl.GL_DEPTH_TEST)
paths = collections.PathCollection("agg+", transform=transform)
paths["miter_limit"] = 4.0
paths["linewidth"] = 50.0
paths["color"] = 0.0,0.0,0.0,0.5
path = svg.Path("""M 300,400
c 0,100 200,-100 200,0
c 0,100 -200,-100 -200,0 z""")
vertices, closed = path.vertices[0]
paths.append(vertices, closed=closed)
window.attach(paths["transform"])
window.attach(paths["viewport"])
app.run()
|
Switch to paho-mqtt and make ready for py3 | #!/usr/bin/python3
#
# test-messages.py - This script publish a random MQTT messages every 2 s.
#
# Copyright (c) 2013-2016, Fabian Affolter <fabian@affolter-engineering.ch>
# Released under the MIT license. See LICENSE file for details.
#
import random
import time
import paho.mqtt.client as mqtt
timestamp = int(time.time())
broker = '127.0.0.1'
port = 1883
element = 'home'
areas = ['front', 'back', 'kitchen', 'basement', 'living']
entrances = ['door', 'window']
states = ['true', 'false']
print('Messages are published on topic %s/#... -> CTRL + C to shutdown' \
% element)
while True:
area = random.choice(areas)
if (area in ['basement', 'living']):
topic = element + '/' + area + '/temp'
message = random.randrange(0, 30, 1)
else:
topic = element + '/' + area + '/' + random.choice(entrances)
message = random.choice(states)
mqttclient = mqtt.Client("mqtt-panel-test")
mqttclient.connect(broker, port=int(port))
mqttclient.publish(topic, message)
time.sleep(2)
| #!/usr/bin/python2
#
# test-messages.py - This script publish a random MQTT messages every 2 s.
#
# Copyright (c) 2013-2015, Fabian Affolter <fabian@affolter-engineering.ch>
# Released under the MIT license. See LICENSE file for details.
#
import random
import time
import mosquitto
timestamp = int(time.time())
broker = '127.0.0.1'
port = 1883
element = 'home'
areas = ['front', 'back', 'kitchen', 'basement', 'living']
entrances = ['door', 'window']
states = ['true', 'false']
print 'Messages are published on topic %s/#... -> CTRL + C to shutdown' \
% element
while True:
area = random.choice(areas)
if (area in ['basement', 'living']):
topic = element + '/' + area + '/temp'
message = random.randrange(0, 30, 1)
else:
topic = element + '/' + area + '/' + random.choice(entrances)
message = random.choice(states)
client = mosquitto.Mosquitto("mqtt-panel-test")
client.connect(broker)
client.publish(topic, message)
time.sleep(2)
|
Reorder UserSettings ZK methods more sensibly | package com.hubspot.singularity.data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityUserSettings;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.transcoders.Transcoder;
public class UserManager extends CuratorManager {
private final Transcoder<SingularityUserSettings> settingsTranscoder;
private static final String USER_ROOT = "/users";
private static final String SETTINGS_ROOT = USER_ROOT + "/settings";
@Inject
public UserManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry,
Transcoder<SingularityUserSettings> settingsTranscoder) {
super(curator, configuration, metricRegistry);
this.settingsTranscoder = settingsTranscoder;
}
private String getUserSettingsPath(String id) {
return ZKPaths.makePath(SETTINGS_ROOT, id);
}
public void updateUserSettings(String id, SingularityUserSettings userSettings) {
save(getUserSettingsPath(id), userSettings, settingsTranscoder);
}
public Optional<SingularityUserSettings> getUserSettings(String id) {
return getData(getUserSettingsPath(id), settingsTranscoder);
}
public void deleteUserSettings(String id) {
delete(getUserSettingsPath(id));
}
}
| package com.hubspot.singularity.data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityUserSettings;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.transcoders.Transcoder;
public class UserManager extends CuratorManager {
private final Transcoder<SingularityUserSettings> settingsTranscoder;
private static final String USER_ROOT = "/users";
private static final String SETTINGS_ROOT = USER_ROOT + "/settings";
@Inject
public UserManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry,
Transcoder<SingularityUserSettings> settingsTranscoder) {
super(curator, configuration, metricRegistry);
this.settingsTranscoder = settingsTranscoder;
}
private String getUserSettingsPath(String id) {
return ZKPaths.makePath(SETTINGS_ROOT, id);
}
public void deleteUserSettings(String id) {
delete(getUserSettingsPath(id));
}
public Optional<SingularityUserSettings> getUserSettings(String id) {
return getData(getUserSettingsPath(id), settingsTranscoder);
}
public void updateUserSettings(String id, SingularityUserSettings userSettings) {
save(getUserSettingsPath(id), userSettings, settingsTranscoder);
}
}
|
Update locket to 0.1.1 for bug fix | #!/usr/bin/env python
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.4',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=[
'blah>=0.1.10,<0.2',
'requests>=1,<2',
"catchy>=0.1.2,<0.2",
"spur>=0.3,<0.4",
"locket>=0.1.1,<0.2",
],
)
| #!/usr/bin/env python
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.4',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=[
'blah>=0.1.10,<0.2',
'requests>=1,<2',
"catchy>=0.1.2,<0.2",
"spur>=0.3,<0.4",
"locket>=0.1,<0.2",
],
)
|
Add initial support for pygments styles | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js'
PYGMENTS_STYLE = 'default'
def get_pygments_stylesheet(selector, style=None):
try:
from pygments.formatters import HtmlFormatter
except ImportError:
return ''
else:
return HtmlFormatter(style=(style or PYGMENTS_STYLE)).get_style_defs(selector) + '\n'
def get_mathjax_url(webenv):
if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
return MATHJAX_LOCAL_URL
else:
return MATHJAX_WEB_URL
| # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js'
def get_pygments_stylesheet(selector):
try:
from pygments.formatters import HtmlFormatter
except ImportError:
return ''
else:
return HtmlFormatter().get_style_defs(selector) + '\n'
def get_mathjax_url(webenv):
if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
return MATHJAX_LOCAL_URL
else:
return MATHJAX_WEB_URL
|
Update string text domain and retab code | <section class="no-results not-found">
<header class="page-header">
<h1 class="page-title"><?php _e('Nothing Found', 'twentyseventeen'); ?></h1>
</header>
<div class="page-content">
<?php if (is_home() && current_user_can('publish_posts')) : ?>
<p><?php printf(__('Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'keitaro'), esc_url(admin_url('post-new.php'))); ?></p>
<?php else : ?>
<p><?php _e('It seems we can’t find what you’re looking for. Perhaps searching can help.', 'keitaro'); ?></p>
<?php
if (!is_search()):
get_search_form();
endif;
endif;
?>
</div><!-- .page-content -->
</section><!-- .no-results -->
| <section class="no-results not-found">
<header class="page-header">
<h1 class="page-title"><?php _e('Nothing Found', 'twentyseventeen'); ?></h1>
</header>
<div class="page-content">
<?php if (is_home() && current_user_can('publish_posts')) : ?>
<p><?php printf(__('Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'twentyseventeen'), esc_url(admin_url('post-new.php'))); ?></p>
<?php else : ?>
<p><?php _e('It seems we can’t find what you’re looking for. Perhaps searching can help.', 'twentyseventeen'); ?></p>
<?php
if (!is_search()):
get_search_form();
endif;
endif;
?>
</div><!-- .page-content -->
</section><!-- .no-results -->
|
Use " instead of ' | /*
* MODERNIZR: Modernizr builder
*/
module.exports = {
prepare: {
devFile: 'remote',
outputFile: 'lib/tmp/modernizr-custom.js',
extra: {
touch: true,
shiv: true,
cssclasses: true,
load: false
},
extensibility: {
teststyles: true,
prefixes: true
},
tests: [
'cookies'
],
uglify: false,
matchCommunityTests: true,
parseFiles: false
}
};
| /*
* MODERNIZR: Modernizr builder
*/
module.exports = {
prepare: {
devFile: "remote",
outputFile: "lib/tmp/modernizr-custom.js",
extra: {
touch: true,
shiv: true,
cssclasses: true,
load: false
},
extensibility: {
teststyles: true,
prefixes: true
},
tests: [
'cookies'
],
uglify: false,
matchCommunityTests: true,
parseFiles: false
}
};
|
Add doc noting Inktank's lockserver URL
Since I just removed it from lockstatus.py. | import os
import yaml
import logging
CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml')
log = logging.getLogger(__name__)
class _Config(object):
"""
This class is intended to unify teuthology's many configuration files and
objects. Currently it serves as a convenient interface to
~/.teuthology.yaml and nothing else.
"""
def __init__(self):
if os.path.exists(CONF_FILE):
self.__conf = yaml.safe_load(file(CONF_FILE))
else:
log.debug("%s not found", CONF_FILE)
self.__conf = {}
# This property declaration exists mainly as an example; it is not
# necessary unless you want to, say, define a set method and/or a
# docstring.
@property
def lock_server(self):
"""
The URL to your lock server. For example, Inktank uses:
http://teuthology.front.sepia.ceph.com/locker/lock
"""
return self.__conf.get('lock_server')
# This takes care of any and all of the rest.
# If the parameter is defined, return it. Otherwise return None.
def __getattr__(self, name):
return self.__conf.get(name)
config = _Config()
| import os
import yaml
import logging
CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml')
log = logging.getLogger(__name__)
class _Config(object):
"""
This class is intended to unify teuthology's many configuration files and
objects. Currently it serves as a convenient interface to
~/.teuthology.yaml and nothing else.
"""
def __init__(self):
if os.path.exists(CONF_FILE):
self.__conf = yaml.safe_load(file(CONF_FILE))
else:
log.debug("%s not found", CONF_FILE)
self.__conf = {}
# This property declaration exists mainly as an example; it is not
# necessary unless you want to, say, define a set method and/or a
# docstring.
@property
def lock_server(self):
return self.__conf.get('lock_server')
# This takes care of any and all of the rest.
# If the parameter is defined, return it. Otherwise return None.
def __getattr__(self, name):
return self.__conf.get(name)
config = _Config()
|
Put sections in desired order | import React from 'react'
import Page from '../../components/page'
import Header from './header'
import PreviousEpisodeSection from './sections/previous-episodes'
import EpisodesSection from './sections/episodes'
import PanelistsSection from './sections/panelists'
import SponsorsSection from '../../components/sponsors'
import Footer from './sections/footer'
import FeatureShowScript from './scripts/feature-show'
export default Home
function Home(
{
futureEpisodes = [],
pastEpisodes = [],
sponsors,
panelists,
}
) {
return (
<Page>
<Header />
<EpisodesSection episodes={futureEpisodes} />
<div className="container">
<PreviousEpisodeSection episodes={pastEpisodes} />
<SponsorsSection {...sponsors} />
</div>
<PanelistsSection panelists={panelists} />
<Footer />
<FeatureShowScript />
</Page>
)
}
| import React from 'react'
import Page from '../../components/page'
import Header from './header'
import PreviousEpisodeSection from './sections/previous-episodes'
import EpisodesSection from './sections/episodes'
import PanelistsSection from './sections/panelists'
import SponsorsSection from '../../components/sponsors'
import Footer from './sections/footer'
import FeatureShowScript from './scripts/feature-show'
export default Home
function Home(
{
futureEpisodes = [],
pastEpisodes = [],
sponsors,
panelists,
}
) {
return (
<Page>
<Header />
<EpisodesSection episodes={futureEpisodes} />
<PanelistsSection panelists={panelists} />
<Footer />
<div className="container">
<SponsorsSection {...sponsors} />
<PreviousEpisodeSection episodes={pastEpisodes} />
<FeatureShowScript />
</div>
</Page>
)
}
|
Revert "only transform exceptions if the request is expecting a json response."
This reverts commit 32c6f94210fe91933e20198de3d73d1d855c5416. | <?php
namespace Flugg\Responder\Exceptions;
use Exception;
use Flugg\Responder\Exceptions\Http\ApiException;
use Flugg\Responder\Traits\HandlesApiErrors;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
use HandlesApiErrors;
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param Exception $exception
* @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*/
public function render($request, Exception $exception)
{
$this->transformException($exception);
if ($exception instanceof ApiException) {
return $this->renderApiError($exception);
}
return parent::render($request, $exception);
}
} | <?php
namespace Flugg\Responder\Exceptions;
use Exception;
use Flugg\Responder\Exceptions\Http\ApiException;
use Flugg\Responder\Traits\HandlesApiErrors;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
use HandlesApiErrors;
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param Exception $exception
* @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*/
public function render($request, Exception $exception)
{
if ($request->expectsJson()) {
$this->transformException($exception);
if ($exception instanceof ApiException) {
return $this->renderApiError($exception);
}
}
return parent::render($request, $exception);
}
} |
fix(shape): Simplify logic where calculates coordinates | import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
* @version 1.0.0
*/
export default class Rectangle extends Shape {
render(cursor) {
let text = this.getText();
let width = this.getWidth();
let height = this.getHeight();
let x1 = this.getX();
let y1 = this.getY();
let x2 = x1 + width;
let y2 = y1 + height;
let background = this.getBackground();
let foreground = this.getForeground();
let filler = ' '.repeat(width);
if (typeof background !== 'undefined') cursor.background(background);
if (typeof foreground !== 'undefined') cursor.foreground(foreground);
cursor.moveTo(x1, y1);
for (let y = y1; y <= y2; y++) {
cursor.write(filler);
cursor.moveTo(x1, y);
}
cursor.moveTo(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);
return this;
}
}
| import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
* @version 1.0.0
*/
export default class Rectangle extends Shape {
render(cursor) {
let text = this.getText();
let width = this.getWidth();
let height = this.getHeight();
let x1 = this.getX();
let y1 = this.getY();
let x2 = x1 + width - 1;
let y2 = y1 + height - 1;
let background = this.getBackground();
let foreground = this.getForeground();
let filler = ' '.repeat(width);
if (typeof background !== 'undefined') cursor.background(background);
if (typeof foreground !== 'undefined') cursor.foreground(foreground);
cursor.moveTo(x1, y1);
while (y1 <= y2) {
cursor.write(filler);
cursor.moveTo(x1, ++y1);
}
cursor.moveTo(x1 + (width / 2 - text.length / 2), this.getY() + (height / 2)).write(text);
return this;
}
}
|
Clean up and refactor printing of request | #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(length)
def _transaction_string(self, command, path, headers, content):
return '%s %s\n%s%s\n' % (command, path, headers, content)
def _print_request(self, *request):
print('--> %s' % self._transaction_string(*request))
def do_POST(self):
content_length = int(self.headers['Content-Length'])
content = self._get_content_from_stream(content_length, self.rfile)
self._print_request(self.command, self.path, self.headers, content)
self.send_response(200)
self.end_headers()
server_address = (SERVER_NAME, SERVER_PORT)
httpd = ServerClass(server_address, JsonPostResponder)
httpd.serve_forever()
| #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(length)
def do_POST(self):
content_length = int(self.headers['Content-Length'])
content = self._get_content_from_stream(content_length, self.rfile)
print('\n--- %s%s\n%s' % (self.command, self.path, self.headers))
print content, '\n'
self.send_response(200)
self.end_headers()
server_address = (SERVER_NAME, SERVER_PORT)
httpd = ServerClass(server_address, JsonPostResponder)
httpd.serve_forever()
|
Fix NullPointerException resulting in MalformedChunk in AcceptanceTests | package org.zalando.nakadi.plugin.auth;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zalando.nakadi.plugin.api.PluginException;
import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute;
import org.zalando.nakadi.plugin.api.authz.AuthorizationService;
import org.zalando.nakadi.plugin.api.authz.Resource;
import org.zalando.nakadi.plugin.api.authz.Subject;
import java.security.Principal;
import java.util.List;
import java.util.Optional;
public class DefaultAuthorizationService implements AuthorizationService {
@Override
public boolean isAuthorized(final Operation operation, final Resource resource) {
return true;
}
@Override
public boolean isAuthorizationAttributeValid(final AuthorizationAttribute authorizationAttribute) {
return true;
}
@Override
public Subject getSubject() {
return () -> Optional.ofNullable(
SecurityContextHolder.getContext().getAuthentication()).map(Principal::getName).orElse(null);
}
@Override
public List<Resource> filter(final List<Resource> input) throws PluginException {
return input;
}
}
| package org.zalando.nakadi.plugin.auth;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zalando.nakadi.plugin.api.PluginException;
import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute;
import org.zalando.nakadi.plugin.api.authz.AuthorizationService;
import org.zalando.nakadi.plugin.api.authz.Resource;
import org.zalando.nakadi.plugin.api.authz.Subject;
import java.util.List;
public class DefaultAuthorizationService implements AuthorizationService {
@Override
public boolean isAuthorized(final Operation operation, final Resource resource) {
return true;
}
@Override
public boolean isAuthorizationAttributeValid(final AuthorizationAttribute authorizationAttribute) {
return true;
}
@Override
public Subject getSubject() {
return () -> SecurityContextHolder.getContext().getAuthentication().getName();
}
@Override
public List<Resource> filter(final List<Resource> input) throws PluginException {
return input;
}
}
|
Stop creating an unbounded number of "Jack is my hero" files under Windows.
Not that Jack doesn't deserve them, but saying it so often cheapens the
sentiment. | #! /usr/bin/env python
"""Test script for the binhex C module
Uses the mechanism of the python binhex module
Roger E. Masse
"""
import binhex
import tempfile
from test_support import verbose, TestSkipped
def test():
try:
fname1 = tempfile.mktemp()
fname2 = tempfile.mktemp()
f = open(fname1, 'w')
except:
raise TestSkipped, "Cannot test binhex without a temp file"
start = 'Jack is my hero'
f.write(start)
f.close()
binhex.binhex(fname1, fname2)
if verbose:
print 'binhex'
binhex.hexbin(fname2, fname1)
if verbose:
print 'hexbin'
f = open(fname1, 'r')
finish = f.readline()
f.close() # on Windows an open file cannot be unlinked
if start != finish:
print 'Error: binhex != hexbin'
elif verbose:
print 'binhex == hexbin'
try:
import os
os.unlink(fname1)
os.unlink(fname2)
except:
pass
test()
| #! /usr/bin/env python
"""Test script for the binhex C module
Uses the mechanism of the python binhex module
Roger E. Masse
"""
import binhex
import tempfile
from test_support import verbose, TestSkipped
def test():
try:
fname1 = tempfile.mktemp()
fname2 = tempfile.mktemp()
f = open(fname1, 'w')
except:
raise TestSkipped, "Cannot test binhex without a temp file"
start = 'Jack is my hero'
f.write(start)
f.close()
binhex.binhex(fname1, fname2)
if verbose:
print 'binhex'
binhex.hexbin(fname2, fname1)
if verbose:
print 'hexbin'
f = open(fname1, 'r')
finish = f.readline()
if start != finish:
print 'Error: binhex != hexbin'
elif verbose:
print 'binhex == hexbin'
try:
import os
os.unlink(fname1)
os.unlink(fname2)
except:
pass
test()
|
Fix a bug on platform detection on Mac OSX | # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
| # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
|
Hide dogs without avatars on homepage slider, randomize dogs on homepage slider | var fs = require('fs');
var _ = require('underscore');
var Backbone = require('backbone');
var Flickity = require('flickity-imagesloaded');
var IndexDogListTemplate = fs.readFileSync(__dirname + '/IndexDogListTemplate.html', 'utf8');
var IndexDogListView = Backbone.View.extend({
template: _.template(IndexDogListTemplate),
initialize: function() {
this.render = _.bind(this.render, this);
this.collection.on('add update', this.render);
},
render: function() {
var dogs = this.collection.models.filter(function(dog) {
return !!(dog.get('avatar'));
}).map(function(dog) {
return dog.attributes;
});
this.$el.html(this.template({
dogs: _.shuffle(dogs)
}));
this.dogsSlider = new Flickity(this.el, {
cellAlign: 'left',
contain: true,
imagesLoaded: true,
percentPosition: true
});
}
});
module.exports = IndexDogListView;
| var fs = require('fs');
var _ = require('underscore');
var Backbone = require('backbone');
var Flickity = require('flickity-imagesloaded');
var IndexDogListTemplate = fs.readFileSync(__dirname + '/IndexDogListTemplate.html', 'utf8');
var IndexDogListView = Backbone.View.extend({
template: _.template(IndexDogListTemplate),
initialize: function() {
this.render = _.bind(this.render, this);
this.collection.on('add update', this.render);
},
render: function() {
this.$el.html(this.template({
dogs: this.collection.models.map(function(dog) {
return dog.attributes;
})
}));
this.dogsSlider = new Flickity(this.el, {
cellAlign: 'left',
contain: true,
imagesLoaded: true,
percentPosition: true
});
}
});
module.exports = IndexDogListView;
|
Add File to polyfills list | // Apply Node polyfills as necessary.
var window = {
Date: Date,
addEventListener: function() {},
removeEventListener: function() {}
};
var location = {
href: "",
host: "",
hostname: "",
protocol: "",
origin: "",
port: "",
pathname: "",
search: "",
hash: "",
username: "",
password: ""
};
var document = { body: {}, createTextNode: function() {}, location: location };
if (typeof FileList === "undefined") {
FileList = function() {};
}
if (typeof File === "undefined") {
File = function() {};
}
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function() {
return {
addEventListener: function() {},
open: function() {},
send: function() {}
};
};
var oldConsoleWarn = console.warn
console.warn = function () {
if (arguments.length === 1 && arguments[0].indexOf('Compiled in DEV mode') === 0) return
return oldConsoleWarn.apply(console, arguments)
}
}
if (typeof FormData === "undefined") {
FormData = function() {
this._data = [];
};
FormData.prototype.append = function() {
this._data.push(Array.prototype.slice.call(arguments));
};
}
| // Apply Node polyfills as necessary.
var window = {
Date: Date,
addEventListener: function() {},
removeEventListener: function() {}
};
var location = {
href: "",
host: "",
hostname: "",
protocol: "",
origin: "",
port: "",
pathname: "",
search: "",
hash: "",
username: "",
password: ""
};
var document = { body: {}, createTextNode: function() {}, location: location };
if (typeof FileList === "undefined") {
FileList = function() {};
}
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function() {
return {
addEventListener: function() {},
open: function() {},
send: function() {}
};
};
var oldConsoleWarn = console.warn
console.warn = function () {
if (arguments.length === 1 && arguments[0].indexOf('Compiled in DEV mode') === 0) return
return oldConsoleWarn.apply(console, arguments)
}
}
if (typeof FormData === "undefined") {
FormData = function() {
this._data = [];
};
FormData.prototype.append = function() {
this._data.push(Array.prototype.slice.call(arguments));
};
}
|
Fix naming and remove unnecessary [] | import React from 'react';
import { Link } from 'react-router';
import Tooltip from 'app/components/Tooltip';
import { FlexRow, FlexColumn, FlexItem } from 'app/components/FlexBox';
const Registration = ({ user }) => (
<Tooltip content={user.fullName}>
<Link to={`/users/${user.username}`} style={{ color: 'white' }}>
{user.firstName}
</Link>
</Tooltip>
);
const nameList = (registrations) => (
<FlexColumn>
{registrations.map((reg) => (
<FlexItem key={reg.id}>{reg.fullName}</FlexItem>
))}
</FlexColumn>
);
const RegistrationList = ({ registrations }) => (
<Tooltip content={nameList(registrations)} list>
{`${registrations.length} ${registrations.length === 1 ? 'annen' : 'andre'}`}
</Tooltip>
);
const RegisteredSummary = ({ registrations }) => (
<FlexRow>
{[<Registration key={0} user={registrations[0]} />,
',\u00A0',
<Registration key={1} user={registrations[1]} />,
'\u00A0og\u00A0',
<RegistrationList key={2} registrations={registrations.slice(2)} />,
'\u00A0er påmeldt']}
</FlexRow>
);
export default RegisteredSummary;
| import React from 'react';
import { Link } from 'react-router';
import Tooltip from 'app/components/Tooltip';
import { FlexRow, FlexColumn, FlexItem } from 'app/components/FlexBox';
const Reg = ({ user }) => (
<Tooltip content={user.fullName}>
<Link to={`/users/${user.username}`} style={{ color: 'white' }}>
{user.firstName}
</Link>
</Tooltip>
);
const namesList = (registrations) => (
<FlexColumn>
{registrations.map((reg) => (
<FlexItem key={reg.id}>{reg.fullName}</FlexItem>
))}
</FlexColumn>
);
const RegList = ({ registrations }) => (
<Tooltip content={namesList(registrations)} list>
{[`${registrations.length} ${registrations.length === 1 ? 'annen' : 'andre'}`]}
</Tooltip>
);
const RegisteredSummary = ({ registrations }) => (
<FlexRow>
{[<Reg key={0} user={registrations[0]} />,
',\u00A0',
<Reg key={1} user={registrations[1]} />,
'\u00A0og\u00A0',
<RegList key={2} registrations={registrations.slice(2)} />,
'\u00A0er påmeldt']}
</FlexRow>
);
export default RegisteredSummary;
|
Make sure powerline class knows that it will use UTF-8 | #!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
import time
from threading import Lock
from argparse import ArgumentParser
from powerline import Powerline
from powerline.lib.monotonic import monotonic
from powerline.lib.encoding import get_unicode_writer
class BarPowerline(Powerline):
get_encoding = staticmethod(lambda: 'utf-8')
def init(self):
super(BarPowerline, self).init(ext='wm', renderer_module='bar')
def render(event=None, data=None, sub=None):
global lock
with lock:
write(powerline.render())
write('\n')
sys.stdout.flush()
if __name__ == '__main__':
parser = ArgumentParser(description='Powerline BAR bindings.')
parser.add_argument(
'--i3', action='store_true',
help='Subscribe for i3 events.'
)
args = parser.parse_args()
powerline = BarPowerline()
interval = 0.5
lock = Lock()
write = get_unicode_writer(encoding='utf-8')
if args.i3:
import i3
sub = i3.Subscription(render, 'workspace')
while True:
start_time = monotonic()
render()
time.sleep(max(interval - (monotonic() - start_time), 0.1))
| #!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
import time
from threading import Lock
from argparse import ArgumentParser
from powerline import Powerline
from powerline.lib.monotonic import monotonic
from powerline.lib.encoding import get_unicode_writer
if __name__ == '__main__':
parser = ArgumentParser(description='Powerline BAR bindings.')
parser.add_argument(
'--i3', action='store_true',
help='Subscribe for i3 events.'
)
args = parser.parse_args()
powerline = Powerline('wm', renderer_module='bar')
powerline.update_renderer()
interval = 0.5
lock = Lock()
write = get_unicode_writer(encoding='utf-8')
def render(event=None, data=None, sub=None):
global lock
with lock:
write(powerline.render())
write('\n')
sys.stdout.flush()
if args.i3:
import i3
sub = i3.Subscription(render, 'workspace')
while True:
start_time = monotonic()
render()
time.sleep(max(interval - (monotonic() - start_time), 0.1))
|
Handle the case when pathSuffix is falsey | import Ember from 'ember';
import { inject as service } from '@ember/service';
import config from '../config/environment';
export default Ember.Route.extend({
queryParams: {
rd: {
refreshModel: true
}
},
routerService: service('-routing'),
model: function(params) {
// console.log("In login route");
var http = location.protocol;
var slashes = http.concat("//");
var ishttp = (location.port === '') || (location.port === 80) || (location.port === 443);
var host = slashes.concat(window.location.hostname) + (ishttp? "": ':'+location.port);
var pathSuffix = decodeURIComponent(params.rd) || "";
var redirectUrl = host;
// Append return route if one exists, ignore login route
if (pathSuffix && pathSuffix.indexOf('/login') === -1) {
redirectUrl += pathSuffix
}
// Append to query string if one exists, otherwise add one
if (redirectUrl.indexOf("?") !== -1) {
redirectUrl += "&token={girderToken}"
} else {
redirectUrl += "?token={girderToken}"
}
let url = config.apiUrl + '/oauth/provider?redirect=' + encodeURIComponent(redirectUrl);
return Ember.$.getJSON(url);
}
});
| import Ember from 'ember';
import { inject as service } from '@ember/service';
import config from '../config/environment';
export default Ember.Route.extend({
queryParams: {
rd: {
refreshModel: true
}
},
routerService: service('-routing'),
model: function(params) {
// console.log("In login route");
var http = location.protocol;
var slashes = http.concat("//");
var ishttp = (location.port === '') || (location.port === 80) || (location.port === 443);
var host = slashes.concat(window.location.hostname) + (ishttp? "": ':'+location.port);
var pathSuffix = decodeURIComponent(params.rd) || "";
// Append to query string if on exists, otherwise add one
if (pathSuffix.indexOf("?") !== -1) {
pathSuffix += "&token={girderToken}"
} else {
pathSuffix += "?token={girderToken}"
}
var redirectUrl = host + pathSuffix;
let url = config.apiUrl + '/oauth/provider?redirect=' + encodeURIComponent(redirectUrl);
return Ember.$.getJSON(url);
}
});
|
Use request and allow passing object | var request = require('request')
module.exports = function(options, cb) {
if ('string' === typeof options) {
options = {
uri: options
}
}
options = options || {}
options.method = 'HEAD'
options.followAllRedirects = true
request(options, function(err, res, body) {
if (err) return cb(err)
var code = res.statusCode
if (code >= 400) {
return cb(new Error('Received invalid status code: ' + code))
}
var len = res.headers['content-length']
if (!len) {
return cb(new Error('Unable to determine file size'))
}
if (isNaN(+len)) {
return cb(new Error('Invalid Content-Length received'))
}
cb(null, +res.headers['content-length'])
})
}
| var url = require('url')
module.exports = function(uri, cb) {
var parsed
try {
parsed = url.parse(uri)
}
catch (err) {
return cb(err)
}
if (!parsed.host) {
return cb(new Error('Invalid url: ' + uri))
}
var opts = {
host: parsed.host
, port: parsed.port
, path: parsed.path
, method: 'HEAD'
, agent: false
}
var http = parsed.protocol === 'https:'
? require('https')
: require('http')
var req = http.request(opts)
req.end()
req.on('response', function(res) {
var code = res.statusCode
if (code >= 400) {
return cb(new Error('Received invalid status code: ' + code))
}
cb(null, +res.headers['content-length'])
})
}
|
Add a make child of method | <?php namespace Modules\Menu\Entities;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Modules\Menu\Support\NestedCollection;
class Menuitem extends Model
{
use Translatable;
public $translatedAttributes = ['title', 'uri', 'url', 'status'];
protected $fillable = [
'menu_id',
'page_id',
'parent_id',
'position',
'target',
'module_name',
'title',
'uri',
'url',
'status',
'is_root',
];
/**
* For nested collection
*
* @var array
*/
public $children = [];
public function menu()
{
return $this->belongsTo('Modules\Menu\Entities\Menu');
}
/**
* Return a custom nested collection
*
* @param array $models
* @return NestedCollection
*/
public function newCollection(array $models = array())
{
return new NestedCollection($models);
}
public function makeChildOf($rootItem)
{
$this->parent_id = $rootItem->id;
}
}
| <?php namespace Modules\Menu\Entities;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Modules\Menu\Support\NestedCollection;
class Menuitem extends Model
{
use Translatable;
public $translatedAttributes = ['title', 'uri', 'url', 'status'];
protected $fillable = [
'menu_id',
'page_id',
'parent_id',
'position',
'target',
'module_name',
'title',
'uri',
'url',
'status',
'is_root',
];
/**
* For nested collection
*
* @var array
*/
public $children = [];
public function menu()
{
return $this->belongsTo('Modules\Menu\Entities\Menu');
}
/**
* Return a custom nested collection
*
* @param array $models
* @return NestedCollection
*/
public function newCollection(array $models = array())
{
return new NestedCollection($models);
}
}
|
Comment out method that put extra string into error message | package com.projectning.service.exceptions;
import com.projectning.util.ErrorMessage;
@SuppressWarnings("serial")
public class NotFoundException extends SdkException
{
private NotFoundExceptionType typeNotFound = NotFoundExceptionType.NOT_SPECIFIED;
// TODO: Could modify message to prepend with typeNotFound.toString()
public NotFoundException()
{
super(ErrorMessage.UNKNOWN_ERROR.getMsg());
}
public NotFoundException(NotFoundExceptionType typeNotFound)
{
super();
this.typeNotFound = typeNotFound;
}
public NotFoundException(String message)
{
super(message);
}
public NotFoundException(NotFoundExceptionType typeNotFound, String message)
{
super(message);
this.typeNotFound = typeNotFound;
}
public NotFoundException(Throwable cause)
{
super(cause);
}
public NotFoundException(NotFoundExceptionType typeNotFound, Throwable cause)
{
super(cause);
this.typeNotFound = typeNotFound;
}
public NotFoundException(String message, Throwable cause)
{
super(message, cause);
}
public NotFoundException(NotFoundExceptionType typeNotFound, String message, Throwable cause)
{
super(message, cause);
this.typeNotFound = typeNotFound;
}
public NotFoundExceptionType getType()
{
return this.typeNotFound;
}
/*
@Override
public String getMessage()
{
return this.typeNotFound.toString() + ": " + super.getMessage();
}
*/
}
| package com.projectning.service.exceptions;
import com.projectning.util.ErrorMessage;
@SuppressWarnings("serial")
public class NotFoundException extends SdkException
{
private NotFoundExceptionType typeNotFound = NotFoundExceptionType.NOT_SPECIFIED;
// TODO: Could modify message to prepend with typeNotFound.toString()
public NotFoundException()
{
super(ErrorMessage.UNKNOWN_ERROR.getMsg());
}
public NotFoundException(NotFoundExceptionType typeNotFound)
{
super();
this.typeNotFound = typeNotFound;
}
public NotFoundException(String message)
{
super(message);
}
public NotFoundException(NotFoundExceptionType typeNotFound, String message)
{
super(message);
this.typeNotFound = typeNotFound;
}
public NotFoundException(Throwable cause)
{
super(cause);
}
public NotFoundException(NotFoundExceptionType typeNotFound, Throwable cause)
{
super(cause);
this.typeNotFound = typeNotFound;
}
public NotFoundException(String message, Throwable cause)
{
super(message, cause);
}
public NotFoundException(NotFoundExceptionType typeNotFound, String message, Throwable cause)
{
super(message, cause);
this.typeNotFound = typeNotFound;
}
public NotFoundExceptionType getType()
{
return this.typeNotFound;
}
@Override
public String getMessage()
{
return this.typeNotFound.toString() + ": " + super.getMessage();
}
}
|
Apply spotless java google code format | /*
* Axelor Business Solutions
*
* Copyright (C) 2019 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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/>.
*/
package com.axelor.apps.stock.translation;
public interface ITranslation {
public static final String STOCK_APP_NAME = /*$$(*/ "value:Stock"; /*)*/
public static final String ABC_ANALYSIS_STOCK_LOCATION = /*$$(*/
"AbcAnalysis.stockLocation"; /*)*/
public static final String PICKING_STOCK_MOVE_NOTE = /*$$(*/ "PickingStockMove.note"; /*)*/
}
| /*
* Axelor Business Solutions
*
* Copyright (C) 2019 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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/>.
*/
package com.axelor.apps.stock.translation;
public interface ITranslation {
public static final String STOCK_APP_NAME = /*$$(*/ "value:Stock"; /*)*/
public static final String ABC_ANALYSIS_STOCK_LOCATION = /*$$(*/
"AbcAnalysis.stockLocation"; /*)*/
public static final String PICKING_STOCK_MOVE_NOTE = /*$$(*/
"PickingStockMove.note"; /*)*/
}
|
Fix link to nyc logo with temporary pointer to webpack-dev-server | "use strict";
import React, { Component } from 'react';
// Bootstrap
import { Grid, Row, Col, Navbar, NavItem, Nav } from 'react-bootstrap';
export default class Header extends Component {
render() {
return(
<Navbar inverse fixedTop>
<Navbar.Header>
<Navbar.Brand>
<img src='http://localhost:8081/assets/img/nyc-logo.png' />
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">Back To Top</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
| "use strict";
import React, { Component } from 'react';
// Bootstrap
import { Grid, Row, Col, Navbar, NavItem, Nav } from 'react-bootstrap';
export default class Header extends Component {
render() {
return(
<Navbar inverse fixedTop>
<Navbar.Header>
<Navbar.Brand>
<img src='/assets/img/nyc-logo.png' />
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">Back To Top</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
|
Add comments for file start/end | #!/usr/bin/env python
import sys
from os.path import basename, dirname, join
import re
INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"')
seen_files = set()
out = sys.stdout
def add_file(filename):
bname = basename(filename)
# Only include each file at most once.
if bname in seen_files:
return
seen_files.add(bname)
path = dirname(filename)
out.write('// Begin file "{0}"\n'.format(filename))
with open(filename, 'r') as f:
for line in f:
m = INCLUDE_PATTERN.match(line)
if m:
add_file(join(path, m.group(1)))
else:
out.write(line)
out.write('// End file "{0}"\n'.format(filename))
for f in sys.argv[1:]:
add_file(f)
| #!/usr/bin/env python
import sys
import os.path
import re
INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"')
seen_files = set()
def add_file(filename):
basename = os.path.basename(filename)
# Only include each file at most once.
if basename in seen_files:
return
seen_files.add(basename)
path = os.path.dirname(filename)
with open(filename, 'r') as f:
for line in f:
m = INCLUDE_PATTERN.match(line)
if m:
add_file(os.path.join(path, m.group(1)))
else:
sys.stdout.write(line)
for f in sys.argv[1:]:
add_file(f)
|
Fix small javascript issue when validating database connection for non SQLCE setups | angular.module("umbraco.install").controller("Umbraco.Installer.DataBaseController", function($scope, $http, installerService){
$scope.checking = false;
$scope.invalidDbDns = false;
$scope.dbs = [
{ name: 'Microsoft SQL Server Compact (SQL CE)', id: 0},
{ name: 'Microsoft SQL Server', id: 1},
{ name: 'Microsoft SQL Azure', id: 3 },
{ name: 'MySQL', id: 2 },
{ name: 'Custom connection string', id: -1}
];
if ( installerService.status.current.model.dbType === undefined ) {
installerService.status.current.model.dbType = 0;
}
$scope.validateAndForward = function(){
if ( !$scope.checking && this.myForm.$valid ) {
$scope.checking = true;
$scope.invalidDbDns = false;
var model = installerService.status.current.model;
$http.post(
Umbraco.Sys.ServerVariables.installApiBaseUrl + "PostValidateDatabaseConnection",
model ).then( function( response ) {
if ( response.data === true ) {
installerService.forward();
}
else {
$scope.invalidDbDns = true;
}
$scope.checking = false;
}, function(){
$scope.invalidDbDns = true;
$scope.checking = false;
});
}
};
});
| angular.module("umbraco.install").controller("Umbraco.Installer.DataBaseController", function($scope, $http, installerService){
$scope.checking = false;
$scope.invalidDbDns = false;
$scope.dbs = [
{ name: 'Microsoft SQL Server Compact (SQL CE)', id: 0},
{ name: 'Microsoft SQL Server', id: 1},
{ name: 'Microsoft SQL Azure', id: 3 },
{ name: 'MySQL', id: 2 },
{ name: 'Custom connection string', id: -1}
];
if ( installerService.status.current.model.dbType === undefined ) {
installerService.status.current.model.dbType = 0;
}
$scope.validateAndForward = function(){
if ( !$scope.checking && this.myForm.$valid ) {
$scope.checking = true;
$scope.invalidDbDns = false;
var model = installerService.status.current.model;
$http.post(
Umbraco.Sys.ServerVariables.installApiBaseUrl + "PostValidateDatabaseConnection",
model ).then( function( response ) {
if ( response.data === "true" ) {
installerService.forward();
}
else {
$scope.invalidDbDns = true;
}
$scope.checking = false;
}, function(){
$scope.invalidDbDns = true;
$scope.checking = false;
});
}
};
});
|
Fix de la page de démarrage |
angular.module('ModuleGlobal')
.controller('TopController', ['LoginService', '$location', function(LoginService, $location) {
var ctrl = this;
ctrl.error = {};
ctrl.error.badLogin = false;
ctrl.error.serverDown = false;
ctrl.identifier = LoginService.identifier;
ctrl.password = '';
ctrl.isConnected = function() {
return LoginService.isConnected();
};
ctrl.connect = function() {
LoginService.connect(ctrl.identifier, ctrl.password, ctrl.rememberMe).then(function(response) {
if(response.connected) {
ctrl.error = {};
ctrl.identifier = LoginService.identifier;
}
else {
if (response.status == 400 || response.status == 403) {
ctrl.error.badLogin = true;
}
else if (response.status == 500 || response.status == 503) {
ctrl.error.serverDown = true;
}
}
ctrl.password = '';
});
};
ctrl.disconnect = function() {
LoginService.disconnect();
};
}]);
|
angular.module('ModuleGlobal')
.controller('TopController', ['LoginService', '$location', function(LoginService, $location) {
var ctrl = this;
ctrl.error = {};
ctrl.error.badLogin = false;
ctrl.error.serverDown = false;
ctrl.identifier = LoginService.identifier;
ctrl.password = '';
ctrl.isConnected = function() {
return LoginService.isConnected();
};
ctrl.connect = function() {
LoginService.connect(ctrl.identifier, ctrl.password, ctrl.rememberMe).then(function(response) {
if(response.connected) {
$location.path('/media');
ctrl.error = {};
ctrl.identifier = LoginService.identifier;
}
else {
if (response.status == 400 || response.status == 403) {
ctrl.error.badLogin = true;
}
else if (response.status == 500 || response.status == 503) {
ctrl.error.serverDown = true;
}
}
ctrl.password = '';
});
};
ctrl.disconnect = function() {
LoginService.disconnect();
};
}]);
|
Define "HasShape" interface" to avoid dependency cycle. | package validates
const (
NON_POSITIVE_SIZE_PANIC = iota
DIFFERENT_SIZE_PANIC
OUT_OF_RANGE_PANIC
)
func ShapeShouldBePositive(row, column int) {
if row > 0 && column > 0 {
return
}
panic(NON_POSITIVE_SIZE_PANIC)
}
type HasShape interface {
Shape() (rows, columns int)
}
func ShapeShouldBeSame(m, n HasShape) {
mRow, mColumn := m.Shape()
nRow, nColumn := n.Shape()
if mRow == nRow && mColumn == nColumn {
return
}
panic(DIFFERENT_SIZE_PANIC)
}
func IndexShouldBeInRange(rows, columns, row, column int) {
if (0 <= row && row < rows) && (0 <= column && column < columns) {
return
}
panic(OUT_OF_RANGE_PANIC)
}
| package validates
import (
"github.com/mitsuse/matrix-go"
)
const (
NON_POSITIVE_SIZE_PANIC = iota
DIFFERENT_SIZE_PANIC
OUT_OF_RANGE_PANIC
)
func ShapeShouldBePositive(row, column int) {
if row > 0 && column > 0 {
return
}
panic(NON_POSITIVE_SIZE_PANIC)
}
func ShapeShouldBeSame(m, n matrix.Matrix) {
mRow, mColumn := m.Shape()
nRow, nColumn := n.Shape()
if mRow == nRow && mColumn == nColumn {
return
}
panic(DIFFERENT_SIZE_PANIC)
}
func IndexShouldBeInRange(rows, columns, row, column int) {
if (0 <= row && row < rows) && (0 <= column && column < columns) {
return
}
panic(OUT_OF_RANGE_PANIC)
}
|
Print the path when things don't work.
Signed-off-by: Ronald G. Minnich <f569d0af9a3481c4007b95c7180d6c41009f2513@gmail.com> | // Copyright 2012 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
sh reads in a line at a time and runs it.
prompt is '% '
*/
package main
import (
"os/exec"
"fmt"
"os"
"strings"
"bufio"
)
func main() {
if len(os.Args) != 1 {
fmt.Println("no scripts/args yet")
os.Exit(1)
}
scanner := bufio.NewScanner(os.Stdin)
fmt.Printf("%% ")
for scanner.Scan() {
cmd := scanner.Text()
argv := strings.Split(cmd, " ")
e := os.Environ()
e = append(e, "GOROOT=/go")
e = append(e, "GOPATH=/")
e = append(e, "GOBIN=/bin")
run := exec.Command(argv[0], argv[1:]...)
run.Env = e
out, err := run.CombinedOutput()
if err != nil {
fmt.Printf("%v: Path %v\n", err, os.Getenv("PATH"))
}
fmt.Printf("%s", out)
fmt.Printf("%% ")
}
}
| // Copyright 2012 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
sh reads in a line at a time and runs it.
prompt is '% '
*/
package main
import (
"os/exec"
"fmt"
"os"
"strings"
"bufio"
)
func main() {
if len(os.Args) != 1 {
fmt.Println("no scripts/args yet")
os.Exit(1)
}
scanner := bufio.NewScanner(os.Stdin)
fmt.Printf("%% ")
for scanner.Scan() {
cmd := scanner.Text()
argv := strings.Split(cmd, " ")
e := os.Environ()
e = append(e, "GOROOT=/go")
e = append(e, "GOPATH=/")
e = append(e, "GOBIN=/bin")
run := exec.Command(argv[0], argv[1:]...)
run.Env = e
out, err := run.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s", out)
fmt.Printf("%% ")
}
}
|
Disable mongo server for now | #!/usr/bin/python
# imports
from pprint import pprint
import urllib2
import socket
import sys
#import re
from bs4 import BeautifulSoup
from pymongo import MongoClient
# read the html content of the random pun page into a string
try:
html_content = urllib2.urlopen('http://www.punoftheday.com/cgi-bin/randompun.pl', timeout = 1).read()
except urllib2.URLError, e:
sys.stderr.write("(url error waiting for pun)\n")
sys.exit(1)
except socket.timeout, e:
sys.stderr.write("(socket timeout waiting for pun)\n")
sys.exit(1)
# create a beautiful soup object out of the raw html (the prettify is probably not necessary)
soup = BeautifulSoup(html_content, "html.parser")
soup.prettify()
# find and print the pun... it's the text in the element: div#main-content div.dropshadow1
pun = soup.find('div', {'id': 'main-content'}).find('div', {'class': 'dropshadow1'}).text
pun = pun.strip()
print pun
#try:
# client = MongoClient()
# db = client['pundb']
# collection = db['puns']
# punDict = {"full": pun}
# collection.update(punDict, punDict, True)
#except:
# # do nothing on insertion error
# pass
| #!/usr/bin/python
# imports
from pprint import pprint
import urllib2
import socket
import sys
#import re
from bs4 import BeautifulSoup
from pymongo import MongoClient
# read the html content of the random pun page into a string
try:
html_content = urllib2.urlopen('http://www.punoftheday.com/cgi-bin/randompun.pl', timeout = 1).read()
except urllib2.URLError, e:
sys.stderr.write("(url error waiting for pun)\n")
sys.exit(1)
except socket.timeout, e:
sys.stderr.write("(socket timeout waiting for pun)\n")
sys.exit(1)
# create a beautiful soup object out of the raw html (the prettify is probably not necessary)
soup = BeautifulSoup(html_content, "html.parser")
soup.prettify()
# find and print the pun... it's the text in the element: div#main-content div.dropshadow1
pun = soup.find('div', {'id': 'main-content'}).find('div', {'class': 'dropshadow1'}).text
pun = pun.strip()
print pun
try:
client = MongoClient()
db = client['pundb']
collection = db['puns']
punDict = {"full": pun}
collection.update(punDict, punDict, True)
except:
# do nothing on insertion error
pass
|
Update Dimensions when window resizes | /**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import debounce from 'lodash.debounce'
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
static set(): void {
dimensions.window = {
fontScale: 1,
height: win.innerHeight,
scale: win.devicePixelRatio || 1,
width: win.innerWidth
}
dimensions.screen = {
fontScale: 1,
height: win.screen.height,
scale: win.devicePixelRatio || 1,
width: win.screen.width
}
}
}
Dimensions.set();
ExecutionEnvironment.canUseDOM && window.addEventListener('resize', debounce(Dimensions.set, 50))
module.exports = Dimensions
| /**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {
screen: {
fontScale: 1,
get height() { return win.screen.height },
scale: win.devicePixelRatio || 1,
get width() { return win.screen.width }
},
window: {
fontScale: 1,
get height() { return win.innerHeight },
scale: win.devicePixelRatio || 1,
get width() { return win.innerWidth }
}
}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
}
module.exports = Dimensions
|
Update link to raw shuffle2.wav file | def cupid():
steptime = .4
kick_angle = -10
for i in range(4):
forward(1, steptime)
wait(steptime)
for i in range(4):
backward(1, steptime)
wait(steptime)
for i in range(2):
turnBy(kick_angle)
wait(.2)
turnBy(-kick_angle)
wait(.2)
kick_angle = -kick_angle
#wait(.5)
turnBy(-90)
from Myro import *
init("sim")
penDown()
# NOTE: be sure to download the wav file at https://github.com/CSavvy/python/blob/master/shuffle2.wav?raw=true
s = makeSound("shuffle2.wav")
for j in range(2): #set number of loops here
c = s.Play(0, 31500)
wait(5)
cupid()
wait(.5)
cupid()
| def cupid():
steptime = .4
kick_angle = -10
for i in range(4):
forward(1, steptime)
wait(steptime)
for i in range(4):
backward(1, steptime)
wait(steptime)
for i in range(2):
turnBy(kick_angle)
wait(.2)
turnBy(-kick_angle)
wait(.2)
kick_angle = -kick_angle
#wait(.5)
turnBy(-90)
from Myro import *
init("sim")
penDown()
# NOTE: be sure to download the wav file at https://github.com/CSavvy/python/blob/master/shuffle2.wav
s = makeSound("shuffle2.wav")
for j in range(2): #set number of loops here
c = s.Play(0, 31500)
wait(5)
cupid()
wait(.5)
cupid()
|
Remove importing of emit() as it's not needed. | import globals from './vars';
import hasOwn from '../util/has-own';
import typeElement from '../type/element';
var definitions = {};
var map = [];
var types = [];
export default globals.registerIfNotExists('registry', {
get (id) {
return hasOwn(definitions, id) && definitions[id];
},
set (id, opts) {
if (this.get(id)) {
throw new Error(`A Skate component with the name of "${id}" already exists.`);
}
var type = opts.type || typeElement;
var typeIndex = types.indexOf(type);
if (typeIndex === -1) {
typeIndex = types.length;
types.push(type);
map[typeIndex] = {};
}
definitions[id] = opts;
map[typeIndex][id] = opts;
return this;
},
find (elem) {
var filtered = [];
var typesLength = types.length;
for (let a = 0; a < typesLength; a++) {
filtered = filtered.concat(types[a].filter(elem, map[a]) || []);
}
return filtered;
}
});
| import apiEmit from '../api/emit';
import globals from './vars';
import hasOwn from '../util/has-own';
import typeElement from '../type/element';
var definitions = {};
var map = [];
var types = [];
export default globals.registerIfNotExists('registry', {
get (id) {
return hasOwn(definitions, id) && definitions[id];
},
set (id, opts) {
if (this.get(id)) {
throw new Error(`A Skate component with the name of "${id}" already exists.`);
}
var type = opts.type || typeElement;
var typeIndex = types.indexOf(type);
if (typeIndex === -1) {
typeIndex = types.length;
types.push(type);
map[typeIndex] = {};
}
definitions[id] = opts;
map[typeIndex][id] = opts;
return this;
},
find (elem) {
var filtered = [];
var typesLength = types.length;
for (let a = 0; a < typesLength; a++) {
filtered = filtered.concat(types[a].filter(elem, map[a]) || []);
}
return filtered;
}
});
|
Disable the test as it fail | /*
* Copyright (c) 2011 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.ning.http.client.async.grizzly;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.async.ByteBufferCapacityTest;
import com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider;
import org.testng.annotations.Test;
public class GrizzlyByteBufferCapacityTest extends ByteBufferCapacityTest {
@Override
public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
if (config == null) {
config = new AsyncHttpClientConfig.Builder().build();
}
return new AsyncHttpClient(new GrizzlyAsyncHttpProvider(config), config);
}
@Test(groups = {"standalone", "default_provider"}, enabled=false)
public void basicByteBufferTest() throws Throwable {
}
}
| /*
* Copyright (c) 2011 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.ning.http.client.async.grizzly;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.async.ByteBufferCapacityTest;
import com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider;
public class GrizzlyByteBufferCapacityTest extends ByteBufferCapacityTest {
@Override
public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
if (config == null) {
config = new AsyncHttpClientConfig.Builder().build();
}
return new AsyncHttpClient(new GrizzlyAsyncHttpProvider(config), config);
}
}
|
Add comment block to unit helper method | <?php namespace Worldpay;
class Translate {
/**
* Set Test Mode
*
* Convert WorldPay environment from string to integer
*
* @var $input string
* @return integer
*/
public static function setTestMode($input)
{
if($input == 'production'){return 0;}
return 100;
}
/**
* Get Test Mode
*
* Convert WorldPay environment from integer to string
*
* @var $input integer
* @return string
*/
public static function getTestMode($input)
{
if($input == 0){return 'production';}
return 'development';
}
/**
* Unit
*
* Convert interval string into correct WorldPay parameter
*
* @var $input string
* @return integer
*/
public static function unit($input)
{
$units = array('day' => 1, 'week' => 2, 'month' => 3, 'year' => 4);
return $units[rtrim($input, 's')];
}
}
| <?php namespace Worldpay;
class Translate {
/**
* Set Test Mode
*
* Convert WorldPay environment from string to integer
*
* @var $input string
* @return integer
*/
public static function setTestMode($input)
{
if($input == 'production'){return 0;}
return 100;
}
/**
* Get Test Mode
*
* Convert WorldPay environment from integer to string
*
* @var $input integer
* @return string
*/
public static function getTestMode($input)
{
if($input == 0){return 'production';}
return 'development';
}
public static function unit($input)
{
$units = array('day' => 1, 'week' => 2, 'month' => 3, 'year' => 4);
return $units[rtrim($input, 's')];
}
}
|
Add a delete method to the user repository for testing purposes. | /*
* Copyright 2014 Open mHealth
*
* 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 org.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.User;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of user accounts.
*
* @author Emerson Farrugia
*/
public interface UserRepository extends Repository<User, String> {
/**
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
*/
Optional<User> findOne(String username);
/**
* @see org.springframework.data.repository.CrudRepository#save(Object)
*/
User save(User user);
/**
* @see org.springframework.data.repository.CrudRepository#delete(java.io.Serializable)
*/
void delete(String username);
}
| /*
* Copyright 2014 Open mHealth
*
* 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 org.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.User;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of user accounts.
*
* @author Emerson Farrugia
*/
public interface UserRepository extends Repository<User, String> {
/**
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
*/
Optional<User> findOne(String username);
/**
* @see org.springframework.data.repository.CrudRepository#save(Object)
*/
User save(User user);
}
|
Use `traverse()` instead of the deprecated `Walker` class | 'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
if ('sexpr' in node) {
node = node.sexpr;
}
node.params = node.params.filter(function(param) {
return !isTestSelector(param.original);
});
node.hash.pairs = node.hash.pairs.filter(function(pair) {
return !isTestSelector(pair.key);
});
}
function StripTestSelectorsTransform() {
this.syntax = null;
}
StripTestSelectorsTransform.prototype.transform = function(ast) {
let { traverse } = this.syntax;
traverse(ast, {
ElementNode(node) {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
},
MustacheStatement(node) {
stripTestSelectors(node);
},
BlockStatement(node) {
stripTestSelectors(node);
},
});
return ast;
};
module.exports = StripTestSelectorsTransform;
| 'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
if ('sexpr' in node) {
node = node.sexpr;
}
node.params = node.params.filter(function(param) {
return !isTestSelector(param.original);
});
node.hash.pairs = node.hash.pairs.filter(function(pair) {
return !isTestSelector(pair.key);
});
}
function StripTestSelectorsTransform() {
this.syntax = null;
}
StripTestSelectorsTransform.prototype.transform = function(ast) {
let walker = new this.syntax.Walker();
walker.visit(ast, function(node) {
if (node.type === 'ElementNode') {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
} else if (node.type === 'MustacheStatement' || node.type === 'BlockStatement') {
stripTestSelectors(node);
}
});
return ast;
};
module.exports = StripTestSelectorsTransform;
|
Add long description for PyPI | """
Copyright 2017 BlazeMeter Inc.
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.
"""
from setuptools import setup
setup(
name="apiritif",
packages=['apiritif'],
version="0.6.1",
description='Python framework for API testing',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
license='Apache 2.0',
platform='any',
author='Dimitri Pribysh',
author_email='pribysh@blazemeter.com',
url='https://github.com/Blazemeter/apiritif',
download_url='https://github.com/Blazemeter/apiritif',
docs_url='https://github.com/Blazemeter/apiritif',
install_requires=['requests>=2.11.1', 'jsonpath-rw', 'lxml'],
)
| """
Copyright 2017 BlazeMeter Inc.
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.
"""
from setuptools import setup
setup(
name="apiritif",
packages=['apiritif'],
version="0.6.1",
description='Python framework for API testing',
license='Apache 2.0',
platform='any',
author='Dimitri Pribysh',
author_email='pribysh@blazemeter.com',
url='https://github.com/Blazemeter/apiritif',
download_url='https://github.com/Blazemeter/apiritif',
docs_url='https://github.com/Blazemeter/apiritif',
install_requires=['requests>=2.11.1', 'jsonpath-rw', 'lxml'],
)
|
Update batch execute for conditions | # coding=utf-8
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from push.models import DeviceTokenModel, NotificationModel
from datetime import datetime
import push_notification
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
def handle(self, *args, **kwargs):
now = '{0:%Y/%m/%d %H:%M}'.format(datetime.now())
notifications = NotificationModel.objects.filter(execute_datetime = now, is_sent = False)
for notification in notifications:
device_tokens = DeviceTokenModel.objects.filter(os_version__gte = notification.os_version,
username = notification.username)
self.prepare_push_notification(notification, device_tokens)
def prepare_push_notification(self, notification, device_tokens):
device_token_lists = []
for item in device_tokens:
device_token_lists.append(item.device_token)
push_notification.execute(device_token_lists, notification)
| # coding=utf-8
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from push.models import DeviceTokenModel, NotificationModel
from datetime import datetime
import push_notification
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
def handle(self, *args, **kwargs):
now = '{0:%Y/%m/%d %H:%M}'.format(datetime.now())
notifications = NotificationModel.objects.filter(execute_datetime = now)
for notification in notifications:
device_tokens = DeviceTokenModel.objects.filter(os_version__gte = notification.os_version,
username = notification.username)
self.prepare_push_notification(notification, device_tokens)
def prepare_push_notification(self, notification, device_tokens):
device_token_lists = []
for item in device_tokens:
device_token_lists.append(item.device_token)
push_notification.execute(device_token_lists, notification)
|
Check if values are set or not | <?php
/**
* @package content
*/
/**
* The AjaxTranslate page is used for translating strings on the fly
* that are used in Symphony's javascript
*/
Class contentAjaxTranslate extends AjaxPage{
public function handleFailedAuthorisation(){
$this->_status = self::STATUS_UNAUTHORISED;
$this->_Result = json_encode(array('status' => __('You are not authorised to access this page.')));
}
public function view(){
$strings = $_GET['strings'];
$namespace = (empty($_GET['namespace']) ? null : $_GET['namespace']);
$new = array();
foreach($strings as $key => $value) {
// Check value
if(empty($value) || $value = 'false') {
$value = $key;
}
// Translate
$new[$value] = Lang::translate(urldecode($value), null, $namespace);
}
$this->_Result = json_encode($new);
}
public function generate(){
header('Content-Type: application/json');
echo $this->_Result;
exit;
}
}
| <?php
/**
* @package content
*/
/**
* The AjaxTranslate page is used for translating strings on the fly
* that are used in Symphony's javascript
*/
Class contentAjaxTranslate extends AjaxPage{
public function handleFailedAuthorisation(){
$this->_status = self::STATUS_UNAUTHORISED;
$this->_Result = json_encode(array('status' => __('You are not authorised to access this page.')));
}
public function view(){
$strings = $_GET['strings'];
$namespace = (empty($_GET['namespace']) ? null : $_GET['namespace']);
$new = array();
foreach($strings as $key => $value) {
// Check value
$value = urldecode($value);
if(empty($value)) {
$value = urldecode($key);
}
// Translate
$new[$value] = Lang::translate($value, null, $namespace);
}
$this->_Result = json_encode($new);
}
public function generate(){
header('Content-Type: application/json');
echo $this->_Result;
exit;
}
}
|
Remove unused dependencies from enviornment_browser.js | "use strict";
var toplevel = global.window || global;
function getPrefixedProperty (object, name) {
if (object == null) {
return;
}
var capitalizedName = name.charAt(0).toUpperCase() + name.slice(1);
var prefixedNames = [name, 'webkit' + capitalizedName, 'moz' + capitalizedName];
for (var i in prefixedNames) {
var property = object[prefixedNames[i]];
if (property) {
return property.bind(object);
}
}
}
module.exports = {
WebSocket: toplevel.WebSocket,
Transport: require('./Transport'),
open: toplevel.open,
Promise: toplevel.Promise,
timers: toplevel,
// Console is not defined in ECMAScript, so just in case...
console: toplevel.console || {
debug: function () {},
log: function () {},
warn: function () {},
error: function () {}
},
addEventListener: getPrefixedProperty(toplevel, 'addEventListener'),
removeEventListener: getPrefixedProperty(toplevel, 'removeEventListener'),
HTMLMediaElement: toplevel.HTMLMediaElement,
};
| "use strict";
var toplevel = global.window || global;
function getPrefixedProperty (object, name) {
if (object == null) {
return;
}
var capitalizedName = name.charAt(0).toUpperCase() + name.slice(1);
var prefixedNames = [name, 'webkit' + capitalizedName, 'moz' + capitalizedName];
for (var i in prefixedNames) {
var property = object[prefixedNames[i]];
if (property) {
return property.bind(object);
}
}
}
module.exports = {
WebSocket: toplevel.WebSocket,
Transport: require('./Transport'),
open: toplevel.open,
Promise: toplevel.Promise,
timers: toplevel,
// Console is not defined in ECMAScript, so just in case...
console: toplevel.console || {
debug: function () {},
log: function () {},
warn: function () {},
error: function () {}
},
MediaStream: getPrefixedProperty(toplevel, 'MediaStream'),
getUserMedia: getPrefixedProperty(toplevel.navigator, 'getUserMedia'),
RTCPeerConnection: getPrefixedProperty(toplevel, 'RTCPeerConnection'),
RTCSessionDescription: getPrefixedProperty(toplevel, 'RTCSessionDescription'),
addEventListener: getPrefixedProperty(toplevel, 'addEventListener'),
removeEventListener: getPrefixedProperty(toplevel, 'removeEventListener'),
HTMLMediaElement: toplevel.HTMLMediaElement,
attachMediaStream: toplevel.attachMediaStream,
createObjectURL: toplevel.URL && toplevel.URL.createObjectURL,
revokeObjectURL: toplevel.URL && toplevel.URL.revokeObjectURL
};
|
Add error log to test | export class ValidationError extends Error {
name = 'ValidationError'
status = 400
constructor(error) {
super(error.message);
this.payload = {
...error,
name: this.name
};
}
}
export class ControllerValidationError extends Error {
name = 'ControllerValidationError';
status = 400;
constructor(errorMessage) {
super(errorMessage);
this.message = errorMessage;
}
}
export class RequestError extends Error {
name = 'RequestError'
status = 400
}
export class NotFoundError extends Error {
name = 'NotFoundError'
message = 'Could not find the entity';
status = 404;
}
export function errorMiddleware(err, req, res, next) {
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
console.log(err.stack);
}
const status = err.status || 500;
return res
.status(status)
.json(err.payload || {
name: err.name,
message: err.message
});
}
export function pageNotFoundMiddleware(req, res) {
res
.status(404)
.json({
message: 'Page Not Found'
});
}
| export class ValidationError extends Error {
name = 'ValidationError'
status = 400
constructor(error) {
super(error.message);
this.payload = {
...error,
name: this.name
};
}
}
export class ControllerValidationError extends Error {
name = 'ControllerValidationError';
status = 400;
constructor(errorMessage) {
super(errorMessage);
this.message = errorMessage;
}
}
export class RequestError extends Error {
name = 'RequestError'
status = 400
}
export class NotFoundError extends Error {
name = 'NotFoundError'
message = 'Could not find the entity';
status = 404;
}
export function errorMiddleware(err, req, res, next) {
if (process.env.NODE_ENV === 'development') {
console.log(err.stack);
}
const status = err.status || 500;
return res
.status(status)
.json(err.payload || {
name: err.name,
message: err.message
});
}
export function pageNotFoundMiddleware(req, res) {
res
.status(404)
.json({
message: 'Page Not Found'
});
}
|
Modify the style of logged in caption.
- Change it to a button, same style as not logged in yet. | import React from 'react';
import Layout from './layout';
const Introduction = () => (
<p>
Depcheck looks at your project files and scans your code to find any unused dependencies. Get rid of useless dependencies, and ship clean package.
</p>
);
const Logo = () => (
<img
src="/assets/logo-480.jpg"
className="img-responsive center-block"
alt="Depcheck Logo"
/>
);
const Login = () => (
<a className="btn btn-default" href="/login/github">
Login with GitHub Account
</a>
);
const Welcome = ({ login, repoListUrl }) => (
<a className="btn btn-default" href={repoListUrl}>
Logged in as <mark>{login.provider}/{login.user}</mark>
</a>
);
export default React.createClass({
render() {
return (
<Layout>
<h1 className="text-center">Depcheck</h1>
<div className="row">
<div className="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<Introduction />
<p className="text-center">
{this.props.login ? <Welcome {...this.props} /> : <Login />}
</p>
</div>
</div>
<Logo />
</Layout>
);
},
});
| import React from 'react';
import Layout from './layout';
const Introduction = () => (
<p>
Depcheck looks at your project files and scans your code to find any unused dependencies. Get rid of useless dependencies, and ship clean package.
</p>
);
const Logo = () => (
<img
src="/assets/logo-480.jpg"
className="img-responsive center-block"
alt="Depcheck Logo"
/>
);
const Login = () => (
<p className="text-center">
<a className="btn btn-default" href="/login/github">
Login with GitHub Account
</a>
</p>
);
const Welcome = ({ login, repoListUrl }) => (
<p>
Logged in as <mark>{login.provider}/{login.user}</mark>. Go to <a href={repoListUrl}>repository list</a>.
</p>
);
export default React.createClass({
render() {
return (
<Layout>
<h1 className="text-center">Depcheck</h1>
<div className="row">
<div className="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<Introduction />
{this.props.login ? <Welcome {...this.props} /> : <Login />}
</div>
</div>
<Logo />
</Layout>
);
},
});
|
Replace & in source with & in output
Avoid accidental HTML entitites by escaping '&' in input with '&' so
that the code output can really be treated as raw code. | <?php
class GoogleCodePrettify {
public static $prettified = false;
public static function parserHook($text, $args = array(), $parser) {
$pre_classes = '';
if (isset($args['lang']) && $args['lang']) {
$lang = $args['lang'];
$pre_classes .= " lang-$lang";
}
if (isset($args['class']) && $args['class']) {
$pre_classes .= ' '. $args['class'];
}
# Replace all '&', '<,' and '>' with their HTML entitites. Order is
# important. You have to do '&' first.
#
$text = str_replace('&', '&', $text);
$text = str_replace('<', '<', $text);
$text = str_replace('>', '>', $text);
self::$prettified = true;
return "<pre class=\"prettyprint$pre_classes\">$text</pre>";
}
public static function beforePageDisplay(&$wgOut, &$sk) {
$wgOut->addModules('ext.GoogleCodePrettify');
// Continue
return true;
}
}
| <?php
class GoogleCodePrettify {
public static $prettified = false;
public static function parserHook($text, $args = array(), $parser) {
$pre_classes = '';
if (isset($args['lang']) && $args['lang']) {
$lang = $args['lang'];
$pre_classes .= " lang-$lang";
}
if (isset($args['class']) && $args['class']) {
$pre_classes .= ' '. $args['class'];
}
# Replace all < and > with their HTML entitites
#
$text = str_replace('<', '<', $text);
$text = str_replace('>', '>', $text);
self::$prettified = true;
return "<pre class=\"prettyprint$pre_classes\">$text</pre>";
}
public static function beforePageDisplay(&$wgOut, &$sk) {
$wgOut->addModules('ext.GoogleCodePrettify');
// Continue
return true;
}
}
|
Fix admin ui for store promo rules
The data is nested under the "stores" attribute.
Closes #11 | $.fn.storeAutocomplete = function() {
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function(element, callback) {
$.get(Spree.routes.store_search, { ids: element.val() }, function(data) {
callback(data.stores)
})
},
ajax: {
url: Spree.routes.store_search,
datatype: 'json',
data: function(term, page) {
return { q: term }
},
results: function(data, page) {
return { results: data.stores }
}
},
formatResult: function(store) {
return store.name;
},
formatSelection: function(store) {
return store.name;
},
id: function(store) {
return store.id
}
});
}
$(document).ready(function () {
$('.store_picker').storeAutocomplete();
})
| $.fn.storeAutocomplete = function() {
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function(element, callback) {
$.get(Spree.routes.store_search, { ids: element.val() }, function(data) {
callback(data)
})
},
ajax: {
url: Spree.routes.store_search,
datatype: 'json',
data: function(term, page) {
return { q: term }
},
results: function(data, page) {
return { results: data }
}
},
formatResult: function(store) {
return store.name;
},
formatSelection: function(store) {
return store.name;
},
id: function(store) {
return store.id
}
});
}
$(document).ready(function () {
$('.store_picker').storeAutocomplete();
})
|
FIX sample data load for Windows | import cPickle
from os.path import dirname
from os.path import join
import numpy as np
def load_letters():
"""Load the OCR letters dataset.
This is a chain classification task.
Each example consists of a word, segmented into letters.
The first letter of each word is ommited from the data,
as it was a capital letter (in contrast to all other letters).
"""
module_path = dirname(__file__)
data_file = open(join(module_path, 'letters.pickle'),'rb')
data = cPickle.load(data_file)
# we add an easy to use image representation:
data['images'] = [np.hstack([l.reshape(16, 8) for l in word])
for word in data['data']]
return data
def load_scene():
module_path = dirname(__file__)
data_file = open(join(module_path, 'scene.pickle'))
return cPickle.load(data_file)
def load_snakes():
module_path = dirname(__file__)
data_file = open(join(module_path, 'snakes.pickle'))
return cPickle.load(data_file)
| import cPickle
from os.path import dirname
from os.path import join
import numpy as np
def load_letters():
"""Load the OCR letters dataset.
This is a chain classification task.
Each example consists of a word, segmented into letters.
The first letter of each word is ommited from the data,
as it was a capital letter (in contrast to all other letters).
"""
module_path = dirname(__file__)
data_file = open(join(module_path, 'letters.pickle'))
data = cPickle.load(data_file)
# we add an easy to use image representation:
data['images'] = [np.hstack([l.reshape(16, 8) for l in word])
for word in data['data']]
return data
def load_scene():
module_path = dirname(__file__)
data_file = open(join(module_path, 'scene.pickle'))
return cPickle.load(data_file)
def load_snakes():
module_path = dirname(__file__)
data_file = open(join(module_path, 'snakes.pickle'))
return cPickle.load(data_file)
|
Fix isBuildable() in buildable repository. | /*
* Copyright 2015 The original authors.
*
* 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 io.sundr.builder.internal;
import javax.lang.model.element.TypeElement;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
public class BuildableRepository {
private final Set<TypeElement> buildables = new LinkedHashSet<>();
public void register(TypeElement buildable) {
buildables.add(buildable);
}
public Set<TypeElement> getBuildables() {
return Collections.unmodifiableSet(buildables);
}
public boolean isBuildable(TypeElement buildable) {
return buildable != null && buildables.contains(buildable);
}
public void clear() {
buildables.clear();
}
}
| /*
* Copyright 2015 The original authors.
*
* 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 io.sundr.builder.internal;
import javax.lang.model.element.TypeElement;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
public class BuildableRepository {
private final Set<TypeElement> buildables = new LinkedHashSet<>();
public void register(TypeElement buildable) {
buildables.add(buildable);
}
public Set<TypeElement> getBuildables() {
return Collections.unmodifiableSet(buildables);
}
public boolean isBuildable(TypeElement buildable) {
return buildable != null && buildables.contains(buildable.getQualifiedName().toString());
}
public void clear() {
buildables.clear();
}
}
|
Use HTTPS for GitHub URLs | #!/usr/bin/env python
from __future__ import print_function
from codecs import open
from setuptools import setup
setup(name="abzer",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["abzer"],
package_dir={"abzer": "abzer"},
download_url=["https://github.com/mineo/abzer/tarball/master"],
url=["https://github.com/mineo/abzer"],
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5"],
description="AcousticBrainz submission tool",
long_description=open("README.txt", encoding="utf-8").read(),
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "abzer/version.py"},
install_requires=["aiohttp"],
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']},
python_requires='>=3.5',
entry_points={
'console_scripts': ['abzer=abzer.__main__:main']
}
)
| #!/usr/bin/env python
from __future__ import print_function
from codecs import open
from setuptools import setup
setup(name="abzer",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["abzer"],
package_dir={"abzer": "abzer"},
download_url=["https://github.com/mineo/abzer/tarball/master"],
url=["http://github.com/mineo/abzer"],
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5"],
description="AcousticBrainz submission tool",
long_description=open("README.txt", encoding="utf-8").read(),
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "abzer/version.py"},
install_requires=["aiohttp"],
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']},
python_requires='>=3.5',
entry_points={
'console_scripts': ['abzer=abzer.__main__:main']
}
)
|
[UPDATE] Return Toggle Todo Object Assign | /*
* Avoiding Object Mutations.
*
* @author: Francisco Maria Calisto
*
*/
const toggleTodo = (todo) => {
return Object.assign({}, todo, {
completed: !todo.completed
});
};
const testToggleTodo = () => {
const todoBefore = {
id: 0,
text: 'Learn Redux',
completed: false
};
const todoAfter = {
id: 0,
text: 'Learn Redux',
completed: true
};
deepFreeze(todoBefore);
expect(
toggleTodo(todoBefore)
).toEqual(todoAfter);
};
testToggleTodo();
console.log('All tests passed.');
| /*
* Avoiding Object Mutations.
*
* @author: Francisco Maria Calisto
*
*/
const toggleTodo = (todo) => {
return {
id: todo.id,
text: todo.text,
completed: !todo.completed
};
};
const testToggleTodo = () => {
const todoBefore = {
id: 0,
text: 'Learn Redux',
completed: false
};
const todoAfter = {
id: 0,
text: 'Learn Redux',
completed: true
};
deepFreeze(todoBefore);
expect(
toggleTodo(todoBefore)
).toEqual(todoAfter);
};
testToggleTodo();
console.log('All tests passed.');
|
Fix filename in generated tsconfig
The generated JavaScript file ends with `.js` and therefore we
should list the full name in our tsconfig as well. We ran into
compilation issues on https://crrev.com/c/3073941 and they required
the full extension to be listed. It's not clear to me why we
didn't run into this before, but it doesn't seem to break
any of the existing CSS file inclusions either.
R=993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org
CC=alexrudenko@chromium.org,kritisapra@google.com
Bug: 1106746
Change-Id: I45d593f4aee56b783349c82ea91cbde9b2db7d66
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3075188
Commit-Queue: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org>
Commit-Queue: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org>
Auto-Submit: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org>
Reviewed-by: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org> | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const fs = require('fs');
const path = require('path');
const CleanCSS = require('clean-css');
const [, , isDebugString, targetName, srcDir, targetGenDir, files] = process.argv;
const filenames = files.split(',');
const configFiles = [];
const cleanCSS = new CleanCSS();
const isDebug = isDebugString === 'true';
for (const fileName of filenames) {
let output = fs.readFileSync(path.join(srcDir, fileName), {encoding: 'utf8', flag: 'r'});
output = output.replace(/\`/g, '\\\'');
fs.writeFileSync(
path.join(targetGenDir, fileName + '.js'),
`// Copyright ${new Date().getFullYear()} The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const styles = new CSSStyleSheet();
styles.replaceSync(
\`${isDebug ? output : cleanCSS.minify(output).styles}
/*# sourceURL=${fileName} */
\`);
export default styles;
`);
configFiles.push(`\"${fileName}.js\"`);
}
fs.writeFileSync(path.join(targetGenDir, `${targetName}-tsconfig.json`), `{
"compilerOptions": {
"composite": true,
"outDir": "."
},
"files": [
${configFiles.join(',\n ')}
]
}
`);
| // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const fs = require('fs');
const path = require('path');
const CleanCSS = require('clean-css');
const [, , isDebugString, targetName, srcDir, targetGenDir, files] = process.argv;
const filenames = files.split(',');
const configFiles = [];
const cleanCSS = new CleanCSS();
const isDebug = isDebugString === 'true';
for (const fileName of filenames) {
let output = fs.readFileSync(path.join(srcDir, fileName), {encoding: 'utf8', flag: 'r'});
output = output.replace(/\`/g, '\\\'');
fs.writeFileSync(
path.join(targetGenDir, fileName + '.js'),
`// Copyright ${new Date().getFullYear()} The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const styles = new CSSStyleSheet();
styles.replaceSync(
\`${isDebug ? output : cleanCSS.minify(output).styles}
/*# sourceURL=${fileName} */
\`);
export default styles;
`);
configFiles.push(`\"${fileName}\"`);
}
fs.writeFileSync(path.join(targetGenDir, `${targetName}-tsconfig.json`), `{
"compilerOptions": {
"composite": true,
"outDir": "."
},
"files": [
${configFiles.join(',\n ')}
]
}
`);
|
Fix the required package name | #!/usr/bin/env python3
from distutils.core import setup
version = "0.0.1"
setup(
name = 'homer',
packages = ['homer'],
license = 'MIT',
version = version,
description = 'Homer is a config handler tool.',
author = 'Manoel Carvalho',
author_email = 'manoelhc@gmail.com',
url = 'https://github.com/manoelhc/homer', # use the URL to the github repo
download_url = 'https://github.com/manoelhc/homer', # I'll explain this in a second
keywords = ['testing', 'configuration'], # arbitrary keywords
install_requires=[
'pycrypto'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
)
| #!/usr/bin/env python3
from distutils.core import setup
version = "0.0.1"
setup(
name = 'homer',
packages = ['homer'],
license = 'MIT',
version = version,
description = 'Homer is a config handler tool.',
author = 'Manoel Carvalho',
author_email = 'manoelhc@gmail.com',
url = 'https://github.com/manoelhc/homer', # use the URL to the github repo
download_url = 'https://github.com/manoelhc/homer', # I'll explain this in a second
keywords = ['testing', 'configuration'], # arbitrary keywords
install_requires=[
'Crypto'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
)
|
Improve readability on error handling. | var logger = require('../support/logger');
var ItemSchema = require('../domain/item-schema');
var instanceSchemaCorrelator = require('../http/instance-schema-correlator');
var instanceRequest = module.exports = {
handle: function(ljsReq, res, callback) {
var collectionName = ljsReq.ljsUrl().collectionName;
ItemSchema.findByCollectionName(collectionName, function(err, itemSchema) {
if (err) { return callback(err); };
if (itemSchema) {
handleRequest(itemSchema, ljsReq);
handleResponse(itemSchema, ljsReq, res);
}
callback();
});
}
};
function handleRequest(itemSchema, ljsReq) {
itemSchema.registerLoopbackModel(ljsReq.req.app);
logger.info('Loopback Model created for JSON Schema collectionName: ', itemSchema.collectionName);
};
function handleResponse(itemSchema, ljsReq, res) {
instanceSchemaCorrelator.correlate(itemSchema, ljsReq, res);
};
| var logger = require('../support/logger');
var ItemSchema = require('../domain/item-schema');
var instanceSchemaCorrelator = require('../http/instance-schema-correlator');
var instanceRequest = module.exports = {
handle: function(ljsReq, res, callback) {
var collectionName = ljsReq.ljsUrl().collectionName;
ItemSchema.findByCollectionName(collectionName, function(err, itemSchema) {
if (err) {
callback(err);
} else {
if (itemSchema) {
handleRequest(itemSchema, ljsReq);
handleResponse(itemSchema, ljsReq, res);
}
callback();
}
});
}
};
function handleRequest(itemSchema, ljsReq) {
itemSchema.registerLoopbackModel(ljsReq.req.app);
logger.info('Loopback Model created for JSON Schema collectionName: ', itemSchema.collectionName);
};
function handleResponse(itemSchema, ljsReq, res) {
instanceSchemaCorrelator.correlate(itemSchema, ljsReq, res);
};
|
Allow configuration methods to be chained. | <?php
namespace Howtomakeaturn\Db2d;
use Ifsnop\Mysqldump\Mysqldump;
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxFile;
class Db2d
{
private $dumper;
private $uploader;
public function configureDatabase($db, $username, $password)
{
$this->dumper = new Mysqldump("mysql:host=localhost;dbname=$db", $username, $password);
return $this;
}
public function configureDropbox($key, $secret, $token)
{
$app = new DropboxApp($key, $secret, $token);
$this->uploader = new Dropbox($app);
return $this;
}
public function backup()
{
$name = 'backup-' . date('Ymd-H-i-s') . '.sql';
$this->dumper->start($name);
$dropboxFile = new DropboxFile($name);
$file = $this->uploader->upload($dropboxFile, "/$name", ['autorename' => true]);
unlink($name);
}
}
| <?php
namespace Howtomakeaturn\Db2d;
use Ifsnop\Mysqldump\Mysqldump;
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxFile;
class Db2d
{
private $dumper;
private $uploader;
public function configureDatabase($db, $username, $password)
{
$this->dumper = new Mysqldump("mysql:host=localhost;dbname=$db", $username, $password);
}
public function configureDropbox($key, $secret, $token)
{
$app = new DropboxApp($key, $secret, $token);
$this->uploader = new Dropbox($app);
}
public function backup()
{
$name = 'backup-' . date('Ymd-H-i-s') . '.sql';
$this->dumper->start($name);
$dropboxFile = new DropboxFile($name);
$file = $this->uploader->upload($dropboxFile, "/$name", ['autorename' => true]);
unlink($name);
}
}
|
Fix URL for home page (thanks jlongster) | from django.conf.urls.defaults import *
from views import home, contribute, channel, firefox_performance, firefox_features, firefox_customize, firefox_happy, firefox_security, firefox_speed, firefox_technology, button, new, sandstone, geolocation
urlpatterns = patterns('',
url(r'^$', home, name='mozorg.home'),
(r'^button/', button),
(r'^channel/', channel),
(r'^new/', new),
(r'^sandstone/', sandstone),
url(r'^contribute/', contribute, name='mozorg.contribute'),
(r'^firefox/geolocation/', geolocation),
url(r'^firefox/customize/', firefox_customize, name='mozorg.firefox_customize'),
url(r'^firefox/features/', firefox_features, name='mozorg.firefox_features'),
url(r'^firefox/happy/', firefox_happy, name='mozorg.firefox_happy'),
url(r'^firefox/performance/', firefox_performance, name='mozorg.firefox_performance'),
url(r'^firefox/security/', firefox_security, name='mozorg.firefox_security'),
url(r'^firefox/speed/', firefox_speed, name='mozorg.firefox_speed'),
url(r'^firefox/technology/', firefox_technology, name='mozorg.firefox_technology'),
)
| from django.conf.urls.defaults import *
from views import home, contribute, channel, firefox_performance, firefox_features, firefox_customize, firefox_happy, firefox_security, firefox_speed, firefox_technology, button, new, sandstone, geolocation
urlpatterns = patterns('',
url(r'^home/', home, name='mozorg.home'),
(r'^button/', button),
(r'^channel/', channel),
(r'^new/', new),
(r'^sandstone/', sandstone),
url(r'^contribute/', contribute, name='mozorg.contribute'),
(r'^firefox/geolocation/', geolocation),
url(r'^firefox/customize/', firefox_customize, name='mozorg.firefox_customize'),
url(r'^firefox/features/', firefox_features, name='mozorg.firefox_features'),
url(r'^firefox/happy/', firefox_happy, name='mozorg.firefox_happy'),
url(r'^firefox/performance/', firefox_performance, name='mozorg.firefox_performance'),
url(r'^firefox/security/', firefox_security, name='mozorg.firefox_security'),
url(r'^firefox/speed/', firefox_speed, name='mozorg.firefox_speed'),
url(r'^firefox/technology/', firefox_technology, name='mozorg.firefox_technology'),
)
|
Use public API route to add tests
Avoid sending credentials | var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/public/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
| var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
|
Support no-args for djangae.core.management.execute_from_commandline - matches django implementation. | import sys
import argparse
import djangae.sandbox as sandbox
def execute_from_command_line(argv=None):
"""Wraps Django's `execute_from_command_line` to initialize a djangae
sandbox before running a management command.
Note: The '--sandbox' arg must come first. All other args are forwarded to
Django as normal.
"""
argv = argv or sys.argv
parser = argparse.ArgumentParser(prog='manage.py')
parser.add_argument(
'--sandbox', default=sandbox.LOCAL, choices=sandbox.SANDBOXES.keys())
parser.add_argument('args', nargs=argparse.REMAINDER)
namespace = parser.parse_args(argv[1:])
django_argv = ['manage.py'] + namespace.args
with sandbox.activate(namespace.sandbox, add_sdk_to_path=True):
import django.core.management as django_management # Now on the path
django_management.execute_from_command_line(django_argv)
| import argparse
import djangae.sandbox as sandbox
def execute_from_command_line(argv=None):
"""Wraps Django's `execute_from_command_line` to initialize a djangae
sandbox before running a management command.
Note: The '--sandbox' arg must come first. All other args are forwarded to
Django as normal.
"""
parser = argparse.ArgumentParser(prog='manage.py')
parser.add_argument(
'--sandbox', default=sandbox.LOCAL, choices=sandbox.SANDBOXES.keys())
parser.add_argument('args', nargs=argparse.REMAINDER)
namespace = parser.parse_args(argv[1:])
django_argv = ['manage.py'] + namespace.args
with sandbox.activate(namespace.sandbox, add_sdk_to_path=True):
import django.core.management as django_management # Now on the path
django_management.execute_from_command_line(django_argv)
|
Resolve client dist output js name from entry point | var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
main: ['./main.js']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
cacheDirectory: true
}
}
]
},
stats: {
colors: true
},
devtool: 'source-map'
};
| var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
cacheDirectory: true
}
}
]
},
stats: {
colors: true
},
devtool: 'source-map'
};
|
Replace Lodash isNumber with Angular isNumber | function ToastFactory($mdToast) {
return {
hide() {
$mdToast.hide();
},
show(message, delay) {
let toast = $mdToast.simple()
.content(message)
.action('OK')
.position('bottom right')
.hideDelay(angular.isNumber(delay) ? delay : Math.pow(2, 31) - 1);
$mdToast.show(toast);
}
};
}
ToastFactory.$inject = ['$mdToast'];
export default ToastFactory; | import isNumber from 'lodash/lang/isNumber';
function ToastFactory($mdToast) {
return {
hide() {
$mdToast.hide();
},
show(message, delay) {
let toast = $mdToast.simple()
.content(message)
.action('OK')
.position('bottom right')
.hideDelay(isNumber(delay) ? delay : Math.pow(2, 31) - 1);
$mdToast.show(toast);
}
};
}
ToastFactory.$inject = ['$mdToast'];
export default ToastFactory; |
Use viewBox instead of width and height. | "use strict";
module.exports = svg;
var xml = require("xml");
var orient = require("./lib/orient");
var trace = require("./lib/trace");
var optimize = require("./lib/optimize");
function svg (pixmap) {
var h = pixmap.length + 2;
var w = pixmap[0].length + 2;
var data = path(optimize(trace(orient(pixmap), w, h)));
return xml({
svg: [{
_attr: {
viewBox: [ 1, 1, w - 2, h - 2].join(" "),
xmlns: "http://www.w3.org/2000/svg",
version: "1.1"
}
},{
path: [{
_attr: {
d: data,
fill: "black"
}
}]
}]
});
}
function path (moves) {
return moves.map(function (move) {
return (move.h
? "h" + move.h
: move.v
? "v" + move.v
: "M" + move.x + "," + move.y);
}).reduce(function (str, move) {
return str + move;
}, "")+ "z";
}
| "use strict";
module.exports = svg;
var xml = require("xml");
var orient = require("./lib/orient");
var trace = require("./lib/trace");
var optimize = require("./lib/optimize");
function svg (pixmap) {
var h = pixmap.length + 2;
var w = pixmap[0].length + 2;
var data = path(optimize(trace(orient(pixmap), w, h)));
return xml({
svg: [{
_attr: {
width: w,
height: h,
xmlns: "http://www.w3.org/2000/svg",
version: "1.1"
}
},{
path: [{
_attr: {
d: data,
fill: "black"
}
}]
}]
});
}
function path (moves) {
return moves.map(function (move) {
return (move.h
? "h" + move.h
: move.v
? "v" + move.v
: "M" + move.x + "," + move.y);
}).reduce(function (str, move) {
return str + move;
}, "")+ "z";
}
|
Use Assert.fail instead of Assert.assertTrue(false) | package com.github.valfirst.jbehave.junit.monitoring;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Class IgnoredTestsTest.
*
* The purpose of this class is to see how an IDE behaves when there is a unit test that passes and a test is ignored.
*
* The result in IntelliJ 2017.2.5 Community Edition is that there are two lines of info reported about test outcomes:
* (OK) IgnoredTestsTest
* (OK) shouldPass
*
* This implies to me that the jbehave-junit-runner should behave similarly that even if there are stories/scenarios
* that are ignored (via meta tag filtering) then the highest level node should show (OK) and not (Pending).
*/
public class IgnoredTestsTest {
@Test
public void shouldPass() {
// Nothing to do. Wish this test to pass.
assertTrue(true);
}
@Ignore
public void shouldBeIgnored() {
// Nothing to do. Wish this test to be ignored.
fail();
}
}
| package com.github.valfirst.jbehave.junit.monitoring;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Class IgnoredTestsTest.
*
* The purpose of this class is to see how an IDE behaves when there is a unit test that passes and a test is ignored.
*
* The result in IntelliJ 2017.2.5 Community Edition is that there are two lines of info reported about test outcomes:
* (OK) IgnoredTestsTest
* (OK) shouldPass
*
* This implies to me that the jbehave-junit-runner should behave similarly that even if there are stories/scenarios
* that are ignored (via meta tag filtering) then the highest level node should show (OK) and not (Pending).
*/
public class IgnoredTestsTest {
@Test
public void shouldPass() {
// Nothing to do. Wish this test to pass.
assertTrue(true);
}
@Ignore
public void shouldBeIgnored() {
// Nothing to do. Wish this test to be ignored.
assertTrue(false);
}
}
|
Fix creation test for Playbook 2.0 | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('playbook', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('playbook:app', ['../../app']);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
'app/index.html',
'app/404.html',
'app/humans.txt',
'app/robots.txt',
'.jshintrc',
'.gitignore',
'.editorconfig',
'.csslintrc',
'.bowerrc',
'bower.json',
'gulpfile.js',
'package.json'
];
helpers.mockPrompt(this.app, {
'authorName': 'foo',
'authorEmail': 'bar',
'jsPre': 'None',
'sassComp': 'Ruby',
'googleAnalytics': false,
'deploy': false
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
| /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('playbook', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('playbook:app', ['../../app']);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
'app/index.html',
'app/404.html',
'app/humans.txt',
'app/robots.txt',
'.jshintrc',
'.gitignore',
'.editorconfig',
'.csslintrc',
'.bowerrc',
'bower.json',
'Gruntfile.js',
'package.json'
];
helpers.mockPrompt(this.app, {
'authorName': 'foo',
'authorEmail': 'bar',
'jsPre': 'None',
'sassComp': 'Ruby',
'googleAnalytics': false,
'deploy': false
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
|
Fix initialization of OC_Filesystem setup from DAV | <?php
/**
* ownCloud
*
* @author Jakob Sack
* @copyright 2011 Jakob Sack kde@jakobsack.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library 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 library. If not, see <http://www.gnu.org/licenses/>.
*
*/
class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
/**
* Validates a username and password
*
* This method should return true or false depending on if login
* succeeded.
*
* @return bool
*/
protected function validateUserPass($username, $password){
OC_Util::setUpFS();//login hooks may need early access to the filesystem
if(OC_User::login($username,$password)){
OC_Util::setUpFS($username);
return true;
}
else{
return false;
}
}
}
| <?php
/**
* ownCloud
*
* @author Jakob Sack
* @copyright 2011 Jakob Sack kde@jakobsack.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library 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 library. If not, see <http://www.gnu.org/licenses/>.
*
*/
class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
/**
* Validates a username and password
*
* This method should return true or false depending on if login
* succeeded.
*
* @return bool
*/
protected function validateUserPass($username, $password){
OC_Util::setUpFS();//login hooks may need early access to the filesystem
if(OC_User::login($username,$password)){
OC_Util::setUpFS();
return true;
}
else{
return false;
}
}
}
|
Include legend label text in update block. | import {Index, Label, Offset, Size, Total, Value} from './constants';
import guideMark from './guide-mark';
import {TextMark} from '../marks/marktypes';
import {LegendLabelRole} from '../marks/roles';
import {addEncode} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter, update;
encode.enter = enter = {
opacity: zero
};
addEncode(enter, 'align', config.labelAlign);
addEncode(enter, 'baseline', config.labelBaseline);
addEncode(enter, 'fill', config.labelColor);
addEncode(enter, 'font', config.labelFont);
addEncode(enter, 'fontSize', config.labelFontSize);
addEncode(enter, 'limit', config.labelLimit);
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1},
text: {field: Label}
};
enter.x = update.x = {
field: Offset,
offset: config.labelOffset
};
enter.y = update.y = {
field: Size,
mult: 0.5,
offset: {
field: Total,
offset: {
field: {group: 'entryPadding'},
mult: {field: Index}
}
}
};
return guideMark(TextMark, LegendLabelRole, Value, dataRef, encode, userEncode);
}
| import {Index, Label, Offset, Size, Total, Value} from './constants';
import guideMark from './guide-mark';
import {TextMark} from '../marks/marktypes';
import {LegendLabelRole} from '../marks/roles';
import {addEncode} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter, update;
encode.enter = enter = {
opacity: zero,
text: {field: Label}
};
addEncode(enter, 'align', config.labelAlign);
addEncode(enter, 'baseline', config.labelBaseline);
addEncode(enter, 'fill', config.labelColor);
addEncode(enter, 'font', config.labelFont);
addEncode(enter, 'fontSize', config.labelFontSize);
addEncode(enter, 'limit', config.labelLimit);
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1}
};
enter.x = update.x = {
field: Offset,
offset: config.labelOffset
};
enter.y = update.y = {
field: Size,
mult: 0.5,
offset: {
field: Total,
offset: {
field: {group: 'entryPadding'},
mult: {field: Index}
}
}
};
return guideMark(TextMark, LegendLabelRole, Value, dataRef, encode, userEncode);
}
|
Change data type of 'savable' column on 'assessments' table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpdateAssessmentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if(Schema::hasTable('assessments')) {
Schema::table('assessments', function($table) {
$table->char('score_comedy')->after('score_nuki')->nullable()->default('');
$table->string('savable', 16)->after('score_all')->nullable()->default('unknown');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if(Schema::hasTable('assessments')) {
Schema::table('assessments', function($table) {
$table->dropColumn(['score_comedy', 'savable']);
});
}
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpdateAssessmentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if(Schema::hasTable('assessments')) {
Schema::table('assessments', function($table) {
$table->char('score_comedy')->after('score_nuki')->nullable()->default('');
$table->boolean('savable')->after('score_all')->nullable();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if(Schema::hasTable('assessments')) {
Schema::table('assessments', function($table) {
$table->dropColumn(['score_comedy', 'savable']);
});
}
}
}
|
Add telegram token example to config example | /**
* Config object, import as JSON
* @type {Object}
*
* @example
* {
* "consulateUrls": {
* "country": "https://example.com/countries.php",
* "consulate": "https://example.com/consulates.php",
* "agenda": "https://example.com/agenda.xhtml"
* },
* "telegram": {
* "token": "57851515:ADf7DbdQcksIF9D_yiveQFYaedDsEYwbDiC",
* "baseUrl": "https://api.telegram.org/bot<bot-token>/"
* }
* }
*/
var config = require('./config');
var fetch = require('./fetcher');
var notify = require('./notifier');
function error(err) {
console.error(err);
}
fetch(config.consulateUrls, function callback(err, data) {
if (err) return error(err);
console.log(JSON.stringify(data, null, 2));
return notify('available-dates-summary', data, 7438652);
}); | /**
* Config object, import as JSON
* @type {Object}
*
* @example
* {
* "consulateUrls": {
* "country": "https://example.com/countries.php",
* "consulate": "https://example.com/consulates.php",
* "agenda": "https://example.com/agenda.xhtml"
* },
* "telegram": {
* "baseUrl": "https://api.telegram.org/bot<bot-token>/"
* }
* }
*/
var config = require('./config');
var fetch = require('./fetcher');
var notify = require('./notifier');
function error(err) {
console.error(err);
}
fetch(config.consulateUrls, function callback(err, data) {
if (err) return error(err);
console.log(JSON.stringify(data, null, 2));
return notify('available-dates-summary', data, 7438652);
}); |
fix: Update axe.source to work with Firefox webdriver | /*exported axe, commons */
/*global axeFunction, module, define */
// exported namespace for aXe
var axe = axe || {};
axe.version = '<%= pkg.version %>';
if (typeof define === 'function' && define.amd) {
define([], function () {
'use strict';
return axe;
});
}
if (typeof module === 'object' && module.exports && typeof axeFunction.toString === 'function') {
axe.source = '(' + axeFunction.toString() + ')(typeof window === "object" ? window : this);';
module.exports = axe;
}
if (typeof window.getComputedStyle === 'function') {
window.axe = axe;
}
// local namespace for common functions
var commons;
function SupportError(error) {
this.name = 'SupportError';
this.cause = error.cause;
this.message = `\`${error.cause}\` - feature unsupported in your environment.`;
if (error.ruleId) {
this.ruleId = error.ruleId;
this.message += ` Skipping ${this.ruleId} rule.`;
}
this.stack = (new Error()).stack;
}
SupportError.prototype = Object.create(Error.prototype);
SupportError.prototype.constructor = SupportError;
| /*exported axe, commons */
/*global axeFunction, module, define */
// exported namespace for aXe
var axe = axe || {};
axe.version = '<%= pkg.version %>';
if (typeof define === 'function' && define.amd) {
define([], function () {
'use strict';
return axe;
});
}
if (typeof module === 'object' && module.exports && typeof axeFunction.toString === 'function') {
axe.source = '(' + axeFunction.toString() + ')(this, this.document);';
module.exports = axe;
}
if (typeof window.getComputedStyle === 'function') {
window.axe = axe;
}
// local namespace for common functions
var commons;
function SupportError(error) {
this.name = 'SupportError';
this.cause = error.cause;
this.message = `\`${error.cause}\` - feature unsupported in your environment.`;
if (error.ruleId) {
this.ruleId = error.ruleId;
this.message += ` Skipping ${this.ruleId} rule.`;
}
this.stack = (new Error()).stack;
}
SupportError.prototype = Object.create(Error.prototype);
SupportError.prototype.constructor = SupportError;
|
Support html on descriptive buttons | import PropTypes from 'prop-types';
import React from 'react';
/**
*
*/
const DescriptiveButton = (props) => {
const { imageUrl, label, svgIcon, description, onClick, className, id } = props;
let visualContent = null;
if (imageUrl) {
visualContent = (<img src={imageUrl} alt={label} width={50} height={50} />);
} else if (svgIcon) {
visualContent = svgIcon;
}
return (
<div
id={id}
className={`descriptive-button ${className || ''}`}
role="button"
onClick={onClick}
tabIndex={0}
onKeyDown={() => null}
>
<div className="image">
{visualContent}
</div>
<b>{label}</b>
<p>{description}</p>
</div>
);
};
DescriptiveButton.propTypes = {
// from parent
imageUrl: PropTypes.string,
svgIcon: PropTypes.node,
label: PropTypes.string.isRequired,
description: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node,
]).isRequired,
onClick: PropTypes.func.isRequired,
className: PropTypes.string,
id: PropTypes.string,
};
export default DescriptiveButton;
| import PropTypes from 'prop-types';
import React from 'react';
/**
*
*/
const DescriptiveButton = (props) => {
const { imageUrl, label, svgIcon, description, onClick, className, id } = props;
let visualContent = null;
if (imageUrl) {
visualContent = (<img src={imageUrl} alt={label} width={50} height={50} />);
} else if (svgIcon) {
visualContent = svgIcon;
}
return (
<div
id={id}
className={`descriptive-button ${className || ''}`}
role="button"
onClick={onClick}
tabIndex={0}
onKeyDown={() => null}
>
<div className="image">
{visualContent}
</div>
<b>{label}</b>
<p>{description}</p>
</div>
);
};
DescriptiveButton.propTypes = {
// from parent
imageUrl: PropTypes.string,
svgIcon: PropTypes.node,
label: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
className: PropTypes.string,
id: PropTypes.string,
};
export default DescriptiveButton;
|
Use queue from multiprocessing library instead of Queue | from multiprocessing import Queue
from Queue import Empty
import json
from .base import BaseQueue
sqs = None
def do_delayed_imports():
global sqs
from boto import sqs
class SQSQueue(BaseQueue):
_cache = Queue()
def __init__(self):
BaseQueue.__init__(self)
do_delayed_imports()
self.conn = sqs.connect_to_region('us-west-2')
self.unprocessed = self.conn.create_queue('structured-catalog-unprocessed')
def push(self, job):
m = sqs.message.Message()
m.set_body(json.dumps(job))
self.unprocessed.write(m)
def get(self):
try:
msg = self._cache.get(block=False)
self.remove(msg)
return json.loads(msg.get_body())
except Empty:
rs = self.unprocessed.get_messages(num_messages=10)
if not rs:
return
for msg in rs:
self._cache.put(msg)
return self.get()
def remove(self, msg):
self.unprocessed.delete_message(msg)
| from Queue import Queue, Empty
import json
from .base import BaseQueue
sqs = None
def do_delayed_imports():
global sqs
from boto import sqs
class SQSQueue(BaseQueue):
_cache = Queue()
def __init__(self):
BaseQueue.__init__(self)
do_delayed_imports()
self.conn = sqs.connect_to_region('us-west-2')
self.unprocessed = self.conn.create_queue('structured-catalog-unprocessed')
def push(self, job):
m = sqs.message.Message()
m.set_body(json.dumps(job))
self.unprocessed.write(m)
def get(self):
try:
msg = self._cache.get(block=False)
self.remove(msg)
return json.loads(msg.get_body())
except Empty:
rs = self.unprocessed.get_messages(num_messages=10)
if not rs:
return
for msg in rs:
self._cache.put(msg)
return self.get()
def remove(self, msg):
self.unprocessed.delete_message(msg)
|
Enable source map in development build | var baseConfig = require('./webpackBaseConfig')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var path = require('path')
module.exports = [Object.assign({}, baseConfig, {
plugins: baseConfig.plugins.concat([
new ExtractTextPlugin('[name].css')
]),
devtool: 'source-map'
}), {
devtool: 'source-map',
entry: {
htmlExport: path.join(__dirname, 'public/js/htmlExport.js')
},
module: {
loaders: [{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}]
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js'
},
plugins: [
new ExtractTextPlugin('html.min.css')
]
}]
| var baseConfig = require('./webpackBaseConfig')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var path = require('path')
module.exports = [Object.assign({}, baseConfig, {
plugins: baseConfig.plugins.concat([
new ExtractTextPlugin('[name].css')
])
}), {
entry: {
htmlExport: path.join(__dirname, 'public/js/htmlExport.js')
},
module: {
loaders: [{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}]
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js'
},
plugins: [
new ExtractTextPlugin('html.min.css')
]
}]
|
Add return types to internal|final|private methods | <?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\Bundle\SecurityBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Event\VoteEvent;
/**
* Listen to vote events from traceable voters.
*
* @author Laurent VOULLEMIER <laurent.voullemier@gmail.com>
*
* @internal
*/
class VoteListener implements EventSubscriberInterface
{
private $traceableAccessDecisionManager;
public function __construct(TraceableAccessDecisionManager $traceableAccessDecisionManager)
{
$this->traceableAccessDecisionManager = $traceableAccessDecisionManager;
}
/**
* Event dispatched by a voter during access manager decision.
*/
public function onVoterVote(VoteEvent $event)
{
$this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $event->getVote());
}
public static function getSubscribedEvents(): array
{
return ['debug.security.authorization.vote' => 'onVoterVote'];
}
}
| <?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\Bundle\SecurityBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Event\VoteEvent;
/**
* Listen to vote events from traceable voters.
*
* @author Laurent VOULLEMIER <laurent.voullemier@gmail.com>
*
* @internal
*/
class VoteListener implements EventSubscriberInterface
{
private $traceableAccessDecisionManager;
public function __construct(TraceableAccessDecisionManager $traceableAccessDecisionManager)
{
$this->traceableAccessDecisionManager = $traceableAccessDecisionManager;
}
/**
* Event dispatched by a voter during access manager decision.
*/
public function onVoterVote(VoteEvent $event)
{
$this->traceableAccessDecisionManager->addVoterVote($event->getVoter(), $event->getAttributes(), $event->getVote());
}
public static function getSubscribedEvents()
{
return ['debug.security.authorization.vote' => 'onVoterVote'];
}
}
|
Reformat and update comment for func Inner() | // Copyright ©2014 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mat64
// Inner computes the generalized inner product
// x^T A y
// between vectors x and y with matrix A. This is only a true inner product if
// A is symmetric positive definite, though the operation works for any matrix A.
//
// Inner panics if len(x) != m or len(y) != n when A is an m x n matrix.
func Inner(x []float64, A Matrix, y []float64) float64 {
m, n := A.Dims()
if len(x) != m {
panic(ErrShape)
}
if len(y) != n {
panic(ErrShape)
}
if m == 0 || n == 0 {
return 0
}
var sum float64
switch b := A.(type) {
case RawMatrixer:
bmat := b.RawMatrix()
for i, xi := range x {
for j, yj := range y {
sum += xi * bmat.Data[i*bmat.Stride+j] * yj
}
}
default:
for i, xi := range x {
for j, yj := range y {
sum += xi * A.At(i, j) * yj
}
}
}
return sum
}
| // Copyright ©2014 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mat64
// Inner computes the generalized inner product between x and y with matrix A.
// x^T A y
// This is only a true inner product if m is symmetric positive definite, though
// the operation works for any matrix A.
//
// Inner panics if len(x) != m or len(y) != n when A is an m x n matrix.
func Inner(x []float64, A Matrix, y []float64) float64 {
m, n := A.Dims()
if len(x) != m {
panic(ErrShape)
}
if len(y) != n {
panic(ErrShape)
}
if m == 0 || n == 0 {
return 0
}
var sum float64
switch b := A.(type) {
case RawMatrixer:
bmat := b.RawMatrix()
for i, xi := range x {
for j, yj := range y {
sum += xi * bmat.Data[i*bmat.Stride+j] * yj
}
}
default:
for i, xi := range x {
for j, yj := range y {
sum += xi * A.At(i, j) * yj
}
}
}
return sum
}
|
Revert the duplication of the reference in resources table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableResources extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('resources', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug');
$table->string('review')->nullable();
$table->string('content')->nullable();
$table->string('attachment')->nullable();
$table->integer('former_id')->unsigned()->nullable();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('resources');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableResources extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('resources', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug');
$table->string('review')->nullable();
$table->string('content')->nullable();
$table->string('attachment')->nullable();
$table->integer('former_id')->unsigned()->nullable();
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('resources');
}
}
|
Remove itemControllers as they are deprecated | import Em from 'ember';
import Row from 'llama-table/controllers/row';
import { makeArray } from 'llama-table/computed';
var computed = Em.computed;
var map = computed.map;
var sort = computed.sort;
var reads = computed.reads;
var SortedRowsMixin = Em.Mixin.create({
_rowsSource: makeArray('rows'),
_rowsSortOrder: makeArray('sortProperties'),
_rowsMapped: map('_rowsSource', function (model) {
if (!(model instanceof Row)) {
return Row.create({ model });
}
return model;
}),
_rowsSorted: sort('_rowsMapped', '_rowsSortOrder'),
/**
* Row values array with added sorting functionality. Uses a custom
* 'RowsController' if table has subcontent. Does not construct this
* custom controller if it is not necessary.
* @property {Ember.ArrayProxy} sortedRows
*/
sortedRows: reads('_rowsSorted'),
});
export default SortedRowsMixin;
| import Em from 'ember';
import Row from 'llama-table/controllers/row';
import { makeArray } from 'llama-table/computed';
var computed = Em.computed;
var map = computed.map;
var sort = computed.sort;
var reads = computed.reads;
var SortedRowsMixin = Em.Mixin.create({
_rowsSource: makeArray('rows'),
_rowsSortOrder: makeArray('sortProperties'),
_rowsMapped: map('_rowsSource', function (model) {
var Controller = this.get('itemController') || Row;
if (Controller) {
return Controller.create({ model });
}
return model;
}),
_rowsSorted: sort('_rowsMapped', '_rowsSortOrder'),
/**
* Row values array with added sorting functionality. Uses a custom
* 'RowsController' if table has subcontent. Does not construct this
* custom controller if it is not necessary.
* @property {Ember.ArrayProxy} sortedRows
*/
sortedRows: reads('_rowsSorted'),
});
export default SortedRowsMixin;
|
Use port 8080 for testing | import request from 'request';
const PROTOCOL = 'http';
const HOST = 'localhost';
const PORT = 8080;
function call(endpoint, method, qs, json) {
let options = {
uri: `${PROTOCOL}://${HOST}:${PORT}/api/${endpoint}`,
method
};
if (typeof qs !== 'undefined') {
options.qs = qs;
}
if (typeof json !== 'undefined') {
options.json = json;
}
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (typeof body === 'string') {
body = JSON.parse(body);
}
if (body.status === 'success') {
resolve(body.data);
} else {
reject(body.message);
}
});
});
}
export function del(endpoint, data) {
return call(endpoint, 'DELETE', data);
}
export function get(endpoint, data) {
return call(endpoint, 'GET', data);
}
export function post(endpoint, data) {
return call(endpoint, 'POST', undefined, data);
}
| import request from 'request';
function call(endpoint, method, qs, json) {
let options = {
uri: `http://localhost/api/${endpoint}`,
method
};
if (typeof qs !== 'undefined') {
options.qs = qs;
}
if (typeof json !== 'undefined') {
options.json = json;
}
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (typeof body === 'string') {
body = JSON.parse(body);
}
if (body.status === 'success') {
resolve(body.data);
} else {
reject(body.message);
}
});
});
}
export function del(endpoint, data) {
return call(endpoint, 'DELETE', data);
}
export function get(endpoint, data) {
return call(endpoint, 'GET', data);
}
export function post(endpoint, data) {
return call(endpoint, 'POST', undefined, data);
}
|
Simplify standard input to allow redirection. | <?php
function rewriteHeader($headline, $oldTag, $newTag) {
if (strpos($headline, $oldTag) === 0) {
$data = substr($headline, strlen($oldTag));
$data = str_replace('"', '', $data);
return $newTag . $data . "\n";
}
else {
return NULL;
}
}
if (count($argv) < 2) {
echo "Too few params. Need a file name to apply changes.";
exit -1;
}
$filename = realpath($argv[1]);
$content = file_get_contents($filename);
$parts = explode('---', $content);
$tokens = count($parts);
$header = explode("\n", $parts[$tokens - 2]);
$body = $parts[$tokens - 1];
$newHeader = "";
foreach ($header as $headline) {
$newHeader .= rewriteHeader($headline, 'title:', 'Title:');
$newHeader .= rewriteHeader($headline, 'date:', 'Date:');
$newHeader .= rewriteHeader($headline, 'categories:', 'Tags:');
}
$newHeader .= "Category: Blog\n";
$newHeader .= "Author: Antonio Jesus Sanchez Padial\n";
echo $newHeader . $body;
| <?php
function rewriteHeader($headline, $oldTag, $newTag) {
if (strpos($headline, $oldTag) === 0) {
$data = substr($headline, strlen($oldTag));
$data = str_replace('"', '', $data);
return $newTag . $data . "\n";
}
else {
return NULL;
}
}
if (count($argv) < 2) {
echo "Too few params. Need a file name to apply changes.";
exit -1;
}
$filename = realpath($argv[1]);
echo "Parsing " . $filename . " ...\n";
$content = file_get_contents($filename);
$parts = explode('---', $content);
$header = explode("\n", $parts[1]);
$body = $parts[2];
$newHeader = "";
foreach ($header as $headline) {
$newHeader .= rewriteHeader($headline, 'title:', 'Title:');
$newHeader .= rewriteHeader($headline, 'date:', 'Date:');
$newHeader .= rewriteHeader($headline, 'categories:', 'Tags:');
}
$newHeader .= "Category: Blog\n";
$newHeader .= "Author: Antonio Jesus Sanchez Padial\n";
echo $newHeader . $body;
|
Correct data migration wheere clause |
exports.up = async function (knex) {
await knex.schema.table('group_widgets', t => {
t.string('context')
})
const now = new Date().toISOString()
await knex.raw(`
INSERT INTO "public"."widgets"("id","name","created_at") VALUES
(15,E'opportunities_to_collaborate','${now}'),
(16,E'farm_map','${now}'),
(17,E'moderators','${now}'),
(18,E'privacy_settings','${now}')
`)
return knex.raw(`
UPDATE group_widgets SET context = 'landing' WHERE context IS NULL;
`)
}
exports.down = async function (knex) {
await knex.raw(`
DELETE FROM widgets WHERE name IN ('opportunities_to_collaborate', 'farm_map', 'moderators', 'privacy_settings');
`)
return knex.schema.table('group_widgets', table => {
table.dropColumn('context')
})
}
|
exports.up = async function (knex) {
await knex.schema.table('group_widgets', t => {
t.string('context')
})
const now = new Date().toISOString()
await knex.raw(`
INSERT INTO "public"."widgets"("id","name","created_at") VALUES
(15,E'opportunities_to_collaborate','${now}'),
(16,E'farm_map','${now}'),
(17,E'moderators','${now}'),
(18,E'privacy_settings','${now}')
`)
return knex.raw(`
UPDATE group_widgets SET context = 'landing' WHERE context = NULL;
`)
}
exports.down = async function (knex) {
await knex.raw(`
DELETE FROM widgets WHERE name IN ('opportunities_to_collaborate', 'farm_map', 'moderators', 'privacy_settings');
`)
return knex.schema.table('group_widgets', table => {
table.dropColumn('context')
})
}
|
Add proper file path name | /**
* ImageController
*
* @description :: Server-side logic for managing Images
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var cloudinary = require('cloudinary');
module.exports = {
create: function (req, res) {
req.file('image').upload({
maxBytes: 10000000
}, function whenDone(err, uploads) {
if (err) {
return res.serverError(err);
}
// If no files were uploaded, respond with an error
if (uploads.length === 0) {
return res.badRequest('No file was uploaded');
}
// Only consider one file per POST request
var upload = uploads[0];
// Upload image via Cloudinary
cloudinary.uploader.upload(upload.fd, function(result) {
sails.log.info(result);
Image.create({
filename: result.public_id,
height: result.height,
width: result.width
}).exec(function (err, image) {
if (err) return res.serverError(err);
return res.created(image);
});
});
});
}
};
| /**
* ImageController
*
* @description :: Server-side logic for managing Images
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var cloudinary = require('cloudinary');
module.exports = {
create: function (req, res) {
req.file('image').upload({
maxBytes: 10000000
}, function whenDone(err, uploads) {
if (err) {
return res.serverError(err);
}
// If no files were uploaded, respond with an error
if (uploads.length === 0) {
return res.badRequest('No file was uploaded');
}
// Only consider one file per POST request
var upload = uploads[0];
// Upload image via Cloudinary
cloudinary.uploader.upload(upload, function(result) {
sails.log.info(result);
Image.create({
filename: result.public_id,
height: result.height,
width: result.width
}).exec(function (err, image) {
if (err) return res.serverError(err);
return res.created(image);
});
});
});
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.