text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
feat(shop): Create relationship for shop table
Create relationship for shop table
see #141
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
public function cities()
{
return $this->hasMany('App\City');
}
public function districts()
{
return $this->hasMany('App\District');
}
public function countries()
{
return $this->hasMany('App\Country');
}
public function types()
{
return $this->hasMany('App\Type');
}
public function shopImages()
{
return $this->hasMany('App\ShopImgae');
}
public function users()
{
return $this->hasMany('App\User');
}
public function shopAssignment()
{
return $this->belongsTo('App\ShopAssignment');
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
public function cities()
{
return $this->hasMany('App\City');
}
public function districts()
{
return $this->hasMany('App\District');
}
public function countries()
{
return $this->hasMany('App\Country');
}
public function types()
{
return $this->hasMany('App\Type');
}
public function shopimages()
{
return $this->hasMany('App\ShopImgae');
}
public function users()
{
return $this->hasMany('App\User');
}
public function shopassignment()
{
return $this->belongsTo('App\ShopAssignment');
}
}
|
Add tasks to list of mq tasks
|
from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftest_task_queue',
backend='rpc',
broker=create_mq_url(options.mq_hostname, options.mq_port,
username=options.mq_username,
password=options.mq_password),
include=[
"tasks.message_tasks"
])
selftest_task_queue.conf.update(**queue_conf)
|
from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftest_task_queue',
backend='rpc',
broker=create_mq_url(options.mq_hostname, options.mq_port,
username=options.mq_username,
password=options.mq_password),
include=[
])
selftest_task_queue.conf.update(**queue_conf)
|
Add backwards compatability for Adobe Lightroom
Because it was renamed it may result in unexpected errors --> breaking
changes.
This is a temporary solution to circumvent the problem. This can be
removed once some other breaking changes are also present and a major
new version is released. I propose removing this change when
https://github.com/simple-icons/simple-icons/issues/1362 is implemented
|
#!/usr/bin/env node
/**
* @fileoverview
* Compiles our icons into static .js files that can be imported in the browser
* and are tree-shakeable.
* The static .js files go in icons/{filename}.js.
* Also generates an index.js that exports all icons by title, but is not tree-shakeable
*/
const dataFile = "../_data/simple-icons.json";
const indexFile = `${__dirname}/../index.js`;
const iconsDir = `${__dirname}/../icons`;
const data = require(dataFile);
const fs = require("fs");
const { titleToFilename } = require("./utils");
const icons = {};
data.icons.forEach(icon => {
const filename = titleToFilename(icon.title);
icon.svg = fs.readFileSync(`${iconsDir}/${filename}.svg`, "utf8");
icons[icon.title] = icon;
// write the static .js file for the icon
fs.writeFileSync(
`${iconsDir}/${filename}.js`,
`module.exports=${JSON.stringify(icon)};`
);
});
/* Backwards compatibility */
// https://github.com/simple-icons/simple-icons/pull/1365
const adobeLightroom = icons["Adobe Lightroom Classic"];
adobeLightroom.title = "Adobe Lightroom";
icons["Adobe Lightroom"] = adobeLightroom;
fs.writeFileSync(
`${iconsDir}/adobelightroom.svg`,
adobeLightroom.svg
);
fs.writeFileSync(
`${iconsDir}/adobelightroom.js`,
`module.exports=${JSON.stringify(adobeLightroom)};`
);
// write our generic index.js
fs.writeFileSync(indexFile, `module.exports=${JSON.stringify(icons)};`);
|
#!/usr/bin/env node
/**
* @fileoverview
* Compiles our icons into static .js files that can be imported in the browser
* and are tree-shakeable.
* The static .js files go in icons/{filename}.js.
* Also generates an index.js that exports all icons by title, but is not tree-shakeable
*/
const dataFile = "../_data/simple-icons.json";
const indexFile = `${__dirname}/../index.js`;
const iconsDir = `${__dirname}/../icons`;
const data = require(dataFile);
const fs = require("fs");
const { titleToFilename } = require("./utils");
const icons = {};
data.icons.forEach(icon => {
const filename = titleToFilename(icon.title);
icon.svg = fs.readFileSync(`${iconsDir}/${filename}.svg`, "utf8");
icons[icon.title] = icon;
// write the static .js file for the icon
fs.writeFileSync(
`${iconsDir}/${filename}.js`,
`module.exports=${JSON.stringify(icon)};`
);
});
// write our generic index.js
fs.writeFileSync(indexFile, `module.exports=${JSON.stringify(icons)};`);
|
Remove globus interface from mcapi - now in its own server
|
#!/usr/bin/env python
from mcapi.mcapp import app, mcdb_connect
from mcapi import utils, access
from mcapi import objects, cache
from mcapi.user import account, usergroups, projects
from os import environ
import optparse
import signal
from mcapi import apikeydb
_HOST = environ.get('MC_SERVICE_HOST') or 'localhost'
def reload_users(signum, frame):
apikeydb.reset()
access.reset()
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="Port to run on", default=5000)
(options, args) = parser.parse_args()
signal.signal(signal.SIGHUP, reload_users)
conn = mcdb_connect()
# cache.load_project_tree_cache(conn)
app.run(debug=True, host=_HOST, port=int(options.port), processes=5)
|
#!/usr/bin/env python
from mcapi.mcapp import app, mcdb_connect
from mcapi import utils, access
from mcapi import objects, cache
from mcapi.user import account, usergroups, projects
from mcapi.globus import globus_service
from os import environ
import optparse
import signal
from mcapi import apikeydb
_HOST = environ.get('MC_SERVICE_HOST') or 'localhost'
def reload_users(signum, frame):
apikeydb.reset()
access.reset()
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="Port to run on", default=5000)
(options, args) = parser.parse_args()
signal.signal(signal.SIGHUP, reload_users)
conn = mcdb_connect()
# cache.load_project_tree_cache(conn)
app.run(debug=True, host=_HOST, port=int(options.port), processes=5)
|
Add getIndices() method to 2D arrays
|
export default function Array2 ({
fill,
size: [width, height]
}) {
const arr2 = []
for (let i = 0; i < width; i++) {
arr2.push(new Array(height).fill(fill))
}
// There should be a better way to include the indices . . .
arr2.forEach2 = (callback) => {
return arr2.forEach((row, i) =>
row.forEach((currentValue, j) =>
callback(currentValue, [i, j])))
}
// map2() and forEach2() differ from their 1D versions as their callback takes in
// 2D indices (Array) rather than a Number.
// function callback (currentValue, indices) {}
// It it necessary to write map2() like this since the return value should
// also contain the Array2 methods.
arr2.map2 = (callback) => {
const copy = Array2({ fill, size: [width, height] })
arr2.forEach2((currentValue, [i, j]) => {
copy[i][j] = callback(currentValue, [i, j])
})
return copy
}
/*
arr2.fill2 = (val) => {
return arr2.map(row => new Array(width).fill(val))
}
*/
arr2.getIndices = (searchElement) => {
for (let i = 0; i < width; i++) {
for (let j = 0; j < height; j++) {
if (arr2[i][j] === searchElement) return [i, j]
}
}
return -1
}
arr2.every2 = (callback) => {
return arr2.every(row => row.every(callback))
}
return arr2
}
|
export default function Array2 ({
fill,
size: [width, height]
}) {
const arr2 = []
for (let i = 0; i < width; i++) {
arr2.push(new Array(height).fill(fill))
}
// There should be a better way to include the indices . . .
arr2.forEach2 = (callback) => {
return arr2.forEach((row, i) =>
row.forEach((currentValue, j) =>
callback(currentValue, [i, j])))
}
// map2() and forEach2() differ from their 1D versions as their callback takes in
// 2D indices (Array) rather than a Number.
// function callback (currentValue, indices) {}
// It it necessary to write map2() like this since the return value should
// also contain the Array2 methods.
arr2.map2 = (callback) => {
const copy = Array2({ fill, size: [width, height] })
arr2.forEach2((currentValue, [i, j]) => {
copy[i][j] = callback(currentValue, [i, j])
})
return copy
}
/*
arr2.fill2 = (val) => {
return arr2.map(row => new Array(width).fill(val))
}
*/
arr2.every2 = (callback) => {
return arr2.every(row => row.every(callback))
}
return arr2
}
|
Remove leftovers from example config
|
package com.quiptiq.wurmrest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import com.quiptiq.wurmrest.rmi.RmiProviderFactory;
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Encapsulates DropWizard Configuration
*/
public class WurmRestConfiguration extends Configuration {
@NotNull
@Valid
private RmiProviderFactory rmiProviderFactory = new RmiProviderFactory();
@JsonProperty("rmi")
public void setRmiProviderFactory(RmiProviderFactory rmiProviderFactory) {
this.rmiProviderFactory = rmiProviderFactory;
}
@JsonProperty("rmi")
public RmiProviderFactory getRmiProviderFactory() {
return rmiProviderFactory;
}
}
|
package com.quiptiq.wurmrest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import com.quiptiq.wurmrest.rmi.RmiProviderFactory;
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Encapsulates DropWizard Configuration
*/
public class WurmRestConfiguration extends Configuration {
@NotEmpty
private String template;
@NotEmpty
private String defaultName = "Stranger";
@NotNull
@Valid
private RmiProviderFactory rmiProviderFactory = new RmiProviderFactory();
@JsonProperty("rmi")
public void setRmiProviderFactory(RmiProviderFactory rmiProviderFactory) {
this.rmiProviderFactory = rmiProviderFactory;
}
@JsonProperty("rmi")
public RmiProviderFactory getRmiProviderFactory() {
return rmiProviderFactory;
}
@JsonProperty
public String getTemplate() {
return template;
}
@JsonProperty
public void setTemplate(String template) {
this.template = template;
}
@JsonProperty
public String getDefaultName() {
return defaultName;
}
@JsonProperty
public void setDefaultName(String defaultName) {
this.defaultName = defaultName;
}
}
|
Add "String...args" into "public..." :maple_leaf:
|
public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
public static void main(String...args){}
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
|
public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
public static void main(){}
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
|
Remove extra space in help string
Extra spaces make the openstack-manuals tests fail with a niceness
error. This patch removes an extra space at the end of a help string.
Change-Id: I29bab90ea5a6f648c4539c7cd20cd9b2b63055c2
|
# Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo.config import cfg
from neutron.extensions import portbindings
eswitch_opts = [
cfg.StrOpt('vnic_type',
default=portbindings.VIF_TYPE_MLNX_DIRECT,
help=_("Type of VM network interface: mlnx_direct or "
"hostdev")),
cfg.BoolOpt('apply_profile_patch',
default=False,
help=_("Enable server compatibility with old nova")),
]
cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
|
# Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo.config import cfg
from neutron.extensions import portbindings
eswitch_opts = [
cfg.StrOpt('vnic_type',
default=portbindings.VIF_TYPE_MLNX_DIRECT,
help=_("Type of VM network interface: mlnx_direct or "
"hostdev")),
cfg.BoolOpt('apply_profile_patch',
default=False,
help=_("Enable server compatibility with old nova ")),
]
cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
|
Update for other js file the linting
|
/* global $, alert, localStorage */
/* eslint-env jquery, browser */
'use strict'
var eq = {
item: {
detail: function () {
var elem = document.getElementById('item-detail-search')
var value = elem.getElementsByTagName('input')[0].value
window.location.href = [
'/action/eq/item-detail/',
value.replace(/ /g, '+')
].join('')
return false
},
reset: function () {
var elem = document.getElementById('item-detail-search')
elem.getElementsByTagName('input')[0].value = ''
}
}
}
$('#item-search-detail').click(function () {
var form = document.getElementById('item-detail-search')
var elem = form.getElementsByTagName('input')[0]
elem.value = $(this).val()
window.location.href = [
'/action/eq/item-detail/',
elem.value.replace(/ /g, '+')
].join('')
})
eq.item.reset()
|
'use strict'
var eq = {
item: {
detail: function () {
var elem = document.getElementById('item-detail-search')
var value = elem.getElementsByTagName('input')[0].value
window.location.href = [
'/action/eq/item-detail/',
value.replace(/ /g, '+')
].join('')
return false
},
reset: function () {
var elem = document.getElementById('item-detail-search')
elem.getElementsByTagName('input')[0].value = ''
}
}
}
$('#item-search-detail').click(function () {
var form = document.getElementById('item-detail-search')
var elem = form.getElementsByTagName('input')[0]
elem.value = $(this).val()
window.location.href = [
'/action/eq/item-detail/',
elem.value.replace(/ /g, '+')
].join('')
})
eq.item.reset()
|
Call onAny listeners in dispatcher context
|
"use strict";
const DiscordieError = require("./DiscordieError");
const Constants = require("../Constants");
const EventTypes = Object.keys(Constants.Events);
const events = require("events");
let lastEvent = null;
function validateEvent(eventType) {
if (EventTypes.indexOf(eventType) < 0)
throw new DiscordieError(`Invalid event '${eventType}'`);
}
class DiscordieDispatcher extends events.EventEmitter {
constructor() {
super();
this._anyeventlisteners = [];
}
static _getLastEvent() { return lastEvent; }
on(eventType, listener) {
validateEvent(eventType);
return super.on.apply(this, arguments);
}
onAny(fn) {
if (typeof fn !== "function")
return this;
this._anyeventlisteners.push(fn);
return this;
}
emit(eventType) {
validateEvent(eventType);
lastEvent = [].slice.call(arguments);
super.emit.apply(this, arguments);
const _arguments = arguments;
this._anyeventlisteners.forEach((fn) => {
fn.apply(this, _arguments);
});
}
}
module.exports = DiscordieDispatcher;
|
"use strict";
const DiscordieError = require("./DiscordieError");
const Constants = require("../Constants");
const EventTypes = Object.keys(Constants.Events);
const events = require("events");
let lastEvent = null;
function validateEvent(eventType) {
if (EventTypes.indexOf(eventType) < 0)
throw new DiscordieError(`Invalid event '${eventType}'`);
}
class DiscordieDispatcher extends events.EventEmitter {
constructor() {
super();
this._anyeventlisteners = [];
}
static _getLastEvent() { return lastEvent; }
on(eventType, listener) {
validateEvent(eventType);
return super.on.apply(this, arguments);
}
onAny(fn) {
if (typeof fn !== "function")
return this;
this._anyeventlisteners.push(fn);
return this;
}
emit(eventType) {
validateEvent(eventType);
lastEvent = [].slice.call(arguments);
super.emit.apply(this, arguments);
const _arguments = arguments;
this._anyeventlisteners.forEach((fn) => {
fn.apply(null, _arguments);
});
}
}
module.exports = DiscordieDispatcher;
|
Fix wrong import for the test setup.
|
import 'Library/TestSetup';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { LikeButton } from 'Components/LikeButton/LikeButton';
const onClickStub = sinon.spy();
const defaultProps = { storyId: 1, active: false, onClick: onClickStub };
const defaultComponent = <LikeButton {...defaultProps} />;
let component;
describe('Like button component', () => {
beforeEach(() => {
component = shallow(defaultComponent);
});
it('should show a button', () => {
component.should.have.a.tagName('button');
});
it('should trigger callback on click', () => {
const button = component.find('button');
button.simulate('click');
onClickStub.should.have.been.called();
});
it('should have an `is-active` class name when the user has liked the story', () => {
component = shallow(<LikeButton {...defaultProps} active />);
component.should.have.className('is_active');
});
});
|
import 'Utils/TestSetup';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { LikeButton } from 'Components/LikeButton/LikeButton';
const onClickStub = sinon.spy();
const defaultProps = { storyId: 1, active: false, onClick: onClickStub };
const defaultComponent = <LikeButton {...defaultProps} />;
let component;
describe('Like button component', () => {
beforeEach(() => {
component = shallow(defaultComponent);
});
it('should show a button', () => {
component.should.have.a.tagName('button');
});
it('should trigger callback on click', () => {
const button = component.find('button');
button.simulate('click');
onClickStub.should.have.been.called();
});
it('should have an `is-active` class name when the user has liked the story', () => {
component = shallow(<LikeButton {...defaultProps} active />);
component.should.have.className('is_active');
});
});
|
Update done() call to run().
|
(function() {
'use strict';
var cli = require('casper').create().cli;
var parapsych = require(cli.raw.get('rootdir') + '/dist/parapsych').create(require);
parapsych.set('cli', cli).set('initUrl', '/').set('initSel', 'body');
describe('group 1', function() {
it('should pass --grep filter' , function() {
this.test.assertEquals(this.fetchText('body').trim(), 'Hello World');
});
it('should not pass --grep filter' , function() {
this.test.assertEquals(true, false);
});
});
describe('group 2', function() {
it('should pass --grep filter' , function() {
this.test.assertEquals(this.fetchText('body').trim(), 'Hello World');
});
it('should not pass --grep filter' , function() {
this.test.assertEquals(true, false);
});
});
parapsych.run();
})();
|
(function() {
'use strict';
var cli = require('casper').create().cli;
var parapsych = require(cli.raw.get('rootdir') + '/dist/parapsych').create(require);
parapsych.set('cli', cli)
.set('initUrl', '/')
.set('initSel', 'body');
describe('group 1', function() {
it('should pass --grep filter' , function() {
this.test.assertEquals(this.fetchText('body').trim(), 'Hello World');
});
it('should not pass --grep filter' , function() {
this.test.assertEquals(true, false);
});
});
describe('group 2', function() {
it('should pass --grep filter' , function() {
this.test.assertEquals(this.fetchText('body').trim(), 'Hello World');
});
it('should not pass --grep filter' , function() {
this.test.assertEquals(true, false);
});
});
parapsych.done();
})();
|
Use build in relative path method
|
"use strict";
const vscode = require("vscode");
const analyser = require("./complexity-analyzer");
const reporter = require("./report-builder.js");
const config = require("./config");
const Output = require("./output-channel");
function buildReport(document) {
const channel = new Output();
const filePath = vscode.workspace.asRelativePath(document.fileName);
channel.write(filePath);
const metrics = config.getMetrics();
const legend = reporter.getLegend(metrics);
channel.write(legend)
const fileContents = document.getText();
const analysis = analyser.analyse(fileContents);
const report = reporter.buildFileReport(analysis, metrics);
channel.write(report);
}
function runAnalysis(editor) {
try {
buildReport(editor.document);
} catch (e) {
vscode.window.showErrorMessage("Failed to analyse file. " + e);
console.log(e);
}
}
module.exports = {
execute: runAnalysis
};
|
"use strict";
const vscode = require("vscode");
const analyser = require("./complexity-analyzer");
const reporter = require("./report-builder.js");
const config = require("./config");
const Output = require("./output-channel");
function getFileRelativePath(document) {
const fileUri = document.fileName;
const projectPath = vscode.workspace.rootPath;
return projectPath ? fileUri.replace(projectPath, "") : fileUri;
}
function buildReport(document) {
const channel = new Output();
const filePath = getFileRelativePath(document);
channel.write(filePath);
const metrics = config.getMetrics();
const legend = reporter.getLegend(metrics);
channel.write(legend)
const fileContents = document.getText();
const analysis = analyser.analyse(fileContents);
const report = reporter.buildFileReport(analysis, metrics);
channel.write(report);
}
function runAnalysis(editor) {
try {
buildReport(editor.document);
} catch (e) {
vscode.window.showErrorMessage("Failed to analyse file. " + e);
console.log(e);
}
}
module.exports = {
execute: runAnalysis
};
|
Improve Iterable Conversion in For Directives
(gensrc): Improved Iterable Conversion for non-list non-range
expressions.
|
package dyvil.tools.gensrc.ast.expression;
import dyvil.collection.iterator.ArrayIterator;
import dyvil.collection.iterator.SingletonIterator;
import dyvil.source.position.SourcePosition;
import dyvil.tools.gensrc.ast.scope.Scope;
import dyvil.tools.parsing.ASTNode;
public interface Expression extends ASTNode
{
default boolean evaluateBoolean(Scope scope)
{
return Boolean.parseBoolean(this.evaluateString(scope));
}
default long evaluateInteger(Scope scope)
{
try
{
return Long.parseLong(this.evaluateString(scope));
}
catch (NumberFormatException ex)
{
return 0L;
}
}
default double evaluateDouble(Scope scope)
{
try
{
return Double.parseDouble(this.evaluateString(scope));
}
catch (NumberFormatException ex)
{
return 0;
}
}
String evaluateString(Scope scope);
default Iterable<Expression> evaluateIterable(Scope scope)
{
final SourcePosition position = this.getPosition();
final String string = this.evaluateString(scope);
if (string.indexOf(',') < 0)
{
final StringValue value = new StringValue(position, string);
return () -> new SingletonIterator<>(value);
}
final String[] split = string.split("\\s*,\\s*");
final Expression[] array = new Expression[split.length];
for (int i = 0; i < split.length; i++)
{
array[i] = new StringValue(position, split[i]);
}
return () -> new ArrayIterator<>(array);
}
@Override
void toString(String indent, StringBuilder builder);
}
|
package dyvil.tools.gensrc.ast.expression;
import dyvil.tools.gensrc.ast.scope.Scope;
import dyvil.tools.parsing.ASTNode;
public interface Expression extends ASTNode
{
default boolean evaluateBoolean(Scope scope)
{
return Boolean.parseBoolean(this.evaluateString(scope));
}
default long evaluateInteger(Scope scope)
{
try
{
return Long.parseLong(this.evaluateString(scope));
}
catch (NumberFormatException ex)
{
return 0L;
}
}
default double evaluateDouble(Scope scope)
{
try
{
return Double.parseDouble(this.evaluateString(scope));
}
catch (NumberFormatException ex)
{
return 0;
}
}
String evaluateString(Scope scope);
default Iterable<Expression> evaluateIterable(Scope scope)
{
return new ExpressionList(this);
}
@Override
void toString(String indent, StringBuilder builder);
}
|
Add a white space after left brackets
|
/**
* DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
package org.unigram.docvalidator.util;
/**
* FakeResultDistributor does nothing. this class is just for testing.
*/
public class FakeResultDistributor implements ResultDistributor {
/**
* Constructor.
*/
public FakeResultDistributor() {
super();
}
@Override
public int flushResult(ValidationError err) {
return 0;
}
@Override
public void setFormatter(Formatter formatter) { }
@Override
public void flushHeader() { }
@Override
public void flushFooter() { }
}
|
/**
* DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
package org.unigram.docvalidator.util;
/**
* FakeResultDistributor does nothing. this class is just for testing.
*/
public class FakeResultDistributor implements ResultDistributor {
/**
* Constructor.
*/
public FakeResultDistributor() {
super();
}
@Override
public int flushResult(ValidationError err) {
return 0;
}
@Override
public void setFormatter(Formatter formatter) {}
@Override
public void flushHeader() {}
@Override
public void flushFooter() {}
}
|
Add custom toString() to SQLiteIndex
|
/*
* Copyright (C) 2013 Jerzy Chalupski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.getbase.autoindexer;
import com.google.common.base.Objects;
import java.util.Arrays;
public class SqliteIndex {
public final String mTable;
public final String[] mColumns;
public SqliteIndex(String table, String... columns) {
mTable = table;
mColumns = columns;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SqliteIndex that = (SqliteIndex) o;
return Objects.equal(mTable, that.mTable) &&
Objects.equal(mColumns, that.mColumns);
}
@Override
public String toString() {
return "SQLiteIndex on " + mTable + Arrays.toString(mColumns);
}
@Override
public int hashCode() {
return Objects.hashCode(mTable, mColumns);
}
}
|
/*
* Copyright (C) 2013 Jerzy Chalupski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.getbase.autoindexer;
import com.google.common.base.Objects;
public class SqliteIndex {
public final String mTable;
public final String[] mColumns;
public SqliteIndex(String table, String... columns) {
mTable = table;
mColumns = columns;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SqliteIndex that = (SqliteIndex) o;
return Objects.equal(mTable, that.mTable) &&
Objects.equal(mColumns, that.mColumns);
}
@Override
public int hashCode() {
return Objects.hashCode(mTable, mColumns);
}
}
|
Remove comma before 'and' in error messages
|
'use strict';
const { toSentence } = require('underscore.string');
// Turn ['a', 'b', 'c'] into 'a, b or c'
const getWordsList = function (
words,
{
op = 'or',
quotes = false,
json = false,
} = {},
) {
if (words.length === 0) { return ''; }
const wordsA = jsonStringify(words, { json });
const wordsB = quoteWords(wordsA, { quotes });
const wordsC = toSentence(wordsB, ', ', ` ${op} `);
return wordsC;
};
const jsonStringify = function (words, { json }) {
if (!json) { return words; }
return words.map(JSON.stringify);
};
const quoteWords = function (words, { quotes }) {
if (!quotes) { return words; }
return words.map(word => `'${word}'`);
};
module.exports = {
getWordsList,
};
|
'use strict';
const { toSentence } = require('underscore.string');
// Turn ['a', 'b', 'c'] into 'a, b or c'
const getWordsList = function (
words,
{
op = 'or',
quotes = false,
json = false,
} = {},
) {
if (words.length === 0) { return ''; }
const wordsA = jsonStringify(words, { json });
const wordsB = quoteWords(wordsA, { quotes });
const wordsC = toSentence(wordsB, ', ', `, ${op} `);
return wordsC;
};
const jsonStringify = function (words, { json }) {
if (!json) { return words; }
return words.map(JSON.stringify);
};
const quoteWords = function (words, { quotes }) {
if (!quotes) { return words; }
return words.map(word => `'${word}'`);
};
module.exports = {
getWordsList,
};
|
Remove the for-loop in favor of mapping the array into event components
|
import Event from './event';
const Day = ({ events }) => {
const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ];
const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ];
const DAY = events[ 0 ].start_time;
const DAY_NAME = DAY_NAMES[ DAY.getDay() ];
const DATE = DAY.getDate();
const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ];
return (
<div>
<h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2>
{ events.map((e, id) => {
return <Event title={e.title} start_time={e.start_time} content={e.content} key={id}/>
})}
<br />
</div>
);
};
export default Day;
|
import Event from './event';
const Day = ({ events }) => {
let id = 0;
let eventList = [];
for (let e of events) {
eventList.push(<Event title={e.title} start_time={e.start_time} content={e.content} key={id}/>);
id++;
}
const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ];
const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ];
const DAY = events[ 0 ].start_time;
const DAY_NAME = DAY_NAMES[ DAY.getDay() ];
const DATE = DAY.getDate();
const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ];
return (
<div>
<h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2>
{eventList}
<br />
</div>
);
};
export default Day;
|
Remove the "only" of the test file :(
|
'use strict';
var Converter = require('..');
var fs = require('fs');
describe('Test JCAMP converter of GCMS', function () {
var result = Converter.convert(fs.readFileSync(__dirname + '/data/misc/gcms.jdx').toString());
var gcms=result.gcms;
it('Check content', function () {
gcms.should.keys(['gc','ms']);
gcms.gc.should.be.type('object');
gcms.ms.should.be.type('object');
gcms.gc.tic.should.be.instanceof(Array);
});
it('Check length', function () {
gcms.gc.tic.length.should.be.equal(4840);
gcms.ms.length.should.be.equal(2420);
});
//console.log(Object.keys(gcms));
//console.log(gcms.tic);
});
|
'use strict';
var Converter = require('..');
var fs = require('fs');
describe.only('Test JCAMP converter of GCMS', function () {
var result = Converter.convert(fs.readFileSync(__dirname + '/data/misc/gcms.jdx').toString());
var gcms=result.gcms;
it('Check content', function () {
gcms.should.keys(['gc','ms']);
gcms.gc.should.be.type('object');
gcms.ms.should.be.type('object');
gcms.gc.tic.should.be.instanceof(Array);
});
it('Check length', function () {
gcms.gc.tic.length.should.be.equal(4840);
gcms.ms.length.should.be.equal(2420);
});
//console.log(Object.keys(gcms));
//console.log(gcms.tic);
});
|
Update message/response test to use new API
|
const assert = require('assert');
const expect = require('chai').expect;
const Doorman = require('../lib/doorman');
const Service = require('../lib/service');
const EventEmitter = require('events').EventEmitter;
describe('Doorman', function () {
it('should expose a constructor', function () {
assert(Doorman instanceof Function);
});
it('can handle a message', function (done) {
let doorman = new Doorman();
let source = new EventEmitter();
let sample = { 'test': 'Successfully handled!' };
doorman.use(sample);
doorman.on('response', function (message) {
assert.equal(message.parent.id, 'local/messages/test');
assert.equal(message.response, sample.test);
done();
});
doorman.start();
doorman.services.local.emit('message', {
id: 'test',
actor: 'Alice',
target: 'test',
object: 'Hello, world! This is a !test of the message handling flow.'
});
});
});
|
const assert = require('assert');
const expect = require('chai').expect;
const Doorman = require('../lib/doorman');
const Service = require('../lib/service');
const EventEmitter = require('events').EventEmitter;
describe('Doorman', function () {
it('should expose a constructor', function () {
assert(Doorman instanceof Function);
});
it('can handle a message', function (done) {
let doorman = new Doorman();
let source = new EventEmitter();
let sample = { 'test': 'Successfully handled!' };
doorman.use(sample);
doorman.on('response', function (message) {
assert.equal(message.parent, 'local/messages/test');
assert.equal(message.response, sample.test);
done();
});
doorman.start();
doorman.services.local.emit('message', {
id: 'test',
actor: 'Alice',
target: 'test',
object: 'Hello, world! This is a !test of the message handling flow.'
});
});
});
|
Remove a commented out, unused import
|
package types
import (
"time"
"github.com/joshheinrichs/geosource/server/types/fields"
)
type PostInfo struct {
Id string `json:"id" gorm:"column:p_postid"`
CreatorId string `json:"creator" gorm:"column:p_userid_creator"`
Channel string `json:"channel" gorm:"column:p_channelname"`
Title string `json:"title" gorm:"column:p_title"`
Time time.Time `json:"time" gorm:"column:p_time"`
Location Location `json:"location" gorm:"column:p_location" sql:"type:POINT NOT NULL"`
}
func (postInfo *PostInfo) TableName() string {
return "posts"
}
type Post struct {
PostInfo
Fields fields.Fields `json:"fields" gorm:"column:p_fields" sql:"type:JSONB NOT NULL"`
}
func (post *Post) TableName() string {
return "posts"
}
type Submission struct {
Title string `json:"title"`
Channel string `json:"channel"`
Location Location `json:"location"`
Values []fields.Value `json:"values"`
}
|
package types
import (
"time"
"github.com/joshheinrichs/geosource/server/types/fields"
)
// "github.com/joshheinrichs/geosource/server/transactions"
type PostInfo struct {
Id string `json:"id" gorm:"column:p_postid"`
CreatorId string `json:"creator" gorm:"column:p_userid_creator"`
Channel string `json:"channel" gorm:"column:p_channelname"`
Title string `json:"title" gorm:"column:p_title"`
Time time.Time `json:"time" gorm:"column:p_time"`
Location Location `json:"location" gorm:"column:p_location" sql:"type:POINT NOT NULL"`
}
func (postInfo *PostInfo) TableName() string {
return "posts"
}
type Post struct {
PostInfo
Fields fields.Fields `json:"fields" gorm:"column:p_fields" sql:"type:JSONB NOT NULL"`
}
func (post *Post) TableName() string {
return "posts"
}
type Submission struct {
Title string `json:"title"`
Channel string `json:"channel"`
Location Location `json:"location"`
Values []fields.Value `json:"values"`
}
|
Add test for same length, same letters, different letter instance counts
One possible solution to detecting an anagram might be to check to see if the words are the same length and that each letter from the first word is contained in the second word. This additional test would guard against that solution appearing to work.
I wasn't sure in what position in the test sequence it ought to go, or what the exact test description should be. Feel free to suggest changes.
|
var Anagram = require('./anagram');
describe('Anagram', function() {
it("no matches",function() {
var detector = new Anagram("diaper");
var matches = detector.match([ "hello", "world", "zombies", "pants"]);
expect(matches).toEqual([]);
});
xit("detects simple anagram",function() {
var detector = new Anagram("ba");
var matches = detector.match(['ab', 'abc', 'bac']);
expect(matches).toEqual(['ab']);
});
xit("does not detect false positives",function() {
var detector = new Anagram("bba");
var matches = detector.match(["aab"]);
expect(matches).toEqual([]);
});
xit("detects multiple anagrams",function() {
var detector = new Anagram("abc");
var matches = detector.match(['ab', 'abc', 'bac']);
expect(matches).toEqual(['abc', 'bac']);
});
xit("detects anagram",function() {
var detector = new Anagram("listen");
var matches = detector.match(['enlists', 'google', 'inlets', 'banana']);
expect(matches).toEqual(['inlets']);
});
xit("detects multiple anagrams",function() {
var detector = new Anagram("allergy");
var matches = detector.match(['gallery', 'ballerina', 'regally', 'clergy', 'largely', 'leading']);
expect(matches).toEqual(['gallery', 'regally', 'largely']);
});
});
|
var Anagram = require('./anagram');
describe('Anagram', function() {
it("no matches",function() {
var detector = new Anagram("diaper");
var matches = detector.match([ "hello", "world", "zombies", "pants"]);
expect(matches).toEqual([]);
});
xit("detects simple anagram",function() {
var detector = new Anagram("ba");
var matches = detector.match(['ab', 'abc', 'bac']);
expect(matches).toEqual(['ab']);
});
xit("detects multiple anagrams",function() {
var detector = new Anagram("abc");
var matches = detector.match(['ab', 'abc', 'bac']);
expect(matches).toEqual(['abc', 'bac']);
});
xit("detects anagram",function() {
var detector = new Anagram("listen");
var matches = detector.match(['enlists', 'google', 'inlets', 'banana']);
expect(matches).toEqual(['inlets']);
});
xit("detects multiple anagrams",function() {
var detector = new Anagram("allergy");
var matches = detector.match(['gallery', 'ballerina', 'regally', 'clergy', 'largely', 'leading']);
expect(matches).toEqual(['gallery', 'regally', 'largely']);
});
});
|
Change to a secret secret key
|
from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
ALLOWED_HOSTS = ['floating-castle-71814.herokuapp.com'] # apparently you need to have this
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),
},
},
}
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = os.getenv('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = os.getenv('SENDGRID_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
FROM_EMAIL = 'ian@ianluo.com'
DOMAIN = 'http://floating-castle-71814.herokuapp.com/'
SECRET_KEY = os.getenv('DJANGO_SECRETKEY')
|
from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
ALLOWED_HOSTS = ['floating-castle-71814.herokuapp.com'] # apparently you need to have this
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),
},
},
}
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = os.getenv('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = os.getenv('SENDGRID_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
FROM_EMAIL = 'ian@ianluo.com'
DOMAIN = 'http://floating-castle-71814.herokuapp.com/'
|
Revert "Remove unnecessary and broken DELETE check."
This reverts commit 7906153b4718f34ed31c193a8e80b171e567209c.
Reverting commit accidentally commited straight to develop.
|
from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
return [{'keyword': k, 'target_endpoint': v}
for k, v in sorted(data.items())]
def to_config(self):
keyword_endpoint_mapping = {}
for form in self:
if (not form.is_valid()) or form.cleaned_data['DELETE']:
continue
keyword = form.cleaned_data['keyword']
target_endpoint = form.cleaned_data['target_endpoint']
keyword_endpoint_mapping[keyword] = target_endpoint
return keyword_endpoint_mapping
KeywordFormSet = forms.formsets.formset_factory(
KeywordForm, can_delete=True, extra=1, formset=BaseKeywordFormSet)
class EditKeywordView(EditRouterView):
edit_forms = (
('keyword_endpoint_mapping', KeywordFormSet),
)
class RouterViewDefinition(RouterViewDefinitionBase):
edit_view = EditKeywordView
|
from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
return [{'keyword': k, 'target_endpoint': v}
for k, v in sorted(data.items())]
def to_config(self):
keyword_endpoint_mapping = {}
for form in self:
if not form.is_valid():
continue
keyword = form.cleaned_data['keyword']
target_endpoint = form.cleaned_data['target_endpoint']
keyword_endpoint_mapping[keyword] = target_endpoint
return keyword_endpoint_mapping
KeywordFormSet = forms.formsets.formset_factory(
KeywordForm, can_delete=True, extra=1, formset=BaseKeywordFormSet)
class EditKeywordView(EditRouterView):
edit_forms = (
('keyword_endpoint_mapping', KeywordFormSet),
)
class RouterViewDefinition(RouterViewDefinitionBase):
edit_view = EditKeywordView
|
Remove obsolete entry from eslint config.
|
module.exports = {
extends: [
"plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
"plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
"plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors.
],
parser: "@typescript-eslint/parser",
parserOptions: {
sourceType: "module",
ecmaVersion: 2020,
ecmaFeatures: {
jsx: true // Allows for the parsing of JSX
}
},
plugins: [
"@typescript-eslint"
],
settings: {
react: {
version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
}
},
// Fine tune rules
rules: {
"@typescript-eslint/no-var-requires": 0
},
};
|
module.exports = {
extends: [
"plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
"plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
"plugin:prettier/recommended", // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors.
"prettier"
],
parser: "@typescript-eslint/parser",
parserOptions: {
sourceType: "module",
ecmaVersion: 2020,
ecmaFeatures: {
jsx: true // Allows for the parsing of JSX
}
},
plugins: [
"@typescript-eslint"
],
settings: {
react: {
version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
}
},
// Fine tune rules
rules: {
"@typescript-eslint/no-var-requires": 0
},
};
|
Remove crypto config from packagerOptions options to fix CI
|
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
const self = defaults.project.findAddonByName('ember-a11y-testing');
const autoImport = self.options.autoImport;
let app = new EmberAddon(defaults, {
autoImport,
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
const { maybeEmbroider } = require('@embroider/test-setup');
return maybeEmbroider(app, {
skipBabel: [
{
package: 'qunit',
},
],
});
};
|
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
const self = defaults.project.findAddonByName('ember-a11y-testing');
const autoImport = self.options.autoImport;
let app = new EmberAddon(defaults, {
autoImport,
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
const { maybeEmbroider } = require('@embroider/test-setup');
return maybeEmbroider(app, {
packagerOptions: {
webpackConfig: {
node: {
crypto: 'empty',
},
},
},
skipBabel: [
{
package: 'qunit',
},
],
});
};
|
BAP-1027: Upgrade Symfony to version 2.3
- fix code style
|
<?php
namespace Oro\Bundle\DataAuditBundle\Entity\Repository;
use Gedmo\Loggable\Entity\Repository\LogEntryRepository;
use Gedmo\Tool\Wrapper\EntityWrapper;
class AuditRepository extends LogEntryRepository
{
public function getLogEntriesQueryBuilder($entity)
{
$wrapped = new EntityWrapper($entity, $this->_em);
$objectClass = $wrapped->getMetadata()->name;
$objectId = $wrapped->getIdentifier();
$qb = $this->createQueryBuilder('a')
->where('a.objectId = :objectId AND a.objectClass = :objectClass')
->orderBy('a.loggedAt', 'DESC')
->setParameters(compact('objectId', 'objectClass'));
return $qb;
}
}
|
<?php
namespace Oro\Bundle\DataAuditBundle\Entity\Repository;
use Gedmo\Loggable\Entity\Repository\LogEntryRepository;
use Gedmo\Tool\Wrapper\EntityWrapper;
class AuditRepository extends LogEntryRepository
{
public function getLogEntriesQueryBuilder($entity)
{
$wrapped = new EntityWrapper($entity, $this->_em);
$objectClass = $wrapped->getMetadata()->name;
$objectId = $wrapped->getIdentifier();
$qb = $this->createQueryBuilder('a')
->where('a.objectId = :objectId AND a.objectClass = :objectClass')
->orderBy('a.loggedAt', 'DESC')
->setParameters(compact('objectId', 'objectClass'));
return $qb;
}
}
|
Change the text format for drawing a stroke. To use 5 digits but not 8 digits to present a point.
|
class TextCodec:
def __init__(self):
pass
def encodeStartPoint(self, p):
return "0{0[0]:02X}{0[1]:02X}".format(p)
def encodeEndPoint(self, p):
return "1{0[0]:02X}{0[1]:02X}".format(p)
def encodeControlPoint(self, p):
return "2{0[0]:02X}{0[1]:02X}".format(p)
def encodeStrokeExpression(self, pointExpressionList):
return ",".join(pointExpressionList)
def encodeCharacterExpression(self, strokeExpressionList):
return ";".join(strokeExpressionList)
def isStartPoint(self, pointExpression):
return pointExpression[0]=='0'
def isEndPoint(self, pointExpression):
return pointExpression[0]=='1'
def isControlPoint(self, pointExpression):
return pointExpression[0]=='2'
def decodePointExpression(self, pointExpression):
e=pointExpression
return (int(e[1:3], 16), int(e[3:5], 16))
def decodeStrokeExpression(self, strokeExpression):
return strokeExpression.split(",")
def decodeCharacterExpression(self, characterExpression):
return characterExpression.split(";")
|
class TextCodec:
def __init__(self):
pass
def encodeStartPoint(self, p):
return "0000{0[0]:02X}{0[1]:02X}".format(p)
def encodeEndPoint(self, p):
return "0001{0[0]:02X}{0[1]:02X}".format(p)
def encodeControlPoint(self, p):
return "0002{0[0]:02X}{0[1]:02X}".format(p)
def encodeStrokeExpression(self, pointExpressionList):
return ",".join(pointExpressionList)
def encodeCharacterExpression(self, strokeExpressionList):
return ";".join(strokeExpressionList)
def isStartPoint(self, pointExpression):
return pointExpression[3]=='0'
def isEndPoint(self, pointExpression):
return pointExpression[3]=='1'
def isControlPoint(self, pointExpression):
return pointExpression[3]=='2'
def decodePointExpression(self, pointExpression):
e=pointExpression
return (int(e[4:6], 16), int(e[6:8], 16))
def decodeStrokeExpression(self, strokeExpression):
return strokeExpression.split(",")
def decodeCharacterExpression(self, characterExpression):
return characterExpression.split(";")
|
Remove referencetree-related imports from the top level vytree package.
|
# vytree.__init__: package init file.
#
# Copyright (C) 2014 VyOS Development Group <maintainers@vyos.net>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
from vytree.node import (
Node,
ChildNotFoundError,
ChildAlreadyExistsError,
)
from vytree.config_node import ConfigNode
|
# vytree.__init__: package init file.
#
# Copyright (C) 2014 VyOS Development Group <maintainers@vyos.net>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
from vytree.node import (
Node,
ChildNotFoundError,
ChildAlreadyExistsError,
)
from vytree.config_node import ConfigNode
from vytree.reference_node import ReferenceNode
from vytree.reference_tree_loader import ReferenceTreeLoader
|
Fix 64bit EUID conversion from String and comparing in Comparator
|
package com.rehivetech.beeeon;
import android.text.TextUtils;
import java.math.BigInteger;
import java.util.Comparator;
public class IdentifierComparator implements Comparator<IIdentifier> {
@Override
public int compare(IIdentifier lhs, IIdentifier rhs) {
return compareNumericIds(lhs, rhs);
}
public static int compareNumericIds(IIdentifier lhs, IIdentifier rhs) {
String lhsId = lhs.getId();
String rhsId = rhs.getId();
if (TextUtils.isDigitsOnly(lhsId) && TextUtils.isDigitsOnly(rhsId)) {
// Numeric comparison
return new BigInteger(lhsId).compareTo(new BigInteger(rhsId));
} else {
// String comparison
return lhsId.compareTo(rhsId);
}
}
}
|
package com.rehivetech.beeeon;
import android.text.TextUtils;
import java.util.Comparator;
public class IdentifierComparator implements Comparator<IIdentifier> {
@Override
public int compare(IIdentifier lhs, IIdentifier rhs) {
return compareNumericIds(lhs, rhs);
}
public static int compareNumericIds(IIdentifier lhs, IIdentifier rhs) {
String lhsId = lhs.getId();
String rhsId = rhs.getId();
if (TextUtils.isDigitsOnly(lhsId) && TextUtils.isDigitsOnly(rhsId)) {
// Numeric comparison
return Long.valueOf(lhsId).compareTo(Long.valueOf(rhsId));
} else {
// String comparison
return lhsId.compareTo(rhsId);
}
}
}
|
Use ellipsis character instead of three points
|
// In a real use case, the endpoint could point to another origin.
var LOG_ENDPOINT = 'report/logs';
// The code in `oninstall` and `onactive` force the service worker to
// control the clients ASAP.
self.oninstall = function(event) {
event.waitUntil(self.skipWaiting());
};
self.onactivate = function(event) {
event.waitUntil(self.clients.claim());
};
self.onfetch = function(event) {
event.respondWith(
// Log the request …
log(event.request)
// … and then actually perform it.
.then(fetch)
);
};
// Post basic information of the request to a backend for historical purposes.
function log(request) {
var returnRequest = function() {
return request;
};
var data = {
method: request.method,
url: request.url
};
return fetch(LOG_ENDPOINT, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
})
.then(returnRequest, returnRequest);
}
|
// In a real use case, the endpoint could point to another origin.
var LOG_ENDPOINT = 'report/logs';
// The code in `oninstall` and `onactive` force the service worker to
// control the clients ASAP.
self.oninstall = function(event) {
event.waitUntil(self.skipWaiting());
};
self.onactivate = function(event) {
event.waitUntil(self.clients.claim());
};
self.onfetch = function(event) {
event.respondWith(
// Log the request ...
log(event.request)
// .. and then actually perform it.
.then(fetch)
);
};
// Post basic information of the request to a backend for historical purposes.
function log(request) {
var returnRequest = function() {
return request;
};
var data = {
method: request.method,
url: request.url
};
return fetch(LOG_ENDPOINT, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
})
.then(returnRequest, returnRequest);
}
|
Fix failing test on Python 3
|
import click
from django.core.exceptions import ObjectDoesNotExist
class ModelInstance(click.ParamType):
def __init__(self, qs):
from django.db import models
if isinstance(qs, type) and issubclass(qs, models.Model):
qs = qs.objects.all()
self.qs = qs
self.name = '{}.{}'.format(
qs.model._meta.app_label,
qs.model.__name__,
)
def convert(self, value, param, ctx):
try:
return self.qs.get(pk=value)
except ObjectDoesNotExist:
pass
# call `fail` outside of exception context to avoid nested exception
# handling on Python 3
msg = 'could not find {} with pk={}'.format(self.name, value)
self.fail(msg, param, ctx)
|
import click
from django.core.exceptions import ObjectDoesNotExist
class ModelInstance(click.ParamType):
def __init__(self, qs):
from django.db import models
if isinstance(qs, type) and issubclass(qs, models.Model):
qs = qs.objects.all()
self.qs = qs
self.name = '{}.{}'.format(
qs.model._meta.app_label,
qs.model.__name__,
)
def convert(self, value, param, ctx):
try:
return self.qs.get(pk=value)
except ObjectDoesNotExist:
msg = 'could not find {} with pk={}'.format(self.name, value)
self.fail(msg, param, ctx)
|
Remove unnecessary full class qualification
|
package org.codeswarm.lipsum;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
/**
* A {@link Lipsum.ParagraphGenerator} implementation backed by an {@link STGroup}.
*/
class STGroupParagraphGenerator implements Lipsum.ParagraphGenerator {
interface TemplateNames {
int getMinIndex();
int getMaxIndex();
String getTemplateName(int index);
}
private final STGroup stg;
private final TemplateNames templateNames;
STGroupParagraphGenerator(STGroup stg, TemplateNames templateNames) {
this.stg = stg;
this.templateNames = templateNames;
}
@Override
public String paragraph(long key) {
int index = templateNames.getMinIndex() + Lipsum.remainder(
Math.abs(key - templateNames.getMinIndex()),
templateNames.getMaxIndex());
String tplName = templateNames.getTemplateName(index);
ST tpl = stg.getInstanceOf(tplName);
return tpl.render();
}
}
|
package org.codeswarm.lipsum;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
/**
* A {@link org.codeswarm.lipsum.Lipsum.ParagraphGenerator} implementation backed by an {@link STGroup}.
*/
class STGroupParagraphGenerator implements Lipsum.ParagraphGenerator {
interface TemplateNames {
int getMinIndex();
int getMaxIndex();
String getTemplateName(int index);
}
private final STGroup stg;
private final TemplateNames templateNames;
STGroupParagraphGenerator(STGroup stg, TemplateNames templateNames) {
this.stg = stg;
this.templateNames = templateNames;
}
@Override
public String paragraph(long key) {
int index = templateNames.getMinIndex() + Lipsum.remainder(
Math.abs(key - templateNames.getMinIndex()),
templateNames.getMaxIndex());
String tplName = templateNames.getTemplateName(index);
ST tpl = stg.getInstanceOf(tplName);
return tpl.render();
}
}
|
Use json naming standards instead of camelCase
|
from pprint import pprint
#[{u'accountId': 2,
#u'add': True,
#u'broadcastUri': u'vlan://untagged',
#u'firstIP': False,
#u'networkRate': 200,
#u'newNic': False,
#u'nicDevId': 1,
#u'oneToOneNat': False,
#u'publicIp': u'10.0.2.102',
#u'sourceNat': True,
#u'trafficType': u'Public',
#u'vifMacAddress': u'06:f6:5e:00:00:03',
#u'vlanGateway': u'10.0.2.1',
#u'vlanNetmask': u'255.255.255.0'}]
def merge(dbag, ip):
added = False
for mac in dbag:
if mac == "id":
continue
for address in dbag[mac]:
if address['public_ip'] == ip['public_ip']:
dbag[mac].remove(address)
if ip['add']:
dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip )
return dbag
|
from pprint import pprint
#[{u'accountId': 2,
#u'add': True,
#u'broadcastUri': u'vlan://untagged',
#u'firstIP': False,
#u'networkRate': 200,
#u'newNic': False,
#u'nicDevId': 1,
#u'oneToOneNat': False,
#u'publicIp': u'10.0.2.102',
#u'sourceNat': True,
#u'trafficType': u'Public',
#u'vifMacAddress': u'06:f6:5e:00:00:03',
#u'vlanGateway': u'10.0.2.1',
#u'vlanNetmask': u'255.255.255.0'}]
def merge(dbag, ip):
added = False
for mac in dbag:
if mac == "id":
continue
for address in dbag[mac]:
if address['publicIp'] == ip['publicIp']:
dbag[mac].remove(address)
if ip['add']:
dbag.setdefault('eth' + str(ip['nicDevId']), []).append( ip )
return dbag
|
Add spacing to isNumeric function.
|
/**
* Utility function related to checking if a given value is numeric.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Checks if a given value is numeric.
*
* @since n.e.x.t
*
* @param {*} value The value to check.
* @return {boolean} TRUE if a value is numeric FALSE otherwise.
*/
export function isNumeric( value ) {
if ( typeof value === 'number' ) {
return true;
}
const string = ( value || '' ).toString();
if ( ! string ) {
return false;
}
return ! isNaN( string );
}
|
/**
* Utility function related to checking if a given value is numeric.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Checks if a given value is numeric.
*
* @since n.e.x.t
*
* @param {*} value The value to check.
* @return {boolean} TRUE if a value is numeric FALSE otherwise.
*/
export function isNumeric( value ) {
if ( typeof value === 'number' ) {
return true;
}
const string = ( value || '' ).toString();
if ( ! string ) {
return false;
}
return ! isNaN( string );
}
|
Use empty test driver for test that doesn't need Mocha
|
var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("'meteor test --port' accepts/rejects proper values", function () {
var s = new Sandbox();
var run;
s.createApp("myapp", "standard-app");
s.cd("myapp");
s.set("")
var runAddPackage = s.run("add", "tmeasday:acceptance-test-driver");
runAddPackage.waitSecs(30);
runAddPackage.match(/tmeasday:acceptance-test-driver\b.*?added/)
runAddPackage.expectExit(0);
run = s.run("test", "--port", "3700", "--driver-package", "tmeasday:acceptance-test-driver");
run.waitSecs(120);
run.match('App running at: http://localhost:3700/');
run.stop();
run = s.run("test", "--port", "127.0.0.1:3700", "--driver-package", "tmeasday:acceptance-test-driver");
run.waitSecs(120);
run.match('App running at: http://127.0.0.1:3700/');
run.stop();
run = s.run("test", "--port", "[::]:3700", "--driver-package", "tmeasday:acceptance-test-driver");
run.waitSecs(120);
run.match('App running at: http://[::]:3700/');
run.stop();
});
|
var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("'meteor test --port' accepts/rejects proper values", function () {
var s = new Sandbox();
var run;
s.createApp("myapp", "standard-app");
s.cd("myapp");
var runAddPackage = s.run("add", "meteortesting:mocha");
runAddPackage.waitSecs(30);
runAddPackage.match(/meteortesting:mocha\b.*?added/)
runAddPackage.expectExit(0);
run = s.run("test", "--port", "3700", "--driver-package", "meteortesting:mocha");
run.waitSecs(120);
run.match('App running at: http://localhost:3700/');
run.stop();
run = s.run("test", "--port", "127.0.0.1:3700", "--driver-package", "meteortesting:mocha");
run.waitSecs(120);
run.match('App running at: http://127.0.0.1:3700/');
run.stop();
run = s.run("test", "--port", "[::]:3700", "--driver-package", "meteortesting:mocha");
run.waitSecs(120);
run.match('App running at: http://[::]:3700/');
run.stop();
});
|
Write out the content of each file in a closure with module and exports defined
|
var http = require('http'),
fs = require('fs'),
util = require('./util')
// require.paths.unshift('.')
var modules = {},
port = 1234,
host = 'localhost'
var closureStart = '(function() {',
moduleDef = 'var module = {exports:{}}; var exports = module.exports;',
closureEnd = '\n})()'
moduleDef += 'var require = function() { return {} };'
var server = http.createServer(function(req, res) {
if (req.url.match(/\.js$/)) {
fs.readFile(req.url, function(err, content) {
if (err) { return res.end('alert("' + err + '")') }
// TODO rewrite require calls to require._["<MODULE PATH>"]
res.write(closureStart + moduleDef)
res.write(content)
res.end(closureEnd)
})
} else {
// main module
var modulePath = __dirname + req.url + '.js'
var deps = util.getDependencyList(modulePath),
base = '//' + host + ':' + port
res.write('var require = {_:{}}\n')
for (var i=0; i<deps.length; i++) {
var path = base + deps[i]
res.write('document.write(\'<script src="'+path+'"></script>\')\n')
}
res.end()
}
})
server.listen(port, host)
|
var http = require('http'),
fs = require('fs'),
util = require('./util')
// require.paths.unshift('.')
var modules = {},
port = 1234,
host = 'localhost'
var server = http.createServer(function(req, res) {
if (req.url.match(/\.js$/)) {
fs.readFile(req.url, function(err, content) {
if (err) { return res.end('alert("' + err + '")') }
// TODO prefix with a (function() { ... })()
res.end(content)
})
} else {
// main module
var modulePath = __dirname + req.url + '.js'
var deps = util.getDependencyList(modulePath),
base = '//' + host + ':' + port
res.write('var require = {_:{}}\n')
for (var i=0; i<deps.length; i++) {
var path = base + deps[i]
res.write('document.write(\'<script src="'+path+'"></script>\')\n')
}
res.end()
}
})
server.listen(port, host)
|
Fix it gau! oh godgp
|
window.onload = function() {
d3.json("examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart");
sizeSVG(commitSVG);
commitChart(commitSVG, dataset);
var scatterFullSVG = d3.select("#scatter-full");
sizeSVG(scatterFullSVG);
scatterFull(scatterFullSVG, dataset);
var lineSVG = d3.select("#line-chart");
sizeSVG(lineSVG);
lineChart(lineSVG, dataset);
});
}
function sizeSVG(svg) {
var width = svg.node().clientWidth;
var height = Math.min(width*.75, 600);
svg.attr("height", height);
}
|
window.onload = function() {
d3.json("../examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart");
sizeSVG(commitSVG);
commitChart(commitSVG, dataset);
var scatterFullSVG = d3.select("#scatter-full");
sizeSVG(scatterFullSVG);
scatterFull(scatterFullSVG, dataset);
var lineSVG = d3.select("#line-chart");
sizeSVG(lineSVG);
lineChart(lineSVG, dataset);
});
}
function sizeSVG(svg) {
var width = svg.node().clientWidth;
var height = Math.min(width*.75, 600);
svg.attr("height", height);
}
|
Add invoice pay and update methods
|
<?php
class Stripe_Invoice extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function upcoming($params=null, $apiKey=null)
{
$requestor = new Stripe_ApiRequestor($apiKey);
$url = self::classUrl(get_class()) . '/upcoming';
list($response, $apiKey) = $requestor->request('get', $url, $params);
return Stripe_Util::convertToStripeObject($response, $apiKey);
}
public function save()
{
$class = get_class();
return self::_scopedSave($class);
}
public function pay()
{
$requestor = new Stripe_ApiRequestor($this->_apiKey);
$url = $this->instanceUrl() . '/pay';
list($response, $apiKey) = $requestor->request('post', $url);
$this->refreshFrom($response, $apiKey);
return $this;
}
}
|
<?php
class Stripe_Invoice extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_scopedRetrieve($class, $id, $apiKey);
}
public static function all($params=null, $apiKey=null)
{
$class = get_class();
return self::_scopedAll($class, $params, $apiKey);
}
public static function upcoming($params=null, $apiKey=null)
{
$requestor = new Stripe_ApiRequestor($apiKey);
$url = self::classUrl(get_class()) . '/upcoming';
list($response, $apiKey) = $requestor->request('get', $url, $params);
return Stripe_Util::convertToStripeObject($response, $apiKey);
}
}
|
Fix react error in NodeDetailsControls
|
const React = require('react');
const NodeControlButton = require('./node-control-button');
const NodeDetailsControls = React.createClass({
render: function() {
let spinnerClassName = 'fa fa-circle-o-notch fa-spin';
if (this.props.pending) {
spinnerClassName += ' node-details-controls-spinner';
} else {
spinnerClassName += ' node-details-controls-spinner hide';
}
return (
<div className="node-details-controls">
<span className="node-details-controls-buttons">
{this.props.controls && this.props.controls.map(control => {
return (
<NodeControlButton control={control} pending={this.props.pending} key={control.id} />
);
})}
</span>
{this.props.controls && <span title="Applying..." className={spinnerClassName}></span>}
{this.props.error && <div className="node-details-controls-error" title={this.props.error}>
<span className="node-details-controls-error-icon fa fa-warning" />
<span className="node-details-controls-error-messages">{this.props.error}</span>
</div>}
</div>
);
}
});
module.exports = NodeDetailsControls;
|
const React = require('react');
const NodeControlButton = require('./node-control-button');
const NodeDetailsControls = React.createClass({
render: function() {
let spinnerClassName = 'fa fa-circle-o-notch fa-spin';
if (this.props.pending) {
spinnerClassName += ' node-details-controls-spinner';
} else {
spinnerClassName += ' node-details-controls-spinner hide';
}
return (
<div className="node-details-controls">
{this.props.controls && this.props.controls.map(control => {
return (
<NodeControlButton control={control} pending={this.props.pending} />
);
})}
{this.props.controls && <span title="Applying..." className={spinnerClassName}></span>}
{this.props.error && <div className="node-details-controls-error" title={this.props.error}>
<span className="node-details-controls-error-icon fa fa-warning" />
<span className="node-details-controls-error-messages">{this.props.error}</span>
</div>}
</div>
);
}
});
module.exports = NodeDetailsControls;
|
Remove duplicated lines in test
|
<?php
namespace Relay;
use ArrayObject;
use InvalidArgumentException;
use Traversable;
class RelayBuilderTest extends \PHPUnit\Framework\TestCase
{
protected $relayBuilder;
protected function setUp()
{
$this->relayBuilder = new RelayBuilder();
}
public function testArray()
{
$queue = [];
$relay = $this->relayBuilder->newInstance($queue);
$this->assertInstanceOf('Relay\Relay', $relay);
}
public function testArrayObject()
{
$queue = new ArrayObject([]);
$relay = $this->relayBuilder->newInstance($queue);
$this->assertInstanceOf('Relay\Relay', $relay);
}
public function testTraversable()
{
$queue = $this->createMock(Traversable::class);
$relay = $this->relayBuilder->newInstance($queue);
$this->assertInstanceOf('Relay\Relay', $relay);
}
public function testInvalidArgument()
{
$this->expectException('TypeError');
$this->relayBuilder->newInstance('bad argument');
}
}
|
<?php
namespace Relay;
use ArrayObject;
use InvalidArgumentException;
use Traversable;
class RelayBuilderTest extends \PHPUnit\Framework\TestCase
{
protected $relayBuilder;
protected function setUp()
{
$this->relayBuilder = new RelayBuilder();
}
public function testArray()
{
$queue = [];
$relay = $this->relayBuilder->newInstance($queue);
$this->assertInstanceOf('Relay\Relay', $relay);
}
public function testArrayObject()
{
$queue = new ArrayObject([]);
$relay = $this->relayBuilder->newInstance($queue);
$this->assertInstanceOf('Relay\Relay', $relay);
$relay = $this->relayBuilder->newInstance($queue);
$this->assertInstanceOf('Relay\Relay', $relay);
}
public function testTraversable()
{
$queue = $this->createMock(Traversable::class);
$relay = $this->relayBuilder->newInstance($queue);
$this->assertInstanceOf('Relay\Relay', $relay);
}
public function testInvalidArgument()
{
$this->expectException('TypeError');
$this->relayBuilder->newInstance('bad argument');
}
}
|
Add a clip to the frameless example
|
"""
===============================
Plotting a Map without any Axes
===============================
This examples shows you how to plot a Map without any annotations at all, i.e.
to save as an image.
"""
##############################################################################
# Start by importing the necessary modules.
import astropy.units as u
import matplotlib.pyplot as plt
import sunpy.map
from sunpy.data.sample import AIA_171_IMAGE
##############################################################################
# Create a `sunpy.map.GenericMap`.
smap = sunpy.map.Map(AIA_171_IMAGE)
##############################################################################
# Plot the Map without a frame.
# Setup a frameless figure and an axes which spans the whole canvas.
figure = plt.figure(frameon=False)
axes = plt.Axes(figure, [0., 0., 1., 1.])
# Disable the axis and add them to the figure.
axes.set_axis_off()
figure.add_axes(axes)
# Plot the map without any annotations
# This might raise a warning about the axes being wrong but we can ignore this
# as we are not plotting any axes.
im = smap.plot(axes=axes, annotate=False, clip_interval=(1, 99.99)*u.percent)
##############################################################################
# At this point you could save the figure with ``plt.savefig()`` or show it:
plt.show()
|
"""
===============================
Plotting a Map without any Axes
===============================
This examples shows you how to plot a Map without any annotations at all, i.e.
to save as an image.
"""
##############################################################################
# Start by importing the necessary modules.
import astropy.units as u
import matplotlib.pyplot as plt
import sunpy.map
from sunpy.data.sample import AIA_171_IMAGE
##############################################################################
# Create a `sunpy.map.GenericMap`.
smap = sunpy.map.Map(AIA_171_IMAGE)
##############################################################################
# Plot the Map without a frame.
# Setup a frameless figure and an axes which spans the whole canvas.
figure = plt.figure(frameon=False)
axes = plt.Axes(figure, [0., 0., 1., 1.])
# Disable the axis and add them to the figure.
axes.set_axis_off()
figure.add_axes(axes)
# Plot the map without any annotations
# This might raise a warning about the axes being wrong but we can ignore this
# as we are not plotting any axes.
im = smap.plot(axes=axes, annotate=False)
##############################################################################
# At this point you could save the figure with ``plt.savefig()`` or show it:
plt.show()
|
Print Preview: Hook up the cancel button.
BUG=57895
TEST=manual
Review URL: http://codereview.chromium.org/5151009
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@66822 0039d316-1c4b-4281-b951-d872f2087c98
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('click', function(e) {
window.close();
});
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('no-printer');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('no-printer');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
|
Use call checker to ensure both writeFile calls go through before killing the mock
|
var should = require('should');
var sinon = require('sinon');
var tasks = require('../tasks.js');
var fs = require('fs');
var dataKeys = {
inProgress: ['toExec', 'resultsFile', 'startedAt', 'inProgress'],
success: ['toExec', 'resultsFile', 'startedAt', 'inProgress', 'finishedAt', 'stdout', 'stderr', 'success'],
failure: ['toExec', 'resultsFile', 'startedAt', 'inProgress', 'finishedAt', 'stdout', 'stderr', 'error']
};
function validateInProgressData(data) {
data.should.have.keys(dataKeys.inProgress);
data.toExec.should.equal('someFunction');
data.resultsFile.should.endWith('.json');
Date.parse(data.startedAt).should.be.ok; // jshint ignore:line
data.inProgress.should.be.true; // jshint ignore:line
}
describe('execSaveResults', function() {
it('should fire a callback with in-progress data', function(done) {
var stubFsWriteFile = sinon.stub(fs, 'writeFile').callsArg(2);
tasks.execSaveResults('someFunction', 'resultsFolder', function(err, data) {
should.not.exist(err);
validateInProgressData(data);
});
var callChecker = setInterval(function() {
if (stubFsWriteFile.callCount >= 2) {
clearInterval(callChecker);
stubFsWriteFile.restore();
done();
}
}, 1);
});
});
|
var should = require('should');
var sinon = require('sinon');
var tasks = require('../tasks.js');
var fs = require('fs');
var dataKeys = {
inProgress: ['toExec', 'resultsFile', 'startedAt', 'inProgress'],
success: ['toExec', 'resultsFile', 'startedAt', 'inProgress', 'finishedAt', 'stdout', 'stderr', 'success'],
failure: ['toExec', 'resultsFile', 'startedAt', 'inProgress', 'finishedAt', 'stdout', 'stderr', 'error']
};
function validateInProgressData(data) {
data.should.have.keys(dataKeys.inProgress);
data.toExec.should.equal('someFunction');
data.resultsFile.should.endWith('.json');
Date.parse(data.startedAt).should.be.ok; // jshint ignore:line
data.inProgress.should.be.true; // jshint ignore:line
}
describe('execSaveResults', function() {
it('should fire a callback with in-progress data', function(done) {
var stubFsWriteFile = sinon.stub(fs, 'writeFile').callsArg(2);
tasks.execSaveResults('someFunction', 'resultsFolder', function(err, data) {
should.not.exist(err);
validateInProgressData(data);
stubFsWriteFile.restore();
done();
});
});
});
|
Add support for data: Uri scheme to RCTImageView (e.g. base64-encoded images)
Summary: ImageRequestHelper was not handling data: scheme correctly, which resulted in images failing to load. This diff is fixing it by considering \"data:\" as a Uri resource, and piping it appropriately.
Reviewed By: sriramramani
Differential Revision: D2919403
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.flat;
import javax.annotation.Nullable;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
/* package */ class ImageRequestHelper {
/* package */ static @Nullable ImageRequest createImageRequest(
Context context,
@Nullable String source) {
if (source == null) {
return null;
}
final ImageRequestBuilder imageRequestBuilder;
if (isUriResource(source)) {
imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(source));
} else {
Resources resources = context.getResources();
int resId = resources.getIdentifier(
source,
"drawable",
context.getPackageName());
imageRequestBuilder = ImageRequestBuilder.newBuilderWithResourceId(resId);
}
return imageRequestBuilder.build();
}
private static boolean isUriResource(String source) {
return
source.startsWith("http://") ||
source.startsWith("https://") ||
source.startsWith("data:");
}
}
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.flat;
import javax.annotation.Nullable;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
/* package */ class ImageRequestHelper {
/* package */ static @Nullable ImageRequest createImageRequest(
Context context,
@Nullable String source) {
if (source == null) {
return null;
}
final ImageRequestBuilder imageRequestBuilder;
if (isNetworkResource(source)) {
imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(source));
} else {
Resources resources = context.getResources();
int resId = resources.getIdentifier(
source,
"drawable",
context.getPackageName());
imageRequestBuilder = ImageRequestBuilder.newBuilderWithResourceId(resId);
}
return imageRequestBuilder.build();
}
private static boolean isNetworkResource(String source) {
return source.startsWith("http://") || source.startsWith("https://");
}
}
|
Add better logging to see when wasm is loaded
|
//only exports browser api. use chloride module
//to get automatic fallbacks!
//load tweetnacl first, so that it works sync, and everything is there.
var exports = require('sodium-browserify-tweetnacl')
for(var k in exports) (function (k) {
if('function' == typeof exports[k])
//functions that wrap references to exports,
//so if you grab a reference when it's pointing at tweetnacl
//it will switch to wasm when that's ready.
module.exports[k] = function () {
return exports[k].apply(this, arguments)
}
})(k)
//now load wasm which has to be async, ugh.
var libsodium = require('libsodium-wrappers')
libsodium.ready.then(function (value, what) {
console.log("loaded sodium browserify wasm version")
require('./browser') (libsodium, exports)
//set module.exports so that it
module.exports = exports
}).catch(function (err) {
//escape from promise land, ugh
setTimeout(function () {
console.log(err.stack)
process.exit(1)
})
})
|
//only exports browser api. use chloride module
//to get automatic fallbacks!
//load tweetnacl first, so that it works sync, and everything is there.
var exports = require('sodium-browserify-tweetnacl')
for(var k in exports) (function (k) {
if('function' == typeof exports[k])
//functions that wrap references to exports,
//so if you grab a reference when it's pointing at tweetnacl
//it will switch to wasm when that's ready.
module.exports[k] = function () {
return exports[k].apply(this, arguments)
}
})(k)
//now load wasm which has to be async, ugh.
var libsodium = require('libsodium-wrappers')
libsodium.ready.then(function (value, what) {
require('./browser') (libsodium, exports)
//set module.exports so that it
module.exports = exports
}).catch(function (err) {
//escape from promise land, ugh
setTimeout(function () {
console.log(err.stack)
process.exit(1)
})
})
|
Refactor and clean up for demo
Messages may be request scoped
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package eu.agilejava.mvc.prg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.mvc.annotation.RedirectScoped;
/**
* @author Ivar Grimstad (ivar.grimstad@gmail.com)
*/
@Named
@RequestScoped
public class Messages implements Serializable {
private static final long serialVersionUID = 601263646224546642L;
private List<String> errors = new ArrayList();
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> messages) {
this.errors = messages;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package eu.agilejava.mvc.prg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import javax.mvc.annotation.RedirectScoped;
/**
* @author Ivar Grimstad (ivar.grimstad@gmail.com)
*/
@Named
@RedirectScoped
public class Messages implements Serializable {
private static final long serialVersionUID = 601263646224546642L;
private List<String> errors = new ArrayList();
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> messages) {
this.errors = messages;
}
}
|
Update docs on selection sort
|
import java.util.Arrays;
public class SelectionSort {
/**
* Selection Sort is an in-place comparison sort.
* Selection Sort has O(n^2) time complexity.
*/
public int[] selection_sort(int[] arr) {
int min, temp;
/* find the min element in the unsorted array */
for (int i = 0; i < arr.length; i++) {
/* assume the min is the first element */
min = i;
/* test against elements after i to find the smallest */
for (int j = i+1; j < arr.length; j++) {
/* if this element is less, then it is the new minimum */
if (arr[j] < arr[min]) {
/* found new minimum; remember its index */
min = j;
}
}
if (min != i) {
/* swap i and min */
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
return arr;
}
}
|
import java.util.Arrays;
public class SelectionSort {
/**
* Selection Sort is an in-place comparison sort.
* It has O(n^2) time complexity.
*/
public int[] selection_sort(int[] arr) {
int min, temp;
/* find the min element in the unsorted array */
for (int i = 0; i < arr.length; i++) {
/* assume the min is the first element */
min = i;
/* test against elements after i to find the smallest */
for (int j = i+1; j < arr.length; j++) {
/* if this element is less, then it is the new minimum */
if (arr[j] < arr[min]) {
/* found new minimum; remember its index */
min = j;
}
}
if (min != i) {
/* swap i and min */
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
return arr;
}
}
|
Fix import, use fileinput.iput as context, and fix its argument
|
#! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
import sys
from dstruct.Sentence import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file__))
BASE_DIR = os.path.realpath(BASE_DIR + "/../..")
## Return the start and end indexes of all subsets of words in the sentence
## sent, with size at most max_phrase_length
def get_all_phrases_in_sentence(sent, max_phrase_length):
for start in range(len(sent.words)):
for end in reversed(range(start + 1, min(len(sent.words), start + 1 + max_phrase_length))):
yield (start, end)
## Return Sentence objects from input lines
def get_input_sentences(input_files=sys.argv[1:]):
with fileinput.input(files=input_files) as f:
for line in f:
sent_dict = json.loads(line)
yield Sentence(sent_dict["doc_id"], sent_dict["sent_id"],
sent_dict["wordidxs"], sent_dict["words"],
sent_dict["poses"], sent_dict["ners"], sent_dict["lemmas"],
sent_dict["dep_paths"], sent_dict["dep_parents"],
sent_dict["bounding_boxes"])
|
#! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
from dstruct import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file__))
BASE_DIR = os.path.realpath(BASE_DIR + "/../..")
## Return the start and end indexes of all subsets of words in the sentence
## sent, with size at most max_phrase_length
def get_all_phrases_in_sentence(sent, max_phrase_length):
for start in range(len(sent.words)):
for end in reversed(range(start + 1, min(len(sent.words), start + 1 + max_phrase_length))):
yield (start, end)
## Return Sentence objects from input lines
def get_input_sentences(input_files=[]):
for line in fileinput.input(input_files):
sent_dict = json.loads(line)
yield Sentence(sent_dict["doc_id"], sent_dict["sent_id"],
sent_dict["wordidxs"], sent_dict["words"],
sent_dict["poses"], sent_dict["ners"], sent_dict["lemmas"],
sent_dict["dep_paths"], sent_dict["dep_parents"],
sent_dict["bounding_boxes"])
|
Add missing api key in product picker.
Fixes #6185
|
$.fn.productAutocomplete = function () {
'use strict';
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(','),
token: Spree.api_key
}, function (data) {
callback(data.products);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
|
$.fn.productAutocomplete = function () {
'use strict';
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(',')
}, function (data) {
callback(data.products);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
|
Establish different settings for minimal port
|
from weblab.admin.script import Creation
APACHE_CONF_NAME = 'apache.conf'
MIN_PORT = 14000
DEFAULT_DEPLOYMENT_SETTINGS = {
Creation.COORD_ENGINE: 'redis',
Creation.COORD_REDIS_DB: 0,
Creation.COORD_REDIS_PORT: 6379,
Creation.DB_ENGINE: 'mysql',
Creation.ADMIN_USER: 'CHANGE_ME', # --admin-user=admin
Creation.ADMIN_NAME: 'CHANGE_ME', # --admin-name=(lo que diga)
Creation.ADMIN_PASSWORD: 'CHANGE_ME', # --admin-password=(lo que diga)
Creation.ADMIN_MAIL: 'CHANGE_ME', # --admin-mail=(lo que diga)
Creation.START_PORTS: 'CHANGE_ME', # --start-port=10000
Creation.SYSTEM_IDENTIFIER: 'CHANGE_ME', # -i (nombre de la uni, puede tener espacios)
Creation.SERVER_HOST: 'weblab.deusto.es', # --server-host=(de settings)
Creation.ENTITY_LINK: 'http://www.deusto.es/', # --entity-link= http://www.deusto.es/
Creation.CORES: 3,
Creation.ADD_FEDERATED_LOGIC : True,
Creation.ADD_FEDERATED_VISIR : True,
Creation.ADD_FEDERATED_SUBMARINE : True,
}
|
from weblab.admin.script import Creation
APACHE_CONF_NAME = 'apache.conf'
MIN_PORT = 10000
DEFAULT_DEPLOYMENT_SETTINGS = {
Creation.COORD_ENGINE: 'redis',
Creation.COORD_REDIS_DB: 0,
Creation.COORD_REDIS_PORT: 6379,
Creation.DB_ENGINE: 'mysql',
Creation.ADMIN_USER: 'CHANGE_ME', # --admin-user=admin
Creation.ADMIN_NAME: 'CHANGE_ME', # --admin-name=(lo que diga)
Creation.ADMIN_PASSWORD: 'CHANGE_ME', # --admin-password=(lo que diga)
Creation.ADMIN_MAIL: 'CHANGE_ME', # --admin-mail=(lo que diga)
Creation.START_PORTS: 'CHANGE_ME', # --start-port=10000
Creation.SYSTEM_IDENTIFIER: 'CHANGE_ME', # -i (nombre de la uni, puede tener espacios)
Creation.SERVER_HOST: 'weblab.deusto.es', # --server-host=(de settings)
Creation.ENTITY_LINK: 'http://www.deusto.es/', # --entity-link= http://www.deusto.es/
Creation.CORES: 3,
Creation.ADD_FEDERATED_LOGIC : True,
Creation.ADD_FEDERATED_VISIR : True,
Creation.ADD_FEDERATED_SUBMARINE : True,
}
|
Fix bad URL schema for list that would could direct URL with no ID not to always match
|
angular.module('app')
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
// TODO: Enable this when server is properly configured
// $locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index', {
url: '/',
templateUrl: 'partials/index.html',
controller: 'MainCtrl'
})
.state('list', {
url: '/r/:resourceName/list/:id?selectionMode',
templateUrl: 'partials/actions/list.html',
controller: 'ListCtrl'
})
.state('add', {
url: '/r/:resourceName/add',
templateUrl: 'partials/actions/add.html',
controller: 'AddCtrl'
})
.state('edit', {
url: '/r/:resourceName/edit/:id',
templateUrl: 'partials/actions/edit.html',
controller: 'EditCtrl'
});
});
|
angular.module('app')
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
// TODO: Enable this when server is properly configured
// $locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index', {
url: '/',
templateUrl: 'partials/index.html',
controller: 'MainCtrl'
})
.state('list', {
url: '/r/:resourceName/list/:id/?selectionMode',
templateUrl: 'partials/actions/list.html',
controller: 'ListCtrl'
})
.state('add', {
url: '/r/:resourceName/add',
templateUrl: 'partials/actions/add.html',
controller: 'AddCtrl'
})
.state('edit', {
url: '/r/:resourceName/edit/:id',
templateUrl: 'partials/actions/edit.html',
controller: 'EditCtrl'
});
});
|
Improve phone regex validation feedback
|
document.addEventListener('DOMContentLoaded', function () {
var phoneFormGroup = document.getElementById('phone-form-group')
var phone = document.getElementById('phone')
var message = document.getElementById('phoneLengthMessage')
var phoneRegex = /^[6, 8, 9]\d{7}$/
function checkPhone () {
if (phoneRegex.test(phone.value)) {
phoneFormGroup.classList.add('has-success')
phone.classList.add('form-control-success')
phoneFormGroup.classList.remove('has-warning')
phone.classList.remove('form-control-warning')
message.textContent = ''
} else {
phoneFormGroup.classList.add('has-warning')
phone.classList.add('form-control-warning')
phoneFormGroup.classList.remove('has-success')
phone.classList.remove('form-control-success')
message.textContent = 'Please provide a valid phone number, e.g. 91234567, omitting +65'
}
}
checkPhone()
phone.addEventListener('input', checkPhone)
})
|
document.addEventListener('DOMContentLoaded', function () {
var phoneFormGroup = document.getElementById('phone-form-group')
var phone = document.getElementById('phone')
var message = document.getElementById('phoneLengthMessage')
var phoneRegex = /^[6, 8, 9]\d{7}$/
function checkPhone () {
if (phoneRegex.test(phone.value)) {
phoneFormGroup.classList.add('has-success')
phone.classList.add('form-control-success')
phoneFormGroup.classList.remove('has-warning')
phone.classList.remove('form-control-warning')
message.textContent = ''
} else {
phoneFormGroup.classList.add('has-warning')
phone.classList.add('form-control-warning')
phoneFormGroup.classList.remove('has-success')
phone.classList.remove('form-control-success')
message.textContent = 'Please provide a valid phone number'
}
}
checkPhone()
phone.addEventListener('input', checkPhone)
})
|
Fix wrong login return page for tracker URLs
|
<?php
declare(strict_types = 1);
namespace Pages\Controllers\Mixed;
use Database\Objects\TrackerInfo;
use Generator;
use Pages\Controllers\AbstractHandlerController;
use Pages\Controllers\Handlers\OptionallyLoadTracker;
use Pages\Controllers\Handlers\RequireLoginState;
use Pages\IAction;
use Pages\Models\Mixed\LoginModel;
use Pages\Views\Mixed\LoginPage;
use Routing\Request;
use Session\Session;
use function Pages\Actions\redirect;
use function Pages\Actions\view;
class LoginController extends AbstractHandlerController{
private ?TrackerInfo $tracker;
protected function prerequisites(): Generator{
yield new RequireLoginState(false);
yield new OptionallyLoadTracker($this->tracker);
}
protected function finally(Request $req, Session $sess): IAction{
$model = new LoginModel($req, $this->tracker);
$data = $req->getData();
if (!empty($data) && $model->loginUser($data, $sess)){
return redirect([BASE_URL_ENC, isset($_GET['return']) ? ltrim($_GET['return'], '/') : '']);
}
return view(new LoginPage($model->load()));
}
}
?>
|
<?php
declare(strict_types = 1);
namespace Pages\Controllers\Mixed;
use Database\Objects\TrackerInfo;
use Generator;
use Pages\Controllers\AbstractHandlerController;
use Pages\Controllers\Handlers\OptionallyLoadTracker;
use Pages\Controllers\Handlers\RequireLoginState;
use Pages\IAction;
use Pages\Models\Mixed\LoginModel;
use Pages\Views\Mixed\LoginPage;
use Routing\Request;
use Session\Session;
use function Pages\Actions\redirect;
use function Pages\Actions\view;
class LoginController extends AbstractHandlerController{
private ?TrackerInfo $tracker;
protected function prerequisites(): Generator{
yield new RequireLoginState(false);
yield new OptionallyLoadTracker($this->tracker);
}
protected function finally(Request $req, Session $sess): IAction{
$model = new LoginModel($req, $this->tracker);
$data = $req->getData();
if (!empty($data) && $model->loginUser($data, $sess)){
return redirect([BASE_URL_ENC,
$req->getBasePath()->encoded(),
isset($_GET['return']) ? ltrim($_GET['return'], '/') : '']);
}
return view(new LoginPage($model->load()));
}
}
?>
|
Improve meetup's validation error messages
|
from django.db import models
from pizzaplace.models import PizzaPlace
from django.core.validators import RegexValidator
from meetup.services.meetup_api_lookup_agent import MeetupApiLookupAgent
from django.core.exceptions import ValidationError
from model_utils.models import TimeStampedModel
def validate_urlname(link):
validator = RegexValidator(
regex='meetup\.com\/\w+(-\w+)*\/$',
message="Url should be in form 'meetup.com/meetup-name/'",
code='invalid_url')
return validator(link)
def validate_meetup_exists(link):
if not MeetupApiLookupAgent(link).meetup_exists():
raise ValidationError("Meetup not found on meetup.com")
class Meetup(TimeStampedModel):
name = models.CharField(max_length=500, null=False, blank=False, default=None, unique=True)
meetup_link = models.URLField(max_length=500,
unique=True,
default=None,
validators=[validate_urlname, validate_meetup_exists])
pizza_places = models.ManyToManyField(PizzaPlace)
def __str__(self):
return self.name
|
from django.db import models
from pizzaplace.models import PizzaPlace
from django.core.validators import RegexValidator
from meetup.services.meetup_api_lookup_agent import MeetupApiLookupAgent
from django.core.exceptions import ValidationError
def validate_urlname(link):
validator = RegexValidator(
regex='meetup\.com\/\w+(-\w+)*\/$',
message="Does not conform to Meetup Url",
code='invalid_url')
return validator(link)
def validate_meetup_exists(link):
looker = MeetupApiLookupAgent(link)
is_real = looker.is_real_meetup()
if not is_real:
raise ValidationError("That's not a meetup")
class Meetup(models.Model):
name = models.CharField(max_length=500, null=False, blank=False, default=None, unique=True)
meetup_link = models.URLField(max_length=500,
unique=True,
default=None,
validators=[validate_urlname, validate_meetup_exists])
pizza_places = models.ManyToManyField(PizzaPlace)
def __str__(self):
return self.name
|
Change method 'alias' to 'bind' for provide facade
|
<?php
namespace AndrewNovikof\Objects;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
], 'config');
$this->publishes([
__DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
__DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
], 'objects');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../resources/config/objects.php',
'config'
);
$this->app->bind('objects', ObjectsService::class);
}
}
|
<?php
namespace AndrewNovikof\Objects;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
], 'config');
$this->publishes([
__DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
__DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
], 'objects');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../resources/config/objects.php',
'config'
);
$this->app->alias('objects', ObjectsService::class);
}
}
|
Check user detail in test
|
# -*- coding: utf-8 -*-
import pytest
from .utils import get, versioned_reverse as reverse, assert_fields_exist
# === util methods ===
def get_list(api_client, version='v1'):
list_url = reverse('user-list', version=version)
return get(api_client, list_url)
def get_detail(api_client, detail_pk, version='v1'):
detail_url = reverse('user-detail', version=version, kwargs={'pk': detail_pk})
return get(api_client, detail_url)
def assert_user_fields_exist(data, version='v1'):
# TODO: incorporate version parameter into version aware
# parts of test code
fields = (
'last_login',
'username',
'email',
'date_joined',
'first_name',
'last_name',
'uuid',
'department_name',
'organization',
'is_staff',
'display_name',
)
assert_fields_exist(data, fields)
# === tests ===
@pytest.mark.django_db
def test__get_user_list(api_client, user, organization):
organization.admin_users.add(user)
api_client.force_authenticate(user=user)
response = get_detail(api_client, user.pk)
print(response.data)
assert_user_fields_exist(response.data)
|
# -*- coding: utf-8 -*-
import pytest
from .utils import get, versioned_reverse as reverse, assert_fields_exist
# === util methods ===
def get_list(api_client, version='v1'):
list_url = reverse('user-list', version=version)
return get(api_client, list_url)
def assert_user_fields_exist(data, version='v1'):
# TODO: incorporate version parameter into version aware
# parts of test code
fields = (
'last_login',
'username',
'email',
'date_joined',
'first_name',
'last_name',
'uuid',
'department_name',
'organization',
'is_staff',
'display_name',
)
assert_fields_exist(data, fields)
# === tests ===
@pytest.mark.django_db
def test__get_user_list(api_client, user, organization):
organization.admin_users.add(user)
api_client.force_authenticate(user=user)
response = get_list(api_client)
print(response.data)
assert_user_fields_exist(response.data['data'][0])
|
Reduce intermediate variables with merge function.
|
var merge = function(a, b){
var f = function(){};
f.prototype = a;
var c = new f();
for (var k in b) { if (b.hasOwnProperty(k)) {
c[k] = b[k];
}}
return c;
};
var defaultMappings = {
matchHost: '',
matchPath: '',
host: 'localhost',
port: 80
};
exports.resolve = function(mappings, request){
var host = (request.headers.host || '').split(':')[0];
var downstream;
for (var i = 0; i < mappings.length; i++) {
var m = merge(defaultMappings, mappings[i]);
if (host.match(m.matchHost) && request.url.match(m.matchPath)) {
downstream = {host: m.host, port: m.port};
break;
}
}
if (downstream === null) { return null; }
return {
host: downstream.host,
port: downstream.port,
method: request.method,
url: request.url,
headers: merge(request.headers, {host: downstream.host})
};
};
|
var clone = function(o){
var f = function(){};
f.prototype = o;
return new f();
};
exports.resolve = function(mappings, request){
var host = (request.headers.host || '').split(':')[0];
var downstream;
for (var i = 0; i < mappings.length; i++) {
var m = mappings[i];
if (host.match(m.matchHost || '') && request.url.match(m.matchPath || '')) {
downstream = {
host: m.host || 'localhost',
port: m.port || 80
};
break;
}
}
if (downstream === null) {
return null;
}
var headers = clone(request.headers);
headers.host = downstream.host;
return {
host: downstream.host,
port: downstream.port,
method: request.method,
url: request.url,
headers: headers
};
};
|
Improve default params handling on Middleware.response.
|
const res = response => Promise.resolve(response);
const rej = err => Promise.reject(err);
class Middleware {
constructor() {
this._req = [];
this._res = [];
}
request(fn) {
this._req.push(fn);
return this._req.length - 1;
}
response(fulfill = res, reject = rej) {
this._res.push({ fulfill, reject });
return this._res.length - 1;
}
resolveRequests(config) {
return this._req.reduce((promise, task) => {
promise = promise.then(task);
return promise;
}, Promise.resolve(config));
}
resolveResponses(response) {
return this._res.reduce((promise, task) => {
promise = promise.then(task.fulfill, task.reject);
return promise;
}, Promise.resolve(response));
}
}
module.exports = Middleware;
|
class Middleware {
constructor() {
this._req = [];
this._res = [];
}
request(fn) {
this._req.push(fn);
return this._req.length - 1;
}
response(fulfill, reject) {
fulfill || (fulfill = res => Promise.resolve(res));
reject || (reject = err => Promise.reject(err));
this._res.push({ fulfill, reject });
return this._res.length - 1;
}
resolveRequests(config) {
return this._req.reduce((promise, task) => {
promise = promise.then(task);
return promise;
}, Promise.resolve(config));
}
resolveResponses(response) {
return this._res.reduce((promise, task) => {
promise = promise.then(task.fulfill, task.reject);
return promise;
}, Promise.resolve(response));
}
}
module.exports = Middleware;
|
Remove pytest-runner from install requirements, add numpy as test requirement
|
from setuptools import setup
version = "0.5.1"
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
],
tests_require=[
"pytest",
"numpy",
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
|
from setuptools import setup
version = "0.5.1"
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
'pytest-runner',
],
tests_require=[
"pytest",
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
|
Add UTC manipulation of dates for to and froms
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { UIDatabase } from '../database';
import { FRIDGE_ACTIONS } from '../actions/FridgeActions';
const initialState = () => {
const fridges = UIDatabase.objects('Location');
return {
fridges,
selectedFridge: fridges[0],
fromDate: moment(new Date())
.subtract(30, 'd')
.toDate(),
toDate: new Date(),
};
};
export const FridgeReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case FRIDGE_ACTIONS.SELECT: {
const { payload } = action;
const { fridge } = payload;
return { ...state, selectedFridge: fridge };
}
case FRIDGE_ACTIONS.CHANGE_FROM_DATE: {
const { payload } = action;
const { date } = payload;
const fromDate = new Date(date);
fromDate.setUTCHours(0, 0, 0, 0);
return { ...state, fromDate };
}
case FRIDGE_ACTIONS.CHANGE_TO_DATE: {
const { payload } = action;
const { date } = payload;
const toDate = new Date(date);
toDate.setUTCHours(23, 59, 59, 999);
return { ...state, toDate };
}
default:
return state;
}
};
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { UIDatabase } from '../database';
import { FRIDGE_ACTIONS } from '../actions/FridgeActions';
const initialState = () => {
const fridges = UIDatabase.objects('Location');
return {
fridges,
selectedFridge: fridges[0],
fromDate: moment(new Date())
.subtract(30, 'd')
.toDate(),
toDate: new Date(),
};
};
export const FridgeReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case FRIDGE_ACTIONS.SELECT: {
const { payload } = action;
const { fridge } = payload;
return { ...state, selectedFridge: fridge };
}
case FRIDGE_ACTIONS.CHANGE_FROM_DATE: {
const { payload } = action;
const { date } = payload;
return { ...state, fromDate: date };
}
case FRIDGE_ACTIONS.CHANGE_TO_DATE: {
const { payload } = action;
const { date } = payload;
return { ...state, toDate: date };
}
default:
return state;
}
};
|
TASK: Exit value depending on the error number
|
<?php
namespace MStruebing\EditorconfigChecker;
use MStruebing\EditorconfigChecker\Cli\Cli;
use MStruebing\EditorconfigChecker\Cli\Logger;
$cliPath = dirname(__FILE__) . '/Cli/Cli.php';
$loggerPath = dirname(__FILE__) . '/Cli/Logger.php';
if (is_file($cliPath)) {
include_once $cliPath;
} else {
throw new \Exception('The CLI-class can not be found. Contact the maintainer.');
}
if (is_file($loggerPath)) {
include_once $loggerPath;
} else {
throw new \Exception('The Logger-class can not be found. Contact the maintainer.');
}
/* The first paaram is only the program-name */
array_shift($argv);
$logger = new Logger();
$cli = new Cli($logger);
$cli->run($argv);
if ($count = $logger->countErrors()) {
$logger->printErrors();
$count < 255 ? exit($count) : exit(255);
} else {
exit(0);
}
|
<?php
namespace MStruebing\EditorconfigChecker;
use MStruebing\EditorconfigChecker\Cli\Cli;
use MStruebing\EditorconfigChecker\Cli\Logger;
$cliPath = dirname(__FILE__) . '/Cli/Cli.php';
$loggerPath = dirname(__FILE__) . '/Cli/Logger.php';
if (is_file($cliPath)) {
include_once $cliPath;
} else {
throw new \Exception('The CLI-class can not be found. Contact the maintainer.');
}
if (is_file($loggerPath)) {
include_once $loggerPath;
} else {
throw new \Exception('The Logger-class can not be found. Contact the maintainer.');
}
/* The first paaram is only the program-name */
array_shift($argv);
$logger = new Logger();
$cli = new Cli($logger);
$cli->run($argv);
if ($logger->countErrors()) {
$logger->printErrors();
exit(1);
} else {
exit(0);
}
|
Add constructor to value encoders
We are adding this so we can extend constructors in subclasses, where needed
|
<?php
/*
* This file is part of the Active Collab Controller project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\Controller\ActionResultEncoder\ValueEncoder;
use Psr\Http\Message\StreamInterface;
use Slim\Http\Stream;
abstract class ValueEncoder implements ValueEncoderInterface
{
public function __construct()
{
}
/**
* Create the message body.
*
* @param string $text
* @return StreamInterface
*/
protected function createBodyFromText(string $text): StreamInterface
{
$handle = fopen('php://temp', 'wb+');
$body = new Stream($handle);
$body->write($text);
$body->rewind();
return $body;
}
}
|
<?php
/*
* This file is part of the Active Collab Controller project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\Controller\ActionResultEncoder\ValueEncoder;
use Psr\Http\Message\StreamInterface;
use Slim\Http\Stream;
abstract class ValueEncoder implements ValueEncoderInterface
{
/**
* Create the message body.
*
* @param string $text
* @return StreamInterface
*/
protected function createBodyFromText(string $text): StreamInterface
{
$handle = fopen('php://temp', 'wb+');
$body = new Stream($handle);
$body->write($text);
$body->rewind();
return $body;
}
}
|
Tidy up gulp jsdoc task
|
var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
livereload = require('gulp-livereload'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: 'ink-docstrap',
systemName: '',
footer: '',
copyright: 'Copyright Money Advice Service ©',
navType: 'vertical',
theme: 'flatly',
linenums: true,
collapseSymbols: false,
inverseNav: false
},
{
plugins: ['plugins/markdown'],
cleverLinks: true
}
)
);
};
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
|
var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
livereload = require('gulp-livereload'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(jsdoc.parser({
plugins: ['plugins/markdown']
}))
.pipe(jsdoc.generator(docsDestDir, {
path: 'ink-docstrap',
systemName: '',
footer: '',
copyright: 'Copyright Money Advice Service ©',
navType: 'vertical',
theme: 'flatly',
linenums: true,
collapseSymbols: false,
inverseNav: false
}));
};
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
|
Replace testing paremeters and implement Routing methods of the FOSJsBundle
|
$(document).ready(function() {
$('.crud-entity-delete').click(function() {
$('#entity-delete .btn-danger').attr('data-id', $(this).attr('data-id'));
$('#entity-delete .btn-danger').attr('data-entity', $(this).attr('data-entity'));
$('#entity-delete').modal();
return false;
});
$('#entity-delete .btn-danger').click(function() {
$.ajax({
type: 'DELETE',
url: Routing.generate('developathe_crud_delete', {'entity': $(this).attr('data-entity'), 'id': $(this).attr('data-id')})
}).done(function(){
location.reload();
});
});
});
|
$(document).ready(function() {
$('.crud-delete').click(function() {
$('#entity-delete .btn-danger').attr('data-id', $(this).attr('data-id'));
$('#entity-delete .btn-danger').attr('data-entity', $(this).attr('data-entity'));
$('#entity-delete').modal();
return false;
});
$('#entity-delete .btn-danger').click(function() {
$.ajax({
type: 'DELETE',
url: 'http://symfony.debian/app_dev.php/crud-delete/' + $(this).attr('data-entity') + '/' + $(this).attr('data-id')
}).done(function(){
location.reload();
});
});
});
|
Fix bad transposition of utility function in sflow
|
import struct, socket
def unpack_address(u):
addrtype = u.unpack_uint()
if addrtype == 1:
address = u.unpack_fopaque(4)
if addrtype == 2:
address = u.unpack_fopaque(16)
return address
class IPv4Address(object):
def __init__(self, addr_int):
self.addr_int = addr_int
self.na = struct.pack(b'!L', addr_int)
def __str__(self):
return socket.inet_ntoa(self.na)
def asString(self):
return str(self)
def __repr__(self):
return "<IPv4Address ip=\"%s\">" % str(self)
|
import struct, socket
def unpack_address(u):
addrtype = u.unpack_uint()
if self.addrtype == 1:
self.address = u.unpack_fopaque(4)
if self.addrtype == 2:
self.address = u.unpack_fopaque(16)
return self.address
class IPv4Address(object):
def __init__(self, addr_int):
self.addr_int = addr_int
self.na = struct.pack(b'!L', addr_int)
def __str__(self):
return socket.inet_ntoa(self.na)
def asString(self):
return str(self)
def __repr__(self):
return "<IPv4Address ip=\"%s\">" % str(self)
|
Rename decorator equality_comparable to equalable
|
from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equalable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equalable(cls, attributes, methods)
cls.__hash__ = HashCodeBuilder.auto_generate(cls, attributes, methods)
return cls
return decorator if cls is None else decorator(cls)
def equalable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls.__eq__ = EqualsBuilder.auto_generate(cls, attributes, methods)
cls.__ne__ = EqualsBuilder.auto_ne_from_eq()
return cls
return decorator if cls is None else decorator(cls)
def _validate_attributes_and_methods(attributes, methods):
assert not isinstance(attributes, basestring), 'attributes must be list'
assert not isinstance(methods, basestring), 'methods must be list'
assert attributes or methods, 'attributes or methods must be NOT empty'
|
from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equality_comparable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equality_comparable(cls, attributes, methods)
cls.__hash__ = HashCodeBuilder.auto_generate(cls, attributes, methods)
return cls
return decorator if cls is None else decorator(cls)
def equality_comparable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls.__eq__ = EqualsBuilder.auto_generate(cls, attributes, methods)
cls.__ne__ = EqualsBuilder.auto_ne_from_eq()
return cls
return decorator if cls is None else decorator(cls)
def _validate_attributes_and_methods(attributes, methods):
assert not isinstance(attributes, basestring), 'attributes must be list'
assert not isinstance(methods, basestring), 'methods must be list'
assert attributes or methods, 'attributes or methods must be NOT empty'
|
Clarify that debugging has to be turned on for DB profiling to work.
git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@2619 653ae4dd-d31e-0410-96ef-6bf7bf53c507
|
<!-- footer -->
<div class="clear"></div>
</div>
<hr>
<p id="footer">
<small><?php Options::out('title'); _e(' is powered by'); ?> <a href="http://www.habariproject.org/" title="Habari">Habari</a> <?php _e('and a huge amount of'); ?>
<a href="http://en.wikipedia.org/wiki/Caffeine" title="<?php _e('Caffeine'); ?>" rel="nofollow">C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub></a></small><br>
<small><a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><?php _e('Atom Entries'); ?></a> <?php _e('and'); ?> <a href="<?php URL::out( 'atom_feed_comments' ); ?>"><?php _e('Atom Comments'); ?></a></small>
</p>
<?php $theme->footer(); ?>
<?php
/* In order to see DB profiling information:
1. Insert this line in your config file: define( 'DEBUG', TRUE );
2.Uncomment the followng line
*/
// include 'db_profiling.php';
?>
</body>
</html>
<!-- /footer -->
|
<!-- footer -->
<div class="clear"></div>
</div>
<hr>
<p id="footer">
<small><?php Options::out('title'); _e(' is powered by'); ?> <a href="http://www.habariproject.org/" title="Habari">Habari</a> <?php _e('and a huge amount of'); ?>
<a href="http://en.wikipedia.org/wiki/Caffeine" title="<?php _e('Caffeine'); ?>" rel="nofollow">C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub></a></small><br>
<small><a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><?php _e('Atom Entries'); ?></a> <?php _e('and'); ?> <a href="<?php URL::out( 'atom_feed_comments' ); ?>"><?php _e('Atom Comments'); ?></a></small>
</p>
<?php $theme->footer(); ?>
<?php
// Uncomment this to view your DB profiling info
// include 'db_profiling.php';
?>
</body>
</html>
<!-- /footer -->
|
Change bases of exception classes extending SpamListsError and ValueError
This commit removes SpamListsError and ValueError as direct base classes
of other exception classes (except SpamListsValueError), and replaces
them with SpamListsValueError.
|
# -*- coding: utf-8 -*-
'''
This module contains all classes of exceptions raised
by the library
'''
from __future__ import unicode_literals
class SpamListsError(Exception):
'''There was an error during testing a url or host'''
class SpamListsValueError(SpamListsError, ValueError):
'''An inapropriate value was used in SpamLists library '''
class UnknownCodeError(SpamListsError, KeyError):
'''The classification code from the service was not recognized'''
class UnathorizedAPIKeyError(SpamListsValueError):
'''The API key used to query the service was not authorized'''
class InvalidHostError(SpamListsValueError):
'''The value is not a valid host'''
class InvalidIPError(InvalidHostError):
''' The value is not a valid IP address'''
class InvalidIPv4Error(InvalidIPError):
'''The value is not a valid IPv4 address'''
class InvalidIPv6Error(InvalidIPError):
'''The value is not a valid IPv6 address'''
class InvalidHostnameError(InvalidHostError):
'''The value is not a valid hostname'''
class InvalidURLError(SpamListsValueError):
'''The value is not a valid url'''
|
# -*- coding: utf-8 -*-
'''
This module contains all classes of exceptions raised
by the library
'''
from __future__ import unicode_literals
class SpamListsError(Exception):
'''There was an error during testing a url or host'''
class SpamListsValueError(SpamListsError, ValueError):
'''An inapropriate value was used in SpamLists library '''
class UnknownCodeError(SpamListsError, KeyError):
'''The classification code from the service was not recognized'''
class UnathorizedAPIKeyError(SpamListsError, ValueError):
'''The API key used to query the service was not authorized'''
class InvalidHostError(SpamListsError, ValueError):
'''The value is not a valid host'''
class InvalidIPError(InvalidHostError):
''' The value is not a valid IP address'''
class InvalidIPv4Error(InvalidIPError):
'''The value is not a valid IPv4 address'''
class InvalidIPv6Error(InvalidIPError):
'''The value is not a valid IPv6 address'''
class InvalidHostnameError(InvalidHostError):
'''The value is not a valid hostname'''
class InvalidURLError(SpamListsError, ValueError):
'''The value is not a valid url'''
|
Add native type to boolean fields
|
<?php
/*
* This file is part of the Active Collab DatabaseStructure project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\DatabaseStructure\Field\Scalar;
use LogicException;
/**
* @package ActiveCollab\DatabaseStructure\Field\Scalar
*/
class BooleanField extends Field
{
/**
* @param string $name
* @param bool $default_value
*/
public function __construct($name, $default_value = false)
{
parent::__construct($name, $default_value);
}
/**
* {@inheritdoc}
*/
public function &unique(...$context)
{
throw new LogicException('Boolean columns cant be made unique');
}
/**
* {@inheritdoc}
*/
public function getNativeType()
{
return 'bool';
}
/**
* {@inheritdoc}
*/
public function getCastingCode($variable_name)
{
return '(bool) $' . $variable_name;
}
}
|
<?php
/*
* This file is part of the Active Collab DatabaseStructure project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\DatabaseStructure\Field\Scalar;
use LogicException;
/**
* @package ActiveCollab\DatabaseStructure\Field\Scalar
*/
class BooleanField extends Field
{
/**
* @param string $name
* @param bool $default_value
*/
public function __construct($name, $default_value = false)
{
parent::__construct($name, $default_value);
}
/**
* Value of this column needs to be unique (in the given context).
*
* @param string[] $context
* @return $this
*/
public function &unique(...$context)
{
throw new LogicException('Boolean columns cant be made unique');
}
/**
* Return value casting code.
*
* @param string $variable_name
* @return string
*/
public function getCastingCode($variable_name)
{
return '(bool) $' . $variable_name;
}
}
|
Revert "Fix broken test in PHP 5.4"
This reverts commit 60a6a6943c76a783f0251245b8a3919d86640f6b.
|
<?php
namespace Test;
// \HttpMessage
use Kambo\HttpMessage\Uri;
use Kambo\HttpMessage\Factories\String\UriFactory;
/**
* Unit test for the UriFactory object.
*
* @package Test
* @author Bohuslav Simek <bohuslav@simek.si>
* @license MIT
*/
class UriFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* Test creating url from string.
*
* @return void
*/
public function testCreate()
{
$uri = UriFactory::create(
'http://user:password@test.com:1111/path/123?q=abc#test'
);
$this->assertInstanceOf(Uri::class, $uri);
$this->assertEquals('http', $uri->getScheme());
$this->assertEquals('user:password', $uri->getUserInfo());
$this->assertEquals('test.com', $uri->getHost());
$this->assertEquals(1111, $uri->getPort());
$this->assertEquals('/path/123', $uri->getPath());
$this->assertEquals('q=abc', $uri->getQuery());
$this->assertEquals('test', $uri->getFragment());
}
}
|
<?php
namespace Test;
// \HttpMessage
use Kambo\HttpMessage\Uri;
use Kambo\HttpMessage\Factories\String\UriFactory;
/**
* Unit test for the UriFactory object.
*
* @package Test
* @author Bohuslav Simek <bohuslav@simek.si>
* @license MIT
*/
class UriFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* Test creating url from string.
*
* @return void
*/
public function testCreate()
{
$uri = UriFactory::create(
'http://user:password@test.com:1111/path/123?q=abc#test'
);
$this->assertInstanceOf('Kambo\HttpMessage\Uri', $uri);
$this->assertEquals('http', $uri->getScheme());
$this->assertEquals('user:password', $uri->getUserInfo());
$this->assertEquals('test.com', $uri->getHost());
$this->assertEquals(1111, $uri->getPort());
$this->assertEquals('/path/123', $uri->getPath());
$this->assertEquals('q=abc', $uri->getQuery());
$this->assertEquals('test', $uri->getFragment());
}
}
|
Add DAG & non-DAG adjacency dicts
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _previsit():
pass
def _postvisit():
pass
def _dfs_explore():
pass
def check_dag():
"""Check Directed Acyclic Graph (DAG)."""
pass
def main():
# Graph adjacency dictionary for DAG.
dag_adj_d = {
'A': ['D'],
'B': ['D'],
'C': ['D'],
'D': ['E', 'G'],
'E': ['J'],
'F': ['G'],
'G': ['I'],
'I': ['J'],
'J': []
}
# Graph adjacency dictionary for non-DAG.
nondag_adj_d = {
'A': ['B'],
'B': ['C', 'E'],
'C': ['C', 'F'],
'D': ['B', 'G'],
'E': ['A', 'D'],
'F': ['H'],
'G': ['E'],
'H': ['I'],
'I': ['F']
}
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _previsit():
pass
def _postvisit():
pass
def _dfs_explore():
pass
def check_dag():
"""Check Directed Acyclic Graph (DAG)."""
pass
def main():
# DAG.
dag_adj_d = {
'A': ['D'],
'B': ['D'],
'C': ['D'],
'D': ['E', 'G'],
'E': ['J'],
'F': ['G'],
'G': ['I'],
'I': ['J'],
'J': []
}
if __name__ == '__main__':
main()
|
Clean up route handling so it's more readable.
|
'use strict';
const express = require('express');
const BodyParser = require('body-parser');
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
exports.attach = function (app, storage) {
app.get('/v1/health', require('./health'));
app.get('/v1/token/default', require('./token')(storage));
// Backend endpoints
app.get('/v1/secret/:token/:path(*)', require('./secret')(storage));
app.get('/v1/cubbyhole/:token/:path', require('./cubbyhole')(storage));
app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage));
app.use(BodyParser.json());
app.post('/v1/transit/:token/decrypt', require('./transit')(storage));
app.use('/v1/transit', Handlers.allowed('POST'));
app.use(Handlers.allowed('GET'));
app.use(Err);
};
|
'use strict';
const express = require('express');
const BodyParser = require('body-parser');
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
exports.attach = function (app, storage) {
app.get('/v1/health', require('./health'));
app.use('/v1/health', Handlers.allowed('GET'));
app.get('/v1/token/default', require('./token')(storage));
app.use('/v1/token', Handlers.allowed('GET'));
// Backend endpoints
app.get('/v1/secret/:token/:path(*)', require('./secret')(storage));
app.use('/v1/secret', Handlers.allowed('GET'));
app.get('/v1/cubbyhole/:token/:path', require('./cubbyhole')(storage));
app.use('/v1/cubbyhole', Handlers.allowed('GET'));
app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage));
app.use('/v1/credential', Handlers.allowed('GET'));
app.use(BodyParser.json());
app.post('/v1/transit/:token/decrypt', require('./transit')(storage));
app.use('/v1/transit', Handlers.allowed('POST'));
app.use(Err);
};
|
Improve thread safety around adding and removing IDataListener's
Previously deadlock was possible if a listener was running in the same
thread as a call attempting to add or remove listeners. As might be
commonly the case for the UI thread.
Also replaced the listeners List with a Set to prevent duplicate
listeners being added. Using a set backed by a ConcurrentHashMap should
allow all operation to complete safely without requiring external
synchronized, this allows the methods in the class to be simplified.
Signed-off-by: James Mudd <50b9fff9a292b5df2aef2220dca201538f796e13@diamond.ac.uk>
|
/*-
* Copyright 2015, 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.january.dataset;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Class used by DynamicDataset to delegate
*/
public class DataListenerDelegate {
private Set<IDataListener> listeners;
public DataListenerDelegate() {
listeners = Collections.newSetFromMap(new ConcurrentHashMap<IDataListener, Boolean>());
}
public void addDataListener(IDataListener l) {
listeners.add(l);
}
public void removeDataListener(IDataListener l) {
listeners.remove(l);
}
public void fire(DataEvent evt) {
for (IDataListener listener : listeners) {
listener.dataChangePerformed(evt);
}
}
public boolean hasDataListeners() {
return listeners.size() > 0;
}
public void clear() {
listeners.clear();
}
}
|
/*-
* Copyright 2015, 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.january.dataset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Class used by DynamicDataset to delegate
*/
public class DataListenerDelegate {
private List<IDataListener> listeners;
public DataListenerDelegate() {
listeners = Collections.synchronizedList(new ArrayList<IDataListener>());
}
public void addDataListener(IDataListener l) {
synchronized (listeners) {
if (!listeners.contains(l)) {
listeners.add(l);
}
}
}
public void removeDataListener(IDataListener l) {
listeners.remove(l);
}
public void fire(DataEvent evt) {
synchronized (listeners) {
for (Iterator<IDataListener> iterator = listeners.iterator(); iterator.hasNext();) {
iterator.next().dataChangePerformed(evt);
}
}
}
public boolean hasDataListeners() {
return listeners.size() > 0;
}
public void clear() {
listeners.clear();
}
}
|
Fix bug on travis CI
|
import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
import configs from '../config/config';
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'test';
const config = configs[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
sequelize = new Sequelize(config.database, config.username,
config.password, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
const fileName = (file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js');
return fileName;
})
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
|
import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
import configs from '../config/config';
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = configs[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
sequelize = new Sequelize(config.database, config.username,
config.password, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
const fileName = (file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js');
return fileName;
})
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
|
Mark internal classes final where possible
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Php54;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
final class Php54
{
public static function hex2bin($data)
{
$len = strlen($data);
if (null === $len) {
return;
}
if ($len % 2) {
trigger_error('hex2bin(): Hexadecimal input string must have an even length', E_USER_WARNING);
return false;
}
$data = pack('H*', $data);
if (false !== strpos($data, "\0")) {
return false;
}
return $data;
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Php54;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class Php54
{
public static function hex2bin($data)
{
$len = strlen($data);
if (null === $len) {
return;
}
if ($len % 2) {
trigger_error('hex2bin(): Hexadecimal input string must have an even length', E_USER_WARNING);
return false;
}
$data = pack('H*', $data);
if (false !== strpos($data, "\0")) {
return false;
}
return $data;
}
}
|
Use the right step name for profiling
|
const _ = require('underscore');
module.exports = function dbConnSetup (pgConnection) {
return function dbConnSetupMiddleware (req, res, next) {
const { user } = res.locals;
pgConnection.setDBConn(user, res.locals, (err) => {
req.profiler.done('dbConnSetup');
if (err) {
if (err.message && -1 !== err.message.indexOf('name not found')) {
err.http_status = 404;
}
return next(err);
}
_.defaults(res.locals, {
dbuser: global.environment.postgres.user,
dbpassword: global.environment.postgres.password,
dbhost: global.environment.postgres.host,
dbport: global.environment.postgres.port
});
res.set('X-Served-By-DB-Host', res.locals.dbhost);
next();
});
};
};
|
const _ = require('underscore');
module.exports = function dbConnSetup (pgConnection) {
return function dbConnSetupMiddleware (req, res, next) {
const { user } = res.locals;
pgConnection.setDBConn(user, res.locals, (err) => {
req.profiler.done('setDBConn');
if (err) {
if (err.message && -1 !== err.message.indexOf('name not found')) {
err.http_status = 404;
}
return next(err);
}
_.defaults(res.locals, {
dbuser: global.environment.postgres.user,
dbpassword: global.environment.postgres.password,
dbhost: global.environment.postgres.host,
dbport: global.environment.postgres.port
});
res.set('X-Served-By-DB-Host', res.locals.dbhost);
next();
});
};
};
|
Remove unused foundation JS components.
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
// TODO: jquery_ujs is currently used for the serverside-rendered logout link on the home page
// and should be removed as soon as a new solution is in place.
//= require jquery_ujs
//= require underscore
//
// ---
//
// TODO: Remove foundation dependencies with upcoming redesign:
//
//= require foundation/jquery.foundation.alerts
//= require foundation/jquery.foundation.reveal
//= require foundation/app
//
// ---
//
//= require_tree ./_domscripting
//= require i18n
//= require i18n/translations
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
// TODO: jquery_ujs is currently used for the serverside-rendered logout link on the home page
// and should be removed as soon as a new solution is in place.
//= require jquery_ujs
//= require underscore
//
// ---
//
// TODO: Remove foundation dependencies with upcoming redesign:
//
//= require foundation/modernizr.foundation
//= require foundation/jquery.placeholder
//= require foundation/jquery.foundation.alerts
//= require foundation/jquery.foundation.accordion
//= require foundation/jquery.foundation.buttons
//= require foundation/jquery.foundation.tooltips
//= require foundation/jquery.foundation.forms
//= require foundation/jquery.foundation.tabs
//= require foundation/jquery.foundation.navigation
//= require foundation/jquery.foundation.topbar
//= require foundation/jquery.foundation.reveal
//= require foundation/jquery.foundation.orbit
//= require foundation/jquery.foundation.joyride
//= require foundation/jquery.foundation.clearing
//= require foundation/jquery.foundation.mediaQueryToggle
//= require foundation/app
//
// ---
//
//= require_tree ./_domscripting
//= require i18n
//= require i18n/translations
|
Put both the window URL and the test URL through an anchor.
Fixes an inconsistency in IE between a.href and window.location about whether default ports are included or not.
|
/*global define*/
define(function() {
"use strict";
var a;
/**
* Given a URL, determine whether that URL is considered cross-origin to the current page.
*
* @private
*/
var isCrossOriginUrl = function(url) {
if (typeof a === 'undefined') {
a = document.createElement('a');
}
// copy window location into the anchor to get consistent results
// when the port is default for the protocol (e.g. 80 for HTTP)
a.href = window.location.href;
// host includes both hostname and port if the port is not standard
var host = a.host;
var protocol = a.protocol;
a.href = url;
a.href = a.href; // IE only absolutizes href on get, not set
return protocol !== a.protocol || host !== a.host;
};
return isCrossOriginUrl;
});
|
/*global define*/
define(function() {
"use strict";
var a;
/**
* Given a URL, determine whether that URL is considered cross-origin to the current page.
*
* @private
*/
var isCrossOriginUrl = function(url) {
if (typeof a === 'undefined') {
a = document.createElement('a');
}
var location = window.location;
a.href = url;
a.href = a.href; // IE only absolutizes href on get, not set
// host includes both hostname and port if the port is not standard
return a.protocol !== location.protocol || a.host !== location.host;
};
return isCrossOriginUrl;
});
|
Add Python3 classfier fo CheeseShop.
|
#!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='http://code.google.com/p/mockito/wiki/MockitoForPython',
download_url='http://bitbucket.org/szczepiq/mockito-python/downloads/',
maintainer='mockito maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description='Mockito is a spying framework based on Java library with the same name.',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3'
],
test_loader = 'mockito_util.test:TestLoader',
test_suite = 'mockito_test',
**extra
)
|
#!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='http://code.google.com/p/mockito/wiki/MockitoForPython',
download_url='http://bitbucket.org/szczepiq/mockito-python/downloads/',
maintainer='mockito maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description='Mockito is a spying framework based on Java library with the same name.',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing'
],
test_loader = 'mockito_util.test:TestLoader',
test_suite = 'mockito_test',
**extra
)
|
Fix expose API host env
|
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'client',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
script: [{ src: 'https://js.stripe.com/v3' }]
},
/*
** Expose env variables
*/
env: {
API_URL: process.env.API_URL
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend(config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
modules: ['bootstrap-vue/nuxt']
}
|
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'client',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
script: [{ src: 'https://js.stripe.com/v3' }]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend(config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
modules: ['bootstrap-vue/nuxt']
}
|
Add check for OS - this gives errors on Mac as-is
|
<?php
/**
* PHP Command Line Tools
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*
* @author James Logsdon <dwarf@girsbrain.org>
* @copyright 2010 James Logsdom (http://girsbrain.org)
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace cli;
/**
* The `Shell` class is a utility class for shell related information such as
* width.
*/
class Shell {
/**
* Returns the number of columns the current shell has for display.
*
* @return int The number of columns.
* @todo Test on more systems.
*/
static public function columns() {
if( isset( $_SERVER['OS'] ) && strpos( $_SERVER['OS'], 'indows' ) !== false )
return exec('/usr/bin/env tput cols');
else
return 80; // default width of cmd window on Windows OS, maybe force using MODE CON COLS=XXX?
}
/**
* Checks whether the output of the current script is a TTY or a pipe / redirect
*
* Returns true if STDOUT output is being redirected to a pipe or a file; false is
* output is being sent directly to the terminal.
*
* @return bool
*/
static public function isPiped() {
return (function_exists('posix_isatty') && !posix_isatty(STDOUT));
}
}
?>
|
<?php
/**
* PHP Command Line Tools
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*
* @author James Logsdon <dwarf@girsbrain.org>
* @copyright 2010 James Logsdom (http://girsbrain.org)
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace cli;
/**
* The `Shell` class is a utility class for shell related information such as
* width.
*/
class Shell {
/**
* Returns the number of columns the current shell has for display.
*
* @return int The number of columns.
* @todo Test on more systems.
*/
static public function columns() {
if( strpos( $_SERVER['OS'], 'indows' ) !== false )
return exec('/usr/bin/env tput cols');
else
return 80; // default width of cmd window on Windows OS, maybe force using MODE CON COLS=XXX?
}
/**
* Checks whether the output of the current script is a TTY or a pipe / redirect
*
* Returns true if STDOUT output is being redirected to a pipe or a file; false is
* output is being sent directly to the terminal.
*
* @return bool
*/
static public function isPiped() {
return (function_exists('posix_isatty') && !posix_isatty(STDOUT));
}
}
?>
|
Fix an imports ordering problem
|
# coding: utf-8
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views.decorators.cache import cache_page
def execute_sql(request):
list(User.objects.all())
return HttpResponse()
def regular_view(request, title):
return render(request, 'basic.html', {'title': title})
def template_response_view(request, title):
return TemplateResponse(request, 'basic.html', {'title': title})
def new_user(request, username='joe'):
User.objects.create_user(username=username)
return render(request, 'basic.html', {'title': 'new user'})
def resolving_view(request, arg1, arg2):
# see test_url_resolving in tests.py
return HttpResponse()
@cache_page(60)
def cached_view(request):
return HttpResponse()
def regular_jinjia_view(request, title):
return render(request, 'jinja2/basic.jinja', {'title': title})
def listcomp_view(request):
lst = [i for i in range(50000) if i % 2 == 0]
return render(request, 'basic.html', {'title': 'List comprehension', 'lst': lst})
def redirect_view(request):
return HttpResponseRedirect('/regular/redirect/')
|
# coding: utf-8
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_page
def execute_sql(request):
list(User.objects.all())
return HttpResponse()
def regular_view(request, title):
return render(request, 'basic.html', {'title': title})
def template_response_view(request, title):
return TemplateResponse(request, 'basic.html', {'title': title})
def new_user(request, username='joe'):
User.objects.create_user(username=username)
return render(request, 'basic.html', {'title': 'new user'})
def resolving_view(request, arg1, arg2):
# see test_url_resolving in tests.py
return HttpResponse()
@cache_page(60)
def cached_view(request):
return HttpResponse()
def regular_jinjia_view(request, title):
return render(request, 'jinja2/basic.jinja', {'title': title})
def listcomp_view(request):
lst = [i for i in range(50000) if i % 2 == 0]
return render(request, 'basic.html', {'title': 'List comprehension', 'lst': lst})
def redirect_view(request):
return HttpResponseRedirect('/regular/redirect/')
|
Fix StatsRequest body type; add default values
|
"""Query the datapath about its current state."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import BinaryData, UBInt16
# Local imports
from pyof.v0x01.common.header import Header, Type
from pyof.v0x01.controller2switch.common import StatsTypes
__all__ = ('StatsRequest',)
class StatsRequest(GenericMessage):
"""Response to the config request."""
#: OpenFlow :class:`.Header`
header = Header(message_type=Type.OFPT_STATS_REQUEST)
body_type = UBInt16(enum_ref=StatsTypes)
flags = UBInt16()
body = BinaryData()
def __init__(self, xid=None, body_type=None, flags=0, body=b''):
"""The constructor just assings parameters to object attributes.
Args:
body_type (StatsTypes): One of the OFPST_* constants.
flags (int): OFPSF_REQ_* flags (none yet defined).
body (ConstantTypeList): Body of the request.
"""
super().__init__(xid)
self.body_type = body_type
self.flags = flags
self.body = body
|
"""Query the datapath about its current state."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import ConstantTypeList, UBInt16
# Local imports
from pyof.v0x01.common.header import Header, Type
from pyof.v0x01.controller2switch.common import StatsTypes
__all__ = ('StatsRequest',)
class StatsRequest(GenericMessage):
"""Response to the config request."""
#: OpenFlow :class:`.Header`
header = Header(message_type=Type.OFPT_STATS_REQUEST)
body_type = UBInt16(enum_ref=StatsTypes)
flags = UBInt16()
body = ConstantTypeList()
def __init__(self, xid=None, body_type=None, flags=None, body=None):
"""The constructor just assings parameters to object attributes.
Args:
body_type (StatsTypes): One of the OFPST_* constants.
flags (int): OFPSF_REQ_* flags (none yet defined).
body (ConstantTypeList): Body of the request.
"""
super().__init__(xid)
self.body_type = body_type
self.flags = flags
self.body = [] if body is None else body
|
Refactor following storage's api backend change
|
# Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_exist(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
|
# Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_find(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
|
Move confirm call directly in the if statement
|
import { bind } from 'decko';
import React from 'react';
import { findDOMNode } from 'react-dom';
/**
* A modal dialog window.
*/
class Dialog extends React.Component {
componentDidMount () {
this.elDialog = findDOMNode(this.refs.dialog);
document.body.addEventListener('keydown', this.onEsc);
}
componentWillUnmount () {
document.body.removeEventListener('keydown', this.onEsc);
}
@bind
onEsc (e) {
e = e || window.event;
if (e.keyCode == 27) {
this.props.onClose();
}
}
@bind
onOverlayClick (e) {
// Close (i.e. cancel) the dialog if the outer overlay is clicked
if (!this.elDialog.contains(e.target) &&
confirm("Are you sure you want to exit the editor " +
"and lose all progress on your current CRC card?")) {
this.props.onClose();
}
}
render () {
return (
<div className='dialog' onClick={this.onOverlayClick}>
<div ref='dialog' className='dialog__window'>
<h2 className='dialog__title'>{this.props.title}</h2>
{this.props.children}
</div>
</div>
);
}
}
export default Dialog;
|
import { bind } from 'decko';
import React from 'react';
import { findDOMNode } from 'react-dom';
/**
* A modal dialog window.
*/
class Dialog extends React.Component {
componentDidMount () {
this.elDialog = findDOMNode(this.refs.dialog);
document.body.addEventListener('keydown', this.onEsc);
}
componentWillUnmount () {
document.body.removeEventListener('keydown', this.onEsc);
}
@bind
onEsc (e) {
e = e || window.event;
if (e.keyCode == 27) {
this.props.onClose();
}
}
@bind
onOverlayClick (e) {
// Close (i.e. cancel) the dialog if the outer overlay is clicked
if (!this.elDialog.contains(e.target)) {
var exit = confirm("Are you sure you want to exit the editor" +
"and lose all progress on your current CRC card?");
if (exit == true) {
this.props.onClose();
}
}
}
render () {
return (
<div className='dialog' onClick={this.onOverlayClick}>
<div ref='dialog' className='dialog__window'>
<h2 className='dialog__title'>{this.props.title}</h2>
{this.props.children}
</div>
</div>
);
}
}
export default Dialog;
|
Test for getting undefined/null values
|
var vows = require('vows'),
assert = require('assert'),
get = require('../src/get');
vows.describe('get()').addBatch({
'Getting': {
topic: function() {
return {
foo: 1,
undef: undefined,
nil: null
};
},
'an existing property returns the value': function(obj) {
assert.equal(get(obj, 'foo'), 1);
},
'a non-existing property returns undefined by default': function(obj) {
assert.isUndefined(get(obj, 'bar'));
},
'a property on a null or undefined object returns undefined by default': function(obj) {
assert.isUndefined(get(null, 'bar'));
assert.isUndefined(get(undefined, 'bar'));
},
'a non-existing property returns the default value if provided': function(obj) {
assert.equal(get(obj, 'foo', 2), 1);
assert.equal(get(obj, 'bar', 2), 2);
},
'an existing property with value undefined does not return the default value': function(obj) {
assert.isUndefined(get(obj, 'undef', 'not-found'));
},
'an existing property with value null does not return the default value': function(obj) {
assert.isNull(get(obj, 'nil', 'not-found'));
},
}
}).export(module);
|
var vows = require('vows'),
assert = require('assert'),
get = require('../src/get');
vows.describe('get()').addBatch({
'Getting': {
topic: function() {
return {
foo: 1
};
},
'an existing property returns the value': function(obj) {
assert.equal(get(obj, 'foo'), 1);
},
'a non-existing property returns undefined by default': function(obj) {
assert.isUndefined(get(obj, 'bar'));
},
'a property on a null or undefined object returns undefined by default': function(obj) {
assert.isUndefined(get(null, 'bar'));
assert.isUndefined(get(undefined, 'bar'));
},
'a non-existing property returns the default value if provided': function(obj) {
assert.equal(get(obj, 'foo', 2), 1);
assert.equal(get(obj, 'bar', 2), 2);
},
}
}).export(module);
|
Add default options for import functionality
|
const path = require('path');
const logger = require('./logger');
const addMetadata = (res, filepath) => {
if (res.constructor === Array) {
return res.map(item => {
item.file = filepath;
return item;
});
} else {
res.file = filepath;
return res;
}
};
module.exports = {
import: (filePath, { strict = false } = {}) => {
try {
const fileContents = require(path.join(process.cwd(), filePath));
let data = typeof fileContents === 'string' ? JSON.parse(fileContents) : fileContents;
data = addMetadata(data, filePath);
return data;
} catch (err) {
logger.error(`Failed to parse "${filePath}"`);
if (strict) {
throw err;
}
}
},
clearCache: filePath => {
delete require.cache[require.resolve(path.join(process.cwd(), filePath))];
}
};
|
const path = require('path');
const logger = require('./logger');
const addMetadata = (res, filepath) => {
if (res.constructor === Array) {
return res.map(item => {
item.file = filepath;
return item;
});
} else {
res.file = filepath;
return res;
}
};
module.exports = {
import: (filePath, { strict = false }) => {
try {
const fileContents = require(path.join(process.cwd(), filePath));
let data = typeof fileContents === 'string' ? JSON.parse(fileContents) : fileContents;
data = addMetadata(data, filePath);
return data;
} catch (err) {
logger.error(`Failed to parse "${filePath}"`);
if (strict) {
throw err;
}
}
},
clearCache: filePath => {
delete require.cache[require.resolve(path.join(process.cwd(), filePath))];
}
};
|
Watch config.Source instead of config.Output
Fixes an issue which caused the watcher to not trigger re-builds, as it
was incorrectly watching the output folder.
|
// (c) 2012 Alexander Solovyov
// under terms of ISC license
package main
import (
"github.com/howeyc/fsnotify"
"os"
"path/filepath"
)
func Watcher(config *SiteConfig) (chan string, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
ch := make(chan string, 10)
go func() {
for {
select {
case ev := <-watcher.Event:
if ev.IsCreate() {
watcher.Watch(ev.Name)
} else if ev.IsDelete() {
watcher.RemoveWatch(ev.Name)
}
ch <- ev.Name
}
}
}()
filepath.Walk(config.Source, watchAll(watcher))
for _, path := range config.Templates {
watcher.Watch(path)
}
return ch, nil
}
func watchAll(watcher *fsnotify.Watcher) filepath.WalkFunc {
return func(fn string, fi os.FileInfo, err error) error {
if err != nil {
return nil
}
watcher.Watch(fn)
return nil
}
}
|
// (c) 2012 Alexander Solovyov
// under terms of ISC license
package main
import (
"github.com/howeyc/fsnotify"
"os"
"path/filepath"
)
func Watcher(config *SiteConfig) (chan string, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
ch := make(chan string, 10)
go func() {
for {
select {
case ev := <-watcher.Event:
if ev.IsCreate() {
watcher.Watch(ev.Name)
} else if ev.IsDelete() {
watcher.RemoveWatch(ev.Name)
}
ch <- ev.Name
}
}
}()
filepath.Walk(config.Output, watchAll(watcher))
for _, path := range config.Templates {
watcher.Watch(path)
}
return ch, nil
}
func watchAll(watcher *fsnotify.Watcher) filepath.WalkFunc {
return func(fn string, fi os.FileInfo, err error) error {
if err != nil {
return nil
}
watcher.Watch(fn)
return nil
}
}
|
Add comments to explain what the script is doing on ingest
|
## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = csv.reader(orig_file, delimiter=",")
with open("/temp/MASTER_CLEANED.csv", "w", newline='') as clean_file:
writer = csv.writer(clean_file)
for orig_record in orig_file_reader:
# some of the data contains trailing spaces/tabs, so we remove those first
new_row = [old_field_data.strip() for old_field_data in orig_record]
# The data has a trailing comma on every single row (including the header row), so remove it as well
new_row_without_trailing_comma = new_row[:-1]
# write out a new CSV, which is then imported into Postgres
writer.writerow(new_row_without_trailing_comma)
|
## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = csv.reader(orig_file, delimiter=",")
with open("/temp/MASTER_CLEANED.csv", "w", newline='') as clean_file:
writer = csv.writer(clean_file)
for orig_record in orig_file_reader:
new_row = [old_field_data.strip() for old_field_data in orig_record]
# The data has a trailing comma on every single row (including the header row), so remove it as well
new_row_without_trailing_comma = new_row[:-1]
writer.writerow(new_row_without_trailing_comma)
|
Fix of the cosinue test for the negative rounding error.
|
<?php
use Litipk\BigNumbers\Decimal as Decimal;
/**
* @group cos
*/
class DecimalCosTest extends PHPUnit_Framework_TestCase
{
public function cosProvider() {
// Some values provided by Mathematica
return array(
array('1', '0.54030230586814', 14),
array('123.123', '-0.82483472946164834', 17),
array('15000000000', '-0.72218064388924347683', 20)
);
}
/**
* @dataProvider cosProvider
*/
public function testSimple($nr, $answer, $digits)
{
$x = Decimal::fromString($nr);
$cosX = $x->cos((int)$digits);
$this->assertTrue(
Decimal::fromString($answer)->equals($cosX),
"The answer must be " . $answer . ", but was " . $cosX
);
}
}
|
<?php
use Litipk\BigNumbers\Decimal as Decimal;
/**
* @group cos
*/
class DecimalCosTest extends PHPUnit_Framework_TestCase
{
public function cosProvider() {
// Some values provided by Mathematica
return array(
array('1', '0.54030230586814', 14),
array('123.123', '-0.82483472946164834', 17),
array('15000000000', '-0.72218064388924347681', 20)
);
}
/**
* @dataProvider cosProvider
*/
public function testSimple($nr, $answer, $digits)
{
$x = Decimal::fromString($nr);
$cosX = $x->cos((int)$digits);
$this->assertTrue(
Decimal::fromString($answer)->equals($cosX),
"The answer must be " . $answer . ", but was " . $cosX
);
}
}
|
Add missing Google Analytics env vars
|
"use strict";
const isCi = require('is-ci');
const jwtSigningKey = process.env.jwtSigningKey ? new Buffer(process.env.jwtSigningKey, 'base64') : '' ;
const dbConfig = {
host: process.env.DB_HOST || '127.0.0.1',
port: process.env.DB_PORT || '5432',
database: process.env.DB_DATABASE || 'postgres',
username: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD,
dialect: process.env.DB_DIALECT || 'postgres',
logging: process.env.DB_LOGGING || false
};
module.exports = {
dbConfig,
host: process.env.HOST || '127.0.0.1',
port: process.env.PORT || 8080,
baseUrl: process.env.baseUrl || 'http://localhost:8080',
jwtSigningKey,
auth0ClientId: process.env.auth0ClientId,
auth0Domain: process.env.auth0Domain,
googleAnalyticsUA: (process.env.NODE_ENV === 'production') ? process.env.GOOGLE_ANALYTICS_UA : '',
ga: {
view_id: process.env.GOOGLE_ANALYTICS_VIEW_ID
}
};
|
"use strict";
const isCi = require('is-ci');
const jwtSigningKey = process.env.jwtSigningKey ? new Buffer(process.env.jwtSigningKey, 'base64') : '' ;
const dbConfig = {
host: process.env.DB_HOST || '127.0.0.1',
port: process.env.DB_PORT || '5432',
database: process.env.DB_DATABASE || 'postgres',
username: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD,
dialect: process.env.DB_DIALECT || 'postgres',
logging: process.env.DB_LOGGING || false
};
module.exports = {
dbConfig,
host: process.env.HOST || '127.0.0.1',
port: process.env.PORT || 8080,
baseUrl: process.env.baseUrl || 'http://localhost:8080',
jwtSigningKey,
auth0ClientId: process.env.auth0ClientId,
auth0Domain: process.env.auth0Domain,
googleAnalyticsUA: (process.env.NODE_ENV === 'production') ? '' : '',
ga: {
view_id: ''
}
};
|
Stop force clearing the dom when gelato is preparing it.
|
var Application = require('application');
module.exports = (function() {
function prepareDOM() {
document.body.appendChild(document.createElement('gelato-application'));
document.body.appendChild(document.createElement('gelato-dialogs'));
document.body.appendChild(document.createElement('gelato-navbars'));
document.body.appendChild(document.createElement('gelato-sidebars'));
}
function start() {
prepareDOM();
window.app = new Application();
window.app.start();
}
if (location.protocol === 'file:') {
$.ajax({
url: 'cordova.js',
dataType: 'script'
}).done(function() {
document.addEventListener('deviceready', start, false);
}).fail(function() {
console.error(new Error('Unable to load cordova.js file.'));
});
} else {
$(document).ready(start);
}
})();
|
var Application = require('application');
module.exports = (function() {
function prepareDOM() {
document.body.innerHTML = '';
document.body.appendChild(document.createElement('gelato-application'));
document.body.appendChild(document.createElement('gelato-dialogs'));
document.body.appendChild(document.createElement('gelato-navbars'));
document.body.appendChild(document.createElement('gelato-sidebars'));
}
function start() {
prepareDOM();
window.app = new Application();
window.app.start();
}
if (location.protocol === 'file:') {
$.ajax({
url: 'cordova.js',
dataType: 'script'
}).done(function() {
document.addEventListener('deviceready', start, false);
}).fail(function() {
console.error(new Error('Unable to load cordova.js file.'));
});
} else {
$(document).ready(start);
}
})();
|
Use standard toObject and fromObject methods
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@64810 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
<?php
/**
* Clip operation attributes
*
* @package api
* @subpackage objects
*/
class KalturaClipAttributes extends KalturaOperationAttributes
{
/**
* Offset in milliseconds
* @var int
*/
public $offset;
/**
* Duration in milliseconds
* @var int
*/
public $duration;
public function toAttributesArray()
{
return array(
'ClipOffset' => $this->offset,
'ClipDuration' => $this->duration,
);
}
private static $map_between_objects = array
(
"offset" ,
"duration"
);
public function getMapBetweenObjects ( )
{
return array_merge ( parent::getMapBetweenObjects() , self::$map_between_objects );
}
public function toObject ( $object_to_fill = null , $props_to_skip = array() )
{
if(is_null($object_to_fill))
$object_to_fill = new kClipAttributes();
return parent::toObject($object_to_fill, $props_to_skip);
}
}
|
<?php
/**
* Clip operation attributes
*
* @package api
* @subpackage objects
*/
class KalturaClipAttributes extends KalturaOperationAttributes
{
/**
* Offset in milliseconds
* @var int
*/
public $offset;
/**
* Duration in milliseconds
* @var int
*/
public $duration;
public function toAttributesArray()
{
return array(
'ClipOffset' => $this->offset,
'ClipDuration' => $this->duration,
);
}
public function toObject ( $object_to_fill = null , $props_to_skip = array() )
{
if(is_null($object_to_fill))
$object_to_fill = new kClipAttributes();
$object_to_fill->setOffset($this->offset);
$object_to_fill->setDuration($this->duration);
return $object_to_fill;
}
}
|
Replace `cls` argument with `self`
Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class.
|
from datetime import datetime, date
from sqlalchemy import Integer, UnicodeText, Float, BigInteger
from sqlalchemy import Boolean, Date, DateTime, Unicode
from sqlalchemy.types import TypeEngine
class Types(object):
"""A holder class for easy access to SQLAlchemy type names."""
integer = Integer
string = Unicode
text = UnicodeText
float = Float
bigint = BigInteger
boolean = Boolean
date = Date
datetime = DateTime
def guess(self, sample):
"""Given a single sample, guess the column type for the field.
If the sample is an instance of an SQLAlchemy type, the type will be
used instead.
"""
if isinstance(sample, TypeEngine):
return sample
if isinstance(sample, bool):
return self.boolean
elif isinstance(sample, int):
return self.bigint
elif isinstance(sample, float):
return self.float
elif isinstance(sample, datetime):
return self.datetime
elif isinstance(sample, date):
return self.date
return self.text
|
from datetime import datetime, date
from sqlalchemy import Integer, UnicodeText, Float, BigInteger
from sqlalchemy import Boolean, Date, DateTime, Unicode
from sqlalchemy.types import TypeEngine
class Types(object):
"""A holder class for easy access to SQLAlchemy type names."""
integer = Integer
string = Unicode
text = UnicodeText
float = Float
bigint = BigInteger
boolean = Boolean
date = Date
datetime = DateTime
def guess(cls, sample):
"""Given a single sample, guess the column type for the field.
If the sample is an instance of an SQLAlchemy type, the type will be
used instead.
"""
if isinstance(sample, TypeEngine):
return sample
if isinstance(sample, bool):
return cls.boolean
elif isinstance(sample, int):
return cls.bigint
elif isinstance(sample, float):
return cls.float
elif isinstance(sample, datetime):
return cls.datetime
elif isinstance(sample, date):
return cls.date
return cls.text
|
Test passes a seqJS.Seq, not String
|
/*global seqJS:true */
(function() {
/*
======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/
Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfequalions)
stop(increment)
start(decrement)
Test equalions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
throws(block, [expected], [message])
*/
module('seqJS.ss');
test('Test ss', function(){
var s = new seqJS.Seq('GGGAAATCC', 'DNA');
equal(seqJS.ss.predict(s), '.(((..)))', 'secondary structure incorrect');
});
}());
|
/*global seqJS:true */
(function() {
/*
======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/
Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfequalions)
stop(increment)
start(decrement)
Test equalions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
throws(block, [expected], [message])
*/
module('seqJS.ss');
test('Test ss', function(){
equal(seqJS.ss.predict('GGGAAATCC'), '.(((..)))', 'secondary structure incorrect');
});
}());
|
Remove PIL and docutils from requirements, easy_thumbnails requires it anyway
|
from distutils.core import setup
from setuptools import setup, find_packages
setup(name = "django-image-cropping",
version = "0.3.0",
description = "A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author = "jonasvp",
author_email = "jvp@jonasundderwolf.de",
url = "http://github.com/jonasundderwolf/django-image-cropping",
#Name the folder where your packages live:
#(If you have other packages (dirs) or modules (py files) then
#put them into the package directory - they will be found
#recursively.)
packages = find_packages(),
include_package_data=True,
install_requires = [
'easy_thumbnails',
],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from distutils.core import setup
from setuptools import setup, find_packages
setup(name = "django-image-cropping",
version = "0.3.0",
description = "A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author = "jonasvp",
author_email = "jvp@jonasundderwolf.de",
url = "http://github.com/jonasundderwolf/django-image-cropping",
#Name the folder where your packages live:
#(If you have other packages (dirs) or modules (py files) then
#put them into the package directory - they will be found
#recursively.)
packages = find_packages(),
include_package_data=True,
install_requires = [
'docutils',
'PIL',
'easy_thumbnails',
],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Use tabs instead of spaces
|
<?php
function backTrace($backtrace)
{
foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if ($args) {
$args .= ', ';
}
if (in_array($bt['function'], array('RawQuery', 'Query', 'FetchResult')) && !$args)
$args .= '"..."';
else
$args .= var_export($a, true);
}
$output .= "<td>{$bt['file']}<td>{$bt['line']}<td><code>";
$output .= htmlspecialchars("{$bt['class']}{$bt['type']}{$bt['function']}($args)");
$output .= "</code><tr class=cell0>";
}
return $output;
}
function var_format($v) // pretty-print var_export
{
return (str_replace(array("\n"," ","array"),
array("<br>"," "," <i>array</i>"),
var_export($v,true))."<br>");
}
|
<?php
function backTrace($backtrace)
{
foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if ($args) {
$args .= ', ';
}
if (in_array($bt['function'], array('RawQuery', 'Query', 'FetchResult')) && !$args)
$args .= '"..."';
else
$args .= var_export($a, true);
}
$output .= "<td>{$bt['file']}<td>{$bt['line']}<td><code>";
$output .= htmlspecialchars("{$bt['class']}{$bt['type']}{$bt['function']}($args)");
$output .= "</code><tr class=cell0>";
}
return $output;
}
function var_format($v) // pretty-print var_export
{
return (str_replace(array("\n"," ","array"),
array("<br>"," "," <i>array</i>"),
var_export($v,true))."<br>");
}
|
Add avatar_url property to User.
|
# coding: utf-8
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from ._base import db
from ..utils.uploadsets import avatars
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50), unique=True)
avatar = db.Column(db.String(200), default='default.png')
password = db.Column(db.String(200))
is_admin = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=datetime.now)
def __setattr__(self, name, value):
# Hash password when set it.
if name == 'password':
value = generate_password_hash(value)
super(User, self).__setattr__(name, value)
def check_password(self, password):
return check_password_hash(self.password, password)
@property
def avatar_url(self):
return avatars.url(self.avatar)
def __repr__(self):
return '<User %s>' % self.name
|
# coding: utf-8
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from ._base import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50), unique=True)
avatar = db.Column(db.String(200))
password = db.Column(db.String(200))
is_admin = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=datetime.now)
def __setattr__(self, name, value):
# Hash password when set it.
if name == 'password':
value = generate_password_hash(value)
super(User, self).__setattr__(name, value)
def check_password(self, password):
return check_password_hash(self.password, password)
def __repr__(self):
return '<User %s>' % self.name
|
Correct static URL in JS
|
function hgvsValidation(element) {
if (element.val().length > 2) {
$('#result_' + element.attr('id')).html('<i>Please wait...</i>');
$.get(window.HGVS_URL, { 'code': element.val() }, function(data) {
result = data['parse_result'];
if (result == true) {
result_text = "<img src='"+ window.STATIC_URL +"images/tick.png'>";
} else {
result_text = "<img src='"+ window.STATIC_URL +"images/cross.png'>";
}
$('#result_' + element.attr('id')).html(result_text);
});
} else {
$('#result_' + element.attr('id')).html('<i>No input to validate</i>');
}
}
|
function hgvsValidation(element) {
if (element.val().length > 2) {
$('#result_' + element.attr('id')).html('<i>Please wait...</i>');
$.get(window.HGVS_URL, { 'code': element.val() }, function(data) {
result = data['parse_result'];
if (result == true) {
result_text = "<img src='"+ window.STATIC_URL +"images/tick.png'>";
} else {
result_text = "<img src='/static/images/cross.png'>";
}
$('#result_' + element.attr('id')).html(result_text);
});
} else {
$('#result_' + element.attr('id')).html('<i>No input to validate</i>');
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.