text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Make autofocusing a configurable option that you can pass into the form | import Ember from 'ember';
import FormSubmissionClassNameMixin from 'ember-easy-form-extensions/mixins/components/form-submission-class-name';
const { computed, on } = Ember;
export default Ember.Component.extend(
FormSubmissionClassNameMixin, {
/* Options */
className: 'form',
novalidate: true,
autoFocus: true,
/* Properties */
attributeBindings: ['novalidate'],
classNameBindings: ['className'],
formIsSubmitted: computed.oneWay('formController.formIsSubmitted'),
tagName: 'form',
/* Properties */
/* A shim to enabled use with controller and components
moving forward */
formController: Ember.computed(function() {
const routeController = this.get('targetObject');
if (this.get('hasFormMixin')) {
return this;
} else if (routeController.get('hasFormMixin')) {
return routeController;
} else {
return null;
}
}),
/* Methods */
/* Autofocus on the first input.
TODO - move to form component
mixin when routeable components land */
autofocus: on('didInsertElement', function() {
if(this.get('autoFocus')) {
var input = this.$().find('input').first();
if (!Ember.$(input).hasClass('datepicker')) {
setTimeout(() => {
input.focus();
}, 100);
}
}
}),
});
| import Ember from 'ember';
import FormSubmissionClassNameMixin from 'ember-easy-form-extensions/mixins/components/form-submission-class-name';
const { computed, on } = Ember;
export default Ember.Component.extend(
FormSubmissionClassNameMixin, {
/* Options */
className: 'form',
novalidate: true,
/* Properties */
attributeBindings: ['novalidate'],
classNameBindings: ['className'],
formIsSubmitted: computed.oneWay('formController.formIsSubmitted'),
tagName: 'form',
/* Properties */
/* A shim to enabled use with controller and components
moving forward */
formController: Ember.computed(function() {
const routeController = this.get('targetObject');
if (this.get('hasFormMixin')) {
return this;
} else if (routeController.get('hasFormMixin')) {
return routeController;
} else {
return null;
}
}),
/* Methods */
/* Autofocus on the first input.
TODO - move to form component
mixin when routeable components land */
autofocus: on('didInsertElement', function() {
var input = this.$().find('input').first();
if (!Ember.$(input).hasClass('datepicker')) {
input.focus();
}
}),
});
|
Allow exec 'env' to inherit from 'process.env'
When executing a command Node uses `process.env` by default. If the 'env'
option is specified, Node assumes that the complete environment is
provided.
As Scripted exec configurations are declarative, and it's practically
impossible to correctly configure an environment declaratively, Scripted
should mix the declared env vars into the 'process.env'.
For example, this is my .scripted config:
"exec": {
"onKeys": {
"cmd+b": {
"cmd": "npm test",
"cwd": "${projectDir}",
"name": "Test Project",
"env": {
"BUSTER_TEST_OPT": "--color none --reporter specification"
}
}
}
}
Before this patch, Node is unable to spawn the child process because the
environment is incomplete. After this patch, it's able to run the command
with 'process.env' as the environment, augmented with 'BUSTER_TEST_OPT'. | /*******************************************************************************
* @license
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
* THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
* ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
* CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
* You can obtain a current copy of the Eclipse Public License from
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* Contributors:
* Kris De Volder - initial API and implementation
******************************************************************************/
/*global console require*/
var servlets = require('../servlets');
var makeRequestHandler = require('./servlet-utils').makeRequestHandler;
var cpExec = require('child_process').exec;
function exec(cmd, callback, errback) {
//cmd looks like this:
// {cmd: "ls -la", ...other options to pass to the nodejs exec function...}
var options = cmd;
cmd = cmd.cmd;
// TODO use mixin, if scipted had one...
// options.env = mixin({}, options.env, process.env);
options.env = options.env || {};
for (var env in process.env) {
if (!(env in options.env)) {
options.env[env] = process.env[env];
}
}
/*var process = */cpExec(cmd, options, callback);
}
exec.remoteType = ['JSON', 'callback'];
servlets.register('/exec', makeRequestHandler(exec)); | /*******************************************************************************
* @license
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
* THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
* ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
* CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
* You can obtain a current copy of the Eclipse Public License from
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* Contributors:
* Kris De Volder - initial API and implementation
******************************************************************************/
/*global console require*/
var servlets = require('../servlets');
var makeRequestHandler = require('./servlet-utils').makeRequestHandler;
var cpExec = require('child_process').exec;
function exec(cmd, callback, errback) {
//cmd looks like this:
// {cmd: "ls -la", ...other options to pass to the nodejs exec function...}
var options = cmd;
cmd = cmd.cmd;
/*var process = */cpExec(cmd, options, callback);
}
exec.remoteType = ['JSON', 'callback'];
servlets.register('/exec', makeRequestHandler(exec)); |
Remove active key since is deprecated | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': "Sale properties dynamic fields",
'version': '1.0',
'category': '',
'author': "Agile Business Group, Odoo Community Association (OCA)",
'website': 'http://www.agilebg.com',
'license': 'AGPL-3',
"depends": [
'sale_properties_easy_creation',
],
"data": [
'mrp_property_group_view.xml',
],
"demo": [
],
"test": [
'test/properties.yml',
],
"installable": True
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': "Sale properties dynamic fields",
'version': '1.0',
'category': '',
'author': "Agile Business Group, Odoo Community Association (OCA)",
'website': 'http://www.agilebg.com',
'license': 'AGPL-3',
"depends": [
'sale_properties_easy_creation',
],
"data": [
'mrp_property_group_view.xml',
],
"demo": [
],
"test": [
'test/properties.yml',
],
"active": False,
"installable": True
}
|
Add a message when listing queues :) | var util = require('util');
var amazon = require("amazon");
var sqs = require("sqs");
var env = process.env;
var accessKeyId = process.env.ACCESS_KEY_ID;
var secretAccessKey = process.env.SECRET_ACCESS_KEY;
var awsAccountId = process.env.AWS_ACCOUNT_ID;
var sqs = new sqs.Sqs(accessKeyId, secretAccessKey, awsAccountId, amazon.US_EAST_1);
console.log( 'Region :', sqs.region() );
console.log( 'EndPoint :', sqs.host() );
console.log( 'AccessKeyId :', sqs.accessKeyId() );
// console.log( 'SecretAccessKey :', sqs.secretAccessKey() );
console.log( 'AwsAccountId :', sqs.awsAccountId() );
sqs.listQueues({}, function(err, data) {
console.log("\nlisting queues - expecting success");
console.log('Error :', util.inspect(err, true, null));
console.log('Data :', util.inspect(data, true, null));
});
| var util = require('util');
var amazon = require("amazon");
var sqs = require("sqs");
var env = process.env;
var accessKeyId = process.env.ACCESS_KEY_ID;
var secretAccessKey = process.env.SECRET_ACCESS_KEY;
var awsAccountId = process.env.AWS_ACCOUNT_ID;
var sqs = new sqs.Sqs(accessKeyId, secretAccessKey, awsAccountId, amazon.US_EAST_1);
console.log( 'Region :', sqs.region() );
console.log( 'EndPoint :', sqs.host() );
console.log( 'AccessKeyId :', sqs.accessKeyId() );
// console.log( 'SecretAccessKey :', sqs.secretAccessKey() );
console.log( 'AwsAccountId :', sqs.awsAccountId() );
sqs.listQueues({}, function(err, data) {
console.log('Error :', util.inspect(err, true, null));
console.log('Data :', util.inspect(data, true, null));
});
|
Fix missing style for TextFilter | /** @jsx hJSX */
import {hJSX} from '@cycle/dom';
import {ControlledInputHook} from 'power-ui/hooks';
import styles from './styles.scss';
hJSX();
function TextFilter(sources) {
const value$ = sources.DOM
.select('.TextFilter input')
.events('input')
.map(ev => ev.target.value);
const vtree$ = sources.props$.map(props =>
<div className={`TextFilter ${styles.textFilter}`}>
<p>Find a person or specific skills</p>
<input type="text" placeholder="Add filter"
data-hook={new ControlledInputHook(props.value)}
/>
</div>
);
const sinks = {
DOM: vtree$,
value$,
};
return sinks;
}
export default TextFilter;
| /** @jsx hJSX */
import {hJSX} from '@cycle/dom';
import {ControlledInputHook} from 'power-ui/hooks';
import styles from './styles.scss';
hJSX();
function TextFilter(sources) {
const value$ = sources.DOM
.select('.TextFilter input')
.events('input')
.map(ev => ev.target.value);
const vtree$ = sources.props$.map(props =>
<div className="TextFilter" style={styles.textFilter}>
<p>Find a person or specific skills</p>
<input type="text" placeholder="Add filter"
data-hook={new ControlledInputHook(props.value)}
/>
</div>
);
const sinks = {
DOM: vtree$,
value$,
};
return sinks;
}
export default TextFilter;
|
Increase timeout to allow travis tests to pass | "use strict";
var screenshot = require('../../lib/pipes/screenshot.js');
var testcases = require('../files/hash.json');
var restbase = require('../../lib/pipes/restbase');
var pipe = require('../..');
describe('screenshot', function () {
testcases.forEach(function (tc) {
it('should take screenshot of svg from ' + JSON.stringify(tc.input), function () {
this.timeout(50000);
var folder = pipe.getFolder(tc.input, pipe.config.conf.out_dir);
var getCheck = restbase.check(tc.input, pipe.config.conf.restbase_url);
var getFormats = restbase.getOutputs(folder, getCheck);
return getFormats
.then(function (res) {
return res.get('svg')
.then(function (svg) {
return screenshot.snapshot(svg);
});
});
});
});
}); | "use strict";
var screenshot = require('../../lib/pipes/screenshot.js');
var testcases = require('../files/hash.json');
var restbase = require('../../lib/pipes/restbase');
var pipe = require('../..');
describe('screenshot', function () {
testcases.forEach(function (tc) {
it('should take screenshot of svg from ' + JSON.stringify(tc.input), function () {
var folder = pipe.getFolder(tc.input, pipe.config.conf.out_dir);
var getCheck = restbase.check(tc.input, pipe.config.conf.restbase_url);
var getFormats = restbase.getOutputs(folder, getCheck);
return getFormats
.then(function (res) {
return res.get('svg')
.then(function (svg) {
return screenshot.snapshot(svg);
});
});
});
});
}); |
Handle error on blank hovertext | CRM.$(function ($) {
$('.fast-action-link').click(function () {
link = $(this)[0];
// Show a confirmation dialog if appropriate
if ($(this).hasClass('fast-action-link-confirm')) {
CRM.confirm("Are you sure you want to take this action?")
.on('crmConfirm:yes', function () {
execute(link);
});
} else {
execute(link);
}
// Suppress the link-following behavior
return false;
});
});
/*
* Make an API call to FastActionLink.execute and update search results with
* notifications and/or dimming the search result.
*/
function execute(link) {
var falId = link.getAttribute('falid');
var entityId = link.getAttribute('entityid');
var params = {"id": falId, "entity_id": entityId};
CRM.api3('FastActionLink', 'execute', params)
.done(function (result) {
if (result.is_error) {
CRM.alert(result.error_message, "", "error");
} else {
if (!result.success_message) {
result.success_message = "Action was successful";
}
CRM.alert(result.success_message, "", "success");
if (result.dim_on_use == 1) {
CRM.$(link).parents('tr').addClass('disabled');
}
}
});
}
| CRM.$(function ($) {
$('.fast-action-link').click(function () {
link = $(this)[0];
// Show a confirmation dialog if appropriate
if ($(this).hasClass('fast-action-link-confirm')) {
CRM.confirm("Are you sure you want to take this action?")
.on('crmConfirm:yes', function () {
execute(link);
});
} else {
execute(link);
}
// Suppress the link-following behavior
return false;
});
});
/*
* Make an API call to FastActionLink.execute and update search results with
* notifications and/or dimming the search result.
*/
function execute(link) {
var falId = link.getAttribute('falid');
var entityId = link.getAttribute('entityid');
var params = {"id": falId, "entity_id": entityId};
CRM.api3('FastActionLink', 'execute', params)
.done(function (result) {
if (result.is_error) {
CRM.alert(result.error_message, "", "error");
} else {
CRM.alert(result.success_message, "", "success");
if (result.dim_on_use == 1) {
CRM.$(link).parents('tr').addClass('disabled');
}
}
});
} |
Add a more helpful error when the user needs to login to perform an operation | import client from '@sanity/client'
import getUserConfig from './getUserConfig'
/**
* Creates a wrapper/getter function to retrieve a Sanity API client.
* Instead of spreading the error checking logic around the project,
* we call it here when (and only when) a command needs to use the API
*/
const defaults = {
requireUser: true,
requireProject: true
}
export default function clientWrapper(manifest, path) {
return function (opts = {}) {
const {requireUser, requireProject, api} = {...defaults, ...opts}
const userConfig = getUserConfig()
const userApiConf = userConfig.get('api')
const token = userConfig.get('authToken')
const apiConfig = api || (manifest && manifest.api) || userApiConf || {}
if (requireUser && !token) {
throw new Error('You must login first - run "sanity login"')
}
if (requireProject && !apiConfig.projectId) {
throw new Error(
`"${path}" does not contain a project identifier ("api.projectId"), `
+ 'which is required for the Sanity CLI to communicate with the Sanity API'
)
}
return client({
...apiConfig,
dataset: apiConfig.dataset || 'dummy',
token: token,
useProjectHostname: requireProject
})
}
}
| import client from '@sanity/client'
import getUserConfig from './getUserConfig'
/**
* Creates a wrapper/getter function to retrieve a Sanity API client.
* Instead of spreading the error checking logic around the project,
* we call it here when (and only when) a command needs to use the API
*/
const defaults = {
requireUser: true,
requireProject: true
}
export default function clientWrapper(manifest, path) {
return function (opts = {}) {
const {requireUser, requireProject, api} = {...defaults, ...opts}
const userConfig = getUserConfig()
const userApiConf = userConfig.get('api')
const token = userConfig.get('authToken')
const apiConfig = api || (manifest && manifest.api) || userApiConf || {}
if (requireUser && !token) {
throw new Error('You must login first')
}
if (requireProject && !apiConfig.projectId) {
throw new Error(
`"${path}" does not contain a project identifier ("api.projectId"), `
+ 'which is required for the Sanity CLI to communicate with the Sanity API'
)
}
return client({
...apiConfig,
dataset: apiConfig.dataset || 'dummy',
token: token,
useProjectHostname: requireProject
})
}
}
|
Set default environment to production in the demo.
git-svn-id: d32e76a03a3123f3a7fc632f553a4a003f6b8db0@574 242cd0b0-a150-0410-b6ef-417cb531347b | <?php
/**
* Zym Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @copyright Copyright (c) 2008 Zym. (http://www.zym-project.com/)
* @license http://www.zym-project.com/license New BSD License
*/
/**
* Project Path
*
*/
define('PATH_PROJECT', dirname(dirname(__FILE__)) . '/');
/**
* Include paths
*/
include_once PATH_PROJECT . 'config/paths.php';
/**
* @see Zym_App
*/
require_once 'Zym/App.php';
/**
* @see Zend_Controller_Front
*/
require_once 'Zend/Controller/Front.php';
Zym_App::run(PATH_PROJECT . 'config/bootstrap.xml', Zym_App::ENV_PRODUCTION);
Zend_Controller_Front::getInstance()->dispatch(); | <?php
/**
* Zym Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @copyright Copyright (c) 2008 Zym. (http://www.zym-project.com/)
* @license http://www.zym-project.com/license New BSD License
*/
/**
* Project Path
*
*/
define('PATH_PROJECT', dirname(dirname(__FILE__)) . '/');
/**
* Include paths
*/
include_once PATH_PROJECT . 'config/paths.php';
/**
* @see Zym_App
*/
require_once 'Zym/App.php';
/**
* @see Zend_Controller_Front
*/
require_once 'Zend/Controller/Front.php';
Zym_App::run(PATH_PROJECT . 'config/bootstrap.xml', Zym_App::ENV_DEVELOPMENT);
Zend_Controller_Front::getInstance()->dispatch(); |
Destroy model only if it's present | var cdb = require('cartodb-deep-insights.js');
/**
* Widget definition Model
*/
module.exports = cdb.core.Model.extend({
initialize: function (attrs, options) {
if (!options.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
this._layerDefModel = options && options.layerDefinitionModel;
this._widgetModel = options && options.widgetModel;
this.once('destroy', this._onDestroy, this);
},
url: function () {
var url = this._layerDefModel.url() + '/widgets';
return this.isNew()
? url
: url + '/' + this.id;
},
setReferenceWidgetModel: function (referenceModel) {
if (!referenceModel || this._widgetModel) {
return false;
}
this._widgetModel = referenceModel;
},
updateReferenceWidgetModel: function () {
// this._widgetModel.set(this.toJSON()); ??
},
parse: function(attrs) {
attrs.options = JSON.parse(attrs.options);
return attrs;
},
toJson: function () {
return {
id: this.get('id'),
type: this.get('type'),
title: this.get('title'),
layer_id: this._layerDefModel.id,
options: this.get('options') || {}
};
},
_onDestroy: function () {
if (this._widgetModel) {
this._widgetModel.remove();
}
}
});
| var cdb = require('cartodb-deep-insights.js');
/**
* Widget definition Model
*/
module.exports = cdb.core.Model.extend({
initialize: function (attrs, options) {
if (!options.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
this._layerDefModel = options && options.layerDefinitionModel;
this._widgetModel = options && options.widgetModel;
this.once('destroy', this._onDestroy, this);
},
url: function () {
var url = this._layerDefModel.url() + '/widgets';
return this.isNew()
? url
: url + '/' + this.id;
},
setReferenceWidgetModel: function (referenceModel) {
if (!referenceModel || this._widgetModel) {
return false;
}
this._widgetModel = referenceModel;
},
updateReferenceWidgetModel: function () {
// this._widgetModel.set(this.toJSON()); ??
},
parse: function(attrs) {
attrs.options = JSON.parse(attrs.options);
return attrs;
},
toJson: function () {
return {
id: this.get('id'),
type: this.get('type'),
title: this.get('title'),
layer_id: this._layerDefModel.id,
options: this.get('options') || {}
};
},
_onDestroy: function () {
this._widgetModel.remove();
}
});
|
Add test for field not found (currently failing) | package narcissus
import (
"testing"
"honnef.co/go/augeas"
)
type foo struct {
A string `path:"a"`
}
func TestParseNotAPtr(t *testing.T) {
n := New(&augeas.Augeas{})
err := n.Parse(foo{}, "/files/some/path")
if err == nil {
t.Error("Expected an error, got nothing")
}
if err.Error() != "not a ptr" {
t.Errorf("Expected error not a ptr, got %s", err.Error())
}
}
func TestParseNotAStruct(t *testing.T) {
n := New(&augeas.Augeas{})
f := "foo"
err := n.Parse(&f, "/files/some/path")
if err == nil {
t.Error("Expected an error, got nothing")
}
if err.Error() != "not a struct" {
t.Errorf("Expected error not a struct, got %s", err.Error())
}
}
func TestParseFieldNotFound(t *testing.T) {
n := New(&augeas.Augeas{})
t.Skip("This causes a segfault with the Augeas lib. Open a bug!")
err := n.Parse(&foo{}, "/files/some/path")
if err == nil {
t.Error("Expected an error, got nothing")
}
}
| package narcissus
import (
"testing"
"honnef.co/go/augeas"
)
type foo struct {
}
func TestParseNotAPtr(t *testing.T) {
n := New(&augeas.Augeas{})
err := n.Parse(foo{}, "/files/some/path")
if err == nil {
t.Error("Expected an error, got nothing")
}
if err.Error() != "not a ptr" {
t.Errorf("Expected error not a ptr, got %s", err.Error())
}
}
func TestParseNotAStruct(t *testing.T) {
n := New(&augeas.Augeas{})
f := "foo"
err := n.Parse(&f, "/files/some/path")
if err == nil {
t.Error("Expected an error, got nothing")
}
if err.Error() != "not a struct" {
t.Errorf("Expected error not a struct, got %s", err.Error())
}
}
|
Remove FRG specific functionality from show-hide controller | import { Controller } from "@hotwired/stimulus";
import { Transition } from "./utils/transition";
export default class ShowHideController extends Controller {
static targets = ["content"];
toggleContent() {
this.toggle(this.contentTarget)
}
toggle(element) {
const hide = element.toggleAttribute("data-collapsed");
// cancel previous animation, if any
if (this.transition) this.transition.cancel();
const transition = this.transition = new Transition(element)
.addCallback("starting", function () {
element.setAttribute("data-collapsed-transitioning", "true")
})
.addCallback("complete", function () {
element.removeAttribute("data-collapsed-transitioning")
});
hide ? transition.collapse() : transition.expand();
transition.start();
}
}
| import { Controller } from "@hotwired/stimulus";
import { Transition } from "./utils/transition";
export default class ShowHideController extends Controller {
static targets = ["content", "priceBand"];
togglePriceBand() {
this.toggle(this.priceBandTarget)
}
toggleContent() {
this.toggle(this.contentTarget)
}
toggle(element) {
const hide = element.toggleAttribute("data-collapsed");
// cancel previous animation, if any
if (this.transition) this.transition.cancel();
const transition = this.transition = new Transition(element)
.addCallback("starting", function () {
element.setAttribute("data-collapsed-transitioning", "true")
})
.addCallback("complete", function () {
element.removeAttribute("data-collapsed-transitioning")
});
hide ? transition.collapse() : transition.expand();
transition.start();
}
}
|
Change the show prefixes commmand output. | package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixMapper();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String key : map.keySet()) {
String prefix = key;
if (StringUtils.isEmpty(prefix)) {
prefix = "(default)"; //
}
out.println(prefix + " = " + map.get(key));
}
}
out.println();
}
}
| package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixMapper();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String prefix : map.keySet()) {
out.println(prefix + ": " + map.get(prefix));
}
}
out.println();
}
}
|
Remove dropbox and boto as dependencies because they are optional and boto is not py3 compat | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
packages = []
package_dir = "dbbackup"
for dirpath, dirnames, filenames in os.walk(package_dir):
# ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
if dirname.startswith("."):
del dirnames[i]
if "__init__.py" in filenames:
pkg = dirpath.replace(os.path.sep, '.')
if os.path.altsep:
pkg = pkg.replace(os.path.altsep, '.')
packages.append(pkg)
setup(
name='django-dbbackup',
version='1.9.0',
description='Management commands to help backup and restore a project database to AmazonS3, Dropbox or local disk.',
long_description=read('README.md'),
author='Michael Shepanski',
author_email='mjs7231@gmail.com',
install_requires=[],
license='BSD',
url='http://bitbucket.org/mjs7231/django-dbbackup',
keywords=['django', 'dropbox', 'database', 'backup', 'amazon', 's3'],
packages=packages
)
| import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
packages = []
package_dir = "dbbackup"
for dirpath, dirnames, filenames in os.walk(package_dir):
# ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
if dirname.startswith("."):
del dirnames[i]
if "__init__.py" in filenames:
pkg = dirpath.replace(os.path.sep, '.')
if os.path.altsep:
pkg = pkg.replace(os.path.altsep, '.')
packages.append(pkg)
setup(
name='django-dbbackup',
version='1.9.0',
description='Management commands to help backup and restore a project database to AmazonS3, Dropbox or local disk.',
long_description=read('README.md'),
author='Michael Shepanski',
author_email='mjs7231@gmail.com',
install_requires=['boto', 'dropbox'],
license='BSD',
url='http://bitbucket.org/mjs7231/django-dbbackup',
keywords=['django', 'dropbox', 'database', 'backup', 'amazon', 's3'],
packages=packages
)
|
Fix typo in trigger() arguments. | function on(nm, cb, capture) {
this.each(function(el) {
el.addEventListener(nm, cb, capture);
});
return this;
}
function off(nm, cb, capture) {
this.each(function(el) {
el.removeEventListener(nm, cb, capture);
});
return this;
}
function trigger(event, bubbles, cancelable, type) {
bubbles = typeof(bubbles) === undefined ? true : bubbles;
cancelable = typeof(cancelable) === undefined ? true : cancelable;
type = type || 'HTMLEvents';
this.each(function(el) {
if(document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
// event type,bubbling,cancelable
evt.initEvent(event, bubbles, cancelable);
return !el.dispatchEvent(evt);
}else{
// dispatch for IE
var evt = document.createEventObject();
return el.fireEvent('on' + event, evt)
}
});
}
function click(bubbles, cancelable) {
return this.trigger('click', bubbles, cancelable, 'MouseEvents');
}
module.exports = function() {
this.on = on;
this.off = off;
this.trigger = trigger;
this.click = click;
}
| function on(nm, cb, capture) {
this.each(function(el) {
el.addEventListener(nm, cb, capture);
});
return this;
}
function off(nm, cb, capture) {
this.each(function(el) {
el.removeEventListener(nm, cb, capture);
});
return this;
}
function trigger(event, bubbles, cancelable, group) {
bubbles = typeof(bubbles) === undefined ? true : bubbles;
cancelable = typeof(cancelable) === undefined ? true : cancelable;
type = type || 'HTMLEvents';
this.each(function(el) {
if(document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
// event type,bubbling,cancelable
evt.initEvent(event, bubbles, cancelable);
return !el.dispatchEvent(evt);
}else{
// dispatch for IE
var evt = document.createEventObject();
return el.fireEvent('on' + event, evt)
}
});
}
function click(bubbles, cancelable) {
return this.trigger('click', bubbles, cancelable, 'MouseEvents');
}
module.exports = function() {
this.on = on;
this.off = off;
this.trigger = trigger;
this.click = click;
}
|
Add babel-polyfill to aquifers SPA | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import BootstrapVue from 'bootstrap-vue'
import '@/common/assets/css/bootstrap-theme.min.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import store from './store'
import ApiService from '@/common/services/ApiService.js'
ApiService.init()
Vue.use(BootstrapVue)
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
})
| /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Vue from 'vue'
import App from './App'
import BootstrapVue from 'bootstrap-vue'
import '@/common/assets/css/bootstrap-theme.min.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import store from './store'
import ApiService from '@/common/services/ApiService.js'
ApiService.init()
Vue.use(BootstrapVue)
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
})
|
Fix import and update help
Use relative module name
The script may be invoked from a single executable without py extension. | #! /usr/bin/python
"""
This script accepts a string with the following syntax:
Get the list of classes that a PHP class depends on.
Generate PHP code that
defines the fields with corresponding
names ( same name as the class name but with the first letter
converted to lower case ).
defines the constructor.
Print out the code to the console.
"""
import sys
from generator import Generator
from pyperclip.pyperclip import copy
def main():
"""
Parse arguments from command line
"""
argv = sys.argv
length = len(argv)
if length != 2:
print_help()
exit()
dependent_list_string = sys.argv[1]
statement = Generator.generate_statements(dependent_list_string)
copy(statement)
print statement
def print_help():
"""
Prints the help string for this script
"""
print "Run this script/executable with the following parameter <dependent class list string>."
main()
| #! /usr/bin/python
"""
This script accepts a string with the following syntax:
Get the list of classes that a PHP class depends on.
Generate PHP code that
defines the fields with corresponding
names ( same name as the class name but with the first letter
converted to lower case ).
defines the constructor.
Print out the code to the console.
"""
import sys
from generator.generator import Generator
from pyperclip.pyperclip import copy
def main():
"""
Parse arguments from command line
"""
argv = sys.argv
length = len(argv)
if length != 2:
print_help()
exit()
dependent_list_string = sys.argv[1]
statement = Generator.generate_statements(dependent_list_string)
copy(statement)
print statement
def print_help():
"""
Prints the help string for this script
"""
print "php-di-gen.py <dependent class list string>"
main()
|
Remove telemetry config from 2.0 sample | // Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "e3b9ad76-9763-4827-b088-80c7a7888f79",
authority: "https://login.microsoftonline.com/tfp/msidlabb2c.onmicrosoft.com/B2C_1_SISOPolicy/",
knownAuthorities: ["login.microsoftonline.com"]
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["https://msidlabb2c.onmicrosoft.com/msidlabb2capi/read"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
}; | // Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "e3b9ad76-9763-4827-b088-80c7a7888f79",
authority: "https://login.microsoftonline.com/tfp/msidlabb2c.onmicrosoft.com/B2C_1_SISOPolicy/",
knownAuthorities: ["login.microsoftonline.com"]
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
telemetry: {
applicationName: 'msalVanillaTestApp',
applicationVersion: 'test1.0',
telemetryEmitter: (events) => {
console.log("Telemetry Events", events);
}
}
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["https://msidlabb2c.onmicrosoft.com/msidlabb2capi/read"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
}; |
Add a wider margin of accuracy | PI = 3.141592654
SAMPLE_TIME = 5
FRAMES_PER_SEC = 30
SEC_PER_MIN = 60
RATE_RANGE = (95, 125) # 100 - 120 BPM (plus some error in measurement)
DEPTH_RANGE = (1.95, 5) # At least 2 in (plus some error in measurement)
RECOIL_THRESH = 0.2 # Allow for FULL chest recoil
# Color ranges
GREEN_COLOR_MIN = (38, 68, 87)
GREEN_COLOR_MAX = (72, 183, 255)
VIOLET_COLOR_MIN = (140, 110, 21)
VIOLET_COLOR_MAX = (206, 255, 236)
YELLOW_COLOR_MIN = (10, 110, 96)
YELLOW_COLOR_MAX = (47, 255, 255)
def ftoi_point(point):
return int(point[0]), int(point[1])
def get_ellipse_size(ellipse):
return max(ellipse[1][0], ellipse[1][1])
def ellipse_area(ellipse):
return ellipse[1][0] * ellipse[1][1] * PI / 4
def get_pixel_size(marker):
return get_ellipse_size(marker[1])
| PI = 3.141592654
SAMPLE_TIME = 5
FRAMES_PER_SEC = 30
SEC_PER_MIN = 60
RATE_RANGE = (95, 125) # 100 - 120 BPM (plus some error in measurement)
DEPTH_RANGE = (2, 5) # At least 2 in (plus some error in measurement)
RECOIL_THRESH = 0.2 # Allow for FULL chest recoil
# Color ranges
GREEN_COLOR_MIN = (38, 68, 87)
GREEN_COLOR_MAX = (72, 183, 255)
VIOLET_COLOR_MIN = (140, 110, 21)
VIOLET_COLOR_MAX = (206, 255, 236)
YELLOW_COLOR_MIN = (10, 110, 96)
YELLOW_COLOR_MAX = (47, 255, 255)
def ftoi_point(point):
return int(point[0]), int(point[1])
def get_ellipse_size(ellipse):
return max(ellipse[1][0], ellipse[1][1])
def ellipse_area(ellipse):
return ellipse[1][0] * ellipse[1][1] * PI / 4
def get_pixel_size(marker):
return get_ellipse_size(marker[1])
|
Use docker connect env vars | 'use strict';
var fs = require('fs');
var crypto = require('crypto');
module.exports = {
root: '',
db: {
host: process.env.RETHINKDB_PORT_29015_TCP_ADDR,
port: process.env.RETHINKDB_PORT_28015_TCP_PORT,
db: 'gandhi'
},
pool: {
max: 1,
min: 1,
timeout: 30000
},
redis: {
host: process.env.REDIS_PORT_6379_TCP_ADDR || '127.0.0.1',
port: process.env.REDIS_PORT_6379_TCP_PORT || 6379
},
lock: {
retry: 50,
timeout: 30000
},
auth: {
secret: 'rubber bunny'
},
mail: {
transport: null,
defaults: {
from: 'test@test.gandhi.io'
}
},
modules: fs.readdirSync(__dirname + '/lib/modules').map(function(dir){
return __dirname + '/lib/modules/' + dir;
}),
files: {
directory: __dirname + '/uploads'
},
port: 3000,
log: false
};
| 'use strict';
var fs = require('fs');
var crypto = require('crypto');
module.exports = {
root: '',
db: {
host: 'localhost',
db: 'gandhi'
},
pool: {
max: 1,
min: 1,
timeout: 30000
},
redis: {
host: process.env.REDIS_PORT_6379_TCP_ADDR || '127.0.0.1',
port: process.env.REDIS_PORT_6379_TCP_PORT || 6379
},
lock: {
retry: 50,
timeout: 30000
},
auth: {
secret: 'rubber bunny'
},
mail: {
transport: null,
defaults: {
from: 'test@test.gandhi.io'
}
},
modules: fs.readdirSync(__dirname + '/lib/modules').map(function(dir){
return __dirname + '/lib/modules/' + dir;
}),
files: {
directory: __dirname + '/uploads'
},
port: 3000,
log: false
};
|
Tweak travis-ci settings for haystack setup and test | # This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.
# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.
DEBUG = False
# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'root',
'HOST': 'localhost',
'PORT': '',
'TEST': {
'CHARSET': 'utf8',
'COLLATION': 'utf8_general_ci',
},
},
}
# must be defined for initial setup
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr/test-derrida',
'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
}
}
# for unit tests, that swap test connection in for default
HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS
# secret key added as a travis build step
| # This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.
# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.
DEBUG = False
# include database settings to use Mariadb ver on production (5.5)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'root',
'HOST': 'localhost',
'PORT': '',
'TEST': {
'CHARSET': 'utf8',
'COLLATION': 'utf8_general_ci',
},
},
}
HAYSTACK_TEST_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr/test-derrida',
'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
}
}
# secret key added as a travis build step
|
Remove unnecessary MatAdd and MatMul imports | from matexpr import MatrixExpr
from sympy import Basic
class Transpose(MatrixExpr):
"""Matrix Transpose
Represents the transpose of a matrix expression.
Use .T as shorthand
>>> from sympy import MatrixSymbol, Transpose
>>> A = MatrixSymbol('A', 3, 5)
>>> B = MatrixSymbol('B', 5, 3)
>>> Transpose(A)
A'
>>> A.T
A'
>>> Transpose(A*B)
B'*A'
"""
is_Transpose = True
def __new__(cls, mat):
if not mat.is_Matrix:
return mat
if hasattr(mat, '_eval_transpose'):
return mat._eval_transpose()
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
@property
def shape(self):
return self.arg.shape[::-1]
def _entry(self, i, j):
return self.arg._entry(j, i)
def _eval_transpose(self):
return self.arg
| from matexpr import MatrixExpr
from sympy import Basic
class Transpose(MatrixExpr):
"""Matrix Transpose
Represents the transpose of a matrix expression.
Use .T as shorthand
>>> from sympy import MatrixSymbol, Transpose
>>> A = MatrixSymbol('A', 3, 5)
>>> B = MatrixSymbol('B', 5, 3)
>>> Transpose(A)
A'
>>> A.T
A'
>>> Transpose(A*B)
B'*A'
"""
is_Transpose = True
def __new__(cls, mat):
if not mat.is_Matrix:
return mat
if hasattr(mat, '_eval_transpose'):
return mat._eval_transpose()
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
@property
def shape(self):
return self.arg.shape[::-1]
def _entry(self, i, j):
return self.arg._entry(j, i)
def _eval_transpose(self):
return self.arg
from matmul import MatMul
from matadd import MatAdd
|
Allow to specify a node name to look for as navmesh
This is useful for models that already embed a navmesh, as we can just use them as they are and not e.g. extract the navmesh in a separate model. | /**
* nav-mesh
*
* Waits for a mesh to be loaded on the current entity, then sets it as the
* nav mesh in the pathfinding system.
*/
module.exports = AFRAME.registerComponent('nav-mesh', {
schema: {
nodeName: {type: 'string'}
},
init: function () {
this.system = this.el.sceneEl.systems.nav;
this.hasLoadedNavMesh = false;
this.nodeName = this.data.nodeName;
this.el.addEventListener('object3dset', this.loadNavMesh.bind(this));
},
play: function () {
if (!this.hasLoadedNavMesh) this.loadNavMesh();
},
loadNavMesh: function () {
var self = this;
const object = this.el.getObject3D('mesh');
const scene = this.el.sceneEl.object3D;
if (!object) return;
let navMesh;
object.traverse((node) => {
if (node.isMesh &&
(!self.nodeName || node.name === self.nodeName)) navMesh = node;
});
if (!navMesh) return;
const navMeshGeometry = navMesh.geometry.isBufferGeometry
? new THREE.Geometry().fromBufferGeometry(navMesh.geometry)
: navMesh.geometry.clone();
scene.updateMatrixWorld();
navMeshGeometry.applyMatrix(navMesh.matrixWorld);
this.system.setNavMeshGeometry(navMeshGeometry);
this.hasLoadedNavMesh = true;
}
});
| /**
* nav-mesh
*
* Waits for a mesh to be loaded on the current entity, then sets it as the
* nav mesh in the pathfinding system.
*/
module.exports = AFRAME.registerComponent('nav-mesh', {
init: function () {
this.system = this.el.sceneEl.systems.nav;
this.hasLoadedNavMesh = false;
this.el.addEventListener('object3dset', this.loadNavMesh.bind(this));
},
play: function () {
if (!this.hasLoadedNavMesh) this.loadNavMesh();
},
loadNavMesh: function () {
const object = this.el.getObject3D('mesh');
const scene = this.el.sceneEl.object3D;
if (!object) return;
let navMesh;
object.traverse((node) => {
if (node.isMesh) navMesh = node;
});
if (!navMesh) return;
const navMeshGeometry = navMesh.geometry.isBufferGeometry
? new THREE.Geometry().fromBufferGeometry(navMesh.geometry)
: navMesh.geometry.clone();
scene.updateMatrixWorld();
navMeshGeometry.applyMatrix(navMesh.matrixWorld);
this.system.setNavMeshGeometry(navMeshGeometry);
this.hasLoadedNavMesh = true;
}
});
|
Update test to support Node.js 6.1.0 | import test from 'ava';
import path from 'path';
import JsonFileConfigurationProvider from '../src/lib/jsonFileConfigurationProvider';
test('Constructor should throw for missing filePath', t => {
t.throws(
() => new JsonFileConfigurationProvider(),
'filePath must be provided.');
});
test('Configuration should set filePath', t => {
const testFilePath = 'test.json';
const provider = new JsonFileConfigurationProvider(testFilePath);
t.is(provider.filePath, testFilePath);
});
test('getConfiguration should throw if file does not exist', t => {
const testFilePath = 'test.json';
const provider = new JsonFileConfigurationProvider(testFilePath);
t.throws(() => provider.getConfiguration(), /ENOENT: no such file or directory/);
});
test('getConfiguration should throw for invalid JSON', t => {
const testFilePath = path.resolve(__dirname, '../test/fixtures/invalidConfiguration.json');
const provider = new JsonFileConfigurationProvider(testFilePath);
t.throws(() => provider.getConfiguration(), /Unexpected token T/);
});
test('getConfiguration should return expected configuration when valid JSON', t => {
const testFilePath = path.resolve(__dirname, '../test/fixtures/validConfiguration.json');
const provider = new JsonFileConfigurationProvider(testFilePath);
const configuration = provider.getConfiguration();
t.is(configuration.analyzers.length, 1);
t.is(configuration.analyzers[0], 'spelling');
t.is(configuration.rules['spelling-error'], 'error');
});
| import test from 'ava';
import path from 'path';
import JsonFileConfigurationProvider from '../src/lib/jsonFileConfigurationProvider';
test('Constructor should throw for missing filePath', t => {
t.throws(
() => new JsonFileConfigurationProvider(),
'filePath must be provided.');
});
test('Configuration should set filePath', t => {
const testFilePath = 'test.json';
const provider = new JsonFileConfigurationProvider(testFilePath);
t.is(provider.filePath, testFilePath);
});
test('getConfiguration should throw if file does not exist', t => {
const testFilePath = 'test.json';
const provider = new JsonFileConfigurationProvider(testFilePath);
t.throws(() => provider.getConfiguration(), /ENOENT: no such file or directory/);
});
test('getConfiguration should throw for invalid JSON', t => {
const testFilePath = path.resolve(__dirname, '../test/fixtures/invalidConfiguration.json');
const provider = new JsonFileConfigurationProvider(testFilePath);
t.throws(() => provider.getConfiguration(), 'Unexpected token T');
});
test('getConfiguration should return expected configuration when valid JSON', t => {
const testFilePath = path.resolve(__dirname, '../test/fixtures/validConfiguration.json');
const provider = new JsonFileConfigurationProvider(testFilePath);
const configuration = provider.getConfiguration();
t.is(configuration.analyzers.length, 1);
t.is(configuration.analyzers[0], 'spelling');
t.is(configuration.rules['spelling-error'], 'error');
});
|
Put some useful stuff into CLI's locals | #!/usr/bin/python
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
# Turn on extra info for event exceptions
import pox.lib.revent.revent as revent
revent.showEventExceptions = True
def startup ():
core.register("topology", pox.topology.topology.Topology())
core.register("openflow", pox.openflow.openflow.OpenFlowHub())
core.register("switch", pox.dumb_l3_switch.dumb_l3_switch.dumb_l3_switch())
pox.openflow.of_01.start()
if __name__ == '__main__':
try:
startup()
core.goUp()
except:
import traceback
traceback.print_exc()
import code
code.interact('Ready.', local=locals())
pox.core.core.quit()
| #!/usr/bin/python
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
# Turn on extra info for event exceptions
import pox.lib.revent.revent as revent
revent.showEventExceptions = True
def startup ():
core.register("topology", pox.topology.topology.Topology())
core.register("openflow", pox.openflow.openflow.OpenFlowHub())
core.register("switch", pox.dumb_l3_switch.dumb_l3_switch.dumb_l3_switch())
pox.openflow.of_01.start()
if __name__ == '__main__':
try:
startup()
core.goUp()
except:
import traceback
traceback.print_exc()
import code
code.interact('Ready.')
pox.core.core.quit()
|
Check the version of any of the supported Psycopg2 packages
A check was introduced in commit 8e0c4857a1c08f257b95d3b1ee5f6eb795d55cdc which
would check what version of the 'psycopg2' Python (pip) package was installed
as the dependency was removed from setup.py.
The check would however only check the 'psycopg2' package and not the other two
supported providers of the psycopg2 module, which meant importing the
sqlalchemy_redshift module would throw an exception, even though they were
installed.
This changes the check to check for either of the three supported psycopg2
packages and throws an exception if any of them fail to validate. | from pkg_resources import DistributionNotFound, get_distribution, parse_version
try:
import psycopg2 # noqa: F401
except ImportError:
raise ImportError(
'No module named psycopg2. Please install either '
'psycopg2 or psycopg2-binary package for CPython '
'or psycopg2cffi for Pypy.'
) from None
for package in ['psycopg2', 'psycopg2-binary', 'psycopg2cffi']:
try:
if get_distribution(package).parsed_version < parse_version('2.5'):
raise ImportError('Minimum required version for psycopg2 is 2.5')
break
except DistributionNotFound:
pass
else:
raise ImportError(
'A module was found named psycopg2, '
'but the version of it could not be checked '
'as it was neither the Python package psycopg2, '
'psycopg2-binary or psycopg2cffi.'
)
__version__ = get_distribution('sqlalchemy-redshift').version
from sqlalchemy.dialects import registry
registry.register("redshift", "sqlalchemy_redshift.dialect", "RedshiftDialect")
registry.register(
"redshift.psycopg2", "sqlalchemy_redshift.dialect", "RedshiftDialect"
)
| from pkg_resources import get_distribution, parse_version
try:
import psycopg2 # noqa: F401
if get_distribution('psycopg2').parsed_version < parse_version('2.5'):
raise ImportError('Minimum required version for psycopg2 is 2.5')
except ImportError:
raise ImportError(
'No module named psycopg2. Please install either '
'psycopg2 or psycopg2-binary package for CPython '
'or psycopg2cffi for Pypy.'
)
__version__ = get_distribution('sqlalchemy-redshift').version
from sqlalchemy.dialects import registry
registry.register("redshift", "sqlalchemy_redshift.dialect", "RedshiftDialect")
registry.register(
"redshift.psycopg2", "sqlalchemy_redshift.dialect", "RedshiftDialect"
)
|
Add get_log_entries method to mock model. | <?php if ( ! defined('EXT')) exit('Invalid file request.');
/**
* Mock OmniLog model.
*
* @author Stephen Lewis (http://github.com/experience/)
* @copyright Experience Internet
* @package Omnilog
*/
class Mock_omnilog_model {
public function get_log_entries($site_id = NULL, $limit = NULL) {}
public function get_package_name() {}
public function get_package_theme_url() {}
public function get_package_version() {}
public function get_site_id() {}
public function install_module() {}
public function install_module_actions() {}
public function install_module_register() {}
public function notify_site_admin_of_log_entry(Omnilog_entry $entry) {}
public function save_entry_to_log(Omnilog_entry $entry) {}
public function uninstall_module() {}
public function update_module($installed_version = '') {}
}
/* End of file : mock.omnilog_model.php */
/* File location : third_party/omnilog/tests/mocks/mock.omnilog_model.php */
| <?php if ( ! defined('EXT')) exit('Invalid file request.');
/**
* Mock OmniLog model.
*
* @author Stephen Lewis (http://github.com/experience/)
* @copyright Experience Internet
* @package Omnilog
*/
class Mock_omnilog_model {
public function get_package_name() {}
public function get_package_theme_url() {}
public function get_package_version() {}
public function get_site_id() {}
public function install_module() {}
public function install_module_actions() {}
public function install_module_register() {}
public function notify_site_admin_of_log_entry(Omnilog_entry $entry) {}
public function save_entry_to_log(Omnilog_entry $entry) {}
public function uninstall_module() {}
public function update_module($installed_version = '') {}
}
/* End of file : mock.omnilog_model.php */
/* File location : third_party/omnilog/tests/mocks/mock.omnilog_model.php */
|
Fix recursive inclusion of the toolbar page
This is most likely to happen during a 404 page which includes
the toolbar, which includes the toolbar which is a 404 page, which
includes... | <?php
class GlobalNavIteratorProperties implements TemplateIteratorProvider {
public static function get_template_iterator_variables() {
return array(
'GlobalNav',
);
}
public function iteratorProperties($pos, $totalItems) {
// If we're already in a toolbarrequest, don't recurse further
// This is most likely to happen during a 404
if (!empty($_GET['globaltoolbar'])) {
$this->globalNav = '';
return;
}
$host = GlobalNavSiteTreeExtension::get_toolbar_hostname();
$path = Config::inst()->get('GlobalNav','snippet_path');
$html = @file_get_contents(Controller::join_links($host, $path, '?globaltoolbar=true'));
if (empty($html)) {
$this->globalNav = '';
}
$this->globalNav = $html;
}
public function GlobalNav() {
Requirements::css(Controller::join_links(GlobalNavSiteTreeExtension::get_toolbar_hostname(), Config::inst()->get('GlobalNav','css_path')));
$html = DBField::create_field('HTMLText',$this->globalNav);
$html->setOptions(array('shortcodes' => false));
return $html;
}
}
| <?php
class GlobalNavIteratorProperties implements TemplateIteratorProvider {
public static function get_template_iterator_variables() {
return array(
'GlobalNav',
);
}
public function iteratorProperties($pos, $totalItems) {
$host = GlobalNavSiteTreeExtension::get_toolbar_hostname();
$path = Config::inst()->get('GlobalNav','snippet_path');
$html = @file_get_contents(Controller::join_links($host,$path));
if (empty($html)) {
$this->globalNav = '';
}
$this->globalNav = $html;
}
public function GlobalNav() {
Requirements::css(Controller::join_links(GlobalNavSiteTreeExtension::get_toolbar_hostname(), Config::inst()->get('GlobalNav','css_path')));
$html = DBField::create_field('HTMLText',$this->globalNav);
$html->setOptions(array('shortcodes' => false));
return $html;
}
}
|
Extend Closeable instead of AutoCloseable. | /**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.api.scan;
import java.io.Closeable;
public interface NodeRangeReader extends Iterable<NodeLabelRange>, Closeable
{
}
| /**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.api.scan;
import java.io.IOException;
public interface NodeRangeReader extends Iterable<NodeLabelRange>, AutoCloseable
{
@Override
public void close() throws IOException;
}
|
Remove input import from six.moves | import random
import unittest
from .config import *
from tweepy import API, OAuthHandler
class TweepyAuthTests(unittest.TestCase):
def testoauth(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
# test getting access token
auth_url = auth.get_authorization_url()
print('Please authorize: ' + auth_url)
verifier = input('PIN: ').strip()
self.assertTrue(len(verifier) > 0)
access_token = auth.get_access_token(verifier)
self.assertTrue(access_token is not None)
# build api object test using oauth
api = API(auth)
s = api.update_status('test %i' % random.randint(0, 1000))
api.destroy_status(s.id)
def testaccesstype(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
auth_url = auth.get_authorization_url(access_type='read')
print('Please open: ' + auth_url)
answer = input('Did Twitter only request read permissions? (y/n) ')
self.assertEqual('y', answer.lower())
| import random
import unittest
from six.moves import input
from .config import *
from tweepy import API, OAuthHandler
class TweepyAuthTests(unittest.TestCase):
def testoauth(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
# test getting access token
auth_url = auth.get_authorization_url()
print('Please authorize: ' + auth_url)
verifier = input('PIN: ').strip()
self.assertTrue(len(verifier) > 0)
access_token = auth.get_access_token(verifier)
self.assertTrue(access_token is not None)
# build api object test using oauth
api = API(auth)
s = api.update_status('test %i' % random.randint(0, 1000))
api.destroy_status(s.id)
def testaccesstype(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
auth_url = auth.get_authorization_url(access_type='read')
print('Please open: ' + auth_url)
answer = input('Did Twitter only request read permissions? (y/n) ')
self.assertEqual('y', answer.lower())
|
Use super() ('newstyle class' in 2.7+) | from __future__ import unicode_literals
import logging
import sys
from pre_commit import color
LOG_LEVEL_COLORS = {
'DEBUG': '',
'INFO': '',
'WARNING': color.YELLOW,
'ERROR': color.RED,
}
class LoggingHandler(logging.Handler):
def __init__(self, use_color, write=sys.stdout.write):
super(LoggingHandler, self).__init__()
self.use_color = use_color
self.__write = write
def emit(self, record):
self.__write(
u'{0}{1}\n'.format(
color.format_color(
'[{0}]'.format(record.levelname),
LOG_LEVEL_COLORS[record.levelname],
self.use_color,
) + ' ',
record.getMessage(),
)
)
sys.stdout.flush()
| from __future__ import unicode_literals
import logging
import sys
from pre_commit import color
LOG_LEVEL_COLORS = {
'DEBUG': '',
'INFO': '',
'WARNING': color.YELLOW,
'ERROR': color.RED,
}
class LoggingHandler(logging.Handler):
def __init__(self, use_color, write=sys.stdout.write):
logging.Handler.__init__(self)
self.use_color = use_color
self.__write = write
def emit(self, record):
self.__write(
u'{0}{1}\n'.format(
color.format_color(
'[{0}]'.format(record.levelname),
LOG_LEVEL_COLORS[record.levelname],
self.use_color,
) + ' ',
record.getMessage(),
)
)
sys.stdout.flush()
|
Move "action" field into "data" field | 'use strict';
/**
GCM helper
----------
Usage:
let push = require('./helpers/push')('/messages');
push.send('create', message);
*/
let gcm = require('node-gcm');
let config = rootRequire('config/config');
let log = require('./logger');
module.exports = function (topic) {
return {
send: (action, doc) => {
let message = new gcm.Message({
data: {
action,
document: doc
}
});
let sender = new gcm.Sender(config.gcm.apiKey);
sender.send(message, {topic: `/topics${topic}`}, 10, (err, result) => {
if (err) {
log.error(`[GCM error]`);
log.error(err);
} else {
log.info(`[GCM result]`);
log.info(result);
}
});
}
};
}; | 'use strict';
/**
GCM helper
----------
Usage:
let push = require('./helpers/push')('/messages');
push.send('create', message);
*/
let gcm = require('node-gcm');
let config = rootRequire('config/config');
let log = require('./logger');
module.exports = function (topic) {
return {
send: (action, doc) => {
let message = new gcm.Message({action, data: {document: doc}});
let sender = new gcm.Sender(config.gcm.apiKey);
sender.send(message, {topic: `/topics${topic}`}, 10, (err, result) => {
if (err) {
log.error(`[GCM error]`);
log.error(err);
} else {
log.info(`[GCM result]`);
log.info(result);
}
});
}
};
}; |
Change virtual path because nginx | // Create an app
var path = require("path")
var fs = require("fs")
var server = require("diet")
var app = server()
var auth = require('diet-auth')(app)
app.listen("http://127.0.0.1:3000") // nginx
var dir = path.join(__dirname, "routes")
fs.readdirSync(dir).forEach(function(file) {
var route = require("./routes/" + file);
console.log(route.path)
app.get(route.path, route.func)
});
// Setup Auth Service
var google = auth('google', {
id : '1097854755118-5415dgruuvifdgumbt12n79kvebdhlqp.apps.googleusercontent.com',
secret : 'o-5-RhA3bMpK00o3ZmHSpnsS',
scope : 'plus.login'
})
// Listen on GET /auth/google/redirect
app.get(google.redirect, function($){
if($.passed){
console.log($.data.user)
$.end('Hello ' + $.data.user.nickname + ' !')
} else {
$.end('Something went wrong: ' + $.error)
}
})
app.missing(function($){
$.end("My Custom 404 Not Found Page")
}) | // Create an app
var path = require("path")
var fs = require("fs")
var server = require("diet")
var app = server()
var auth = require('diet-auth')(app)
app.listen("http://localhost:8000")
var dir = path.join(__dirname, "routes")
fs.readdirSync(dir).forEach(function(file) {
var route = require("./routes/" + file);
console.log(route.path)
app.get(route.path, route.func)
});
// Setup Auth Service
var google = auth('google', {
id : '1097854755118-5415dgruuvifdgumbt12n79kvebdhlqp.apps.googleusercontent.com',
secret : 'o-5-RhA3bMpK00o3ZmHSpnsS',
scope : 'plus.login'
})
// Listen on GET /auth/google/redirect
app.get(google.redirect, function($){
if($.passed){
console.log($.data.user)
$.end('Hello ' + $.data.user.nickname + ' !')
} else {
$.end('Something went wrong: ' + $.error)
}
})
app.missing(function($){
$.end("My Custom 404 Not Found Page")
}) |
Create final version of User SignIn and Error Handling | 'use strict';
angular.module('myApp.register',['ngRoute', 'firebase'])
//Declare route
.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/register', {
templateUrl: 'register/register.html',
controller: 'RegisterCtrl'
});
}])
// Register Controller
.controller('RegisterCtrl', ['$scope', '$location', '$firebaseAuth', function($scope, $location, $firebaseAuth){
var firebaseObj = new Firebase("https://blazing-heat-8641.firebaseio.com");
var auth = $firebaseAuth(firebaseObj);
$scope.signUp = function(){
if(!$scope.regForm.$invalid){
var email = $scope.user.email;
var password = $scope.user.password;
if (email && password) {
auth.$createUser({email, password})
.then(function() {
console.log("Successfully created user account");
$location.path('/home');
}, function(error){
console.log("Error creating user:", error);
$scope.regError = true;
$scope.regErrorMessage = error.message;
});
}
}
};
}]);
| 'use strict';
angular.module('myApp.register',['ngRoute', 'firebase'])
//Declare route
.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/register', {
templateUrl: 'register/register.html',
controller: 'RegisterCtrl'
});
}])
// Register Controller
.controller('RegisterCtrl', ['$scope', '$location', '$firebaseAuth', function($scope, $location, $firebaseAuth){
var firebaseObj = new Firebase("https://blazing-heat-8641.firebaseio.com");
var auth = $firebaseAuth(firebaseObj);
$scope.signUp = function(){
if(!$scope.regForm.$invalid){
var email = $scope.user.email;
var password = $scope.user.password;
// if (email && password) {
auth.$createUser({email, password})
.then(function() {
console.log("Successfully created user account");
$location.path('/home');
}, function(error){
console.log("Error creating user:", error);
$scope.regError = true;
$scope.regErrorMessage = error.message;
});
// }
}
};
}]);
|
Refactor layout controllers layout attributes to static members | Space.Object.extend('Todos.LayoutController', {
mixin: [
Space.messaging.EventSubscribing
],
dependencies: {
layout: 'Layout',
_: 'underscore'
},
_currentLayout: null,
_currentSections: {},
eventSubscriptions() {
return [{
'Todos.RouteTriggered': function(event) {
switch (event.routeName) {
//case 'routeName': this._routeHanlder(); break;
default: this._renderIndexPage();
}
}
}];
},
_renderIndexPage() {
this._render('index', {
input: 'input',
todo_list: 'todo_list',
footer: 'footer'
});
},
_render(layout, sections) {
this._currentLayout = layout;
this._.extend(this._currentSections, sections);
this.layout.render(this._currentLayout, this._currentSections);
},
_updateSections(sections) {
this._render(this._currentLayout, sections);
}
});
| Space.Object.extend('Todos.LayoutController', {
mixin: [
Space.messaging.EventSubscribing
],
dependencies: {
layout: 'Layout',
_: 'underscore'
},
Constructor() {
this._currentLayout = null;
this._currentSections = {};
},
eventSubscriptions() {
return [{
'Todos.RouteTriggered': function(event) {
switch (event.routeName) {
//case 'routeName': this._routeHanlder(); break;
default: this._renderIndexPage();
}
}
}];
},
_renderIndexPage() {
this._render('index', {
input: 'input',
todo_list: 'todo_list',
footer: 'footer'
});
},
_render(layout, sections) {
this._currentLayout = layout;
this._.extend(this._currentSections, sections);
this.layout.render(this._currentLayout, this._currentSections);
},
_updateSections(sections) {
this._render(this._currentLayout, sections);
}
});
|
Change script to update offering on Host instead Instance | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan)
strong_offering = infra_offering.offering
weaker_offering = plan_attr.get_weaker_offering()
for host in infra_offering.databaseinfra.hosts:
host.offering = strong_offering if host.database_instance() else weaker_offering
host.save()
| # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan)
strong_offering = infra_offering.offering
weaker_offering = plan_attr.get_weaker_offering()
for instance in infra_offering.databaseinfra.instances.all():
if instance.is_database:
instance.offering = strong_offering
else:
instance.oferring = weaker_offering
instance.save()
|
Make character stub for tests override the parent constructor | <?php
/**
* This file is part of the PierstovalCharacterManagerBundle package.
*
* (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pierstoval\Bundle\CharacterManagerBundle\Tests\Fixtures\Stubs\Entity;
use Doctrine\ORM\Mapping as ORM;
use Pierstoval\Bundle\CharacterManagerBundle\Entity\Character as BaseCharacter;
/**
* @ORM\Entity()
* @ORM\Table(name="character_stubs")
*/
class CharacterStub extends BaseCharacter
{
/**
* @var int
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct('Stub characte', 'stub-character');
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
}
| <?php
/**
* This file is part of the PierstovalCharacterManagerBundle package.
*
* (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pierstoval\Bundle\CharacterManagerBundle\Tests\Fixtures\Stubs\Entity;
use Doctrine\ORM\Mapping as ORM;
use Pierstoval\Bundle\CharacterManagerBundle\Entity\Character as BaseCharacter;
/**
* @ORM\Entity()
* @ORM\Table(name="character_stubs")
*/
class CharacterStub extends BaseCharacter
{
/**
* @var int
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
}
|
Use full class name for Context class | /**
* @fileoverview A JS interface to the Rhino parser.
*/
/**
* Parse a script resource and return its AST tree.
* @param resource {Resource} an instance of org.helma.repository.Resource
*/
exports.parseScriptResource = function(resource) {
return getParser().parse(resource.content, resource.name, 0);
};
/**
* Parse a script resource and apply the visitor function to its AST tree.
* The function takes one argument which is a org.mozilla.javascript.ast.AstNode.
* The function must return true to visit child nodes of the current node.
* @param resource {Resource} an instance of org.helma.repository.Resource
* @param visitorFunction {Function} the visitor function
*/
exports.visitScriptResource = function(resource, visitorFunction) {
var ast = getParser().parse(resource.content, resource.name, 0);
ast.visit(new org.mozilla.javascript.ast.NodeVisitor({
visit: visitorFunction
}));
};
function getParser() {
var ce = new org.mozilla.javascript.CompilerEnvirons();
ce.setRecordingComments(true);
ce.setRecordingLocalJsDocComments(true);
ce.initFromContext(org.mozilla.javascript.Context.getCurrentContext());
return new org.mozilla.javascript.Parser(ce, ce.getErrorReporter());
}
| /**
* @fileoverview A JS interface to the Rhino parser.
*/
/**
* Parse a script resource and return its AST tree.
* @param resource {Resource} an instance of org.helma.repository.Resource
*/
exports.parseScriptResource = function(resource) {
return getParser().parse(resource.content, resource.name, 0);
};
/**
* Parse a script resource and apply the visitor function to its AST tree.
* The function takes one argument which is a org.mozilla.javascript.ast.AstNode.
* The function must return true to visit child nodes of the current node.
* @param resource {Resource} an instance of org.helma.repository.Resource
* @param visitorFunction {Function} the visitor function
*/
exports.visitScriptResource = function(resource, visitorFunction) {
var ast = getParser().parse(resource.content, resource.name, 0);
ast.visit(new org.mozilla.javascript.ast.NodeVisitor({
visit: visitorFunction
}));
};
function getParser() {
var ce = new org.mozilla.javascript.CompilerEnvirons();
ce.setRecordingComments(true);
ce.setRecordingLocalJsDocComments(true);
ce.initFromContext(Context.getCurrentContext());
return new org.mozilla.javascript.Parser(ce, ce.getErrorReporter());
}
|
Remove unneeded abstract method implementation | <?php
/*
* This file is part of the Sonata project.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\PageBundle\Page\Service;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Sonata\PageBundle\Model\PageInterface;
/**
* Abstract page service that provides a basic implementation
*
* @author Olivier Paradis <paradis.olivier@gmail.com>
*/
abstract class BasePageService implements PageServiceInterface
{
/**
* Page service name used in the admin
*
* @var string
*/
protected $name;
/**
* Constructor
*
* @param string $name Page service name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
} | <?php
/*
* This file is part of the Sonata project.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\PageBundle\Page\Service;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Sonata\PageBundle\Model\PageInterface;
/**
* Abstract page service that provides a basic implementation
*
* @author Olivier Paradis <paradis.olivier@gmail.com>
*/
abstract class BasePageService implements PageServiceInterface
{
/**
* Page service name used in the admin
*
* @var string
*/
protected $name;
/**
* Constructor
*
* @param string $name Page service name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
abstract public function execute(PageInterface $page, Request $request, array $parameters = array(), Response $response = null);
} |
Remove redundant import from test | const { describe, it } = require('mocha')
const assert = require('assert')
const ECPair = require('../src/ecpair')
const Psbt = require('..').Psbt
const fixtures = require('./fixtures/psbt')
describe(`Psbt`, () => {
// constants
const keyPair = ECPair.fromPrivateKey(Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex'))
describe('signInput', () => {
fixtures.signInput.checks.forEach(f => {
it(f.description, () => {
const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt)
assert.doesNotThrow(() => {
psbtThatShouldsign.signInput(f.shouldSign.inputToCheck, keyPair)
})
const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt)
assert.throws(() => {
psbtThatShouldThrow.signInput(f.shouldThrow.inputToCheck, keyPair)
}, {message: f.shouldThrow.errorMessage})
})
})
})
})
| const { describe, it, beforeEach } = require('mocha')
const assert = require('assert')
const ECPair = require('../src/ecpair')
const Psbt = require('..').Psbt
const fixtures = require('./fixtures/psbt')
describe(`Psbt`, () => {
// constants
const keyPair = ECPair.fromPrivateKey(Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex'))
describe('signInput', () => {
fixtures.signInput.checks.forEach(f => {
it(f.description, () => {
const psbtThatShouldsign = Psbt.fromBase64(f.shouldSign.psbt)
assert.doesNotThrow(() => {
psbtThatShouldsign.signInput(f.shouldSign.inputToCheck, keyPair)
})
const psbtThatShouldThrow = Psbt.fromBase64(f.shouldThrow.psbt)
assert.throws(() => {
psbtThatShouldThrow.signInput(f.shouldThrow.inputToCheck, keyPair)
}, {message: f.shouldThrow.errorMessage})
})
})
})
})
|
Add dependency on `physicalproperty` module
Closes #23. | # -*- coding: utf-8 -*-
from setuptools import setup
import ibei
setup(name="ibei",
version=ibei.__version__,
author="Joshua Ryan Smith",
author_email="joshua.r.smith@gmail.com",
packages=["ibei", "physicalproperty"],
url="https://github.com/jrsmith3/ibei",
description="Calculator for incomplete Bose-Einstein integral",
classifiers=["Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Physics",
"Natural Language :: English", ],
install_requires=["numpy",
"sympy",
"astropy",
"physicalproperty"],)
| # -*- coding: utf-8 -*-
from setuptools import setup
import ibei
setup(name="ibei",
version=ibei.__version__,
author="Joshua Ryan Smith",
author_email="joshua.r.smith@gmail.com",
packages=["ibei", "physicalproperty"],
url="https://github.com/jrsmith3/ibei",
description="Calculator for incomplete Bose-Einstein integral",
classifiers=["Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Physics",
"Natural Language :: English", ],
install_requires=["numpy",
"sympy",
"astropy"],)
|
Add status code assertion in test case | package net.interfax.rest.client.impl;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import net.interfax.rest.client.InterFAXClient;
import net.interfax.rest.client.domain.Response;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
public class InterFAXJerseyClientTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
@Test
public void testSendFax() throws Exception {
String faxNumber = "+442084978672";
String absoluteFilePath = this.getClass().getClassLoader().getResource("test.pdf").getFile();
File file = new File(absoluteFilePath);
InterFAXClient interFAXClient = new InterFAXJerseyClient();
Response response = interFAXClient.sendFax(faxNumber, file);
Assert.assertEquals(201, response.getStatusCode());
}
} | package net.interfax.rest.client.impl;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import net.interfax.rest.client.InterFAXClient;
import net.interfax.rest.client.domain.Response;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
public class InterFAXJerseyClientTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
@Test
public void testSendFax() throws Exception {
String faxNumber = "+442084978672";
String absoluteFilePath = this.getClass().getClassLoader().getResource("test.pdf").getFile();
File file = new File(absoluteFilePath);
InterFAXClient interFAXClient = new InterFAXJerseyClient();
Response response = interFAXClient.sendFax(faxNumber, file);
System.out.println(response.getStatusCode());
}
} |
Fix secretName error while getting secret | const SecretsManager = require("./secretsmanager");
class Secrets {
constructor(options) {
this.options = options;
if(!options.isDev) {
if(!options.region || !options.secretName) {
throw new Error("Need both region and secretName in options");
}
this.manager = new SecretsManager(this.options.region);
}
}
async googleKey() {
if(this.options.isDev) {
return this.options.googleKey;
}
return this.getSecretsKey("GOOGLE_KEY_VALUE");
}
async recaptchaPrivateKey() {
if(this.options.isDev) {
return this.options.recaptchaPrivateKey;
}
return this.getSecretsKey("RECAPTCHA_PRIVATE_KEY");
}
async getSecretsKey(name) {
let secrets = await this.manager.getSecretValue(name);
return secrets[name];
}
}
module.exports = Secrets; | const SecretsManager = require("./secretsmanager");
class Secrets {
constructor(options) {
this.options = options;
if(!options.isDev) {
if(!options.region || !options.secretName) {
throw new Error("Need both region and secretName in options");
}
this.manager = new SecretsManager(this.options.region);
}
}
async googleKey() {
if(this.options.isDev) {
return this.options.googleKey;
}
return this.getSecretsKey("GOOGLE_KEY_VALUE");
}
async recaptchaPrivateKey() {
if(this.options.isDev) {
return this.options.recaptchaPrivateKey;
}
return this.getSecretsKey("RECAPTCHA_PRIVATE_KEY");
}
async getSecretsKey(name) {
let secrets = await this.manager.getSecretValue(this.config.secretName);
return secrets[name];
}
}
module.exports = Secrets; |
Update packaging for Dojo builder | var profile = (function () {
var testResourceRe = /^core\/tests\//,
copyOnly = function (filename, mid) {
var list = {
'core/package': 1,
'core/package.json': 1,
'core/tests': 1,
'core/third_party': 1,
'core/node_modules': 1
};
return (mid in list) ||
/^core\/tests\/\w+$/ ||
/^core\/node_modules\/\w+$/ ||
// /^core\/third_party\/\w+$/ ||
/(png|jpg|jpeg|gif|tiff)$/.test(filename);
};
return {
resourceTags: {
test: function (filename, mid) {
return testResourceRe.test(mid) || mid === 'core/tests';
},
copyOnly: function (filename, mid) {
return copyOnly(filename, mid);
},
amd: function (filename, mid) {
return !testResourceRe.test(mid) && !copyOnly(filename, mid) && /\.js$/.test(filename);
}
}
};
})(); | var profile = (function () {
var testResourceRe = /^core\/tests\//,
copyOnly = function (filename, mid) {
var list = {
'core/package': 1,
'core/package.json': 1,
'core/tests': 1,
'core/third_party': 1,
'core/node_modules': 1
};
return (mid in list) ||
/(png|jpg|jpeg|gif|tiff)$/.test(filename);
};
return {
resourceTags: {
test: function (filename, mid) {
return testResourceRe.test(mid) || mid === 'core/tests';
},
copyOnly: function (filename, mid) {
return copyOnly(filename, mid);
},
amd: function (filename, mid) {
return !testResourceRe.test(mid) && !copyOnly(filename, mid) && /\.js$/.test(filename);
}
}
};
})(); |
Put in a better fix for the asset injection routine | <?php namespace GeneaLabs\LaravelCasts\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\RedirectResponse;
class AssetInjection
{
public function handle($request, Closure $next)
{
$response = $next($request);
if (! method_exists($response, 'content')) {
return $response;
}
$content = $response->content();
if (preg_match('/<form/', $content)) {
return $response->setContent(str_replace(
'</body>',
'<script src="' . asset('genealabs-laravel-casts/app.js') . '"></script></body>',
$content
));
}
return $response;
}
}
| <?php namespace GeneaLabs\LaravelCasts\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\RedirectResponse;
class AssetInjection
{
public function handle($request, Closure $next)
{
$response = $next($request);
if (is_a($response, RedirectResponse::class)) {
return $response;
}
$content = $response->content();
if (preg_match('/<form/', $content)) {
return $response->setContent(str_replace(
'</body>',
'<script src="' . asset('genealabs-laravel-casts/app.js') . '"></script></body>',
$content
));
}
return $response;
}
}
|
Fix production build for rails-ujs. | import '../font_awesome_icons';
import '../reports';
import dataTablesInit from 'datatables.net';
import dataTablesBs5Init from 'datatables.net-bs5';
import Rails from 'rails-ujs';
import $ from 'jquery';
dataTablesInit(window, $);
dataTablesBs5Init(window, $);
// Conditional needed:
// https://github.com/ElMassimo/vite_ruby/issues/246#issuecomment-1235743299
// https://github.com/ElMassimo/jumpstart-vite/commit/f25668a989c3bfd50b9063ee99645771c7a56101#r84399950
if (!window.Rails) {
Rails.start();
}
$.fn.DataTable.defaults.headerCallback = function(thead) {
$(thead).find('th:not(.sort-arrows-added)').append('<i class="fas fa-sort"></i><i class="fas fa-sort-up"></i><i class="fas fa-sort-down"></i>');
$(thead).find('th').addClass('sort-arrows-added');
};
$(document).ready(function(){
$('table.table-data-tables').DataTable({
pageLength: 50,
order: [[3, 'desc']],
columnDefs: [
{ targets: 3, type: 'string' },
{ targets: 4, type: 'string' },
{ targets: 5, orderable: false },
]
});
});
| import '../font_awesome_icons';
import '../reports';
import dataTablesInit from 'datatables.net';
import dataTablesBs5Init from 'datatables.net-bs5';
import Rails from 'rails-ujs';
import $ from 'jquery';
dataTablesInit(window, $);
dataTablesBs5Init(window, $);
Rails.start();
$.fn.DataTable.defaults.headerCallback = function(thead) {
$(thead).find('th:not(.sort-arrows-added)').append('<i class="fas fa-sort"></i><i class="fas fa-sort-up"></i><i class="fas fa-sort-down"></i>');
$(thead).find('th').addClass('sort-arrows-added');
};
$(document).ready(function(){
$('table.table-data-tables').DataTable({
pageLength: 50,
order: [[3, 'desc']],
columnDefs: [
{ targets: 3, type: 'string' },
{ targets: 4, type: 'string' },
{ targets: 5, orderable: false },
]
});
});
|
Change CNTL to new loader format | define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(item) {
return item.getBytes().then(function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
item.setDataObject({
rectangle: {
top: dv.getInt16(0, false),
left: dv.getInt16(2, false),
bottom: dv.getInt16(4, false),
right: dv.getInt16(6, false),
},
initialSetting: dv.getUint16(8, false),
visible: !!bytes[10],
fill: !!bytes[11],
maximumSetting: dv.getInt16(12, false),
minimumSetting: dv.getInt16(14, false),
cdefID: dv.getInt16(16, false),
referenceConstant: dv.getInt32(18, false),
text: macintoshRoman(bytes, 23, bytes[22]),
});
});
};
});
| define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(resource) {
var dv = new DataView(resource.data.buffer, resource.data.byteOffset, resource.data.byteLength);
resource.dataObject = {
rectangle: {
top: dv.getInt16(0, false),
left: dv.getInt16(2, false),
bottom: dv.getInt16(4, false),
right: dv.getInt16(6, false),
},
initialSetting: dv.getUint16(8, false),
visible: !!resource.data[10],
fill: !!resource.data[11],
maximumSetting: dv.getInt16(12, false),
minimumSetting: dv.getInt16(14, false),
cdefID: dv.getInt16(16, false),
referenceConstant: dv.getInt32(18, false),
text: macintoshRoman(resource.data, 23, resource.data[22]),
};
};
});
|
Fix type / batchId parameter order bug | <?php
namespace CascadeEnergy\DistributedOperations\Elasticsearch;
use CascadeEnergy\DistributedOperations\Operation;
use Elasticsearch\Helper\Iterators\SearchHitIterator;
class ProviderIterator implements \Iterator
{
/** @var SearchHitIterator */
private $hitIterator;
public function __construct(SearchHitIterator $hitIterator)
{
$this->hitIterator = $hitIterator;
}
public function current()
{
$hit = $this->hitIterator->current();
$source = $hit['_source'];
$operation = new Operation($hit['_type'], $source['batchId'], $source['options']);
$operation->setState($source['state']);
$operation->setDisposition($source['disposition']);
$operation->setId($hit['_id']);
$operation->setStorageAttribute('indexName', $hit['_index']);
return $operation;
}
public function next()
{
$this->hitIterator->next();
}
public function key()
{
return $this->hitIterator->key();
}
public function valid()
{
return $this->hitIterator->valid();
}
public function rewind()
{
$this->hitIterator->rewind();
}
}
| <?php
namespace CascadeEnergy\DistributedOperations\Elasticsearch;
use CascadeEnergy\DistributedOperations\Operation;
use Elasticsearch\Helper\Iterators\SearchHitIterator;
class ProviderIterator implements \Iterator
{
/** @var SearchHitIterator */
private $hitIterator;
public function __construct(SearchHitIterator $hitIterator)
{
$this->hitIterator = $hitIterator;
}
public function current()
{
$hit = $this->hitIterator->current();
$source = $hit['_source'];
$operation = new Operation($source['batchId'], $hit['_type'], $source['options']);
$operation->setState($source['state']);
$operation->setDisposition($source['disposition']);
$operation->setId($hit['_id']);
$operation->setStorageAttribute('indexName', $hit['_index']);
return $operation;
}
public function next()
{
$this->hitIterator->next();
}
public function key()
{
return $this->hitIterator->key();
}
public function valid()
{
return $this->hitIterator->valid();
}
public function rewind()
{
$this->hitIterator->rewind();
}
}
|
Update django-pylibmc dependency to >=0.6.1
As a bonus, django-pylibmc 0.5.0+ supports Python 3, for which testing
will be enabled in another PR.
I've switched to using greater than, since the Python packaging
guidelines say it's not best practice to use `install_requires` to pin
dependencies to specific versions:
http://python-packaging-user-guide.readthedocs.org/en/latest/requirements/#install-requires | from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name = 'django-heroku-memcacheify',
version = '0.8',
py_modules = ('memcacheify',),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package dependencies:
install_requires = ['django-pylibmc>=0.6.1'],
# Metadata for PyPI:
author = 'Randall Degges',
author_email = 'r@rdegges.com',
license = 'UNLICENSE',
url = 'https://github.com/rdegges/django-heroku-memcacheify',
keywords = 'django heroku cloud cache memcache memcached awesome epic',
description = 'Automatic Django memcached configuration on Heroku.',
long_description = open(normpath(join(dirname(abspath(__file__)),
'README.md'))).read()
)
| from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name = 'django-heroku-memcacheify',
version = '0.8',
py_modules = ('memcacheify',),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package dependencies:
install_requires = ['django-pylibmc==0.5.0'],
# Metadata for PyPI:
author = 'Randall Degges',
author_email = 'r@rdegges.com',
license = 'UNLICENSE',
url = 'https://github.com/rdegges/django-heroku-memcacheify',
keywords = 'django heroku cloud cache memcache memcached awesome epic',
description = 'Automatic Django memcached configuration on Heroku.',
long_description = open(normpath(join(dirname(abspath(__file__)),
'README.md'))).read()
)
|
Fix missing server error information | 'use strict';
const http = require('http');
const { host, port } = require('../../../config');
const { addStopFunctions } = require('./stop');
// Start HTTP server
const startServer = function ({
serverState: { handleRequest, handleListening, processLog },
}) {
const server = http.createServer(function requestHandler(req, res) {
handleRequest({ req, res });
});
addStopFunctions(server);
server.protocolName = 'HTTP';
server.listen(port, host, function listeningHandler() {
const { address: usedHost, port: usedPort } = server.address();
handleListening({ protocol: 'HTTP', host: usedHost, port: usedPort });
});
handleClientError({ server, log: processLog });
const promise = new Promise((resolve, reject) => {
server.on('listening', () => resolve(server));
server.on('error', error => reject(error));
});
return promise;
};
// Report TCP client errors
const handleClientError = function ({ server, log }) {
server.on('clientError', async (error, socket) => {
const message = 'Client TCP socket error';
await log.process({ value: error, message });
socket.end('');
});
};
module.exports = {
HTTP: {
startServer,
},
};
| 'use strict';
const http = require('http');
const { host, port } = require('../../../config');
const { addStopFunctions } = require('./stop');
// Start HTTP server
const startServer = function ({
serverState: { handleRequest, handleListening, processLog },
}) {
const server = http.createServer(function requestHandler(req, res) {
handleRequest({ req, res });
});
addStopFunctions(server);
server.protocolName = 'HTTP';
server.listen(port, host, function listeningHandler() {
handleListening({ protocol: 'HTTP', host, port });
});
handleClientError({ server, log: processLog });
const promise = new Promise((resolve, reject) => {
server.on('listening', () => resolve(server));
server.on('error', () => reject());
});
return promise;
};
// Report TCP client errors
const handleClientError = function ({ server, log }) {
server.on('clientError', async (error, socket) => {
const message = 'Client TCP socket error';
await log.process({ value: error, message });
socket.end('');
});
};
module.exports = {
HTTP: {
startServer,
},
};
|
Change CORS access origin to wildcard | var express = require('express');
var bodyParser = require('body-parser');
function AppFactory () {
// Nothing here yet...
}
AppFactory.prototype.NewApp = function(config) {
// Create app
var app = express();
// Add middleware
app.use(bodyParser.json());
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
// res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// Add routers
return require('./controllers/scene-api')(config)
.then(function(router){
app.use('/scene',router);
})
.then(function(){
return app;
});
};
module.exports = AppFactory; | var express = require('express');
var bodyParser = require('body-parser');
function AppFactory () {
// Nothing here yet...
}
AppFactory.prototype.NewApp = function(config) {
// Create app
var app = express();
// Add middleware
app.use(bodyParser.json());
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://skeleton-scene-app-web.s3-website-ap-southeast-2.amazonaws.com');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// Add routers
return require('./controllers/scene-api')(config)
.then(function(router){
app.use('/scene',router);
})
.then(function(){
return app;
});
};
module.exports = AppFactory; |
Add yield handler example in devapp | var Controller = require('../../').Controller;
module.exports = Controller.create({
index(req, res) {
res.render("index");
},
*yield(req, res) {
const message = yield new Promise((resolve, reject) => {
setTimeout(() => {
resolve("this message passed with yield* (*゜ᴗ ゜*)");
}, 1000);
});
res.type("text/html; charset=UTF-8");
res.end(message);
},
"403"(req, res) {
throw new maya.NotAllowedException();
},
error(req, res) {
throw new Error("Handled correctry?");
},
socket(req, res) {
res.render("socket");
},
json(req, res) {
res.json({"its": "response json"});
},
plain(req, res) {
res.type("text/plain; charset=UTF-8").write("plain");
},
_private(req, res) {
res
.type("text/html; charset=UTF-8")
.end("Correctry called private method via routes.js");
}
});
| var Controller = require('../../').Controller;
module.exports = Controller.create({
index(req, res) {
res.render("index");
},
"403"(req, res) {
throw new maya.NotAllowedException();
},
error(req, res) {
throw new Error("Handled correctry?");
},
socket(req, res) {
res.render("socket");
},
json(req, res) {
res.json({"its": "response json"});
},
plain(req, res) {
res.type("text/plain; charset=UTF-8").write("plain");
},
_private(req, res) {
res
.type("text/html; charset=UTF-8")
.end("Correctry called private method via routes.js");
}
});
|
Update offset tests for no arg | import test from 'ava';
import inView from '../src/in-view';
test('inView.offset returns the offset', t => {
const stub = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
t.deepEqual(inView.offset(0), stub);
t.deepEqual(inView.offset(), stub);
});
test('inView.offset accepts a number', t => {
t.deepEqual(inView.offset(10), {
top: 10,
right: 10,
bottom: 10,
left: 10
});
});
test('inView.offset accepts an object', t => {
t.deepEqual(inView.offset({
top: 25,
right: 50,
bottom: 75,
left: 100
}), {
top: 25,
right: 50,
bottom: 75,
left: 100
});
});
| import test from 'ava';
import inView from '../src/in-view';
test('inView.offset returns the offset', t => {
t.deepEqual(inView.offset(0), {
top: 0,
right: 0,
bottom: 0,
left: 0
});
});
test('inView.offset accepts a number', t => {
t.deepEqual(inView.offset(10), {
top: 10,
right: 10,
bottom: 10,
left: 10
});
});
test('inView.offset accepts an object', t => {
t.deepEqual(inView.offset({
top: 25,
right: 50,
bottom: 75,
left: 100
}), {
top: 25,
right: 50,
bottom: 75,
left: 100
});
});
|
Rename the test case to match the renamed module. | from subprocess import CalledProcessError
from textwrap import dedent
from unittest import TestCase
from test_recovery import (
parse_new_state_server_from_error,
)
class AssessRecoveryTestCase(TestCase):
def test_parse_new_state_server_from_error(self):
output = dedent("""
Waiting for address
Attempting to connect to 10.0.0.202:22
Attempting to connect to 1.2.3.4:22
The fingerprint for the ECDSA key sent by the remote host is
""")
error = CalledProcessError(1, ['foo'], output)
address = parse_new_state_server_from_error(error)
self.assertEqual('1.2.3.4', address)
| from subprocess import CalledProcessError
from textwrap import dedent
from unittest import TestCase
from test_recovery import (
parse_new_state_server_from_error,
)
class RecoveryTestCase(TestCase):
def test_parse_new_state_server_from_error(self):
output = dedent("""
Waiting for address
Attempting to connect to 10.0.0.202:22
Attempting to connect to 1.2.3.4:22
The fingerprint for the ECDSA key sent by the remote host is
""")
error = CalledProcessError(1, ['foo'], output)
address = parse_new_state_server_from_error(error)
self.assertEqual('1.2.3.4', address)
|
Change assignment to boolean equals | from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
#FIXME: add compose, machine, etc
else:
#FIXME: print failure case
pass
elif Config.OS == 'Darwin':
#brew_cask.install('dockertoolbox')
pass
else:
#FIXME: print failure, handle osx/windows
pass
| from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
#FIXME: add compose, machine, etc
else:
#FIXME: print failure case
pass
elif Config.OS = 'Darwin':
#brew_cask.install('dockertoolbox')
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
Use django's bundled and customised version of six | import json
from django.utils import six
from django.utils.html import format_html, mark_safe
from django.core.urlresolvers import reverse
from django.utils.encoding import python_2_unicode_compatible
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls).__new__(cls, name, bases, attrs)
if klass.chart_slug:
CHARTS[klass.chart_slug] = klass
return klass
@six.add_metaclass(ChartMeta)
@python_2_unicode_compatible
class Chart(object):
options = {}
chart_slug = None
columns = None
def get_data(self):
raise NotImplementedError
def __str__(self):
return format_html(
"<div "
"data-chart-options='{0}'"
"data-chart-url='{1}'"
"></div>",
json.dumps(self.options),
reverse(
'djgc-chart-data',
args=(self.chart_slug,),
),
) | import six
import json
from django.utils.html import format_html, mark_safe
from django.core.urlresolvers import reverse
from django.utils.encoding import python_2_unicode_compatible
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls).__new__(cls, name, bases, attrs)
if klass.chart_slug:
CHARTS[klass.chart_slug] = klass
return klass
@six.add_metaclass(ChartMeta)
@python_2_unicode_compatible
class Chart(object):
options = {}
chart_slug = None
columns = None
def get_data(self):
raise NotImplementedError
def __str__(self):
return format_html(
"<div "
"data-chart-options='{0}'"
"data-chart-url='{1}'"
"></div>",
json.dumps(self.options),
reverse(
'djgc-chart-data',
args=(self.chart_slug,),
),
) |
Add homeRoutePath to User Accounts config | AccountsTemplates.configure({
defaultLayout: 'defaultLayout',
defaultContentRegion: 'main',
// Behaviour
confirmPassword: true,
enablePasswordChange: true,
forbidClientAccountCreation: false,
overrideLoginErrors: true,
sendVerificationEmail: false,
homeRoutePath: '/teams/public',
// Appearance
showAddRemoveServices: false,
showForgotPasswordLink: false,
showLabels: false,
showPlaceholders: true,
// Client-side Validation
continuousValidation: false,
negativeFeedback: false,
negativeValidation: true,
positiveValidation: true,
positiveFeedback: true,
showValidating: true
});
AccountsTemplates.configureRoute('signIn');
AccountsTemplates.configureRoute('signUp');
AccountsTemplates.configureRoute('resetPwd');
AccountsTemplates.configureRoute('verifyEmail');
var passwordField = AccountsTemplates.removeField('password');
AccountsTemplates.removeField('email');
AccountsTemplates.addFields([
{
_id: "username",
type: "text",
displayName: "username",
required: true,
minLength: 5
},
{
_id: 'email',
type: 'email',
required: true,
displayName: "email",
re: /.+@(.+){2,}\.(.+){2,}/,
errStr: 'Invalid email'
},
passwordField
]);
| AccountsTemplates.configure({
defaultLayout: 'defaultLayout',
defaultContentRegion: 'main',
// Behaviour
confirmPassword: true,
enablePasswordChange: true,
forbidClientAccountCreation: false,
overrideLoginErrors: true,
sendVerificationEmail: false,
// Appearance
showAddRemoveServices: false,
showForgotPasswordLink: false,
showLabels: false,
showPlaceholders: true,
// Client-side Validation
continuousValidation: false,
negativeFeedback: false,
negativeValidation: true,
positiveValidation: true,
positiveFeedback: true,
showValidating: true
});
AccountsTemplates.configureRoute('signIn');
AccountsTemplates.configureRoute('signUp');
AccountsTemplates.configureRoute('resetPwd');
AccountsTemplates.configureRoute('verifyEmail');
var passwordField = AccountsTemplates.removeField('password');
AccountsTemplates.removeField('email');
AccountsTemplates.addFields([
{
_id: "username",
type: "text",
displayName: "username",
required: true,
minLength: 5
},
{
_id: 'email',
type: 'email',
required: true,
displayName: "email",
re: /.+@(.+){2,}\.(.+){2,}/,
errStr: 'Invalid email'
},
passwordField
]);
|
Fix custom emote parsing in polls | var PollModule = function () {
};
PollModule.prototype.Message = function(message)
{
if(message.deletable)
{
message.delete();
}
var keyword = "poll";
var pollIndex = message.content.indexOf(keyword);
var questionmarkIndex = message.content.lastIndexOf("?");
var question = message.content.substring(pollIndex + keyword.length,questionmarkIndex+1).trim();
var options = message.content.substring(questionmarkIndex+1).trim().split(' ').map(s => s.replace(/[<>]/g, ''));
if(question.length > 0 && options.length > 0)
{
message.channel.send(question).then(function (poll) {
for (var i = 0; i < options.length; i++) {
poll.react(options[i]);
}
});
}
}
module.exports = PollModule; | var PollModule = function () {
};
PollModule.prototype.Message = function(message)
{
if(message.deletable)
{
message.delete();
}
var keyword = "poll";
var pollIndex = message.content.indexOf(keyword);
var questionmarkIndex = message.content.lastIndexOf("?");
var question = message.content.substring(pollIndex + keyword.length,questionmarkIndex+1).trim();
var options = message.content.substring(questionmarkIndex+1).trim().split(' ');
if(question.length > 0 && options.length > 0)
{
message.channel.send(question).then(function (poll) {
for (var i = 0; i < options.length; i++) {
poll.react(options[i]);
}
});
}
}
module.exports = PollModule; |
Update footer for latest version of Jquery | <script src="{{ asset('vendor/flare/plugins/jQuery/jQuery-2.2.0.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/bootstrap/js/bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/js/app.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/plugins/morris/morris.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/plugins/select2/select2.full.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/plugins/input-mask/jquery.inputmask.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/input-mask/jquery.inputmask.date.extensions.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/input-mask/jquery.inputmask.extensions.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/pace/pace.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js" type="text/javascript"></script>
@yield('enqueued-js')
</body>
</html> | <script src="{{ asset('vendor/flare/plugins/jQuery/jQuery-2.1.4.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/bootstrap/js/bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/js/app.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/plugins/morris/morris.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/plugins/select2/select2.full.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/flare/plugins/input-mask/jquery.inputmask.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/input-mask/jquery.inputmask.date.extensions.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/input-mask/jquery.inputmask.extensions.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js') }}"></script>
<script src="{{ asset('vendor/flare/plugins/pace/pace.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js" type="text/javascript"></script>
@yield('enqueued-js')
</body>
</html> |
Split up tests and fixed misspelling. | # -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_no_user(client):
user_resp = client.get('/user/1')
assert b'No user here' in user_resp.data
def test_no_todo(client):
todo_resp = client.get('/todo/1')
assert b'No ToDo here' in todo_resp.data
| # -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_empty_db(client):
user_resp = client.get('/user/1')
todo_resp = client.get('/todo/1')
assert b'No user here' in user_resp
assert b'No todo here' in todo_resp
assert 0 == 1
|
Add test for complex indexing | import scipy.interpolate
import numpy as np
import pytest
import naturalneighbor
@pytest.mark.parametrize("grid_ranges", [
[[0, 4, 0.6], [-3, 3, 1.0], [0, 1, 3]],
[[0, 2, 1], [0, 2, 1j], [0, 2, 2j]],
])
def test_output_size_matches_scipy(grid_ranges):
points = np.random.rand(10, 3)
values = np.random.rand(10)
mesh_grids = tuple(np.mgrid[
grid_ranges[0][0]:grid_ranges[0][1]:grid_ranges[0][2],
grid_ranges[1][0]:grid_ranges[1][1]:grid_ranges[1][2],
grid_ranges[2][0]:grid_ranges[2][1]:grid_ranges[2][2],
])
scipy_result = scipy.interpolate.griddata(points, values, mesh_grids)
nn_result = naturalneighbor.griddata(points, values, grid_ranges)
assert scipy_result.shape == nn_result.shape
| import scipy.interpolate
import numpy as np
import naturalneighbor
def test_output_size_matches_scipy():
points = np.random.rand(10, 3)
values = np.random.rand(10)
grid_ranges = [
[0, 4, 0.6], # step isn't a multiple
[-3, 3, 1.0], # step is a multiple
[0, 1, 3], # step is larger than stop - start
]
mesh_grids = tuple(np.mgrid[
grid_ranges[0][0]:grid_ranges[0][1]:grid_ranges[0][2],
grid_ranges[1][0]:grid_ranges[1][1]:grid_ranges[1][2],
grid_ranges[2][0]:grid_ranges[2][1]:grid_ranges[2][2],
])
scipy_result = scipy.interpolate.griddata(points, values, mesh_grids)
nn_result = naturalneighbor.griddata(points, values, grid_ranges)
assert scipy_result.shape == nn_result.shape
|
Make sure to finish span when there is an exception | from __future__ import absolute_import
import opentracing.ext.tags as ext
import instana
import opentracing
import wrapt
@wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen')
def urlopen_with_instana(wrapped, instance, args, kwargs):
try:
span = instana.internal_tracer.start_span("urllib3")
span.set_tag(ext.HTTP_URL, args[1])
span.set_tag(ext.HTTP_METHOD, args[0])
instana.internal_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"])
rv = wrapped(*args, **kwargs)
span.set_tag(ext.HTTP_STATUS_CODE, rv.status)
if 500 <= rv.status <= 599:
span.set_tag("error", True)
ec = span.tags.get('ec', 0)
span.set_tag("ec", ec+1)
except Exception as e:
span.log_kv({'message': e})
span.set_tag("error", True)
ec = span.tags.get('ec', 0)
span.set_tag("ec", ec+1)
span.finish()
raise
else:
span.finish()
return rv
| from __future__ import absolute_import
import opentracing.ext.tags as ext
import instana
import opentracing
import wrapt
@wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen')
def urlopen_with_instana(wrapped, instance, args, kwargs):
try:
span = instana.internal_tracer.start_span("urllib3")
span.set_tag(ext.HTTP_URL, args[1])
span.set_tag(ext.HTTP_METHOD, args[0])
instana.internal_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"])
rv = wrapped(*args, **kwargs)
span.set_tag(ext.HTTP_STATUS_CODE, rv.status)
if 500 <= rv.status <= 599:
span.set_tag("error", True)
ec = span.tags.get('ec', 0)
span.set_tag("ec", ec+1)
except Exception as e:
span.log_kv({'message': e})
span.set_tag("error", True)
ec = span.tags.get('ec', 0)
span.set_tag("ec", ec+1)
raise
else:
span.finish()
return rv
|
Work on base migration command. | <?php
namespace Illuminate\Database\Console\Migrations;
use Illuminate\Console\Command;
class BaseCommand extends Command
{
/**
* Get all of the migration paths.
*
* @return array
*/
protected function getMigrationPaths()
{
// Here, we will check to see if a path option has been defined. If it has we will
// use the path relative to the root of the installation folder so our database
// migrations may be run for any customized path from within the application.
if ($this->input->hasOption('path') && $this->option('path')) {
return [$this->laravel->basePath().'/'.$this->option('path')];
}
return array_merge(
[$this->getMigrationPath()], $this->migrator->paths()
);
}
/**
* Get the path to the migration directory.
*
* @return string
*/
protected function getMigrationPath()
{
return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'migrations';
}
}
| <?php
namespace Illuminate\Database\Console\Migrations;
use Illuminate\Console\Command;
class BaseCommand extends Command
{
/**
* Get the path to the migration directory.
*
* @return string
*/
protected function getMigrationPath()
{
return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'migrations';
}
/**
* Get all of the migration paths.
*
* @return array
*/
protected function getMigrationPaths()
{
// Here, we will check to see if a path option has been defined. If it has
// we will use the path relative to the root of this installation folder
// so that migrations may be run for any path within the applications.
if ($this->input->hasOption('path') && $this->option('path')) {
return [$this->laravel->basePath().'/'.$this->option('path')];
}
return array_merge(
[$this->getMigrationPath()], $this->migrator->paths()
);
}
}
|
Make source utf-8 encoded bytes. | class BaseGrader(object):
def __init__(self, judge, problem, language, source):
if isinstance(source, unicode):
source = source.encode('utf-8')
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = None
def grade(self, case):
raise NotImplementedError
def _generate_binary(self):
raise NotImplementedError
def terminate_grading(self):
self._terminate_grading = True
if self._current_proc:
try:
self._current_proc.kill()
except OSError:
pass
pass
| class BaseGrader(object):
def __init__(self, judge, problem, language, source):
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = None
def grade(self, case):
raise NotImplementedError
def _generate_binary(self):
raise NotImplementedError
def terminate_grading(self):
self._terminate_grading = True
if self._current_proc:
try:
self._current_proc.kill()
except OSError:
pass
pass
|
Prepare to push repo into Github by changing database URI | const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const contactRoutes = require('./routes/contactsRouter');
const userRoutes = require('./routes/usersRouter');
const app = express();
// Use body-parser middleware
app.use(bodyParser.json());
// Use Express Router
app.use('/api/contacts', contactRoutes);
app.use('/api/users', userRoutes);
// Create database variable outside of the connection
var db;
// Connect to mongoose (Change the URI or localhost path for mongodb as needed)
mongoose.connect(process.env.MONGODB_URI || 'Database address go here', {
useMongoClient: true
}, function(err) {
// Exit process if unable to connect to db
if (err) {
console.log(err);
process.exit(1);
}
// Save databse object
db = mongoose.connection;
console.log("Database connection ready");
// Serve the app
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log("App now running on port", port);
});
});
// API home
app.get('/', function(req, res) {
res.send('Use /api/contacts, or /api/users');
});
| const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const contactRoutes = require('./routes/contactsRouter');
const userRoutes = require('./routes/usersRouter');
const app = express();
// Use body-parser middleware
app.use(bodyParser.json());
// Use Express Router
app.use('/api/contacts', contactRoutes);
app.use('/api/users', userRoutes);
// Create database variable outside of the connection
var db;
// Connect to mongoose (Change the URI or localhost path for mongodb as needed)
mongoose.connect(process.env.MONGODB_URI || 'mongodb://achowdhury2015:absolute2895@ds025263.mlab.com:25263/achowdhury-mean-contact', {
useMongoClient: true
}, function(err) {
// Exit process if unable to connect to db
if (err) {
console.log(err);
process.exit(1);
}
// Save databse object
db = mongoose.connection;
console.log("Database connection ready");
// Serve the app
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log("App now running on port", port);
});
});
// API home
app.get('/', function(req, res) {
res.send('Use /api/contacts, or /api/users');
});
|
Add an additional layer for the for loop | #notes: will do it using oop.
import json
import itertools
with open('products.json') as data_file:
data = json.load(data_file)
products = data['products']
products_temp = []
for index, item in enumerate(products):
products_temp.append(item)
products = products_temp
products_temp = [] # delete the variable
for index, item in enumerate(products):
products_temp.append(item)
products = products_temp
products_temp = None
computers,keyboards = [],[]
for index, item in enumerate(products):
if item ['product_type'] == 'Computer':
computers.append((item['title'],item['options']))
else: pass
if item ['product_type'] == 'Keyboard':
keyboards.append((item['title'],item['options']))
print item
else: pass
for index, item in enumerate(item):
# Do the second step
pass
print computers
| import json
import itertools
with open('products.json') as data_file:
data = json.load(data_file)
products = data['products']
products_temp = []
for index, item in enumerate(products):
products_temp.append(item)
products = products_temp
products_temp = [] # delete the variable
for index, item in enumerate(products):
products_temp.append(item)
products = products_temp
products_temp = None
computers,keyboards = [],[]
for index, item in enumerate(products):
if item ['product_type'] == 'Computer':
computers.append((item['title'],item['options']))
print item
print "====="
else: pass
if item ['product_type'] == 'Keyboard':
keyboards.append(item)
print item
print "==="
else: pass
print computers
|
Put two lines into one line | <?php
require_once('../config.php');
function unauthorized() {
header('WWW-Authenticate: Basic realm="' . APP_NAME . '"');
header('HTTP/1.0 401 Unauthorized');
die ('Unauthorized');
}
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
unauthorized();
}
$user = trim(strtolower($_SERVER['PHP_AUTH_USER']));
$password = $_SERVER['PHP_AUTH_PW'];
$users_filepath = STORAGE_PATH . 'users.json';
$users = json_decode(file_get_contents($users_filepath), true);
$valid_users = array_keys($users);
$user_exists = (in_array($user, $valid_users));
if (!$user_exists && strlen($user) > 0 && strlen($password) >= 6) {
$users[$user] = password_hash($password, PASSWORD_BCRYPT);
file_put_contents($users_filepath, json_encode($users), LOCK_EX);
}
$validated = $user_exists && password_verify($password, $users[$user]);
if (!$validated) {
unauthorized();
}
define('STORAGE_FILEPATH', STORAGE_PATH . "users/$user.csv");
| <?php
require_once('../config.php');
function unauthorized() {
header('WWW-Authenticate: Basic realm="' . APP_NAME . '"');
header('HTTP/1.0 401 Unauthorized');
die ('Unauthorized');
}
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
unauthorized();
}
$user = trim(strtolower($_SERVER['PHP_AUTH_USER']));
$password = $_SERVER['PHP_AUTH_PW'];
$users_filepath = STORAGE_PATH . 'users.json';
$users = json_decode(file_get_contents($users_filepath), true);
$valid_users = array_keys($users);
$user_exists = (in_array($user, $valid_users));
if (!$user_exists && strlen($user) > 0 && strlen($password) >= 6) {
$users[$user] = password_hash($password, PASSWORD_BCRYPT);
file_put_contents($users_filepath, json_encode($users), LOCK_EX);
}
$validated = $user_exists && password_verify($password, $users[$user]);
if (!$validated) {
unauthorized();
}
define('STORAGE_FILEPATH', STORAGE_PATH . "users/$user.csv");
|
Use condition instead of setActive and listeners | import ExtentInteraction from '../src/ol/interaction/Extent.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {shiftKeyOnly} from '../src/ol/events/condition.js';
const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON(),
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
new VectorLayer({
source: vectorSource,
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const extent = new ExtentInteraction({condition: shiftKeyOnly});
map.addInteraction(extent);
| import ExtentInteraction from '../src/ol/interaction/Extent.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON(),
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
new VectorLayer({
source: vectorSource,
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const extent = new ExtentInteraction();
map.addInteraction(extent);
extent.setActive(false);
//Enable interaction by holding shift
window.addEventListener('keydown', function (event) {
if (event.keyCode == 16) {
extent.setActive(true);
}
});
window.addEventListener('keyup', function (event) {
if (event.keyCode == 16) {
extent.setActive(false);
}
});
|
Change the import location of DeprecationWarning used by plotting module
The SympyDeprecationWarning was moved from its original location. The change
was done in the master branch. The same change must be mirrored in this
development branch. | from warnings import warn
from sympy.utilities.exceptions import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
| from warnings import warn
from sympy.core.compatibility import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
|
Check if the dom node for the theme about to be activated exists. To minimize js errors. | /* theme selector
*/
(function() {
'use strict';
var themeActive = '';
var $themeActive;
var $container = document.querySelector('.themes-box');
function hashChange () {
themeActive = window.util.hash('theme');
// if no theme in the url
if (!themeActive) {
// select the first in the list
$container.querySelector('.theme-item').click();
return;
}
// uncheck previous active theme
$themeActive = $container.querySelector('.active');
if ($themeActive) {
window.util.removeClass($themeActive, 'active');
}
$themeActive = $container.querySelector('.js-' + themeActive);
if ($themeActive) {
window.util.addClass($themeActive, 'active');
}
}
hashChange();
window.addEventListener('hashchange', hashChange, false);
})(); | /* theme selector
*/
(function() {
'use strict';
var themeActive = '';
var $container = document.querySelector('.themes-box');
function hashChange () {
themeActive = window.util.hash('theme');
// if no theme in the url
if (!themeActive) {
// select the first in the list
$container.querySelector('.theme-item').click();
return;
}
// uncheck previous active theme
var $themeActive = $container.querySelector('.active');
if ($themeActive) {
window.util.removeClass($themeActive, 'active');
}
$themeActive = $container.querySelector('.js-' + themeActive);
window.util.addClass($themeActive, 'active');
}
hashChange();
window.addEventListener('hashchange', hashChange, false);
})(); |
Add constructors with initial value. | package fr.vergne.taskmanager.history;
public class DefaultHistorizable<T> implements Historizable<T> {
private final boolean isNullForbiden;
public DefaultHistorizable(T initialValue, boolean forbidNull) {
this(forbidNull);
set(initialValue);
}
public DefaultHistorizable(T initialValue) {
this(initialValue, false);
}
public DefaultHistorizable(boolean forbidNull) {
isNullForbiden = forbidNull;
}
public DefaultHistorizable() {
this(false);
}
public T get() {
return history.getCurrentValue();
}
public void set(T value) {
if (isNullForbiden && value == null) {
throw new NullPointerException("Null values are forbidden.");
} else {
history.push(value);
}
}
private final History<T> history = new History<T>();
@Override
public History<T> getHistory() {
return history;
}
@Override
public String toString() {
return history.getCurrentValue().toString();
}
public boolean isNullForbiden() {
return isNullForbiden;
}
}
| package fr.vergne.taskmanager.history;
public class DefaultHistorizable<T> implements Historizable<T> {
private final boolean isNullForbiden;
public DefaultHistorizable(boolean forbidNull) {
isNullForbiden = forbidNull;
}
public DefaultHistorizable() {
this(false);
}
public T get() {
return history.getCurrentValue();
}
public void set(T value) {
if (isNullForbiden && value == null) {
throw new NullPointerException("Null values are forbidden.");
} else {
history.push(value);
}
}
private final History<T> history = new History<T>();
@Override
public History<T> getHistory() {
return history;
}
@Override
public String toString() {
return history.getCurrentValue().toString();
}
public boolean isNullForbiden() {
return isNullForbiden;
}
}
|
Fix bug that was crashing worker. | var request = require('request');
var {processAddress, prefetchAddress} = require('./utils');
const GEOCODE_BASE_URL = 'http://open.mapquestapi.com/geocoding/v1/address';
function MapQuest(apiKey) {
this.key = apiKey;
return this;
}
MapQuest.prototype.geocode = function (address, location) {
return new Promise((resolve, reject) => {
let prefetched = prefetchAddress(address, location);
if (prefetched) {
resolve(prefetched);
}
address = processAddress(address);
let uri = `${GEOCODE_BASE_URL}?key=${this.key}&street=${address}&county=Oahu&state=HI`;
request({uri, json: true}, (err, _, response) => {
// There should be a location at the county level.
if (response.results && response.results[0].locations.length > 0) {
let location = response.results[0].locations[0];
(location.geocodeQuality === 'STREET') ? resolve(location) : resolve(null);
}
else {
// Let's just resolve this for now. Not really an error yet.
resolve(null);
}
});
});
}
module.exports = MapQuest;
| var request = require('request');
var {processAddress, prefetchAddress} = require('./utils');
const GEOCODE_BASE_URL = 'http://open.mapquestapi.com/geocoding/v1/address';
function MapQuest(apiKey) {
this.key = apiKey;
return this;
}
MapQuest.prototype.geocode = function (address, location) {
return new Promise((resolve, reject) => {
let prefetched = prefetchAddress(address, location);
if (prefetched) {
resolve(prefetched);
}
address = processAddress(address);
let uri = `${GEOCODE_BASE_URL}?key=${this.key}&street=${address}&county=Oahu&state=HI`;
request({uri, json: true}, (err, _, response) => {
// There should be a location at the county level.
if (response.results[0].locations.length > 0) {
let location = response.results[0].locations[0];
(location.geocodeQuality === 'STREET') ? resolve(location) : resolve(null);
}
else {
// Let's just resolve this for now. Not really an error yet.
resolve(null);
}
});
});
}
module.exports = MapQuest;
|
Test view content in greeting integration test. | package hello;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class GreetingControllerIntegrationTest {
@LocalServerPort
private int port;
private URL greeting;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws MalformedURLException {
this.greeting = new URL("http://localhost:" + port + "/greeting");
}
@Test
public void getGreeting() {
ResponseEntity<String> response = template.getForEntity(greeting.toString(), String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
assertThat(response.getBody(), containsString("Hello, World!"));
}
}
| package hello;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class GreetingControllerIntegrationTest {
@LocalServerPort
private int port;
private URL greeting;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws MalformedURLException {
this.greeting = new URL("http://localhost:" + port + "/greeting");
}
@Test
public void getGreeting() {
ResponseEntity<String> response = template.getForEntity(greeting.toString(), String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
}
|
Update with reference to global nav partial | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-text-align/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/text-align/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-text-align/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8')
var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/typography/text-align/index.html', html)
|
Verify in a layout test that replacing a notification closes the old one.
We do this by listening to the "close" event on the old notification as
well. This test passes with or without the Chrome-sided fix because it's
properly implemented in the LayoutTestNotificationManager, but is a good
way of verifying the fix manually.
BUG=366098
Review URL: https://codereview.chromium.org/750563005
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@186033 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | if (self.importScripts) {
importScripts('/resources/testharness.js');
importScripts('worker-helpers.js');
}
async_test(function(test) {
if (Notification.permission != 'granted') {
assert_unreached('No permission has been granted for displaying notifications.');
return;
}
// We require two asynchronous events to happen when a notification gets updated, (1)
// the old instance should receive the "close" event, and (2) the new notification
// should receive the "show" event, but only after (1) has happened.
var closedOriginalNotification = false;
var notification = new Notification('My Notification', { tag: 'notification-test' });
notification.addEventListener('show', function() {
var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' });
updatedNotification.addEventListener('show', function() {
assert_true(closedOriginalNotification);
test.done();
});
});
notification.addEventListener('close', function() {
closedOriginalNotification = true;
});
notification.addEventListener('error', function() {
assert_unreached('The error event should not be thrown.');
});
}, 'Replacing a notification will discard the previous notification.');
if (isDedicatedOrSharedWorker())
done();
| if (self.importScripts) {
importScripts('/resources/testharness.js');
importScripts('worker-helpers.js');
}
async_test(function(test) {
if (Notification.permission != 'granted') {
assert_unreached('No permission has been granted for displaying notifications.');
return;
}
var notification = new Notification('My Notification', { tag: 'notification-test' });
notification.addEventListener('show', function() {
var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' });
updatedNotification.addEventListener('show', function() {
test.done();
});
});
// FIXME: Replacing a notification should fire the close event on the
// notification that's being replaced.
notification.addEventListener('error', function() {
assert_unreached('The error event should not be thrown.');
});
}, 'Replacing a notification will discard the previous notification.');
if (isDedicatedOrSharedWorker())
done();
|
Change default API port to 8000 | "use strict";
require('babel-register')({ only: /src/ });
var request = require('request')
, server = require('../src/server')
, apiURL = process.env.EDITORSNOTES_API_URL || 'http://127.0.0.1:8000'
, port = process.env.EDITORSNOTES_RENDERER_PORT || 8450
, production = process.env.NODE_ENV === 'production'
console.log(`Verifying Editors\' Notes API address at ${apiURL}`);
function start() {
request(apiURL, { headers: { Accept: 'application/json' }}, function (err) {
if (err) {
if (err.code === 'ECONNREFUSED') {
console.error(`\nCould not connect to Editor\'s Notes API server at ${apiURL}`)
console.error('Retrying in 5 seconds...');
setTimeout(start, 5000);
return;
} else {
throw err;
}
}
console.log(`Starting server on port ${port} (${production ? 'production' : 'development'} mode)`);
server.serve(port, apiURL, !production)
});
}
start();
| "use strict";
require('babel-register')({ only: /src/ });
var request = require('request')
, server = require('../src/server')
, apiURL = process.env.EDITORSNOTES_API_URL || 'http://127.0.0.1:8001'
, port = process.env.EDITORSNOTES_RENDERER_PORT || 8450
, production = process.env.NODE_ENV === 'production'
console.log(`Verifying Editors\' Notes API address at ${apiURL}`);
function start() {
request(apiURL, { headers: { Accept: 'application/json' }}, function (err) {
if (err) {
if (err.code === 'ECONNREFUSED') {
console.error(`\nCould not connect to Editor\'s Notes API server at ${apiURL}`)
console.error('Retrying in 5 seconds...');
setTimeout(start, 5000);
return;
} else {
throw err;
}
}
console.log(`Starting server on port ${port} (${production ? 'production' : 'development'} mode)`);
server.serve(port, apiURL, !production)
});
}
start();
|
Update email address to @moz | #! /usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# Complain on 32-bit systems. See README for more details
import struct
if struct.calcsize('P') < 8:
raise RuntimeError(
'Simhash-py does not work on 32-bit systems. See README.md')
ext_modules = [Extension('simhash.table', [
'simhash/table.pyx',
'simhash/simhash-cpp/src/simhash.cpp'
], language='c++', libraries=['Judy']),
]
setup(name = 'simhash',
version = '0.1.1',
description = 'Near-Duplicate Detection with Simhash',
url = 'http://github.com/seomoz/simhash-py',
author = 'Dan Lecocq',
author_email = 'dan@moz.com',
packages = ['simhash'],
package_dir = {'simhash': 'simhash'},
cmdclass = {'build_ext': build_ext},
dependencies = [],
ext_modules = ext_modules,
classifiers = [
'Programming Language :: Python',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP'
],
)
| #! /usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# Complain on 32-bit systems. See README for more details
import struct
if struct.calcsize('P') < 8:
raise RuntimeError(
'Simhash-py does not work on 32-bit systems. See README.md')
ext_modules = [Extension('simhash.table', [
'simhash/table.pyx',
'simhash/simhash-cpp/src/simhash.cpp'
], language='c++', libraries=['Judy']),
]
setup(name = 'simhash',
version = '0.1.1',
description = 'Near-Duplicate Detection with Simhash',
url = 'http://github.com/seomoz/simhash-py',
author = 'Dan Lecocq',
author_email = 'dan@seomoz.org',
packages = ['simhash'],
package_dir = {'simhash': 'simhash'},
cmdclass = {'build_ext': build_ext},
dependencies = [],
ext_modules = ext_modules,
classifiers = [
'Programming Language :: Python',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP'
],
)
|
Set "buttons together" state from client property for override, otherwise from global UI property. | /*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglasslookandfeel.state;
import javax.swing.JComponent;
import javax.swing.UIManager;
/**
* Are scroll bar buttons to be placed together or apart?
*/
public class ScrollBarButtonsTogetherState extends State {
public ScrollBarButtonsTogetherState() {
super("ButtonsTogether");
}
public boolean isInState(JComponent c) {
Object clientProperty = c.getClientProperty("SeaGlass.Override.ScrollBarButtonsTogether");
if (clientProperty != null && clientProperty instanceof Boolean) {
return (Boolean) clientProperty;
}
return UIManager.getBoolean("SeaGlass.ScrollBarButtonsTogether");
}
}
| /*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglasslookandfeel.state;
import javax.swing.JComponent;
/**
* Are scroll bar buttons to be placed together or apart?
*/
public class ScrollBarButtonsTogetherState extends State {
public ScrollBarButtonsTogetherState() {
super("ButtonsTogether");
}
public boolean isInState(JComponent c) {
if (false) {
return true;
}
return false;
}
}
|
Use tables_names.users config for User validation | <?php
namespace Backpack\PermissionManager\app\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserStoreCrudRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return \Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
'email' => 'required|unique:'.config('laravel-permission.table_names.users', 'users').',email',
'name' => 'required',
'password' => 'required|confirmed',
];
return $rules;
}
}
| <?php
namespace Backpack\PermissionManager\app\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserStoreCrudRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return \Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
'email' => 'required|unique:users,email',
'name' => 'required',
'password' => 'required|confirmed',
];
return $rules;
}
}
|
Use double quotes instead of single ones. | var gulp = require("gulp");
var tasks = [];
// Browserify
var browserify = require("browserify");
var vinylSourceStream = require("vinyl-source-stream");
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform("brfs");
bundle = function() {
bundler.bundle()
.pipe(vinylSourceStream(output+".js"))
.pipe(gulp.dest(destination));
};
bundle();
});
tasks.push(output+"-browserify");
};
makeBrowserify("./api/index.js", "./public", "api");
makeBrowserify("./runtime/index.js", "./public", "runtime");
// Watch
gulp.task("watch", function() {
gulp.watch("./api/*", ["api-browserify"]);
gulp.watch("./runtime/*", ["runtime-browserify"]);
});
// All
gulp.task("default", tasks);
| var gulp = require('gulp');
var tasks = [];
// Browserify
var browserify = require('browserify');
var vinylSourceStream = require('vinyl-source-stream');
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform('brfs');
bundle = function() {
bundler.bundle()
.pipe(vinylSourceStream(output+".js"))
.pipe(gulp.dest(destination));
};
bundle();
});
tasks.push(output+"-browserify");
};
makeBrowserify("./api/index.js", "./public", "api");
makeBrowserify("./runtime/index.js", "./public", "runtime");
// Watch
gulp.task("watch", function() {
gulp.watch("./api/*", ["api-browserify"]);
gulp.watch("./runtime/*", ["runtime-browserify"]);
});
// All
gulp.task('default', tasks);
|
Clear status field on every request | <?php
class HttpClient
{
public $status;
public $response;
public function get($url)
{
$this->status = NULL;
$this->response = @file_get_contents($url);
if (isset($http_response_header))
{
$this->parseResponseHeader($http_response_header);
return TRUE;
}
else
{
$this->response = NULL;
return FALSE;
}
}
private function parseResponseHeader($header)
{
// HTTP/1.1 200 OK
$pattern = '#HTTP/\d\.\d (\d{3})#';
// Clear fields
$this->status = NULL;
foreach($header as $entry)
{
$match = preg_match($pattern, $entry, $matches);
if ($match == 1)
{
$this->status = (int)$matches[1];
break;
}
}
}
} | <?php
class HttpClient
{
public $status;
public $response;
public function get($url)
{
$this->response = @file_get_contents($url);
if (isset($http_response_header))
{
$this->parseResponseHeader($http_response_header);
return TRUE;
}
else
{
$this->response = NULL;
return FALSE;
}
}
private function parseResponseHeader($header)
{
// HTTP/1.1 200 OK
$pattern = '#HTTP/\d\.\d (\d{3})#';
// Clear fields
$this->status = NULL;
foreach($header as $entry)
{
$match = preg_match($pattern, $entry, $matches);
if ($match == 1)
{
$this->status = (int)$matches[1];
break;
}
}
}
} |
Handle logging when a '%' character is in the URL. | # -*- coding: utf-8 -*-
"""Extend werkzeug request handler to suit our needs."""
import time
from werkzeug.serving import BaseRequestHandler
class ShRequestHandler(BaseRequestHandler):
"""Extend werkzeug request handler to suit our needs."""
def handle(self):
self.shRequestStarted = time.time()
rv = super(ShRequestHandler, self).handle()
return rv
def send_response(self, *args, **kw):
self.shRequestProcessed = time.time()
super(ShRequestHandler, self).send_response(*args, **kw)
def log_request(self, code='-', size='-'):
duration = int((self.shRequestProcessed - self.shRequestStarted) * 1000)
self.log('info', u'"{0}" {1} {2} [{3}ms]'.format(self.requestline.replace('%', '%%'), code, size, duration))
| # -*- coding: utf-8 -*-
"""Extend werkzeug request handler to suit our needs."""
import time
from werkzeug.serving import BaseRequestHandler
class ShRequestHandler(BaseRequestHandler):
"""Extend werkzeug request handler to suit our needs."""
def handle(self):
self.shRequestStarted = time.time()
rv = super(ShRequestHandler, self).handle()
return rv
def send_response(self, *args, **kw):
self.shRequestProcessed = time.time()
super(ShRequestHandler, self).send_response(*args, **kw)
def log_request(self, code='-', size='-'):
duration = int((self.shRequestProcessed - self.shRequestStarted) * 1000)
self.log('info', '"{0}" {1} {2} [{3}ms]'.format(self.requestline, code, size, duration))
|
Add blank line to fix flake8-isort | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from os import path
import pytest
@pytest.mark.nondestructive
def test_execute(axe):
"""Run axe against base_url and verify JSON output."""
axe.inject()
data = axe.execute()
assert data is not None, data
@pytest.mark.nondestructive
def test_report(axe):
"""Test that report exists."""
axe.inject()
results = axe.execute()
violations = results["violations"]
report = axe.report(violations)
assert report is not None, report
@pytest.mark.nondestructive
def test_write_results(base_url, axe):
"""Assert that write results method creates a non-empty file."""
axe.inject()
data = axe.execute()
filename = 'results.json'
axe.write_results(filename, data)
# check that file exists and is not empty
assert path.exists(filename), 'Output file not found.'
assert path.getsize(filename) > 0, 'File contains no data.'
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from os import path
import pytest
@pytest.mark.nondestructive
def test_execute(axe):
"""Run axe against base_url and verify JSON output."""
axe.inject()
data = axe.execute()
assert data is not None, data
@pytest.mark.nondestructive
def test_report(axe):
"""Test that report exists."""
axe.inject()
results = axe.execute()
violations = results["violations"]
report = axe.report(violations)
assert report is not None, report
@pytest.mark.nondestructive
def test_write_results(base_url, axe):
"""Assert that write results method creates a non-empty file."""
axe.inject()
data = axe.execute()
filename = 'results.json'
axe.write_results(filename, data)
# check that file exists and is not empty
assert path.exists(filename), 'Output file not found.'
assert path.getsize(filename) > 0, 'File contains no data.'
|
Fix module: web-view -> web-frame | 'use strict';
var webpack = require('webpack');
var JsonpTemplatePlugin = webpack.JsonpTemplatePlugin;
var FunctionModulePlugin = require('webpack/lib/FunctionModulePlugin');
var NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin');
var ExternalsPlugin = webpack.ExternalsPlugin;
var LoaderTargetPlugin = webpack.LoaderTargetPlugin;
module.exports = function(options) {
return function webpackTargetElectronRenderer(compiler) {
compiler.apply(
new JsonpTemplatePlugin(options.output),
new FunctionModulePlugin(options.output),
new NodeTargetPlugin(),
new ExternalsPlugin('commonjs', [
'app',
'auto-updater',
'browser-window',
'content-tracing',
'dialog',
'global-shortcut',
'ipc',
'menu',
'menu-item',
'power-monitor',
'protocol',
'tray',
'remote',
'web-frame',
'clipboard',
'crash-reporter',
'screen',
'shell'
]),
new LoaderTargetPlugin(options.target)
);
};
};
| 'use strict';
var webpack = require('webpack');
var JsonpTemplatePlugin = webpack.JsonpTemplatePlugin;
var FunctionModulePlugin = require('webpack/lib/FunctionModulePlugin');
var NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin');
var ExternalsPlugin = webpack.ExternalsPlugin;
var LoaderTargetPlugin = webpack.LoaderTargetPlugin;
module.exports = function(options) {
return function webpackTargetElectronRenderer(compiler) {
compiler.apply(
new JsonpTemplatePlugin(options.output),
new FunctionModulePlugin(options.output),
new NodeTargetPlugin(),
new ExternalsPlugin('commonjs', [
'app',
'auto-updater',
'browser-window',
'content-tracing',
'dialog',
'global-shortcut',
'ipc',
'menu',
'menu-item',
'power-monitor',
'protocol',
'tray',
'remote',
'web-view',
'clipboard',
'crash-reporter',
'screen',
'shell'
]),
new LoaderTargetPlugin(options.target)
);
};
};
|
Fix output from GitHub help | package github
import (
"fmt"
"strings"
"github.com/hashicorp/vault/api"
)
type CLIHandler struct{}
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
mount, ok := m["mount"]
if !ok {
mount = "github"
}
token, ok := m["token"]
if !ok {
return "", fmt.Errorf("'token' var must be set")
}
path := fmt.Sprintf("auth/%s/login", mount)
secret, err := c.Logical().Write(path, map[string]interface{}{
"token": token,
})
if err != nil {
return "", err
}
if secret == nil {
return "", fmt.Errorf("empty response from credential provider")
}
return secret.Auth.ClientToken, nil
}
func (h *CLIHandler) Help() string {
help := `
The GitHub credential provider allows you to authenticate with GitHub.
To use it, specify the "token" var with the "-var" flag. The value should
be a personal access token for your GitHub account. You can generate a personal
access token on your account settings page on GitHub.
Example: vault auth -method=github token=<token>
`
return strings.TrimSpace(help)
}
| package github
import (
"fmt"
"strings"
"github.com/hashicorp/vault/api"
)
type CLIHandler struct{}
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
mount, ok := m["mount"]
if !ok {
mount = "github"
}
token, ok := m["token"]
if !ok {
return "", fmt.Errorf("'token' var must be set")
}
path := fmt.Sprintf("auth/%s/login", mount)
secret, err := c.Logical().Write(path, map[string]interface{}{
"token": token,
})
if err != nil {
return "", err
}
if secret == nil {
return "", fmt.Errorf("empty response from credential provider")
}
return secret.Auth.ClientToken, nil
}
func (h *CLIHandler) Help() string {
help := `
The GitHub credential provider allows you to authenticate with GitHub.
To use it, specify the "token" var with the "-var" flag. The value should
be a personal access token for your GitHub account. You can generate a personal
access token on your account settings page on GitHub.
Example: vault auth -method=github -var="token=<token>"
`
return strings.TrimSpace(help)
}
|
Add function FieldDisabled to test for disabled controls | # -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
| # -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
Swap order of Key x and y to make Keys sortable | import abc
from collections import namedtuple
Key = namedtuple('Key', ['y', 'x'])
class Keyboard(metaclass=abc.ABCMeta):
def __init__(self):
pass
@abc.abstractproperty
def keys(self):
""" Return the keys of this keyboard.
:returns: An iterable of keys
"""
pass
class Actor(metaclass=abc.ABCMeta):
def __init__(self):
pass
@abc.abstractmethod
def evaluate(self, keyboard, layout, corpus):
""" Calculate how much effort the actor has to exert to type the corpus using the layout.
:param keyboard: The keyboard the layout is applied to.
:type keyboard: Keyboard
:param layout: The layout function to be evaluated.
:type layout: dict
:param corpus: The corpus used for evaluation.
:type corpus: iterable of strings
:returns: A floating point value in range [0, +inf] where lower values indicate less effort
"""
pass
| import abc
from collections import namedtuple
Key = namedtuple('Key', ['x', 'y'])
class Keyboard(metaclass=abc.ABCMeta):
def __init__(self):
pass
@abc.abstractproperty
def keys(self):
""" Return the keys of this keyboard.
:returns: An iterable of keys
"""
pass
class Actor(metaclass=abc.ABCMeta):
def __init__(self):
pass
@abc.abstractmethod
def evaluate(self, keyboard, layout, corpus):
""" Calculate how much effort the actor has to exert to type the corpus using the layout.
:param keyboard: The keyboard the layout is applied to.
:type keyboard: Keyboard
:param layout: The layout function to be evaluated.
:type layout: dict
:param corpus: The corpus used for evaluation.
:type corpus: iterable of strings
:returns: A floating point value in range [0, +inf] where lower values indicate less effort
"""
pass
|
Throw ImportException instead of RuntimeException. | package io.bit3.jsass.importer;
import io.bit3.jsass.context.ImportStack;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class JsassCustomHeaderImporter implements Importer {
private final ImportStack importStack;
public JsassCustomHeaderImporter(ImportStack importStack) {
this.importStack = importStack;
}
@Override
public Collection<Import> apply(String url, Import previous) {
List<Import> list = new LinkedList<>();
list.add(createCustomHeaderImport(previous));
return list;
}
private Import createCustomHeaderImport(Import previous) {
int id = importStack.register(previous);
StringBuilder source = new StringBuilder();
// $jsass-void: jsass_import_stack_push(<id>) !global;
source.append(
String.format(
"$jsass-void: jsass_import_stack_push(%d) !global;%n",
id
)
);
try {
return new Import(
new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"),
new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"),
source.toString()
);
} catch (URISyntaxException e) {
throw new ImportException(e);
}
}
}
| package io.bit3.jsass.importer;
import io.bit3.jsass.context.ImportStack;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class JsassCustomHeaderImporter implements Importer {
private final ImportStack importStack;
public JsassCustomHeaderImporter(ImportStack importStack) {
this.importStack = importStack;
}
@Override
public Collection<Import> apply(String url, Import previous) {
List<Import> list = new LinkedList<>();
list.add(createCustomHeaderImport(previous));
return list;
}
private Import createCustomHeaderImport(Import previous) {
int id = importStack.register(previous);
StringBuilder source = new StringBuilder();
// $jsass-void: jsass_import_stack_push(<id>) !global;
source.append(
String.format(
"$jsass-void: jsass_import_stack_push(%d) !global;%n",
id
)
);
try {
return new Import(
new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"),
new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"),
source.toString()
);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
|
Optimize jump game ii solution | import java.util.*;
public class Solution {
public int jump(int[] jumps) {
if (jumps.length == 0) return 0;
if (jumps.length == 1) return 0;
int lastIndex = jumps.length - 1;
boolean[] visited = new boolean[jumps.length];
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(0);
int stepCount = 0;
visited[0] = true;
while (!queue.isEmpty()) {
int queueSize = queue.size();
for (int i = 0; i < queueSize; i++) {
int index = queue.removeFirst();
int maxIndex = Math.min(index + jumps[index], lastIndex);
if (maxIndex == lastIndex) {
return stepCount + 1;
}
for (int newIndex = maxIndex; newIndex > index; newIndex--) {
if (visited[newIndex]) break;
visited[newIndex] = true;
queue.addLast(newIndex);
}
}
stepCount++;
}
return stepCount;
}
}
| import java.util.*;
public class Solution {
public int jump(int[] jumps) {
if (jumps.length == 0) return 0;
int lastIndex = jumps.length - 1;
boolean[] visited = new boolean[jumps.length];
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(0);
int stepCount = 0;
visited[0] = true;
while (!queue.isEmpty()) {
int queueSize = queue.size();
for (int i = 0; i < queueSize; i++) {
int index = queue.removeFirst();
if (index == lastIndex) {
return stepCount;
}
int maxJump = jumps[index];
for (int jump = 1; jump <= maxJump; jump++) {
int newIndex = index + jump;
if (newIndex >= jumps.length) {
break;
}
if (!visited[newIndex]) {
visited[newIndex] = true;
queue.addLast(newIndex);
}
}
}
stepCount++;
}
return stepCount;
}
}
|
[Glitch] Fix searching for additional hashtags in hashtag column
Port 3f382e337d5c40db18995a88c0bf6b1b34f031b7 to glitch-soc
Signed-off-by: Claire <82b964c50e9d1d222e48cf5046e6484a966a7b07@sitedethib.com> | import { connect } from 'react-redux';
import ColumnSettings from '../components/column_settings';
import { changeColumnParams } from 'flavours/glitch/actions/columns';
import api from 'flavours/glitch/util/api';
const mapStateToProps = (state, { columnId }) => {
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === columnId);
if (!(columnId && index >= 0)) {
return {};
}
return {
settings: columns.get(index).get('params'),
onLoad (value) {
return api(() => state).get('/api/v2/search', { params: { q: value, type: 'hashtags' } }).then(response => {
return (response.data.hashtags || []).map((tag) => {
return { value: tag.name, label: `#${tag.name}` };
});
});
},
};
};
const mapDispatchToProps = (dispatch, { columnId }) => ({
onChange (key, value) {
dispatch(changeColumnParams(columnId, key, value));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(ColumnSettings);
| import { connect } from 'react-redux';
import ColumnSettings from '../components/column_settings';
import { changeColumnParams } from 'flavours/glitch/actions/columns';
import api from 'flavours/glitch/util/api';
const mapStateToProps = (state, { columnId }) => {
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === columnId);
if (!(columnId && index >= 0)) {
return {};
}
return { settings: columns.get(index).get('params') };
};
const mapDispatchToProps = (dispatch, { columnId }) => ({
onChange (key, value) {
dispatch(changeColumnParams(columnId, key, value));
},
onLoad (value) {
return api().get('/api/v2/search', { params: { q: value, type: 'hashtags' } }).then(response => {
return (response.data.hashtags || []).map((tag) => {
return { value: tag.name, label: `#${tag.name}` };
});
});
},
});
export default connect(mapStateToProps, mapDispatchToProps)(ColumnSettings);
|
Add getter for roles to ensure Permissions::ROLE_EVERYONE always exists. | <?php
namespace Bolt\Storage\Entity;
use Bolt\AccessControl\Permissions;
/**
* Entity for User.
*/
class Users extends Entity
{
protected $id;
protected $username;
protected $password;
protected $email;
protected $lastseen;
protected $lastip;
protected $displayname;
protected $stack = [];
protected $enabled = 1;
protected $shadowpassword = '';
protected $shadowtoken = '';
protected $shadowvalidity;
protected $failedlogins = 0;
protected $throttleduntil;
protected $roles = [];
/**
* Getter for roles to ensure Permissions::ROLE_EVERYONE always exists.
*
* @param array $roles
*/
public function getRoles()
{
if (!in_array(Permissions::ROLE_EVERYONE, $this->roles)) {
$this->roles[] = Permissions::ROLE_EVERYONE;
}
return $this->roles;
}
/**
* Setter for roles to ensure the array is always unique.
*
* @param array $roles
*/
public function setRoles(array $roles)
{
$this->roles = array_unique($roles);
}
}
| <?php
namespace Bolt\Storage\Entity;
/**
* Entity for User.
*/
class Users extends Entity
{
protected $id;
protected $username;
protected $password;
protected $email;
protected $lastseen;
protected $lastip;
protected $displayname;
protected $stack = [];
protected $enabled = 1;
protected $shadowpassword = '';
protected $shadowtoken = '';
protected $shadowvalidity;
protected $failedlogins = 0;
protected $throttleduntil;
protected $roles = [];
/**
* Setter for roles to ensure the array is always unique.
*
* @param array $roles
*/
public function setRoles(array $roles)
{
$this->roles = array_unique($roles);
}
}
|
Fix ConcurrentModificationException in tile chunk load hook | package codechicken.lib.world;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import java.util.ArrayList;
import java.util.List;
public class TileChunkLoadHook
{
private static boolean init;
public static void init() {
if(init) return;
init = true;
MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook());
}
@SubscribeEvent
public void onChunkLoad(ChunkEvent.Load event) {
List<TileEntity> list = new ArrayList<TileEntity>(event.getChunk().chunkTileEntityMap.values());
for(TileEntity t : list)
if(t instanceof IChunkLoadTile)
((IChunkLoadTile)t).onChunkLoad();
}
}
| package codechicken.lib.world;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
public class TileChunkLoadHook
{
private static boolean init;
public static void init() {
if(init) return;
init = true;
MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook());
}
@SubscribeEvent
public void onChunkLoad(ChunkEvent.Load event) {
for(TileEntity t : ((Iterable<TileEntity>)event.getChunk().chunkTileEntityMap.values()))
if(t instanceof IChunkLoadTile)
((IChunkLoadTile)t).onChunkLoad();
}
}
|
Fix incorrect cache &debug stat descriptions | package com.tisawesomeness.minecord.debug;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import lombok.NonNull;
/**
* Debugs a Caffeine {@link com.github.benmanes.caffeine.cache.Cache}.
*/
public abstract class CacheDebugOption implements DebugOption {
public static final int MILLION = 1_000_000;
public @NonNull String debug() {
CacheStats stats = getCacheStats();
return String.format("**%s Stats**\n", getName()) +
String.format("Hits: `%s/%s %.2f%%`\n", stats.hitCount(), stats.requestCount(), 100*stats.hitRate()) +
String.format("Load Failures: `%s/%s %.2f%%`\n", stats.loadFailureCount(), stats.loadCount(), 100*stats.loadFailureRate()) +
String.format("Eviction Count: `%s`\n", stats.evictionCount()) +
String.format("Average Load Penalty: `%.3fms`\n", stats.averageLoadPenalty() / MILLION) +
String.format("Total Load Time: `%sms`", stats.totalLoadTime() / MILLION);
}
/**
* @return The cache stats to be used in {@link #debug()}.
*/
public abstract @NonNull CacheStats getCacheStats();
}
| package com.tisawesomeness.minecord.debug;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import lombok.NonNull;
/**
* Debugs a Caffeine {@link com.github.benmanes.caffeine.cache.Cache}.
*/
public abstract class CacheDebugOption implements DebugOption {
public static final int MILLION = 1_000_000;
public @NonNull String debug() {
CacheStats stats = getCacheStats();
return String.format("**%s Stats**\n", getName()) +
String.format("Hits: `%s/%s %.2f%%`\n", stats.hitCount(), stats.requestCount(), 100*stats.hitRate()) +
String.format("Load Exceptions: `%s/%s %.2f%%`\n", stats.loadFailureCount(), stats.loadCount(), 100*stats.loadFailureRate()) +
String.format("Eviction Count: `%s`\n", stats.evictionCount()) +
String.format("Average Load Penalty: `%.3fms`\n", stats.averageLoadPenalty() / MILLION) +
String.format("Total Load Time: `%sms`", stats.totalLoadTime() / MILLION);
}
/**
* @return The cache stats to be used in {@link #debug()}.
*/
public abstract @NonNull CacheStats getCacheStats();
}
|
Add render trait function to render validation errors | <?php
namespace RCatlin\Blog\Behavior;
use Assert\Assertion;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Http\Response;
trait RenderError
{
public function renderNotFound(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(404);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
public function renderBadRequest(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(400);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
public function renderValidationError(Response $response, array $errors)
{
$response->setStatusCode(400);
$response->setResult(ResourceFactory::result(['errors' => $errors]));
return $response;
}
}
| <?php
namespace RCatlin\Blog\Behavior;
use Assert\Assertion;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Http\Response;
trait RenderError
{
public function renderNotFound(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(404);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
public function renderBadRequest(Response $response, $message)
{
Assertion::string($message);
$response->setStatusCode(400);
$response->setResult(ResourceFactory::result(['message' => $message]));
return $response;
}
}
|
Fix compile issue in Vert.x 3 test. | /*
* Copyright 2015 the original author or 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 net.kuujo.copycat.vertx;
import net.kuujo.copycat.protocol.Protocol;
import net.kuujo.copycat.test.ProtocolTest;
import org.testng.annotations.Test;
/**
* Vert.x 3 event bus protocol test.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
@Test
public class VertxEventBusProtocolTest extends ProtocolTest {
@Override
protected Protocol createProtocol() {
return new VertxEventBusProtocol();
}
@Override
protected String createUri(int id) {
return String.format("eventbus://test%d", id);
}
}
| /*
* Copyright 2015 the original author or 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 net.kuujo.copycat.vertx;
import net.kuujo.copycat.protocol.Protocol;
import net.kuujo.copycat.test.ProtocolTest;
import org.testng.annotations.Test;
/**
* Vert.x 3 event bus protocol test.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
@Test
public class VertxEventBusProtocolTest extends ProtocolTest {
@Override
protected Protocol createProtocol() {
return new VertxEventBusProtocol();
}
@Override
protected String createUri() {
return "eventbus://test";
}
}
|
Add test for the sake of coverage | // @flow
import React from 'react';
import { mount } from 'enzyme';
import { Provider, Consumer } from './ItemContainer';
describe('ItemContainer', () => {
let mock;
beforeEach(() => {
mock = jest.fn(() => null);
});
it('Propagates uuid by context', () => {
const uuid = 'foo';
mount(
<Provider uuid={uuid}>
<Consumer>{mock}</Consumer>
</Provider>,
).instance();
expect(mock).toHaveBeenCalledWith(
expect.objectContaining({
uuid,
}),
);
});
it('renders Provider without children', () => {
expect(() => mount(<Provider uuid="foo" />)).not.toThrow();
});
});
| // @flow
import React from 'react';
import { mount } from 'enzyme';
import { Provider, Consumer } from './ItemContainer';
describe('ItemContainer', () => {
let mock;
beforeEach(() => {
mock = jest.fn(() => null);
});
it('Propagates uuid by context', () => {
const uuid = 'foo';
mount(
<Provider uuid={uuid}>
<Consumer>{mock}</Consumer>
</Provider>,
).instance();
expect(mock).toHaveBeenCalledWith(
expect.objectContaining({
uuid,
}),
);
});
});
|
Use List from NativeBase to display job types in ChooseJobTypeScreen | import React, { Component } from 'react';
import { Container, Content, List } from 'native-base';
import JobTypeCard from './jobTypeCard';
import GlobalStyle from '../../common/globalStyle';
// Temporary constants. These will be moved and implemented in another way in the future!
const EXAMPLE_IMAGE_URL = 'https://facebook.github.io/react/img/logo_og.png';
const JOB_TYPES = ['Snöskottning', 'Lövkrattning', 'Städning', 'Ogräsrensning'];
export default class ChooseJobTypeScreen extends Component {
static navigationOptions = {
title: 'Choose Job Type',
};
renderRow = jobType => (
<JobTypeCard
title={jobType} subtitle={`Behöver du hjälp med ${jobType.toLowerCase()}?`}
cover={EXAMPLE_IMAGE_URL} icon={EXAMPLE_IMAGE_URL}
/>
);
render() {
return (
<Container>
<Content contentContainerStyle={GlobalStyle.padder}>
<List dataArray={JOB_TYPES} renderRow={this.renderRow} />
</Content>
</Container>
);
}
}
| import React, { Component } from 'react';
import { Container, Content } from 'native-base';
import JobTypeCard from './jobTypeCard';
import GlobalStyle from '../../common/globalStyle';
// Temporary constants. These will be moved and implemented in another way in the future!
const EXAMPLE_IMAGE_URL = 'https://facebook.github.io/react/img/logo_og.png';
const JOBS = ['Snöskottning', 'Lövkrattning', 'Städning', 'Ogräsrensning'];
export default class ChooseJobTypeScreen extends Component {
static navigationOptions = {
title: 'Choose Job Type',
};
render() {
// Creates a JobTypeCard for each job in the JOBS array.
const jobTypeCards = JOBS.map((job, i) => <JobTypeCard key={job.concat(i)} title={job} subtitle={`Behöver du hjälp med ${job.toLowerCase()}?`} cover={EXAMPLE_IMAGE_URL} icon={EXAMPLE_IMAGE_URL} />);
return (
<Container>
<Content contentContainerStyle={GlobalStyle.padder}>
{jobTypeCards}
</Content>
</Container>
);
}
}
|
Move files to archive test case | """test_remove_file_more_than_a_week.py: Moves files to archive than a more than a week"""
import os
import time
def get_files():
files_array = []
files_directory = 'files/'
extension = 'todo'
for file in os.listdir(files_directory):
if file.endswith(extension):
files_array.append(file)
return files_array
def move_file(source, target):
os.rename(source, target)
def test_should_return_file_duration():
files_directory = 'files/'
archive_directory = 'archive/'
date_format = '%Y-%m-%d %H:%M:%S'
one_week = time.time() - 604800
file_list = get_files()
for file in file_list:
file_path = files_directory + file
file_stat = os.stat(file_path)
mtime = file_stat.st_mtime
file_creation_time = time.strftime(date_format, time.localtime(mtime))
if mtime < one_week:
print('Moving {} | Creation date: [{}]'.format(file, file_creation_time))
target_path = files_directory + archive_directory + file
move_file(file_path, target_path)
def main():
test_should_return_file_duration()
if __name__ == '__main__':
main()
| """test_remove_file_more_than_a_week.py: Creates an todo file with title name as current date"""
import os
import time
def get_files():
files_array = []
for file in os.listdir("files/"):
if file.endswith(".todo"):
files_array.append(file)
return files_array
# todo: fix file duration
def test_should_return_file_duration():
files_directory = 'files/'
file_list = get_files()
one_week = time.time() - 604800
for file in file_list:
file_path = files_directory + file
file_stat = os.stat(file_path)
mtime = file_stat.st_mtime
if mtime > one_week:
print('Remove ' + file + ' at the age of ' + mtime)
def main():
test_should_return_file_duration()
if __name__ == '__main__':
main()
|
Update test for changed indexing | package org.vaadin.elements;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.vaadin.elements.impl.RootImpl;
import com.vaadin.ui.Label;
import elemental.json.JsonArray;
public class RootTest {
private RootImpl root;
private Element child;
@Before
public void init() {
child = Elements.create("div");
root = (RootImpl) ElementIntegration.getRoot(new Label());
}
@Test
public void testAppendChild() {
root.appendChild(child);
JsonArray pendingCommands = root.flushPendingCommands();
Assert.assertEquals(
"[[\"createElement\",2,\"div\"],[\"appendChild\",0,2]]",
pendingCommands.toJson());
}
@Test
public void testRemoveChild() {
root.appendChild(child);
root.flushPendingCommands();
child.remove();
JsonArray pendingCommands = root.flushPendingCommands();
Assert.assertEquals("[[\"remove\",2]]", pendingCommands.toJson());
}
}
| package org.vaadin.elements;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.vaadin.elements.impl.RootImpl;
import com.vaadin.ui.Label;
import elemental.json.JsonArray;
public class RootTest {
private RootImpl root;
private Element child;
@Before
public void init() {
child = Elements.create("div");
root = (RootImpl) ElementIntegration.getRoot(new Label());
}
@Test
public void testAppendChild() {
root.appendChild(child);
JsonArray pendingCommands = root.flushPendingCommands();
Assert.assertEquals(
"[[\"createElement\",3,\"div\"],[\"appendChild\",0,3]]",
pendingCommands.toJson());
}
@Test
public void testRemoveChild() {
root.appendChild(child);
root.flushPendingCommands();
child.remove();
JsonArray pendingCommands = root.flushPendingCommands();
Assert.assertEquals("[[\"remove\",3]]", pendingCommands.toJson());
}
}
|
Fix the error from react-router | import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { fromJS } from 'immutable';
import configureStore from './configureStore';
import routes from './routes';
const initialState = fromJS(window.__INITIAL_STATE__); // redux-immutable only allow immutable obj
const store = configureStore(initialState);
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: state => state.get('routing').toJS(),
});
const mountNode = document.getElementById('react-view');
const renderApp = (CurrentRoutes) => {
render(
<AppContainer>
<Provider store={store}>
<Router history={history} routes={CurrentRoutes} />
</Provider>
</AppContainer>,
mountNode
);
};
renderApp(routes);
// Enable hot reload by react-hot-loader
if (module.hot) {
module.hot.accept('./routes', () => {
const NextRoutes = require('./routes').default;
// Prevent the error of "[react-router] You cannot change ; it will be ignored"
// from react-router
unmountComponentAtNode(mountNode);
renderApp(NextRoutes);
});
}
| import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { fromJS } from 'immutable';
import configureStore from './configureStore';
import routes from './routes';
const initialState = fromJS(window.__INITIAL_STATE__); // redux-immutable only allow immutable obj
const store = configureStore(initialState);
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: state => state.get('routing').toJS(),
});
const renderApp = (CurrentRoutes) => {
render(
<AppContainer>
<Provider store={store}>
<Router history={history} routes={CurrentRoutes} />
</Provider>
</AppContainer>,
document.getElementById('react-view')
);
};
renderApp(routes);
// Enable hot reload by react-hot-loader
if (module.hot) {
module.hot.accept('./routes', () => {
const NextRoutes = require('./routes');
renderApp(NextRoutes);
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.