text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Remove not useful function creator | function formatFunctionName(type) {
let formattedName = '';
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
type.split('_').map((val, i) => {
if (i === 0) {
formattedName += val.toLowerCase();
} else {
formattedName += capitalizeFirstLetter(val.toLowerCase());
}
return true;
});
return formattedName;
}
function generalFactory(type, payloadTranslator) {
return function nomeDaSostituire(data) {
const action = {
type,
};
if (data) {
switch (typeof payloadTranslator) {
case 'function':
action.payload = payloadTranslator(data);
break;
default:
action.payload = data;
break;
}
}
return action;
};
}
module.exports = function actionsCreatorFactory(actionsConfig) {
const funcToExport = {};
actionsConfig.map((config) => {
let type = null;
let payload = null;
if (typeof config === 'string') {
type = config;
} else {
type = config.type;
payload = config.payload;
}
const functionName = formatFunctionName(type);
const customFunction = generalFactory(type, payload);
const customStringFunction = customFunction;
funcToExport[functionName] = customStringFunction;
return true;
});
return funcToExport;
};
| function createDynamicFunction(customAction) {
return Function('action', 'return function (){ return action.apply(this, [...arguments]) };')(customAction);
}
function formatFunctionName(type) {
let formattedName = '';
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
type.split('_').map((val, i) => {
if (i === 0) {
formattedName += val.toLowerCase();
} else {
formattedName += capitalizeFirstLetter(val.toLowerCase());
}
return true;
});
return formattedName;
}
function generalFactory(type, payloadTranslator) {
return function nomeDaSostituire(data) {
const action = {
type,
};
if (data) {
switch (typeof payloadTranslator) {
case 'function':
action.payload = payloadTranslator(data);
break;
default:
action.payload = data;
break;
}
}
return action;
};
}
module.exports = function actionsCreatorFactory(actionsConfig) {
const funcToExport = {};
actionsConfig.map((config) => {
let type = null;
let payload = null;
if (typeof config === 'string') {
type = config;
} else {
type = config.type;
payload = config.payload;
}
const functionName = formatFunctionName(type);
const customFunction = generalFactory(type, payload);
const customStringFunction = createDynamicFunction(customFunction);
funcToExport[functionName] = customStringFunction;
return true;
});
return funcToExport;
};
|
Return just a boolean from find | /**
* @fileoverview Enforce emojis are wrapped in <span> and provide screenreader access.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import emojiRegex from 'emoji-regex';
import { getProp, getLiteralPropValue, elementType } from 'jsx-ast-utils';
import { generateObjSchema } from '../util/schemas';
const errorMessage =
'Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby.';
const schema = generateObjSchema();
module.exports = {
meta: {
docs: {},
schema: [schema],
},
create: context => ({
JSXOpeningElement: (node) => {
const literalChildValue = node.parent.children.find(
child => child.type === 'Literal',
);
if (literalChildValue && emojiRegex().test(literalChildValue.value)) {
const rolePropValue = getLiteralPropValue(getProp(node.attributes, 'role'));
const ariaLabelProp = getProp(node.attributes, 'aria-label');
const arialLabelledByProp = getProp(node.attributes, 'aria-labelledby');
const hasLabel = ariaLabelProp !== undefined || arialLabelledByProp !== undefined;
const isSpan = elementType(node) === 'span';
if (hasLabel === false || rolePropValue !== 'img' || isSpan === false) {
context.report({
node,
message: errorMessage,
});
}
}
},
}),
};
| /**
* @fileoverview Enforce emojis are wrapped in <span> and provide screenreader access.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import emojiRegex from 'emoji-regex';
import { getProp, getLiteralPropValue, elementType } from 'jsx-ast-utils';
import { generateObjSchema } from '../util/schemas';
const errorMessage =
'Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby.';
const schema = generateObjSchema();
module.exports = {
meta: {
docs: {},
schema: [schema],
},
create: context => ({
JSXOpeningElement: (node) => {
const literalChildValue = node.parent.children.find((child) => {
if (child.type === 'Literal') {
return child.value;
}
return false;
});
if (literalChildValue && emojiRegex().test(literalChildValue.value)) {
const rolePropValue = getLiteralPropValue(getProp(node.attributes, 'role'));
const ariaLabelProp = getProp(node.attributes, 'aria-label');
const arialLabelledByProp = getProp(node.attributes, 'aria-labelledby');
const hasLabel = ariaLabelProp !== undefined || arialLabelledByProp !== undefined;
const isSpan = elementType(node) === 'span';
if (hasLabel === false || rolePropValue !== 'img' || isSpan === false) {
context.report({
node,
message: errorMessage,
});
}
}
},
}),
};
|
Add test for solc backward compatibility | package org.ethereum.solidity;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import org.ethereum.solidity.Abi.Entry;
import org.ethereum.solidity.Abi.Entry.Type;
import org.junit.Test;
import java.io.IOException;
public class AbiTest {
@Test
public void simpleTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"payable\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.payable);
assertTrue(onlyFunc.constant);
}
@Test
public void simpleLegacyTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.constant);
}
}
| package org.ethereum.solidity;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import org.ethereum.solidity.Abi.Entry;
import org.ethereum.solidity.Abi.Entry.Type;
import org.junit.Test;
import java.io.IOException;
public class AbiTest {
@Test
public void simpleTest() throws IOException {
String contractAbi = "[{"
+ "\"name\":\"simpleFunction\","
+ "\"constant\":true,"
+ "\"payable\":true,"
+ "\"type\":\"function\","
+ "\"inputs\": [{\"name\":\"_in\", \"type\":\"bytes32\"}],"
+ "\"outputs\":[{\"name\":\"_out\",\"type\":\"bytes32\"}]}]";
Abi abi = Abi.fromJson(contractAbi);
assertEquals(abi.size(), 1);
Entry onlyFunc = abi.get(0);
assertEquals(onlyFunc.type, Type.function);
assertEquals(onlyFunc.inputs.size(), 1);
assertEquals(onlyFunc.outputs.size(), 1);
assertTrue(onlyFunc.payable);
assertTrue(onlyFunc.constant);
}
public static void main(String[] args) throws Exception {
new AbiTest().simpleTest();
}
}
|
Fix an error when no samples were found. | # -*- coding: utf-8 -*-
#
# views.py
# wide-language-index-demo
#
"""
Public facing frontpage.
"""
import json
import random
from flask import (Blueprint, request, render_template, redirect)
from . import forms
from ..index import util
blueprint = Blueprint('public', __name__, static_folder="../static")
@blueprint.route("/", methods=["GET", "POST"])
def home():
language = request.args.get('language')
if language:
return _render_language(language)
form = forms.SearchForm()
return render_template("public/home.html",
form=form,
has_query=False)
def _render_language(language):
index = util.get_index()
if language == 'random':
language = random.choice(list(index.keys()))
return redirect('/?language={0}'.format(language))
records = index.get(language)
inverted_name = util.get_languages().get(language)
record = None
record_json = None
if records:
record = random.choice(records)
record_json = json.dumps(record, indent=2, sort_keys=True)
form = forms.SearchForm(request.args)
return render_template("public/home.html", form=form, record=record,
record_json=record_json,
inverted_name=inverted_name,
has_query=bool(request.args))
| # -*- coding: utf-8 -*-
#
# views.py
# wide-language-index-demo
#
"""
Public facing frontpage.
"""
import json
import random
from flask import (Blueprint, request, render_template, redirect)
from . import forms
from ..index import util
blueprint = Blueprint('public', __name__, static_folder="../static")
@blueprint.route("/", methods=["GET", "POST"])
def home():
language = request.args.get('language')
if language:
return _render_language(language)
form = forms.SearchForm()
return render_template("public/home.html",
form=form,
has_query=False)
def _render_language(language):
index = util.get_index()
if language == 'random':
language = random.choice(list(index.keys()))
return redirect('/?language={0}'.format(language))
records = index.get(language)
inverted_name = util.get_languages().get(language)
if records:
record = random.choice(records)
record_json = json.dumps(record, indent=2, sort_keys=True)
form = forms.SearchForm(request.args)
return render_template("public/home.html", form=form, record=record,
record_json=record_json,
inverted_name=inverted_name,
has_query=bool(request.args))
|
Use a varchar instead of an enum. Enums are not supported in sqlite and on postgresql it requires extra work to use | <?php
namespace atk4\data\tests\smbo;
class SMBOTestCase extends \atk4\data\tests\SQLTestCase
{
public function setUp()
{
parent::setUp();
$queryClass = $this->getProtected($this->db->connection, 'query_class');
$escapeChar = $this->getProtected(new $queryClass, 'escape_char');
$s = new \atk4\data\tests\Structure(['connection' => $this->db->connection]);
$s->setEscapeChar($escapeChar);
$x = clone $s;
$x->table('account')->drop()
->id()
->field('name')
->create();
$x = clone $s;
$x->table('document')->drop()
->id()
->field('reference')
->field('contact_from_id')
->field('contact_to_id')
->field('doc_type')
->field('amount', ['type' => 'decimal(8,2)'])
->create();
$x = clone $s;
$x->table('payment')->drop()
->id()
->field('document_id', ['type' => 'integer'])
->field('account_id', ['type' => 'integer'])
->field('cheque_no')
//->field('misc_payment', ['type' => 'enum(\'N\',\'Y\')'])
->field('misc_payment', ['type' => 'varchar(2)'])
->field('transfer_document_id')
->create();
}
}
| <?php
namespace atk4\data\tests\smbo;
class SMBOTestCase extends \atk4\data\tests\SQLTestCase
{
public function setUp()
{
parent::setUp();
$s = new \atk4\data\tests\Structure(['connection' => $this->db->connection]);
$x = clone $s;
$x->table('account')->drop()
->id()
->field('name')
->create();
$x = clone $s;
$x->table('document')->drop()
->id()
->field('reference')
->field('contact_from_id')
->field('contact_to_id')
->field('doc_type')
->field('amount', ['type' => 'decimal(8,2)'])
->create();
$x = clone $s;
$x->table('payment')->drop()
->id()
->field('document_id', ['type' => 'integer'])
->field('account_id', ['type' => 'integer'])
->field('cheque_no')
->field('misc_payment', ['type' => 'enum("N","Y")'])
->field('transfer_document_id')
->create();
}
}
|
Create destination path if it does no exist and copy file using shutil | import os
import shutil
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[prefix:])
if not os.path.exists(destpath):
os.makedirs(destpath)
print()
print('-'*25)
print('Pages')
for f in files:
src = os.path.join(root, f)
base, ext = os.path.splitext(f)
if ext in ['.md', '.markdown']:
dest = os.path.join(destpath, "%s%s" % (base, '.html'))
self.parse(src, dest)
else:
dest = os.path.join(destpath, f)
shutil.copy(src, dest)
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(destpath, d))
def parse(self, source, destination):
print("Parse Source: %s Destination: %s" % (source, destination))
| import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
src = os.path.join(root, f)
base, ext = os.path.splitext(f)
if ext in ['.md', '.markdown']:
dest = os.path.join(destpath, "%s%s" % (base, '.html'))
self.parse(src, dest)
else:
dest = os.path.join(destpath, f)
self.copy(src, dest)
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(destpath, d))
def parse(self, source, destination):
print("Parse Source: %s Destination: %s" % (source, destination))
def copy(self, source, destination):
print("Copy Source: %s Destination: %s" % (source, destination))
|
Add support for more than one subdomain. | var parseDomain = require("parse-domain");
function getLeadingLeafDomain(subdomain) {
var leafDomains = subdomain.split(".");
return leafDomains[0];
}
function getDomainDataFromHost(host) {
var defaultSubdomain = "www";
var subdomainAliases = {
"local": defaultSubdomain
};
var url = parseDomain(host);
var subdomain = getLeadingLeafDomain(url.subdomain || defaultSubdomain);
var resolvedSubdomain = subdomainAliases[subdomain] || subdomain;
url.subdomain = resolvedSubdomain;
return url;
}
module.exports = function getDomainRoutes(domains, header, cb) {
var host = header.host;
var url = getDomainDataFromHost(host);
var domain = url.domain;
var subdomain = url.subdomain;
var resolveDomain;
if (domains[domain]) {
resolveDomain = domains[domain];
if (typeof resolveDomain !== "function") {
return cb(null, resolveDomain);
}
return resolveDomain(host, function getSubDomainRoutes(err, domainRoutes) {
if (err) {
return cb(err);
}
var resolveSubdomain = (domainRoutes.domains || domainRoutes)[subdomain];
if (typeof resolveSubdomain !== "function") {
return cb(null, resolveSubdomain);
}
return resolveSubdomain(host, cb);
});
}
resolveDomain = domains[subdomain];
if (typeof resolveDomain !== "function") {
return cb(null, resolveDomain);
}
return resolveDomain(host, cb);
};
| var parseDomain = require("parse-domain");
function getDomainDataFromHost(host) {
var defaultSubdomain = "www";
var subdomainAliases = {
"local": defaultSubdomain
};
var url = parseDomain(host);
var subdomain = url.subdomain;
var resolvedSubdomain = subdomainAliases[subdomain] || subdomain || defaultSubdomain;
url.subdomain = resolvedSubdomain;
return url;
}
module.exports = function getDomainRoutes(domains, header, cb) {
var host = header.host;
var url = getDomainDataFromHost(host);
var domain = url.domain;
var subdomain = url.subdomain;
var resolveDomain;
if (domains[domain]) {
resolveDomain = domains[domain];
if (typeof resolveDomain !== "function") {
return cb(null, resolveDomain);
}
return resolveDomain(host, function (err, domainRoutes) {
if (err) {
throw new Error(err);
}
var resolveSubdomain = domainRoutes[subdomain];
if (typeof resolveSubdomain !== "function") {
return cb(null, resolveSubdomain);
}
return resolveSubdomain(host, cb);
});
}
resolveDomain = domains[subdomain];
if (typeof resolveDomain !== "function") {
return cb(null, resolveDomain);
}
return resolveDomain(host, cb);
};
|
Add help text for Roles module. | import discord
import shlex
from modules.botModule import BotModule
class Roles(BotModule):
name = 'Roles'
description = 'Allow for the assignment and removal of roles.'
help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.'
' Executing it when you already have the role assigned will remove you'
' from that role.')
trigger_string = '!role' # String to listen for as trigger
async def parse_command(self, message, client):
server_roles = message.server.roles # Grab a list of all roles as Role objects
server_roles_str = [x.name for x in server_roles] # String-ify it into their names
msg = shlex.split(message.content)
role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is
role_to_assign = message.server.roles[role[0]]
if len(msg) != 1:
try:
if role_to_assign in message.author.roles:
await client.remove_roles(message.author, role_to_assign)
msg = ":ok_hand: Removed you from " + role_to_assign.name + " ."
else:
await client.add_roles(message.author, role_to_assign)
msg = ":ok_hand: Added you to " + role_to_assign.name + " ."
except discord.DiscordException:
msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that."
await client.send_message(message.channel, msg)
else:
pass
| import discord
import shlex
from modules.botModule import BotModule
class Roles(BotModule):
name = 'Roles'
description = 'Allow for the assignment and removal of roles.'
help_text = ''
trigger_string = '!role' # String to listen for as trigger
async def parse_command(self, message, client):
server_roles = message.server.roles # Grab a list of all roles as Role objects
server_roles_str = [x.name for x in server_roles] # String-ify it into their names
msg = shlex.split(message.content)
role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is
role_to_assign = message.server.roles[role[0]]
if len(msg) != 1:
try:
if role_to_assign in message.author.roles:
await client.remove_roles(message.author, role_to_assign)
msg = ":ok_hand: Removed you from " + role_to_assign.name + " ."
else:
await client.add_roles(message.author, role_to_assign)
msg = ":ok_hand: Added you to " + role_to_assign.name + " ."
except discord.DiscordException:
msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that."
await client.send_message(message.channel, msg)
else:
pass
|
Use MockRedis instead of dict to mock redis in unit tests | """Unit tests configuration file."""
import pickle
import numpy as np
import pytest
from sklearn import linear_model, tree, svm
from mockredis import MockRedis
from cf_predict import create_app
def pytest_configure(config):
"""Disable verbose output when running tests."""
terminal = config.pluginmanager.getplugin('terminal')
base = terminal.TerminalReporter
class QuietReporter(base):
"""A py.test reporting that only shows dots when running tests."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.verbosity = 0
self.showlongtestinfo = False
self.showfspath = False
terminal.TerminalReporter = QuietReporter
@pytest.fixture
def app(monkeypatch):
"""Create a Flask test client."""
monkeypatch.setattr("cf_predict.resources.get_db", models)
app = create_app("unit_testing")
return app
def models():
"""Create some sample machine learning models."""
rng = np.random.RandomState(42)
X = rng.random_sample((20, 5))
y = rng.random_sample(20)
lm = linear_model.LinearRegression()
dt = tree.DecisionTreeRegressor()
svr = svm.SVR()
lm.fit(X, y)
dt.fit(X, y)
svr.fit(X, y)
r = MockRedis()
r.set("1.0.0", pickle.dumps(lm))
r.set("1.1.0", pickle.dumps(dt))
r.set("1.2.0", pickle.dumps(svr))
return r
| """Unit tests configuration file."""
import pickle
import numpy as np
import pytest
from sklearn import linear_model, tree, svm
from cf_predict import create_app
def pytest_configure(config):
"""Disable verbose output when running tests."""
terminal = config.pluginmanager.getplugin('terminal')
base = terminal.TerminalReporter
class QuietReporter(base):
"""A py.test reporting that only shows dots when running tests."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.verbosity = 0
self.showlongtestinfo = False
self.showfspath = False
terminal.TerminalReporter = QuietReporter
@pytest.fixture
def app(monkeypatch):
"""Create a Flask test client."""
monkeypatch.setattr("cf_predict.resources.get_db", models)
app = create_app("unit_testing")
return app
def models():
"""Create some sample machine learning models."""
X = np.random.random_sample((20, 5))
y = np.random.random_sample(20)
lm = linear_model.LinearRegression()
dt = tree.DecisionTreeRegressor()
svr = svm.SVR()
lm.fit(X, y)
dt.fit(X, y)
svr.fit(X, y)
return {"1.0.0": pickle.dumps(lm),
"1.1.0": pickle.dumps(dt),
"1.2.0": pickle.dumps(svr)}
|
Fix session event variable import. | # -*- test-case-name: vumi.middleware.tests.test_session_length -*-
import time
from twisted.internet.defer import inlineCallbacks, returnValue
from vumi.message import TransportUserMessage
from vumi.middleware.base import BaseMiddleware
from vumi.persist.txredis_manager import TxRedisManager
class SessionLengthMiddleware(BaseMiddleware):
""" Middleware for storing the session length in the message.
Session length is stored if the end of the session is reached.
Configuration option:
:param dict redis:
Redis configuration parameters.
"""
SESSION_NEW, SESSION_CLOSE = (
TransportUserMessage.SESSION_NEW, TransportUserMessage.SESSION_CLOSE)
@inlineCallbacks
def setup_middleware(self):
r_config = self.config.get('redis_manager', {})
self.redis = yield TxRedisManager.from_config(r_config)
@inlineCallbacks
def teardown_middleware(self):
yield self.redis.close_manager()
def handle_inbound(self, message, connector_name):
redis_key = '%s:%s' % (message.get('from_addr'), 'session_created')
if message.get('event_type') == self.SESSION_NEW:
yield self.redis.set(redis_key, str(time.time()))
elif message.get('event_type') == self.SESSION_CLOSE:
created_time = yield self.redis.get(redis_key)
if created_time:
created_time = float(created_time)
time_diff = time.time() - created_time
message['session_length'] = time_diff
yield self.redis.delete(redis_key)
returnValue(message)
| # -*- test-case-name: vumi.middleware.tests.test_session_length -*-
import time
from twisted.internet.defer import inlineCallbacks, returnValue
from vumi.message.TransportUserMessage import SESSION_NEW, SESSION_CLOSE
from vumi.middleware.base import BaseMiddleware
from vumi.persist.txredis_manager import TxRedisManager
class SessionLengthMiddleware(BaseMiddleware):
""" Middleware for storing the session length in the message.
Session length is stored if the end of the session is reached.
Configuration option:
:param dict redis:
Redis configuration parameters.
"""
@inlineCallbacks
def setup_middleware(self):
r_config = self.config.get('redis_manager', {})
self.redis = yield TxRedisManager.from_config(r_config)
@inlineCallbacks
def teardown_middleware(self):
yield self.redis.close_manager()
def handle_inbound(self, message, connector_name):
redis_key = '%s:%s' % (message.get('from_addr'), 'session_created')
if message.get('event_type') == SESSION_NEW:
yield self.redis.set(redis_key, str(time.time()))
elif message.get('event_type') == SESSION_CLOSE:
created_time = yield self.redis.get(redis_key)
if created_time:
created_time = float(created_time)
time_diff = time.time() - created_time
message['session_length'] = time_diff
yield self.redis.delete(redis_key)
returnValue(message)
|
Make swagger use symetric with recess | 'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('swagger', 'Generate Source from Swagger files', function(){
var fs = require('fs');
var request = require('request');
var done = this.async();
var options = this.options();
var dest = options.dest;
var count = options.apis.length;
options.apis.forEach(function(api, index){
var swagger = fs.readFileSync(api.swagger);
request({
uri: 'http://secxbrl-beta.xbrl.io/angular.jq',
qs: { module: api.module, service: api.service, 'new-module': api.newModule },
headers: { 'Content-Type': 'text/json; utf-8' },
body: swagger
}, function(error, response, body){
if(response.statusCode !== 200) {
grunt.fail.fatal("Sever replied with: " + response.statusCode);
}
fs.writeFileSync(dest + '/' + api.service + '.js', body);
grunt.log.writeln(dest + '/' + api.service + '.js written (' + api.module + '.' + api.service + ')');
count--;
if(count === 0) {
done();
}
});
});
});
};
| 'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('swagger', 'Generate Source from Swagger files', function(){
var fs = require('fs');
var request = require('request');
var done = this.async();
var options = this.options();
var dest = options.dest;
var count = options.apis.length;
options.apis.forEach(function(api, index){
var swagger = fs.readFileSync(api.swagger);
request({
uri: 'http://secxbrl-beta.xbrl.io/angular.jq',
qs: { module: api.module, service: api.service, 'new-module': api.newModule },
headers: { 'Content-Type': 'text/json; utf-8' },
body: swagger
}, function(error, response, body){
if(response.statusCode !== 200) {
grunt.fail.fatal("Sever replied with: " + resposne.statusCode);
}
fs.writeFileSync(dest + '/' + api.service + '.js', body);
grunt.log.writeln(dest + '/' + api.service + '.js written (' + api.module + '.' + api.service + ')');
count--;
if(count === 0) {
done();
}
});
});
});
};
|
Fix for HTTP method exception. | @extends('caravel::master')
@inject('form', 'adamwathan.form')
@inject('bootForm', 'bootform')
@section('container')
<div class="row">
<div class="col-md-12">
{!! $bootForm->open()->action($action)->addClass('caravel-form') !!}
@if (isset($model->id))
{!! $bootForm->bind($model) !!}
{!! $bootForm->hidden('_method')->value('PUT') !!}
@endif
@foreach ($fields as $field)
@include('caravel::fields.' . $field->type, ['field' => $field])
@endforeach
{!! $bootForm->submit('Save')->addClass('btn-primary m-t') !!}
{!! $bootForm->close() !!}
</div>
</div>
{{-- <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.10/vue.min.js"></script>
<script>
new Vue({
el: '#caravel-list-resource',
ready: function() {
console.log('list loaded');
}
});
</script> --}}
@endsection
| @extends('caravel::master')
@inject('form', 'adamwathan.form')
@inject('bootForm', 'bootform')
@section('container')
<div class="row">
<div class="col-md-12">
{!! $bootForm->open()->action($action)->addClass('caravel-form') !!}
@if (isset($model))
{!! $bootForm->bind($model) !!}
{!! $bootForm->hidden('_method')->value('PUT') !!}
@endif
@foreach ($fields as $field)
@include('caravel::fields.' . $field->type, ['field' => $field])
@endforeach
{!! $bootForm->submit('Save')->addClass('btn-primary m-t') !!}
{!! $bootForm->close() !!}
</div>
</div>
{{-- <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.10/vue.min.js"></script>
<script>
new Vue({
el: '#caravel-list-resource',
ready: function() {
console.log('list loaded');
}
});
</script> --}}
@endsection
|
Move away from using the with statement for 2.4 support | # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.log = logging.getLogger('diamond')
# Initialize Data
self.config = config
# Initialize Lock
self.lock = threading.Condition(threading.Lock())
def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
try:
self.log.debug("Running Handler %s locked" % (self))
self.lock.acquire()
self.process(metric)
self.lock.release()
except Exception:
self.log.error(traceback.format_exc())
finally:
self.lock.release()
self.log.debug("Unlocked Handler %s" % (self))
def process(self, metric):
"""
Process a metric
Should be overridden in subclasses
"""
raise NotImplementedError
def flush(self):
"""
Flush metrics
Optional: Should be overridden in subclasses
"""
pass
| # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.log = logging.getLogger('diamond')
# Initialize Data
self.config = config
# Initialize Lock
self.lock = threading.Condition(threading.Lock())
def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
try:
self.log.debug("Running Handler %s locked" % (self))
with self.lock:
self.process(metric)
except Exception:
self.log.error(traceback.format_exc())
finally:
self.log.debug("Unlocked Handler %s" % (self))
def process(self, metric):
"""
Process a metric
Should be overridden in subclasses
"""
raise NotImplementedError
def flush(self):
"""
Flush metrics
Optional: Should be overridden in subclasses
"""
pass
|
Use "Custom" as default recipient label | Ext.define('SlateAdmin.model.person.progress.NoteRecipient', {
extend: 'Ext.data.Model',
groupField: 'RelationshipGroup',
fields: [
{
name: 'PersonID',
type: 'integer'
},
{
name: 'FullName',
type: 'string'
},
{
name: 'Email',
type: 'string',
allowNull: true
},
{
name: 'Label',
type: 'string',
convert: function (v) {
return v || 'Custom';
}
},
{
name: 'RelationshipGroup',
convert: function (v) {
return v || 'Other';
}
},
// virtual fields
{
name: 'selected',
type: 'boolean',
convert: function (v, record) {
var selected = !Ext.isEmpty(record.get('Status'));
return selected;
}
}
],
proxy: {
type: 'slaterecords',
startParam: null,
limitParam: null,
api: {
read: '/notes/progress/recipients',
update: '/notes/save',
create: '/notes/save',
destory: '/notes/save'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json',
rootProperty: 'data',
writeAllFields: false,
allowSingle: false
}
}
});
| Ext.define('SlateAdmin.model.person.progress.NoteRecipient', {
extend: 'Ext.data.Model',
groupField: 'RelationshipGroup',
fields: [
{
name: 'PersonID',
type: 'integer'
},
{
name: 'FullName',
type: 'string'
},
{
name: 'Email',
type: 'string',
allowNull: true
},
{
name: 'Label',
type: 'string',
allowNull: true
},
{
name: 'RelationshipGroup',
convert: function (v) {
return v || 'Other';
}
},
// virtual fields
{
name: 'selected',
type: 'boolean',
convert: function (v, record) {
var selected = !Ext.isEmpty(record.get('Status'));
return selected;
}
}
],
proxy: {
type: 'slaterecords',
startParam: null,
limitParam: null,
api: {
read: '/notes/progress/recipients',
update: '/notes/save',
create: '/notes/save',
destory: '/notes/save'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json',
rootProperty: 'data',
writeAllFields: false,
allowSingle: false
}
}
});
|
Update parser unit tests according to new comment block indent system | <?php
namespace Phug\Test\Parser\TokenHandler;
use Phug\Lexer;
use Phug\Lexer\Token\TagToken;
use Phug\Parser\State;
use Phug\Parser\TokenHandler\CommentTokenHandler;
use Phug\Test\AbstractParserTest;
/**
* @coversDefaultClass Phug\Parser\TokenHandler\CommentTokenHandler
*/
class CommentTokenHandlerTest extends AbstractParserTest
{
/**
* @covers ::<public>
*/
public function testHandleToken()
{
$this->assertNodes('// foo', [
'[DocumentNode]',
' [CommentNode]',
' [TextNode]',
]);
$this->assertNodes("//-\n foo", [
'[DocumentNode]',
' [CommentNode]',
' [TextNode]',
]);
$documentNodes = $this->parser->parse('// foo')->getChildren();
self::assertSame(" foo\n", $documentNodes[0]->getChildren()[0]->getValue());
$documentNodes = $this->parser->parse("//-\n foo")->getChildren();
self::assertSame("\n foo\n", $documentNodes[0]->getChildren()[0]->getValue());
}
/**
* @covers ::<public>
* @expectedException \RuntimeException
* @expectedExceptionMessage You can only pass comment tokens to this token handler
*/
public function testHandleTokenTokenException()
{
$lexer = new Lexer();
$state = new State($lexer->lex(''));
$handler = new CommentTokenHandler();
$handler->handleToken(new TagToken(), $state);
}
}
| <?php
namespace Phug\Test\Parser\TokenHandler;
use Phug\Lexer;
use Phug\Lexer\Token\TagToken;
use Phug\Parser\State;
use Phug\Parser\TokenHandler\CommentTokenHandler;
use Phug\Test\AbstractParserTest;
/**
* @coversDefaultClass Phug\Parser\TokenHandler\CommentTokenHandler
*/
class CommentTokenHandlerTest extends AbstractParserTest
{
/**
* @covers ::<public>
*/
public function testHandleToken()
{
$this->assertNodes('// foo', [
'[DocumentNode]',
' [CommentNode]',
' [TextNode]',
]);
$this->assertNodes("//-\n foo", [
'[DocumentNode]',
' [CommentNode]',
' [TextNode]',
]);
$documentNodes = $this->parser->parse('// foo')->getChildren();
self::assertSame('foo', $documentNodes[0]->getChildren()[0]->getValue());
$documentNodes = $this->parser->parse("//-\n foo")->getChildren();
self::assertSame("foo\n", $documentNodes[0]->getChildren()[0]->getValue());
}
/**
* @covers ::<public>
* @expectedException \RuntimeException
* @expectedExceptionMessage You can only pass comment tokens to this token handler
*/
public function testHandleTokenTokenException()
{
$lexer = new Lexer();
$state = new State($lexer->lex(''));
$handler = new CommentTokenHandler();
$handler->handleToken(new TagToken(), $state);
}
}
|
Fix incorrect function config call | <?php
namespace Soy\Codeception;
trait ConfigTrait
{
/**
* @var Config
*/
protected $config;
/**
* @return string
*/
public function getBinary()
{
return $this->config->getBinary();
}
/**
* @param string $binary
* @return $this
*/
public function setBinary($binary)
{
$this->config->setBinary($binary);
return $this;
}
/**
* @return string
*/
public function getConfigDirectory()
{
return $this->config->getConfigDirectory();
}
/**
* @param string $configDirectory
* @return $this
*/
public function setConfigDirectory($configDirectory)
{
$this->config->setConfigDirectory($configDirectory);
return $this;
}
/**
* @return bool
*/
public function isInteractionEnabled()
{
return $this->config->isInteractionEnabled();
}
/**
* @return $this
*/
public function enableInteraction()
{
$this->config->enableInteraction();
return $this;
}
/**
* @return $this
*/
public function disableInteraction()
{
$this->config->disableInteraction();
return $this;
}
}
| <?php
namespace Soy\Codeception;
trait ConfigTrait
{
/**
* @var Config
*/
protected $config;
/**
* @return string
*/
public function getBinary()
{
return $this->config->getBinary();
}
/**
* @param string $binary
* @return $this
*/
public function setBinary($binary)
{
$this->config->setBinary($binary);
return $this;
}
/**
* @return string
*/
public function getConfigDirectory()
{
return $this->getConfigDirectory();
}
/**
* @param string $configDirectory
* @return $this
*/
public function setConfigDirectory($configDirectory)
{
$this->setConfigDirectory($configDirectory);
return $this;
}
/**
* @return bool
*/
public function isInteractionEnabled()
{
return $this->config->isInteractionEnabled();
}
/**
* @return $this
*/
public function enableInteraction()
{
$this->config->enableInteraction();
return $this;
}
/**
* @return $this
*/
public function disableInteraction()
{
$this->config->disableInteraction();
return $this;
}
}
|
Allow a type to have - in it's name which is not in spec but required for backward compatability. | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.StopCharTester;
import java.util.BitSet;
/**
* Created by peter on 16/08/15.
*/
enum TextStopCharTesters implements StopCharTester {
END_OF_TYPE {
BitSet EOW = new BitSet();
{
for (int i = 0; i < 127; i++)
if (!Character.isJavaIdentifierPart(i))
EOW.set(i);
EOW.clear('['); // not in spec
EOW.clear(']'); // not in spec
EOW.clear('-'); // not in spec
EOW.clear('!');
EOW.clear('.');
EOW.clear('$');
}
@Override
public boolean isStopChar(int ch) {
return EOW.get(ch);
}
}
}
| /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.StopCharTester;
import java.util.BitSet;
/**
* Created by peter on 16/08/15.
*/
enum TextStopCharTesters implements StopCharTester {
END_OF_TYPE {
BitSet EOW = new BitSet();
{
for (int i = 0; i < 127; i++)
if (!Character.isJavaIdentifierPart(i))
EOW.set(i);
EOW.clear('['); // not in spec
EOW.clear(']'); // not in spec
EOW.clear('!');
EOW.clear('.');
EOW.clear('$');
}
@Override
public boolean isStopChar(int ch) {
return EOW.get(ch);
}
}
}
|
Use default arguments removed by mypy | from typing import Any
from flask import Flask
from relayer import Relayer
class FlaskRelayer(object):
def __init__(self, app: Flask = None, logging_topic: str = None, kafka_hosts: str = None, **kwargs: str) -> None:
if app:
self.init_app(
app,
logging_topic,
kafka_hosts=kafka_hosts,
**kwargs,
)
def init_app(self, app: Flask, logging_topic: str, kafka_hosts: str = None, **kwargs: str) -> None:
kafka_hosts = kafka_hosts or app.config.get('KAFKA_HOSTS')
self.event_relayer = Relayer(
logging_topic,
kafka_hosts=kafka_hosts,
**kwargs,
)
def emit(self, *args: str, **kwargs: str) -> None:
self.event_relayer.emit(*args, **kwargs)
def emit_raw(self, *args: Any, **kwargs: Any) -> None:
self.event_relayer.emit_raw(*args, **kwargs)
def log(self, *args: str, **kwargs: str) -> None:
self.event_relayer.log(*args, **kwargs)
def flush(self, *args: str, **kwargs: str) -> None:
self.event_relayer.flush()
| from typing import Any
from flask import Flask
from relayer import Relayer
class FlaskRelayer(object):
def __init__(self, app: Flask, logging_topic: str, kafka_hosts: str = None, **kwargs: str) -> None:
if app:
self.init_app(
app,
logging_topic,
kafka_hosts=kafka_hosts,
**kwargs,
)
def init_app(self, app: Flask, logging_topic: str, kafka_hosts: str = None, **kwargs: str) -> None:
kafka_hosts = kafka_hosts or app.config.get('KAFKA_HOSTS')
self.event_relayer = Relayer(
logging_topic,
kafka_hosts=kafka_hosts,
**kwargs,
)
def emit(self, *args: str, **kwargs: str) -> None:
self.event_relayer.emit(*args, **kwargs)
def emit_raw(self, *args: Any, **kwargs: Any) -> None:
self.event_relayer.emit_raw(*args, **kwargs)
def log(self, *args: str, **kwargs: str) -> None:
self.event_relayer.log(*args, **kwargs)
def flush(self, *args: str, **kwargs: str) -> None:
self.event_relayer.flush()
|
Use imported constants in middleware | import { _SUCCESS, _ERROR } from 'constants'
const pendingIds = {} // requestIDs to timeoutIDs
let nextRequestID = 0
export default function createSocketMiddleware(socket, prefix) {
return ({ dispatch }) => {
// Wire socket.io to dispatch actions sent by the server.
socket.on('action', dispatch)
return next => action => {
const { type, meta, payload } = action
// only apply to socket.io requests
if (!type || type.indexOf(prefix) !== 0) {
return next(action)
}
const requestID = nextRequestID++
// fire request action
next(action)
// error action if socket.io callback timeout
if (meta && meta.requireAck !== false) {
pendingIds[requestID] = setTimeout(() => {
next({
type: type + _ERROR,
meta: {
error: `No response from server; check network connection (on action ${type})`,
}
})
}, 2000)
}
// emit with callback method (3rd arg) that is
// called using ctx.acknowledge(action) on the server
socket.emit('action', action, responseAction => {
// cancel dead man's timer
clearTimeout(pendingIds[requestID])
// action should typically have type *_SUCCESS or *_ERROR
return next(responseAction)
})
}
}
}
| const _SUCCESS = '_SUCCESS'
const _ERROR = '_ERROR'
const pendingIds = {} // requestIDs to timeoutIDs
let nextRequestID = 0
export default function createSocketMiddleware(socket, prefix) {
return ({ dispatch }) => {
// Wire socket.io to dispatch actions sent by the server.
socket.on('action', dispatch)
return next => action => {
const { type, meta, payload } = action
// only apply to socket.io requests
if (!type || type.indexOf(prefix) !== 0) {
return next(action)
}
const requestID = nextRequestID++
// fire request action
next(action)
// error action if socket.io callback timeout
if (meta && meta.requireAck !== false) {
pendingIds[requestID] = setTimeout(() => {
next({
type: type + _ERROR,
meta: {
error: `No response from server; check network connection (on action ${type})`,
}
})
}, 2000)
}
// emit with callback method (3rd arg) that is
// called using ctx.acknowledge(action) on the server
socket.emit('action', action, responseAction => {
// cancel dead man's timer
clearTimeout(pendingIds[requestID])
// action should typically have type *_SUCCESS or *_ERROR
return next(responseAction)
})
}
}
}
|
Add skimage to install_requires list | #!/usr/bin/env python3
import os
import sys
import OpenPNM
sys.path.append(os.getcwd())
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'OpenPNM',
description = 'A framework for conducting pore network modeling simulations of multiphase transport in porous materials.',
version = OpenPNM.__version__,
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Physics'
],
packages = [
'OpenPNM',
'OpenPNM.Base',
'OpenPNM.Network',
'OpenPNM.Network.models',
'OpenPNM.Geometry',
'OpenPNM.Geometry.models',
'OpenPNM.Phases',
'OpenPNM.Phases.models',
'OpenPNM.Physics',
'OpenPNM.Physics.models',
'OpenPNM.Utilities',
'OpenPNM.Algorithms',
'OpenPNM.Postprocessing'
],
install_requires = [
'numpy',
'scipy>=0.14.0',
'matplotlib',
'skimage'
],
author = 'OpenPNM Team',
author_email = '[email protected]',
download_url = 'https://github.com/pmeal/OpenPNM/',
url = 'https://github.com/pmeal/OpenPNM'
)
| #!/usr/bin/env python3
import os
import sys
import OpenPNM
sys.path.append(os.getcwd())
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'OpenPNM',
description = 'A framework for conducting pore network modeling simulations of multiphase transport in porous materials.',
version = OpenPNM.__version__,
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Physics'
],
packages = [
'OpenPNM',
'OpenPNM.Base',
'OpenPNM.Network',
'OpenPNM.Network.models',
'OpenPNM.Geometry',
'OpenPNM.Geometry.models',
'OpenPNM.Phases',
'OpenPNM.Phases.models',
'OpenPNM.Physics',
'OpenPNM.Physics.models',
'OpenPNM.Utilities',
'OpenPNM.Algorithms',
'OpenPNM.Postprocessing'
],
install_requires = [
'numpy',
'scipy>=0.14.0',
'matplotlib'
],
author = 'OpenPNM Team',
author_email = '[email protected]',
download_url = 'https://github.com/pmeal/OpenPNM/',
url = 'https://github.com/pmeal/OpenPNM'
)
|
Fix bug with older man | import Entity, { printMessage, action, time, state } from "Entity";
import { isInInventory, removeItem } from "inventory";
export class OlderMan extends Entity {
name() {
return 'eldery man';
}
actions() {
return [
action(
"Give granola bar.", () => {
if (state.doom.started && state.doom.progress === 50) {
state.doom.progress += 10; // Progress: 60
printMessage(`
The eldery man won't take the granola bar. His eyes fixated on
your arm.
`);
printMessage(`
As you turn away, you hear a strange noise coming from the back
of the restaurant.
`);
} else {
removeItem("granolaBar");
state.olderManFed = true;
printMessage("The eldery man takes the granola bar and smiles.");
}
state.currentTime.add(15, 'minutes');
},
() => {
if (state.doom.started) {
return state.doom.progress === 50;
} else {
return isInInventory("granolaBar");
}
}
)
];
}
}
export default new OlderMan();
| import Entity, { printMessage, action, time, state } from "Entity";
import { isInInventory, removeItem } from "inventory";
export class OlderMan extends Entity {
name() {
return 'eldery man';
}
actions() {
return [
action(
"Give granola bar.", () => {
if (state.doom.started && state.doom.progress === 50) {
state.doom.progress += 10; // Progress: 60
printMessage(`
The eldery man won't take the granola bar. His eyes fixated on
your arm.
`);
printMessage(`
As you turn away, you hear a strange noise coming from the back
of the restaurant.
`);
} else {
removeItem("granolaBar");
state.customers.olderManFed = true;
printMessage("The eldery man takes the granola bar and smiles.");
}
state.currentTime.add(15, 'minutes');
},
() => {
if (state.doom.started) {
return state.doom.progress === 50;
} else {
return isInInventory("granolaBar");
}
}
)
];
}
}
export default new OlderMan();
|
Use var = function syntax | import { select, local } from "d3-selection";
var myLocal = local(),
noop = function (){};
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
myCreate = function (){
var my = myLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
create(my.selection, function setState(state){
Object.assign(my.state, state);
my.render();
});
my.render = function (){
render(my.selection, my.props, my.state);
};
},
myRender = function (props){
var my = myLocal.get(this);
my.props = props;
my.render();
},
myDestroy = function (props){
destroy(myLocal.get(this).state);
},
selector = className ? "." + className : tagName,
component = function (selection, props){
var components = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]);
components
.enter().append(tagName)
.attr("class", className)
.each(myCreate)
.merge(components)
.each(myRender);
components
.exit()
.each(myDestroy)
.remove();
};
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
| import { select, local } from "d3-selection";
var myLocal = local(),
noop = function (){};
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
selector = className ? "." + className : tagName;
function myCreate(){
var my = myLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
create(my.selection, function setState(state){
Object.assign(my.state, state);
my.render();
});
my.render = function (){
render(my.selection, my.props, my.state);
};
}
function myRender(props){
var my = myLocal.get(this);
my.props = props;
my.render();
}
function myDestroy(props){
destroy(myLocal.get(this).state);
}
function component(selection, props){
var components = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]);
components
.enter().append(tagName)
.attr("class", className)
.each(myCreate)
.merge(components)
.each(myRender);
components
.exit()
.each(myDestroy)
.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
|
Use alt naming convention instead | from django.test import TestCase
from django.conf import settings
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
class PdfTests(StaticLiveServerTestCase):
"""
Open a browser
Make API call at url /report/<str:property_id>/pdf
Check PDF in page title
Check PDF images are correct size
"""
@classmethod
def setUpClass(self):
super().setUpClass()
self.selenium = webdriver.firefox.webdriver.WebDriver()
self.selenium.implicitly_wait(10)
@classmethod
def tearDownClass(self):
self.selenium.quit()
super().tearDownClass()
def test_cover_map_img(self):
property_id = 'Demo%7C583966%7C862934'
# New URL
self.selenium.get("http://localhost:8000/report/%s/%s/map_alt" % (property_id, 'property'))
# return img
# check dimensions
# self.assert()
def test_create_pdf(self):
property_id = 'Demo%7C583966%7C862934'
self.selenium.get("http://localhost:8000/report/%s/pdf" % property_id)
self.assertIn('pdf', self.selenium.title)
| from django.test import TestCase
from django.conf import settings
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
class PdfTests(StaticLiveServerTestCase):
"""
Open a browser
Make API call at url /report/<str:property_id>/pdf
Check PDF in page title
Check PDF images are correct size
"""
@classmethod
def setUpClass(self):
super().setUpClass()
self.selenium = webdriver.firefox.webdriver.WebDriver()
self.selenium.implicitly_wait(10)
@classmethod
def tearDownClass(self):
self.selenium.quit()
super().tearDownClass()
def test_cover_map_img(self):
property_id = 'Demo%7C583966%7C862934'
# New URL
self.selenium.get("http://localhost:8000/report/%s/%s/map_509x722" % (property_id, 'property'))
# return img
# check dimensions
# self.assert()
def test_create_pdf(self):
property_id = 'Demo%7C583966%7C862934'
self.selenium.get("http://localhost:8000/report/%s/pdf" % property_id)
self.assertIn('pdf', self.selenium.title)
|
Create initial counts outside the test class | import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
def create_initial_counts(extra=()):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
initial_counts = initial_counts + extra
for count in initial_counts:
CachedCount(**count).save()
class CachedCountTechCase(TestCase):
def setUp(self):
create_initial_counts()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
| import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
class CachedCountTechCase(TestCase):
def setUp(self):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
for count in initial_counts:
CachedCount(**count).save()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
|
Remove per patch version classifiers | #!/usr/bin/env python
from setuptools import setup
from setuptools import find_packages
import re
def find_version():
return re.search(r"^__version__ = '(.*)'$",
open('cantools/version.py', 'r').read(),
re.MULTILINE).group(1)
setup(name='cantools',
version=find_version(),
description='CAN BUS tools.',
long_description=open('README.rst', 'r').read(),
author='Erik Moqvist',
author_email='[email protected]',
license='MIT',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
],
keywords=['can', 'can bus', 'dbc', 'kcd', 'automotive'],
url='https://github.com/eerimoq/cantools',
packages=find_packages(exclude=['tests']),
python_requires='>=3.6',
install_requires=[
'bitstruct>=6.0.0',
'python-can>=2.2.0',
'textparser>=0.21.1',
'diskcache',
'argparse_addons',
],
test_suite="tests",
entry_points = {
'console_scripts': ['cantools=cantools.__init__:_main']
})
| #!/usr/bin/env python
from setuptools import setup
from setuptools import find_packages
import re
def find_version():
return re.search(r"^__version__ = '(.*)'$",
open('cantools/version.py', 'r').read(),
re.MULTILINE).group(1)
setup(name='cantools',
version=find_version(),
description='CAN BUS tools.',
long_description=open('README.rst', 'r').read(),
author='Erik Moqvist',
author_email='[email protected]',
license='MIT',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
keywords=['can', 'can bus', 'dbc', 'kcd', 'automotive'],
url='https://github.com/eerimoq/cantools',
packages=find_packages(exclude=['tests']),
python_requires='>=3.6',
install_requires=[
'bitstruct>=6.0.0',
'python-can>=2.2.0',
'textparser>=0.21.1',
'diskcache',
'argparse_addons',
],
test_suite="tests",
entry_points = {
'console_scripts': ['cantools=cantools.__init__:_main']
})
|
Add `${args}` marker to cmd | from SublimeLinter.lint import Linter, util
class CSSLint(Linter):
cmd = 'csslint --format=compact ${args} ${temp_file}'
regex = r'''(?xi)
^.+:\s* # filename
# csslint emits errors that pertain to the code as a whole,
# in which case there is no line/col information, so that
# part is optional.
(?:line\ (?P<line>\d+),\ col\ (?P<col>\d+),\ )?
(?:(?P<error>error)|(?P<warning>warning))\ -\ (?P<message>.*)
'''
word_re = r'^([#\.]?[-\w]+)'
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'css'
defaults = {
'selector': 'source.css - meta.attribute-with-value',
'--errors=,': '',
'--warnings=,': '',
'--ignore=,': ''
}
def split_match(self, match):
"""
Extract and return values from match.
We override this method so that general errors that do not have
a line number can be placed at the beginning of the code.
"""
match, line, col, error, warning, message, near = super().split_match(match)
if line is None and message:
line = 0
col = 0
return match, line, col, error, warning, message, near
| from SublimeLinter.lint import Linter, util
class CSSLint(Linter):
cmd = 'csslint --format=compact ${temp_file}'
regex = r'''(?xi)
^.+:\s* # filename
# csslint emits errors that pertain to the code as a whole,
# in which case there is no line/col information, so that
# part is optional.
(?:line\ (?P<line>\d+),\ col\ (?P<col>\d+),\ )?
(?:(?P<error>error)|(?P<warning>warning))\ -\ (?P<message>.*)
'''
word_re = r'^([#\.]?[-\w]+)'
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'css'
defaults = {
'selector': 'source.css - meta.attribute-with-value',
'--errors=,': '',
'--warnings=,': '',
'--ignore=,': ''
}
def split_match(self, match):
"""
Extract and return values from match.
We override this method so that general errors that do not have
a line number can be placed at the beginning of the code.
"""
match, line, col, error, warning, message, near = super().split_match(match)
if line is None and message:
line = 0
col = 0
return match, line, col, error, warning, message, near
|
Switch props to data, as they aren't passed in | Vue.component('spark-kiosk-notify', {
props: [
],
data: {
'notifications': []
'users': []
'createNotification': {
"user_id": null
}
}
ready(){
this.getNotifications();
this.getUsers();
},
methods: {
/**
* Get all of the announcements.
*/
getNotifications: function(){
this.$http.get('/skn/notifications')
.then(response => {
this.notifications = response.data;
});
},
/**
* Get all of the users.
*/
getUsers: function(){
this.$http.get('/skn/users')
.then(response => {
this.users = response.data;
});
},
/**
* Create Notification.
*/
createNotification: function(){
this.$http.get('/skn/notifications/create', this.createNotification)
.then(response => {
this.createNotification = {};
this.getNotifications();
});
}
}
});
| Vue.component('spark-kiosk-notify', {
props: [
'notifications',
'users',
'createNotification'
],
ready(){
this.getNotifications();
this.getUsers();
},
methods: {
/**
* Get all of the announcements.
*/
getNotifications: function(){
this.$http.get('/skn/notifications')
.then(response => {
this.notifications = response.data;
});
},
/**
* Get all of the users.
*/
getUsers: function(){
this.$http.get('/skn/users')
.then(response => {
this.users = response.data;
});
},
/**
* Create Notification.
*/
createNotification: function(){
this.$http.get('/skn/notifications/create', this.createNotification)
.then(response => {
this.createNotification = {};
this.getNotifications();
});
}
}
});
|
Remove notification block on log out | app.directive('pbNotifications', ['Restangular', 'AuthService', 'config', function(Restangular, AuthService, config) {
return {
restrict: 'E',
templateUrl: config.partialsDir + '/broadcast_block.html',
link: function(scope) {
var notifications = Restangular.all('notifications');
var updateNotifications = function() {
notifications.getList().then(function(response) {
if (response.length) {
scope.selectedNotification = response[0];
} else {
scope.selectedNotification = undefined;
}
});
};
scope.markAsSeen = function(notification) {
notification.patch().then(updateNotifications);
};
scope.$on('userLoggedIn', function() {
updateNotifications();
});
scope.$on('userLoggedOut', function() {
scope.selectedNotification = undefined;
});
if (AuthService.isAuthenticated()) {
updateNotifications();
}
}
};
}]);
| app.directive('pbNotifications', ['Restangular', 'AuthService', 'config', function(Restangular, AuthService, config) {
return {
restrict: 'E',
templateUrl: config.partialsDir + '/broadcast_block.html',
link: function(scope, element, attrs) {
var notifications = Restangular.all('notifications');
var updateNotifications = function() {
notifications.getList().then(function(response) {
if (response.length) {
scope.selectedNotification = response[0];
} else {
scope.selectedNotification = undefined;
}
});
};
scope.markAsSeen = function(notification) {
notification.patch().then(updateNotifications);
};
scope.$on('userLoggedIn', function(event) {
updateNotifications();
});
if (AuthService.isAuthenticated()) {
updateNotifications();
}
}
};
}]);
|
Refactor unit test to use `sinon.test` for automatic cleanup | 'use strict';
var auth = require('./auth.json');
var sinon = require('sinon');
var expect = require('chai').expect;
var should = require('chai').should();
var request = require('request');
describe('SAP module', function () {
var sap;
function initModule(auth) {
sap = require('../index')(auth);
}
beforeEach(function () {
sap = undefined;
initModule(auth);
});
describe('initialization', function () {
var error;
beforeEach(function () {
error = sinon.stub(console, 'error');
});
afterEach(function () {
error.restore();
});
it('sets auth options', function () {
should.exist(sap.client_id);
should.exist(sap.client_secret);
should.exist(sap.refresh_token);
});
describe('when no options are passed', function () {
it('logs an error to the console', function () {
sap = undefined;
initModule();
sinon.assert.calledOnce(error);
});
});
describe('when insufficient options are passed', function () {
it('logs an error to the console', function () {
sap = undefined;
initModule({ client_id: 'foo', client_secret: 'bar' });
sinon.assert.calledOnce(error);
});
});
});
describe('getAccessToken', function() {
it('sends a POST request', sinon.test(function() {
var postRequest = this.stub(request, 'post');
sap.getAccessToken();
sinon.assert.calledOnce(postRequest);
}));
});
});
| 'use strict';
var auth = require('./auth.json');
var sinon = require('sinon');
var expect = require('chai').expect;
var should = require('chai').should();
var request = require('request');
describe('SAP module', function () {
var sap;
function initModule(auth) {
sap = require('../index')(auth);
}
beforeEach(function () {
sap = undefined;
initModule(auth);
});
describe('initialization', function () {
var error;
beforeEach(function () {
error = sinon.stub(console, 'error');
});
afterEach(function () {
error.restore();
});
it('sets auth options', sinon.test(function () {
should.exist(sap.client_id);
should.exist(sap.client_secret);
should.exist(sap.refresh_token);
}));
describe('when no options are passed', function () {
it('logs an error to the console', function () {
sap = undefined;
initModule();
sinon.assert.calledOnce(error);
});
});
describe('when insufficient options are passed', function () {
it('logs an error to the console', function () {
sap = undefined;
initModule({ client_id: 'foo', client_secret: 'bar' });
sinon.assert.calledOnce(error);
});
});
});
describe('getAccessToken', function() {
var postRequest;
beforeEach(function () {
postRequest = sinon.stub(request, 'post');
});
afterEach(function () {
postRequest.restore();
});
it('sends a POST request', function() {
sap.getAccessToken();
sinon.assert.calledOnce(postRequest);
});
});
});
|
Allow method chaining after setUrl() | <?php
namespace RuiGomes\RssFeedFinder;
use Illuminate\Support\Collection;
use PHPHtmlParser\Dom;
class FeedFinder
{
/**
* @var \PHPHtmlParser\Dom
*/
protected $dom;
/**
* @var string
*/
protected $url;
protected $feedTypes = [
'application/rss+xml',
'application/atom+xml',
];
public function __construct($url)
{
$this->dom = new Dom();
$this->url = $url;
}
public function find()
{
$this->dom->loadFromUrl($this->url);
$feeds = new Collection($this->dom->find('link[rel=alternate]'));
$feedUrls = $feeds->filter(function ($feed) {
return in_array($feed->getAttribute('type'), $this->feedTypes);
})->map(function ($feed) {
return $feed->getAttribute('href');
})->toArray();
return $feedUrls;
}
public function setUrl($url)
{
$this->url = $url;
return $this;
}
public function getUrl()
{
return $this->url;
}
public function setDom($dom)
{
$this->dom = $dom;
}
public function getDom()
{
return $this->dom;
}
}
| <?php
namespace RuiGomes\RssFeedFinder;
use Illuminate\Support\Collection;
use PHPHtmlParser\Dom;
class FeedFinder
{
/**
* @var \PHPHtmlParser\Dom
*/
protected $dom;
/**
* @var string
*/
protected $url;
protected $feedTypes = [
'application/rss+xml',
'application/atom+xml',
];
public function __construct($url)
{
$this->dom = new Dom();
$this->url = $url;
}
public function find()
{
$this->dom->loadFromUrl($this->url);
$feeds = new Collection($this->dom->find('link[rel=alternate]'));
$feedUrls = $feeds->filter(function ($feed) {
return in_array($feed->getAttribute('type'), $this->feedTypes);
})->map(function ($feed) {
return $feed->getAttribute('href');
})->toArray();
return $feedUrls;
}
public function setUrl($url)
{
$this->url = $url;
}
public function getUrl()
{
return $this->url;
}
public function setDom($dom)
{
$this->dom = $dom;
}
public function getDom()
{
return $this->dom;
}
}
|
Install the setActiveItem function to the view for convenience | Blend.defineClass('Blend.layout.container.Stacked', {
extend: 'Blend.layout.container.Fit',
alias: 'layout.stacked',
cssPrefix: 'stacked',
activeItem: null,
init: function () {
var me = this;
me.callParent.apply(me, arguments);
/**
* Install the setActiveItem to the view for convenience
* @returns {undefined}
*/
me.view.setActiveItem = function () {
me.setActiveItem.apply(me, arguments);
}
},
getVisibleItemIndex: function () {
var me = this, index;
me.activeItem = me.activeItem || (me.view.items.length !== 0 ? 0 : null);
if (Blend.isObject(me.activeItem) && me.activeItem.$className$) {
/**
* Need to find the index from view items
*/
Blend.foreach(me.view.items, function (view, idx) {
if (view === me.activeItem) {
index = idx;
return false; // will stop the iteration;
}
});
} else {
index = me.activeItem;
}
return index;
},
setActiveItem: function (item) {
var me = this;
if (item !== me.activeItem) {
me.activeItem = item;
me.performLayout();
}
}
});
| Blend.defineClass('Blend.layout.container.Stacked', {
extend: 'Blend.layout.container.Fit',
alias: 'layout.stacked',
cssPrefix: 'stacked',
activeItem: null,
init: function () {
var me = this;
me.callParent.apply(me, arguments);
me.view.setActiveItem = function () {
me.setActiveItem.apply(me, arguments);
}
},
getVisibleItemIndex: function () {
var me = this, index;
me.activeItem = me.activeItem || (me.view.items.length !== 0 ? 0 : null);
if (Blend.isObject(me.activeItem) && me.activeItem.$className$) {
/**
* Need to find the index from view items
*/
Blend.foreach(me.view.items, function (view, idx) {
if (view === me.activeItem) {
index = idx;
return false; // will stop the iteration;
}
});
} else {
index = me.activeItem;
}
return index;
},
setActiveItem: function (item) {
var me = this;
if (item !== me.activeItem) {
me.activeItem = item;
me.performLayout();
}
}
});
|
Add root URL to Book model
Since model is used independently of collection in some cases | define([
'app',
'backbone'
], function(App, Backbone) {
var Entities = App.module('Entities');
//==============================
// Entities
//==============================
Entities.Book = Backbone.Model.extend({
urlRoot: '/api/book/'
});
Entities.Books = Backbone.Collection.extend({
model: Entities.Book,
url: '/api/book/'
});
//==============================
// API access layer
//==============================
var API = {
getBookById: function(bookId) {
var book = new Entities.Book({ id: bookId }),
defer = $.Deferred();
book.fetch({
success: function(data) {
defer.resolve(data);
},
error: function(data) {
defer.resolve(undefined);
}
});
return defer.promise();
},
getBooks: function() {
var books = new Entities.Books(),
defer = $.Deferred();
books.fetch({
success: function(data) {
defer.resolve(data);
},
error: function(data) {
defer.resolve(undefined);
}
});
return defer.promise();
}
};
//==============================
// Application handlers
//==============================
App.reqres.setHandler('book:entity', function(bookId) {
return API.getBookById(bookId);
});
App.reqres.setHandler('book:entities', function() {
return API.getBooks();
});
return Entities;
});
| define([
'app',
'backbone'
], function(App, Backbone) {
var Entities = App.module('Entities');
//==============================
// Entities
//==============================
Entities.Book = Backbone.Model.extend({ });
Entities.Books = Backbone.Collection.extend({
model: Entities.Book,
url: '/api/book/'
});
//==============================
// API access layer
//==============================
var API = {
getBookById: function(bookId) {
var book = new Entities.Book({ id: bookId }),
defer = $.Deferred();
book.fetch({
success: function(data) {
defer.resolve(data);
},
error: function(data) {
defer.resolve(undefined);
}
});
return defer.promise();
},
getBooks: function() {
var books = new Entities.Books(),
defer = $.Deferred();
books.fetch({
success: function(data) {
defer.resolve(data);
},
error: function(data) {
defer.resolve(undefined);
}
});
return defer.promise();
}
};
//==============================
// Application handlers
//==============================
App.reqres.setHandler('book:entity', function(bookId) {
return API.getBookById(bookId);
});
App.reqres.setHandler('book:entities', function() {
return API.getBooks();
});
return Entities;
});
|
Fix exception handling in management command. Clean up. | """Creates an admin user if there aren't any existing superusers."""
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, parser):
parser.add_argument('--username',
action='store',
dest='username',
default=None,
help='Admin username')
parser.add_argument('--password',
action='store',
dest='password',
default=None,
help='Admin password')
def handle(self, *args, **options):
username = options.get('username')
password = options.get('password')
if not username or not password:
raise CommandError('You must specify a username and password')
# Get the current superusers
su_count = User.objects.filter(is_superuser=True).count()
if su_count == 0:
# there aren't any superusers, create one
user, created = User.objects.get_or_create(username=username)
user.set_password(password)
user.is_staff = True
user.is_superuser = True
user.save()
print(f'{username} updated')
else:
print(f'There are already {su_count} superusers')
| '''
Creates an admin user if there aren't any existing superusers
'''
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from optparse import make_option
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, parser):
parser.add_argument('--username',
action='store',
dest='username',
default=None,
help='Admin username')
parser.add_argument('--password',
action='store',
dest='password',
default=None,
help='Admin password')
def handle(self, *args, **options):
username = options.get('username')
password = options.get('password')
if not username or not password:
raise StandardError('You must specify a username and password')
# Get the current superusers
su_count = User.objects.filter(is_superuser=True).count()
if su_count == 0:
# there aren't any superusers, create one
user, created = User.objects.get_or_create(username=username)
user.set_password(password)
user.is_staff = True
user.is_superuser = True
user.save()
print('{0} updated'.format(username))
else:
print('There are already {0} superusers'.format(su_count))
|
Use slightly better type hinting | <?php
namespace Dock\Doctor;
use Dock\IO\ProcessRunner;
use Dock\Installer\InstallerTask;
class DnsDock extends Task
{
/**
* @var InstallerTask $dnsDockInstaller
*/
private $dnsDockInstaller;
/**
* @var InstallerTask $dockerRouting
*/
private $dockerRouting;
/**
* @param ProcessRunner $processRunner
* @param InstallerTask $dnsDockInstaller
* @param InstallerTask $dockerRouting
*/
public function __construct(
ProcessRunner $processRunner,
InstallerTask $dnsDockInstaller,
InstallerTask $dockerRouting)
{
$this->processRunner = $processRunner;
$this->dnsDockInstaller = $dnsDockInstaller;
$this->dockerRouting = $dockerRouting;
}
/**
* {@inheritdoc}
*/
public function run($dryRun)
{
$this->handle(
"test 0 -lt `docker ps -q --filter=name=dnsdock | wc -l`",
"It seems dnsdock is not running.",
"Install and start dnsdock by running: `dock-cli docker:install`",
$this->dnsDockInstaller,
$dryRun
);
$this->handle(
"ping -c1 dnsdock.docker",
"It seems your dns is not set up properly.",
"Add 172.17.42.1 as one of your DNS servers. `dock-cli docker:install` will try to do that",
$this->dockerRouting,
$dryRun
);
}
}
| <?php
namespace Dock\Doctor;
use Dock\IO\ProcessRunner;
class DnsDock extends Task
{
/**
* @var mixed
*/
private $dnsDockInstaller;
/**
* @var mixed
*/
private $dockerRouting;
/**
* @param ProcessRunner $processRunner
* @param mixed $dnsDockInstaller
* @param mixed $dockerRouting
*/
public function __construct(ProcessRunner $processRunner, $dnsDockInstaller, $dockerRouting)
{
$this->processRunner = $processRunner;
$this->dnsDockInstaller = $dnsDockInstaller;
$this->dockerRouting = $dockerRouting;
}
/**
* {@inheritdoc}
*/
public function run($dryRun)
{
$this->handle(
"test 0 -lt `docker ps -q --filter=name=dnsdock | wc -l`",
"It seems dnsdock is not running.",
"Install and start dnsdock by running: `dock-cli docker:install`",
$this->dnsDockInstaller,
$dryRun
);
$this->handle(
"ping -c1 dnsdock.docker",
"It seems your dns is not set up properly.",
"Add 172.17.42.1 as one of your DNS servers. `dock-cli docker:install` will try to do that",
$this->dockerRouting,
$dryRun
);
}
}
|
Add root path to configuration | /* eslint key-spacing:0 spaced-comment:0 */
const path = require('path');
const ip = require('ip');
const projectBase = path.resolve(__dirname, '..');
/************************************************
/* Default configuration
*************************************************/
var configuration = {
env : process.env.NODE_ENV || 'development',
log : {
level : 'debug'
},
/*************************************************
/* Project Structure
*************************************************/
structure : {
root : projectBase,
client : path.join(projectBase, 'app'),
build : path.join(projectBase, 'build'),
server : path.join(projectBase, 'server'),
config : path.join(projectBase, 'config'),
test : path.join(projectBase, 'tests')
},
/*************************************************
/* Server configuration
*************************************************/
server : {
host : ip.address(), // use string 'localhost' to prevent exposure on local network
port : process.env.PORT || 3000
},
/*************************************************
/* Compiler configuration
*************************************************/
compiler : {
babel : {
cache_directory : true,
plugins : ['transform-runtime'],
presets : ['es2015', 'react', 'stage-0']
},
devtool : 'source-map',
hash_type : 'hash',
fail_on_warning : false,
quiet : false,
public_path : '/',
stats : {
chunks : false,
chunkModules : false,
colors : true
}
},
/*************************************************
/* Build configuration
*************************************************/
build : {},
/*************************************************
/* Test configuration
*************************************************/
test : {}
};
module.exports = configuration;
| /* eslint key-spacing:0 spaced-comment:0 */
const path = require('path');
const ip = require('ip');
const projectBase = path.resolve(__dirname, '..');
/************************************************
/* Default configuration
*************************************************/
module.exports = {
env : process.env.NODE_ENV || 'development',
log : {
level : 'debug'
},
/*************************************************
/* Project Structure
*************************************************/
structure : {
client : path.join(projectBase, 'app'),
build : path.join(projectBase, 'build'),
server : path.join(projectBase, 'server'),
config : path.join(projectBase, 'config'),
test : path.join(projectBase, 'tests')
},
/*************************************************
/* Server configuration
*************************************************/
server : {
host : ip.address(), // use string 'localhost' to prevent exposure on local network
port : process.env.PORT || 3000
},
/*************************************************
/* Compiler configuration
*************************************************/
compiler : {
babel : {
cache_directory : true,
plugins : ['transform-runtime'],
presets : ['es2015', 'react', 'stage-0']
},
devtool : 'source-map',
hash_type : 'hash',
fail_on_warning : false,
quiet : false,
public_path : '/',
stats : {
chunks : false,
chunkModules : false,
colors : true
}
},
/*************************************************
/* Build configuration
*************************************************/
build : {},
/*************************************************
/* Test configuration
*************************************************/
test : {}
};
|
Improve proxy web page example | // Web page retrieval using server-side proxy support to get around CORS restrictions
requirejs(["sanitizeHTML", "vendor/purify"], function(sanitizeHTML, DOMPurify) {
let content
// const url = "http://kurtz-fernhout.com/"
const url = "http://pdfernhout.net/"
const crossOriginService = "/api/proxy"
m.request({
method: "POST",
url: crossOriginService,
data: { url },
}).then((result) => {
console.log("result", result)
content = result.content
m.redraw()
}).catch((error) => {
console.log("An error occured:", error)
content = JSON.stringify(error)
m.redraw()
})
Twirlip7.show(() => {
return m("div", [
content ?
// Two examples of ways to sanitize web content for display locally -- but always a bit of a risk to display remote content
sanitizeHTML.generateSanitizedHTMLForMithrilWithAttributes(m, DOMParser, content, {allowLinks: true, allowImages: true, baseURL: url})
// m.trust(DOMPurify.sanitize(content))
:
"loading..."
])
}, { title: url })
})
| // Web page retrieval using server-side proxy support to get around CORS restrictions
requirejs(["sanitizeHTML", "vendor/purify"], function(sanitizeHTML, DOMPurify) {
let content
const url = "http://kurtz-fernhout.com/"
// const url = "http://pdfernhout.net/"
const crossOriginService = "/api/proxy"
m.request({
method: "POST",
url: crossOriginService,
data: { url },
}).then((result) => {
console.log("result", result)
content = result.content
m.redraw()
}).catch((error) => {
console.log("An error occured:", error)
content = JSON.stringify(error)
m.redraw()
})
Twirlip7.show(() => {
return m("div", [
content ?
// Two examples of ways to sanitize web content for display locally -- but always a bit of a risk to display remote content
sanitizeHTML.generateSanitizedHTMLForMithrilWithAttributes(m, DOMParser, content, {allowLinks: true, allowImages: true, baseURL: url})
// m.trust(DOMPurify.sanitize(content))
:
"loading..."
])
})
})
|
Include windows.cpp only on Windows | #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"]
extra_link_args = [] if os.name == 'nt' else ["-g"]
platform_src = ["src/windows.cpp"] if os.name == 'nt' else []
mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
sources=['src/thinning.cpp',
'src/distance.cpp',
'src/grassfire.cpp',
'src/popcount.cpp',
'src/neighbours.cpp'] + platform_src,
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args)
setup(
name='cv_algorithms',
license='Apache license 2.0',
packages=find_packages(exclude=['tests*']),
install_requires=['cffi>=0.7'],
ext_modules=[mod_cv_algorithms],
test_suite='nose.collector',
tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'],
setup_requires=['nose>=1.0'],
platforms="any",
zip_safe=False,
version='1.0.0',
long_description=io.open("README.rst", encoding="utf-8").read(),
description='Optimized OpenCV extra algorithms for Python',
url="https://github.com/ulikoehler/"
)
| #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"]
extra_link_args = [] if os.name == 'nt' else ["-g"]
mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
sources=['src/thinning.cpp',
'src/distance.cpp',
'src/grassfire.cpp',
'src/popcount.cpp',
'src/neighbours.cpp'],
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args)
setup(
name='cv_algorithms',
license='Apache license 2.0',
packages=find_packages(exclude=['tests*']),
install_requires=['cffi>=0.7'],
ext_modules=[mod_cv_algorithms],
test_suite='nose.collector',
tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'],
setup_requires=['nose>=1.0'],
platforms="any",
zip_safe=False,
version='1.0.0',
long_description=io.open("README.rst", encoding="utf-8").read(),
description='Optimized OpenCV extra algorithms for Python',
url="https://github.com/ulikoehler/"
)
|
Fix for ignoring BPMN validation - JBPM-4000 - corrected formatting | package org.jbpm.migration;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/** Convenience class for making the error handling within the parsing and validation processes a little more verbose. */
abstract class ErrorCollector<T extends Exception> {
private final List<T> warningList = new ArrayList<T>();
private final List<T> errorList = new ArrayList<T>();
private final List<T> fatalList = new ArrayList<T>();
public void warning(final T ex) {
warningList.add(ex);
}
public void error(final T ex) {
errorList.add(ex);
}
public void fatalError(final T ex) {
fatalList.add(ex);
}
public boolean didErrorOccur() {
// checking warnings might be too restrictive
return !warningList.isEmpty() || !errorList.isEmpty() || !fatalList.isEmpty();
}
public List<T> getWarningList() {
return warningList;
}
public List<T> getErrorList() {
return errorList;
}
public List<T> getFatalList() {
return fatalList;
}
public void logErrors(final Logger logger) {
for (final T ex : warningList) {
logger.warn("==>", ex);
}
for (final T ex : errorList) {
logger.error("==>", ex);
}
for (final T ex : fatalList) {
logger.fatal("==>", ex);
}
}
}
| package org.jbpm.migration;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/** Convenience class for making the error handling within the parsing and validation processes a little more verbose. */
abstract class ErrorCollector<T extends Exception> {
private final List<T> warningList = new ArrayList<T>();
private final List<T> errorList = new ArrayList<T>();
private final List<T> fatalList = new ArrayList<T>();
public void warning(final T ex) {
warningList.add(ex);
}
public void error(final T ex) {
errorList.add(ex);
}
public void fatalError(final T ex) {
fatalList.add(ex);
}
public boolean didErrorOccur() {
// checking warnings might be too restrictive
return !warningList.isEmpty() || !errorList.isEmpty() ||!fatalList.isEmpty();
}
public List<T> getWarningList() {
return warningList;
}
public List<T> getErrorList() {
return errorList;
}
public List<T> getFatalList() {
return fatalList;
}
public void logErrors(final Logger logger) {
for (final T ex : warningList) {
logger.warn("==>", ex);
}
for (final T ex : errorList) {
logger.error("==>", ex);
}
for (final T ex : fatalList) {
logger.fatal("==>", ex);
}
}
}
|
Fix proxy urls for main uuid functions | (function(){
'use strict';
angular
.module('SAKapp')
.controller('UuidController', ['$scope', '$http', '$log', '$q', 'toaster', UuidController]);
function UuidController ($scope, $http, $log, $q, toaster) {
$scope.getUUIDs = function () {
$scope.uuids = "";
$scope.errorMsg = "";
var url = '/proxy?url=http://pz-discover.cf.piazzageo.io/api/v1/resources/pz-uuidgen';
var posturl = '';
$http({
method: "GET",
url: url
}).then(function(result) {
if ($scope.uuidCount === undefined){
posturl = "/proxy?url=http://"+result.data.host +"/v1/uuids"
}
else {
posturl = "/proxy?url=http://"+result.data.host +"/v1/uuids%3Fcount="+$scope.uuidCount;
}
console.log(posturl);
$http({
method: "POST",
url: posturl,
}).then(function successCallback( html ) {
$scope.uuids = html.data.data;
/*angular.forEach($scope.logs, function(item){
console.log(item);
})*/
}, function errorCallback(response){
console.log("fail");
toaster.pop('error', "Error", "There was an issue retrieving UUID(s)");
//$scope.errorMsg = "There was an issue with your request. Please make sure ..."
});
});
};
}
})(); | (function(){
'use strict';
angular
.module('SAKapp')
.controller('UuidController', ['$scope', '$http', '$log', '$q', 'toaster', UuidController]);
function UuidController ($scope, $http, $log, $q, toaster) {
$scope.getUUIDs = function () {
$scope.uuids = "";
$scope.errorMsg = "";
var url = 'http://pz-discover.cf.piazzageo.io/api/v1/resources/pz-uuidgen';
var posturl = '';
$http({
method: "GET",
url: url
}).then(function(result) {
if ($scope.uuidCount === undefined){
posturl = "http://"+result.data.host +"/v1/uuids"
}
else {
posturl = "http://"+result.data.host +"/v1/uuids?count="+$scope.uuidCount;
}
console.log(posturl);
$http({
method: "POST",
url: posturl,
}).then(function successCallback( html ) {
$scope.uuids = html.data.data;
/*angular.forEach($scope.logs, function(item){
console.log(item);
})*/
}, function errorCallback(response){
console.log("fail");
toaster.pop('error', "Error", "There was an issue retrieving UUID(s)");
//$scope.errorMsg = "There was an issue with your request. Please make sure ..."
});
});
};
}
})(); |
Change listener failure logging level to warn. | <?php
namespace FOQ\ElasticaBundle\Doctrine;
use FOQ\ElasticaBundle\Persister\ObjectPersister;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
abstract class AbstractListener
{
/**
* Object persister
*
* @var ObjectPersister
*/
protected $objectPersister;
/**
* Class of the domain model
*
* @var string
*/
protected $objectClass;
/**
* List of subscribed events
*
* @var array
*/
protected $events;
protected $logger;
/**
* Constructor
**/
public function __construct(ObjectPersister $objectPersister, $objectClass, array $events, LoggerInterface $logger = null)
{
$this->objectPersister = $objectPersister;
$this->objectClass = $objectClass;
$this->events = $events;
$this->logger = $logger;
}
/**
* @return array
*/
public function getSubscribedEvents()
{
return $this->events;
}
/**
* Log the failure message if a logger is available
*
* $param string $message
*/
protected function logFailure($message)
{
if (null !== $this->logger) {
$this->logger->warn(sprintf('%s: %s', get_class($this), $message));
}
}
}
| <?php
namespace FOQ\ElasticaBundle\Doctrine;
use FOQ\ElasticaBundle\Persister\ObjectPersister;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
abstract class AbstractListener
{
/**
* Object persister
*
* @var ObjectPersister
*/
protected $objectPersister;
/**
* Class of the domain model
*
* @var string
*/
protected $objectClass;
/**
* List of subscribed events
*
* @var array
*/
protected $events;
protected $logger;
/**
* Constructor
**/
public function __construct(ObjectPersister $objectPersister, $objectClass, array $events, LoggerInterface $logger = null)
{
$this->objectPersister = $objectPersister;
$this->objectClass = $objectClass;
$this->events = $events;
$this->logger = $logger;
}
/**
* @return array
*/
public function getSubscribedEvents()
{
return $this->events;
}
/**
* Log the failure message if a logger is available
*
* $param string $message
*/
protected function logFailure($message)
{
if (null !== $this->logger) {
$this->logger->err(sprintf('%s: %s', get_class($this), $message));
}
}
}
|
Use L&F that is available on JDK 1.3
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1344 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | package com.thoughtworks.acceptance;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class SwingTest extends AbstractAcceptanceTest {
// JTable is one of the nastiest components to serialize. If this works, we're in good shape :)
public void testJTable() {
// Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
JTable original = new JTable();
String originalXml = xstream.toXML(original);
JTable deserialized = (JTable) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
}
public void testDefaultListModel() {
final DefaultListModel original = new DefaultListModel();
final JList list = new JList();
list.setModel(original);
String originalXml = xstream.toXML(original);
DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
list.setModel(deserialized);
}
public void testMetalLookAndFeel() {
LookAndFeel plaf = new MetalLookAndFeel();
String originalXml = xstream.toXML(plaf);
assertBothWays(plaf, originalXml);
}
}
| package com.thoughtworks.acceptance;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.synth.SynthLookAndFeel;
public class SwingTest extends AbstractAcceptanceTest {
// JTable is one of the nastiest components to serialize. If this works, we're in good shape :)
public void testJTable() {
// Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
JTable original = new JTable();
String originalXml = xstream.toXML(original);
JTable deserialized = (JTable) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
}
public void testDefaultListModel() {
final DefaultListModel original = new DefaultListModel();
final JList list = new JList();
list.setModel(original);
String originalXml = xstream.toXML(original);
DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
list.setModel(deserialized);
}
public void testSynthLookAndFeel() {
LookAndFeel plaf = new SynthLookAndFeel();
String originalXml = xstream.toXML(plaf);
assertBothWays(plaf, originalXml);
}
}
|
Add missing comma after last element in an array | <?php
/**
* Updates the database layout during the update from 5.4 to 5.5.
*
* @author Matthias Schmidt
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core
*/
use wcf\system\database\table\column\DefaultFalseBooleanDatabaseTableColumn;
use wcf\system\database\table\column\EnumDatabaseTableColumn;
use wcf\system\database\table\index\DatabaseTableIndex;
use wcf\system\database\table\PartialDatabaseTable;
return [
PartialDatabaseTable::create('wcf1_blacklist_entry')
->indices([
DatabaseTableIndex::create('lastSeen')
->columns(['lastSeen']),
]),
PartialDatabaseTable::create('wcf1_comment')
->columns([
DefaultFalseBooleanDatabaseTableColumn::create('hasEmbeddedObjects'),
]),
PartialDatabaseTable::create('wcf1_comment_response')
->columns([
DefaultFalseBooleanDatabaseTableColumn::create('hasEmbeddedObjects'),
]),
PartialDatabaseTable::create('wcf1_style')
->columns([
EnumDatabaseTableColumn::create('apiVersion')
->enumValues(['3.0', '3.1', '5.2', '5.5'])
->notNull()
->defaultValue('3.0'),
]),
];
| <?php
/**
* Updates the database layout during the update from 5.4 to 5.5.
*
* @author Matthias Schmidt
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core
*/
use wcf\system\database\table\column\DefaultFalseBooleanDatabaseTableColumn;
use wcf\system\database\table\column\EnumDatabaseTableColumn;
use wcf\system\database\table\index\DatabaseTableIndex;
use wcf\system\database\table\PartialDatabaseTable;
return [
PartialDatabaseTable::create('wcf1_blacklist_entry')
->indices([
DatabaseTableIndex::create('lastSeen')
->columns(['lastSeen']),
]),
PartialDatabaseTable::create('wcf1_comment')
->columns([
DefaultFalseBooleanDatabaseTableColumn::create('hasEmbeddedObjects'),
]),
PartialDatabaseTable::create('wcf1_comment_response')
->columns([
DefaultFalseBooleanDatabaseTableColumn::create('hasEmbeddedObjects'),
]),
PartialDatabaseTable::create('wcf1_style')
->columns([
EnumDatabaseTableColumn::create('apiVersion')
->enumValues(['3.0', '3.1', '5.2', '5.5'])
->notNull()
->defaultValue('3.0')
]),
];
|
Make $arguments public => protected | <?php
namespace CodeGen;
use Exception;
use CodeGen\Renderable;
use CodeGen\Raw;
use CodeGen\VariableDeflator;
use ArrayAccess;
use IteratorAggregate;
use ArrayIterator;
/**
* Argument list for function call
*/
class ArgumentList implements Renderable, ArrayAccess, IteratorAggregate
{
protected $arguments;
public function __construct(array $arguments = array())
{
$this->arguments = $arguments;
}
public function setArguments(array $args)
{
$this->arguments = $args;
}
public function add($arg)
{
$this->arguments[] = $arg;
return $this;
}
public function offsetExists($offset)
{
return isset($this->arguments[ $offset ]);
}
public function offsetGet($offset)
{
return $this->arguments[ $offset ];
}
public function offsetUnset($offset)
{
unset($this->arguments[$offset]);
}
public function offsetSet($offset, $value)
{
if ($offset) {
$this->arguments[$offset] = $value;
} else {
$this->arguments[] = $value;
}
}
public function getIterator()
{
return new ArrayIterator($this->arguments);
}
public function render(array $args = array())
{
$strs = array();
foreach ($this->arguments as $arg) {
$strs[] = VariableDeflator::deflate($arg);
}
return join(', ',$strs);
}
}
| <?php
namespace CodeGen;
use Exception;
use CodeGen\Renderable;
use CodeGen\Raw;
use CodeGen\VariableDeflator;
use ArrayAccess;
use IteratorAggregate;
use ArrayIterator;
/**
* Argument list for function call
*/
class ArgumentList implements Renderable, ArrayAccess, IteratorAggregate
{
public $arguments;
public function __construct(array $arguments = array())
{
$this->arguments = $arguments;
}
public function setArguments(array $args)
{
$this->arguments = $args;
}
public function add($arg)
{
$this->arguments[] = $arg;
return $this;
}
public function offsetExists($offset)
{
return isset($this->arguments[ $offset ]);
}
public function offsetGet($offset)
{
return $this->arguments[ $offset ];
}
public function offsetUnset($offset)
{
unset($this->arguments[$offset]);
}
public function offsetSet($offset, $value)
{
if ($offset) {
$this->arguments[$offset] = $value;
} else {
$this->arguments[] = $value;
}
}
public function getIterator()
{
return new ArrayIterator($this->arguments);
}
public function render(array $args = array())
{
$strs = array();
foreach ($this->arguments as $arg) {
$strs[] = VariableDeflator::deflate($arg);
}
return join(', ',$strs);
}
}
|
Use tuples of attnames instead of lists | VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
from django.db.models import Model
from django.db.models.base import ModelState
try:
from itertools import izip
except ImportError:
izip = zip
def attnames(cls, _cache={}):
try:
return _cache[cls]
except KeyError:
_cache[cls] = tuple(f.attname for f in cls._meta.fields)
return _cache[cls]
def model_unpickle(cls, vector, db, adding):
obj = cls.__new__(cls)
obj.__dict__.update(izip(attnames(cls), vector))
# Restore state. This is the fastest way to create object I know.
obj._state = ModelState.__new__(ModelState)
obj._state.__dict__ = {'db': db, 'adding': adding}
return obj
model_unpickle.__safe_for_unpickle__ = True
def Model__reduce__(self):
cls = self.__class__
data = self.__dict__.copy()
state = data.pop('_state')
try:
vector = tuple(data.pop(name) for name in attnames(cls))
return (model_unpickle, (cls, vector, state.db, state.adding), data)
except KeyError:
# data.pop() raises when some attnames are deferred
return original_Model__reduce__(self)
if Model.__reduce__ != Model__reduce__:
original_Model__reduce__ = Model.__reduce__
Model.__reduce__ = Model__reduce__
del Model.__setstate__ # Drop django version check
| VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
from django.db.models import Model
from django.db.models.base import ModelState
try:
from itertools import izip
except ImportError:
izip = zip
def attnames(cls, _cache={}):
try:
return _cache[cls]
except KeyError:
_cache[cls] = [f.attname for f in cls._meta.fields]
return _cache[cls]
def model_unpickle(cls, vector, db, adding):
obj = cls.__new__(cls)
obj.__dict__.update(izip(attnames(cls), vector))
# Restore state. This is the fastest way to create object I know.
obj._state = ModelState.__new__(ModelState)
obj._state.__dict__ = {'db': db, 'adding': adding}
return obj
model_unpickle.__safe_for_unpickle__ = True
def Model__reduce__(self):
cls = self.__class__
data = self.__dict__.copy()
state = data.pop('_state')
try:
vector = tuple(data.pop(name) for name in attnames(cls))
return (model_unpickle, (cls, vector, state.db, state.adding), data)
except KeyError:
# data.pop() raises when some attnames are deferred
return original_Model__reduce__(self)
if Model.__reduce__ != Model__reduce__:
original_Model__reduce__ = Model.__reduce__
Model.__reduce__ = Model__reduce__
del Model.__setstate__ # Drop django version check
|
Fix to help garbage-collector work more rapidly | import EventManager from '../helpers/event-manager';
const createObjectUrl = (src) => {
const blob = new Blob([src], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
return url;
};
class Thread extends EventManager {
constructor() {
super(null);
this.currentWorker = null;
this.jobId = null;
this.active = false;
}
setActive(bool) {
this.active = bool;
}
startProcessing() {
this.setActive(true);
this.triggerStartProcessing();
}
doneProcessing() {
this.setActive(false);
this.triggerDoneProcessing(this);
}
process(operation, bool) {
this.startProcessing();
let worker;
if (bool || operation.id === this.jobId) {
worker = this.currentWorker;
} else {
worker = this.spawnWorker(operation.src);
this.jobId = operation.id;
}
worker.onmessage = ({ data }) => {
this.triggerData(operation, data);
this.doneProcessing();
};
worker.onerror = (e) => {
this.triggerDataError(operation, e);
this.doneProcessing();
};
worker.postMessage(operation.data);
operation.data = null;
}
spawnWorker(src) {
if (this.currentWorker) {
this.currentWorker.terminate();
}
const url = createObjectUrl(src);
const worker = new Worker(url);
return this.currentWorker = worker;
}
}
export default Thread;
| import EventManager from '../helpers/event-manager';
const createObjectUrl = (src) => {
const blob = new Blob([src], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
return url;
};
class Thread extends EventManager {
constructor() {
super(null);
this.currentWorker = null;
this.jobId = null;
this.active = false;
}
setActive(bool) {
this.active = bool;
}
startProcessing() {
this.setActive(true);
this.triggerStartProcessing();
}
doneProcessing() {
this.setActive(false);
this.triggerDoneProcessing(this);
}
process(operation, bool) {
this.startProcessing();
let worker;
if (bool || operation.id === this.jobId) {
worker = this.currentWorker;
} else {
worker = this.spawnWorker(operation.src);
this.jobId = operation.id;
}
worker.onmessage = ({ data }) => {
this.triggerData(operation, data);
this.doneProcessing();
};
worker.onerror = (e) => {
this.triggerDataError(operation, e);
this.doneProcessing();
};
worker.postMessage(operation.data);
}
spawnWorker(src) {
if (this.currentWorker) {
this.currentWorker.terminate();
}
const url = createObjectUrl(src);
const worker = new Worker(url);
return this.currentWorker = worker;
}
}
export default Thread;
|
Change HTTP method for validate endpoint | import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400):
return Response({ 'success': False }, status = status)
def API(name, backend):
app = flask.Flask(name)
app.config.from_object(name)
@app.route('/')
def api_root():
return SuccessResponse(backend.dataset_id)
@app.route('/load', methods=['POST'])
def api_load():
backend.load(request.json)
return SuccessResponse(backend.dataset_id)
@app.route('/fit', methods=['POST'])
def api_fit():
if not backend.loaded():
return ErrorResponse()
backend.fit()
return SuccessResponse(backend.dataset_id)
@app.route('/validate', methods=['POST'])
def api_validate():
if not backend.loaded():
return ErrorResponse()
data = backend.validate()
return Response(data)
@app.route('/predict', methods=['POST'])
def api_predict():
if not backend.trained():
return ErrorResponse()
data = backend.predict(request.json).tolist()
return Response(data)
return app
| import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400):
return Response({ 'success': False }, status = status)
def API(name, backend):
app = flask.Flask(name)
app.config.from_object(name)
@app.route('/')
def api_root():
return SuccessResponse(backend.dataset_id)
@app.route('/load', methods=['POST'])
def api_load():
backend.load(request.json)
return SuccessResponse(backend.dataset_id)
@app.route('/fit', methods=['POST'])
def api_fit():
if not backend.loaded():
return ErrorResponse()
backend.fit()
return SuccessResponse(backend.dataset_id)
@app.route('/validate', methods=['PUT'])
def api_validate():
if not backend.loaded():
return ErrorResponse()
data = backend.validate()
return Response(data)
@app.route('/predict', methods=['POST'])
def api_predict():
if not backend.trained():
return ErrorResponse()
data = backend.predict(request.json).tolist()
return Response(data)
return app
|
Correct github URL for chessmoves module |
import chessmoves # Source: https://github.com/kervinck/chessmoves.git
import floyd as engine
import sys
def parseEpd(rawLine):
# 4-field FEN
line = rawLine.strip().split(' ', 4)
pos = ' '.join(line[0:4])
# EPD fields
operations = {'bm': '', 'am': ''}
fields = [op for op in line[4].split(';') if len(op) > 0]
fields = [op.strip().split(' ', 1) for op in fields]
operations.update(dict(fields))
return pos, operations
nrPassed = 0
nrTests = 0
movetime = float(sys.argv[1])
for rawLine in sys.stdin:
print rawLine,
nrTests += 1
pos, operations = parseEpd(rawLine)
bm = [chessmoves.move(pos, bm, notation='uci')[0] for bm in operations['bm'].split()] # best move
am = [chessmoves.move(pos, am, notation='uci')[0] for am in operations['am'].split()] # avoid move
score, move = engine.search(pos, movetime=movetime, info='uci')
print 'bestmove', move
print 'test',
if (len(bm) == 0 or move in bm) and\
(len(am) == 0 or move not in am):
print 'result OK',
nrPassed += 1
else:
print 'result FAILED',
print 'passed %d total %d' % (nrPassed, nrTests)
print
|
import chessmoves # Source: https://github.com/kervinck/floyd.git
import floyd as engine
import sys
def parseEpd(rawLine):
# 4-field FEN
line = rawLine.strip().split(' ', 4)
pos = ' '.join(line[0:4])
# EPD fields
operations = {'bm': '', 'am': ''}
fields = [op for op in line[4].split(';') if len(op) > 0]
fields = [op.strip().split(' ', 1) for op in fields]
operations.update(dict(fields))
return pos, operations
nrPassed = 0
nrTests = 0
movetime = float(sys.argv[1])
for rawLine in sys.stdin:
print rawLine,
nrTests += 1
pos, operations = parseEpd(rawLine)
bm = [chessmoves.move(pos, bm, notation='uci')[0] for bm in operations['bm'].split()] # best move
am = [chessmoves.move(pos, am, notation='uci')[0] for am in operations['am'].split()] # avoid move
score, move = engine.search(pos, movetime=movetime, info='uci')
print 'bestmove', move
print 'test',
if (len(bm) == 0 or move in bm) and\
(len(am) == 0 or move not in am):
print 'result OK',
nrPassed += 1
else:
print 'result FAILED',
print 'passed %d total %d' % (nrPassed, nrTests)
print
|
Change the way the configuration file is loaded | <?php
namespace ProjectLint\Console\Command;
use ProjectLint\Item\ItemManager;
use ProjectLint\Report\Renderer\TextRenderer;
use ProjectLint\Rule\RuleSet;
use ProjectLint\Rule\RuleSetChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Logger\ConsoleLogger;
class ProjectLintCommand extends Command
{
protected function configure()
{
$this->setName('projectlint')
->setDescription('Checks project structure')
->setHelp(PHP_EOL . 'Checks project layout against a ruleset' . PHP_EOL)
->addArgument('path', InputArgument::OPTIONAL, 'Project path', 'Current directory');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$logger = new ConsoleLogger($output);
$projectPath = $input->getArgument('path');
if ('Current directory' == $projectPath) {
$projectPath = getcwd();
}
$ruleSet = new RuleSet($projectPath . '/projectlint.yml', $logger);
$itemManager = new ItemManager($projectPath);
$checker = new RuleSetChecker($itemManager);
$report = $checker->check($ruleSet);
$renderer = new TextRenderer($output);
$renderer->render($report);
// Set exit code
return $report->hasViolations() ? 1 : 0;
}
}
| <?php
namespace ProjectLint\Console\Command;
use ProjectLint\Item\ItemManager;
use ProjectLint\Report\Renderer\TextRenderer;
use ProjectLint\Rule\RuleSet;
use ProjectLint\Rule\RuleSetChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Logger\ConsoleLogger;
class ProjectLintCommand extends Command
{
protected function configure()
{
$this->setName('projectlint')
->setDescription('Checks project structure')
->setHelp(PHP_EOL . 'Checks project layout against a ruleset' . PHP_EOL)
->addArgument('ruleset', InputArgument::OPTIONAL, 'Ruleset path', 'projectlint.yml');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$logger = new ConsoleLogger($output);
$ruleSetPath = $input->getArgument('ruleset');
$ruleSet = new RuleSet($ruleSetPath, $logger);
$itemManager = new ItemManager(getcwd());
$checker = new RuleSetChecker($itemManager);
$report = $checker->check($ruleSet);
$renderer = new TextRenderer($output);
$renderer->render($report);
// Set exit code
return $report->hasViolations() ? 1 : 0;
}
}
|
Fix (profil): Text files should end with a newline character | <?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;
class UserProfilType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('aboutme', TextareaType::class, array(
'attr' => array( 'class' => 'materialize-textarea'),
'required' => false
))
->add('imagepath', FileType::class, array(
'label' => false,
'mapped' => false,
'data_class' => null,
'required' => false,
'attr' => array('class' => 'upload'),
'constraints' => [
new File([
'maxSize' => '5M',
'mimeTypes' => [
'image/jpeg',
'image/gif',
'image/png'
],
'mimeTypesMessage' => 'avatar_format',
'maxSizeMessage' => 'avatar_size',
])
]
))
;
}
public function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'error_bubbling' => true
));
}
public function getName()
{
return 'profil_form';
}
}
| <?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;
class UserProfilType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('aboutme', TextareaType::class, array(
'attr' => array( 'class' => 'materialize-textarea'),
'required' => false
))
->add('imagepath', FileType::class, array(
'label' => false,
'mapped' => false,
'data_class' => null,
'required' => false,
'attr' => array('class' => 'upload'),
'constraints' => [
new File([
'maxSize' => '5M',
'mimeTypes' => [
'image/jpeg',
'image/gif',
'image/png'
],
'mimeTypesMessage' => 'avatar_format',
'maxSizeMessage' => 'avatar_size',
])
]
))
;
}
public function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'error_bubbling' => true
));
}
public function getName()
{
return 'profil_form';
}
} |
Return value instead of null | Kwf.Form.ShowField = Ext.extend(Ext.form.Field,
{
defaultAutoCreate : {tag: 'div', cls: 'kwf-form-show-field'},
/**
* {value} wenn kein objekt übergeben, sonst index aus objekt
*/
tpl: '{value}',
initValue : function(){
if(this.value !== undefined){
this.setValue(this.value);
}
},
afterRender : function(){
Kwf.Form.ShowField.superclass.afterRender.call(this);
if (typeof this.tpl == 'string') this.tpl = new Ext.XTemplate(this.tpl);
this.tpl.compile();
this.setRawValue(" "); //bugfix für IE 7 -> /kwf/test/kwf_form_show-field_value-overlaps-error
},
getName: function(){
return this.name;
},
setRawValue : function(v){
return this.el.update(v);
},
getRawValue : function(){
return this.el.dom.innerHTML;
},
getValue : function()
{
return this.value;
},
setValue : function(value)
{
this.value = value;
if(this.rendered){
if (!value) {
this.setRawValue(value);
} else {
if (typeof value != 'object') value = { value : value };
this.tpl.overwrite(this.el, value);
}
}
if (this.getRawValue() == '') {
this.setRawValue(" ");
}
}
});
Ext.reg('showfield', Kwf.Form.ShowField);
| Kwf.Form.ShowField = Ext.extend(Ext.form.Field,
{
defaultAutoCreate : {tag: 'div', cls: 'kwf-form-show-field'},
/**
* {value} wenn kein objekt übergeben, sonst index aus objekt
*/
tpl: '{value}',
initValue : function(){
if(this.value !== undefined){
this.setValue(this.value);
}
},
afterRender : function(){
Kwf.Form.ShowField.superclass.afterRender.call(this);
if (typeof this.tpl == 'string') this.tpl = new Ext.XTemplate(this.tpl);
this.tpl.compile();
this.setRawValue(" "); //bugfix für IE 7 -> /kwf/test/kwf_form_show-field_value-overlaps-error
},
getName: function(){
return this.name;
},
setRawValue : function(v){
return this.el.update(v);
},
getRawValue : function(){
return this.el.dom.innerHTML;
},
getValue : function()
{
return null;
},
setValue : function(value)
{
this.value = value;
if(this.rendered){
if (!value) {
this.setRawValue(value);
} else {
if (typeof value != 'object') value = { value : value };
this.tpl.overwrite(this.el, value);
}
}
if (this.getRawValue() == '') {
this.setRawValue(" ");
}
}
});
Ext.reg('showfield', Kwf.Form.ShowField);
|
Add move operation to user item | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def move(self, folder_id):
r = self._create_operation_request(self, "move", method="POST", data={"folder": folder_id})
return send_session_request(self._session, r).json()
def delete(self):
r = self._create_operation_request(self, "delete", method="POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method="POST", data=updated_item_info)
return send_session_request(self._session, r).json() | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def delete(self):
r = self._create_operation_request(self, "delete", method = "POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method = "POST", data = updated_item_info)
return send_session_request(self._session, r).json() |
Add id to translation of designer. | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDesignerTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('designer', function (Blueprint $table) {
$table->increments('id');
// Non-translated content
$table->integer('image_id')->unsigned()->nullable(); // ID of image
$table->integer('user_id')->unsigned()->nullable(); // Who own designer page
// Timestamps
$table->timestamps();
$table->softDeletes();
});
Schema::create('designer_translation', function (Blueprint $table) {
$table->increments('id');
$table->integer('designer_id')->unsigned();
$table->string('locale')->index();
$table->boolean('complete');
// Translated content
$table->string('name');
$table->text('content');
$table->timestamps();
// Unique and foreign key
// When deleting designer model, also delete all translation models
$table->unique(['designer_id','locale']);
$table->foreign('designer_id')->references('id')->on('designer')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('designer_translation');
Schema::drop('designer');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDesignerTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('designer', function (Blueprint $table) {
$table->increments('id');
// Non-translated content
$table->integer('image_id')->unsigned()->nullable(); // ID of image
$table->integer('user_id')->unsigned()->nullable(); // Who own designer page
// Timestamps
$table->timestamps();
$table->softDeletes();
});
Schema::create('designer_translation', function (Blueprint $table) {
$table->integer('designer_id')->unsigned();
$table->string('locale')->index();
$table->boolean('complete');
// Translated content
$table->string('name');
$table->text('content');
$table->timestamps();
// Unique and foreign key
// When deleting designer model, also delete all translation models
$table->unique(['designer_id','locale']);
$table->foreign('designer_id')->references('id')->on('designer')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('designer_translation');
Schema::drop('designer');
}
}
|
Correct syntax while creating indexes
Change-Id: I90625647d8723531dbc7498d5d25e84ef1a3ed2b
Reviewed-on: http://review.couchbase.org/50007
Tested-by: buildbot <[email protected]>
Reviewed-by: Michael Wiederhold <[email protected]> | INDEX_STATEMENTS = {
'basic': (
'CREATE INDEX by_city ON `{}` (city.f.f)',
'CREATE INDEX by_county ON `{}` (county.f.f)',
'CREATE INDEX by_realm ON `{}` (`realm.f`)',
),
'range': (
'CREATE INDEX by_coins ON `{}` (coins.f)',
'CREATE INDEX by_achievement ON `{}` (achievements)',
'CREATE INDEX by_category ON `{}` (category)',
'CREATE INDEX by_year ON `{}` (year)',
),
'multi_emits': (
'CREATE INDEX by_city ON `{}` (city.f.f)',
'CREATE INDEX by_county ON `{}` (county.f.f)',
'CREATE INDEX by_country ON `{}` (country.f)',
),
'body': (
'CREATE INDEX by_city ON `{}` (city.f.f)',
'CREATE INDEX by_realm ON `{}` (`realm.f`)',
'CREATE INDEX by_country ON `{}` (country.f)',
),
'group_by': (
'CREATE INDEX by_state ON `{}` (state.f)',
'CREATE INDEX by_year ON `{}` (year)',
'CREATE INDEX by_gmtime ON `{}` (gmtime)',
'CREATE INDEX by_full_state ON `{}` (full_state.f)',
),
'distinct': (
'CREATE INDEX by_state ON `{}` (state.f)',
'CREATE INDEX by_year ON `{}` (year)',
'CREATE INDEX by_full_state ON `{}` (full_state.f)',
),
}
| INDEX_STATEMENTS = {
'basic': (
'CREATE INDEX by_city ON {}(city.f.f)',
'CREATE INDEX by_county ON {}(county.f.f)',
'CREATE INDEX by_realm ON {}(realm.f)',
),
'range': (
'CREATE INDEX by_coins ON {}(coins.f)',
'CREATE INDEX by_achievement ON {}(achievements)',
'CREATE INDEX by_category ON {}(category)',
'CREATE INDEX by_year ON {}(year)',
),
'multi_emits': (
'CREATE INDEX by_city ON {}(city.f.f)',
'CREATE INDEX by_county ON {}(county.f.f)',
'CREATE INDEX by_country ON {}(country.f)',
),
'body': (
'CREATE INDEX by_city ON {}(city.f.f)',
'CREATE INDEX by_realm ON {}(realm.f)',
'CREATE INDEX by_country ON {}(country.f)',
),
'group_by': (
'CREATE INDEX by_state ON {}(state.f)',
'CREATE INDEX by_year ON {}(year)',
'CREATE INDEX by_gmtime ON {}(gmtime)',
'CREATE INDEX by_full_state ON {}(full_state.f)',
),
'distinct': (
'CREATE INDEX by_state ON {}(state.f)',
'CREATE INDEX by_year ON {}(year)',
'CREATE INDEX by_full_state ON {}(full_state.f)',
),
}
|
Fix Django version in requirements
Current version of requirements in setup.py doesn't work well with (pip-compile)[https://github.com/nvie/pip-tools/] (concrete problem is discussed (here) [https://github.com/nvie/pip-tools/issues/323]). This commit changes `<=1.9` to `<1.10`. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
readme = open('README.md').read()
history = open('HISTORY.md').read().replace('.. :changelog:', '')
requirements = [
'Django<1.10',
]
test_requirements = [
'nose>=1.3,<2',
'factory_boy>=2.4,<3.0',
'fake-factory>=0.4.0,<1',
'nosexcover>=1.0.8, <2',
'ipdb',
'mock',
]
setup(
name='django-cache-manager',
version='0.4',
description='Cache manager for django models',
long_description=readme + '\n\n' + history,
author='Vijay Katam',
url='https://github.com/vijaykatam/django-cache-manager',
packages=find_packages(exclude=('tests',)),
package_dir={'django_cache_manager':
'django_cache_manager'},
include_package_data=True,
install_requires=requirements,
zip_safe=False,
keywords='django-cache-manager',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
],
test_suite='nose.collector',
tests_require=test_requirements,
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
readme = open('README.md').read()
history = open('HISTORY.md').read().replace('.. :changelog:', '')
requirements = [
'Django<=1.9',
]
test_requirements = [
'nose>=1.3,<2',
'factory_boy>=2.4,<3.0',
'fake-factory>=0.4.0,<1',
'nosexcover>=1.0.8, <2',
'ipdb',
'mock',
]
setup(
name='django-cache-manager',
version='0.4',
description='Cache manager for django models',
long_description=readme + '\n\n' + history,
author='Vijay Katam',
url='https://github.com/vijaykatam/django-cache-manager',
packages=find_packages(exclude=('tests',)),
package_dir={'django_cache_manager':
'django_cache_manager'},
include_package_data=True,
install_requires=requirements,
zip_safe=False,
keywords='django-cache-manager',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
],
test_suite='nose.collector',
tests_require=test_requirements,
)
|
Check if ga is a function | /* eslint-disable */
import Vue from 'vue';
import Router from 'vue-router';
import Component from './Component';
import Docs from './Docs';
import DocsPage from './DocsPage';
import Layouts from './Layouts';
import Theming from './Layouts/Theming';
import QuickStart from '../README.md';
import Contributing from '../CONTRIBUTING.md';
Vue.use(Router);
const router = new Router({
routes: [
{
path: '/layouts/theming',
component: Theming,
},
{
path: '/',
component: Docs,
children: [
{
path: '/',
component: DocsPage,
props: { markdown: QuickStart },
},
{
path: '/contributing',
component: DocsPage,
props: { markdown: Contributing },
},
{
path: '/layouts',
component: Layouts,
},
{
path: '/:type/:componentName',
component: Component,
props: true,
},
],
},
],
linkExactActiveClass: 'active',
});
router.afterEach((to) => {
if (typeof ga === 'function') {
ga('set', 'page', to.path);
ga('send', 'pageview');
}
if (to.hash) {
const el = document.getElementById(to.hash.substr(1));
if (el) el.scrollIntoView();
}
});
export default router;
| /* eslint-disable */
import Vue from 'vue';
import Router from 'vue-router';
import Component from './Component';
import Docs from './Docs';
import DocsPage from './DocsPage';
import Layouts from './Layouts';
import Theming from './Layouts/Theming';
import QuickStart from '../README.md';
import Contributing from '../CONTRIBUTING.md';
Vue.use(Router);
const router = new Router({
routes: [
{
path: '/layouts/theming',
component: Theming,
},
{
path: '/',
component: Docs,
children: [
{
path: '/',
component: DocsPage,
props: { markdown: QuickStart },
},
{
path: '/contributing',
component: DocsPage,
props: { markdown: Contributing },
},
{
path: '/layouts',
component: Layouts,
},
{
path: '/:type/:componentName',
component: Component,
props: true,
},
],
},
],
linkExactActiveClass: 'active',
});
router.afterEach((to) => {
ga('set', 'page', to.path);
ga('send', 'pageview');
if (to.hash) {
const el = document.getElementById(to.hash.substr(1));
if (el) el.scrollIntoView();
}
});
export default router;
|
Add eslint error if console is used | module.exports = {
env: {
node: true,
mocha: true,
es6: true
},
extends: 'react-app',
parserOptions: {
ecmaFeature: {
jsx: true
}
},
plugins: ['react', 'jsx-a11y', 'import'],
rules: {
indent: ['error', 4, { SwitchCase: 1 }],
'func-names': 'off',
'no-underscore-dangle': 'off',
'import/no-unresolved': ['error', { ignore: ['react'] }],
'comma-dangle': ['error', 'never'],
'no-plusplus': 'off',
'import/no-extraneous-dependencies': ['error', { devDependencies: true }],
'no-param-reassign': ['error', { props: false }],
'new-cap': ['error', { capIsNew: false }],
'no-mixed-operators': [
'error',
{
allowSamePrecedence: true
}
],
'object-curly-spacing': ['error', 'always'],
'arrow-parens': [
'error',
'as-needed',
{
requireForBlockBody: true
}
],
'max-len': [
'error',
{
code: 100
}
],
'space-before-function-paren': [
'error',
{
anonymous: 'always',
named: 'never',
asyncArrow: 'always'
}
],
quotes: ['error', 'single'],
'no-console': ['error']
}
};
| module.exports = {
env: {
node: true,
mocha: true,
es6: true
},
extends: 'react-app',
parserOptions: {
ecmaFeature: {
jsx: true
}
},
plugins: ['react', 'jsx-a11y', 'import'],
rules: {
indent: ['error', 4, { SwitchCase: 1 }],
'func-names': 'off',
'no-underscore-dangle': 'off',
'import/no-unresolved': ['error', { ignore: ['react'] }],
'comma-dangle': ['error', 'never'],
'no-plusplus': 'off',
'import/no-extraneous-dependencies': ['error', { devDependencies: true }],
'no-param-reassign': ['error', { props: false }],
'new-cap': ['error', { capIsNew: false }],
'no-mixed-operators': [
'error',
{
allowSamePrecedence: true
}
],
'object-curly-spacing': ['error', 'always'],
'arrow-parens': [
'error',
'as-needed',
{
requireForBlockBody: true
}
],
'max-len': [
'error',
{
code: 100
}
],
'space-before-function-paren': [
'error',
{
anonymous: 'always',
named: 'never',
asyncArrow: 'always'
}
],
quotes: ['error', 'single']
}
};
|
Update the timeline endpoint for instagram | <?php
namespace duncan3dc\OAuth;
use duncan3dc\Helpers\Helper;
use duncan3dc\Serial\Json;
class Instagram extends OAuth2
{
public function __construct(array $options)
{
$options = Helper::getOptions($options, [
"client" => "",
"secret" => "",
"username" => "",
]);
parent::__construct([
"type" => "instagram",
"client" => $options["client"],
"secret" => $options["secret"],
"username" => $options["username"],
"authoriseUrl" => "https://api.instagram.com/oauth/authorize",
"redirectUrl" => "https://api.instagram.com/oauth/redirect",
"accessUrl" => "https://api.instagram.com/oauth/access_token",
]);
}
public function timeline(array $options = null)
{
$options = Helper::getOptions($options, [
"min" => false,
"limit" => 200,
]);
$url = "https://api.instagram.com/v1/users/self/media/recent";
$params = [];
if ($val = $options["min"]) {
$params["min_id"] = $val;
}
if ($val = $options["limit"]) {
$params["count"] = $val;
}
return $this->fetch($url, $params);
}
}
| <?php
namespace duncan3dc\OAuth;
use duncan3dc\Helpers\Helper;
use duncan3dc\Serial\Json;
class Instagram extends OAuth2
{
public function __construct(array $options)
{
$options = Helper::getOptions($options, [
"client" => "",
"secret" => "",
"username" => "",
]);
parent::__construct([
"type" => "instagram",
"client" => $options["client"],
"secret" => $options["secret"],
"username" => $options["username"],
"authoriseUrl" => "https://api.instagram.com/oauth/authorize",
"redirectUrl" => "https://api.instagram.com/oauth/redirect",
"accessUrl" => "https://api.instagram.com/oauth/access_token",
]);
}
public function timeline(array $options = null)
{
$options = Helper::getOptions($options, [
"min" => false,
"limit" => 200,
]);
$url = "https://api.instagram.com/v1/users/self/feed";
$params = [];
if ($val = $options["min"]) {
$params["min_id"] = $val;
}
if ($val = $options["limit"]) {
$params["count"] = $val;
}
return $this->fetch($url, $params);
}
}
|
Add fallback for empty dependencies and devDependencies | 'use strict';
var github = require('./github');
var npm = require('./npm');
var db = require('./db');
var email = require('./email');
var _ = require('underscore');
var cache = {};
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
npm.getLatestPackages(yesterday, function(error, packages) {
if (error) {
return console.error(error);
}
cache = packages;
console.info('There are ' + cache.length + ' package updates.');
db.readSubscriptions(function(error, subscriptions) {
if (error) {
return console.error(error);
}
_.each(subscriptions, function(subscription) {
var user = github.getUserFromUrl(subscription.repourl);
var repo = github.getRepoFromUrl(subscription.repourl);
github.getPackageJson(user, repo, processPackageJson(subscription));
});
});
});
function processPackageJson(subscription) {
return function(error, json) {
if (error) {
return console.error(error);
}
var packages = _.filter(_.extend(json.dependencies || {}, json.devDependencies || {}), isPackageInCache);
_.each(packages, function(packageName) {
var cached = cache[packageName];
var versionRange = packages[packageName];
email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version);
});
};
}
function isPackageInCache(dependency) {
return !!cache[dependency];
}
| 'use strict';
var github = require('./github');
var npm = require('./npm');
var db = require('./db');
var email = require('./email');
var _ = require('underscore');
var cache = {};
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
npm.getLatestPackages(yesterday, function(error, packages) {
if (error) {
return console.error(error);
}
cache = packages;
console.info('There are ' + cache.length + ' package updates.');
db.readSubscriptions(function(error, subscriptions) {
if (error) {
return console.error(error);
}
_.each(subscriptions, function(subscription) {
var user = github.getUserFromUrl(subscription.repourl);
var repo = github.getRepoFromUrl(subscription.repourl);
github.getPackageJson(user, repo, processPackageJson(subscription));
});
});
});
function processPackageJson(subscription) {
return function(error, json) {
if (error) {
return console.error(error);
}
var packages = _.filter(_.extend(json.dependencies, json.devDependencies), isPackageInCache);
_.each(packages, function(packageName) {
var cached = cache[packageName];
var versionRange = packages[packageName];
email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version);
});
};
}
function isPackageInCache(dependency) {
return !!cache[dependency];
}
|
BAP-11412: Implement enable/disable operations
- CS Fix | <?php
namespace Oro\Bundle\TranslationBundle\Helper;
use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration;
use Oro\Bundle\TranslationBundle\Entity\Language;
class LanguageHelper
{
/** @var ConfigManager */
protected $configManager;
/**
* @param ConfigManager $configManager
*/
public function __construct(ConfigManager $configManager)
{
$this->configManager = $configManager;
}
/**
* @param Language $language
*/
public function updateSystemConfiguration(Language $language)
{
$languages = (array)$this->configManager->get($this->getConfigurationName(), true);
if ($language->isEnabled()) {
if (!in_array($language->getCode(), $languages, true)) {
$languages[] = $language->getCode();
}
} else {
if (false !== ($index = array_search($language->getCode(), $languages, true))) {
unset($languages[$index]);
}
}
$this->configManager->set($this->getConfigurationName(), $languages);
$this->configManager->flush();
}
/**
* @return string
*/
protected function getConfigurationName()
{
return Configuration::getConfigKeyByName(Configuration::LANGUAGES);
}
}
| <?php
namespace Oro\Bundle\TranslationBundle\Helper;
use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration;
use Oro\Bundle\TranslationBundle\Entity\Language;
class LanguageHelper
{
/** @var ConfigManager */
protected $configManager;
/**
* @param ConfigManager $configManager
*/
public function __construct(ConfigManager $configManager)
{
$this->configManager = $configManager;
}
/**
* @param Language $language
*/
public function updateSystemConfiguration(Language $language)
{
$languages = $this->configManager->get($this->getConfigurationName(), true);
if ($language->isEnabled()) {
if (!in_array($language->getCode(), $languages, true)) {
$languages[] = $language->getCode();
}
} else {
if (false !== ($index = array_search($language->getCode(), $languages, true))) {
unset($languages[$index]);
}
}
$this->configManager->set($this->getConfigurationName(), $languages);
$this->configManager->flush();
}
/**
* @return string
*/
protected function getConfigurationName()
{
return Configuration::getConfigKeyByName(Configuration::LANGUAGES);
}
}
|
Set debug level DEBUG in sample application | /*
* WireSpider
*
* Copyright (c) 2015 kazyx
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
package net.kazyx.wirespider.sampleapp;
import android.app.Application;
import android.util.Log;
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
net.kazyx.wirespider.Log.writer(new net.kazyx.wirespider.Log.Writer() {
@Override
public void v(String tag, String message) {
Log.v(tag, message);
}
@Override
public void d(String tag, String message) {
Log.d(tag, message);
}
@Override
public void e(String tag, String message) {
Log.e(tag, message);
}
@Override
public void printStackTrace(String tag, Throwable th) {
Log.wtf(tag, th);
}
});
net.kazyx.wirespider.Log.logLevel(net.kazyx.wirespider.Log.Level.DEBUG);
}
}
| /*
* WireSpider
*
* Copyright (c) 2015 kazyx
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
package net.kazyx.wirespider.sampleapp;
import android.app.Application;
import android.util.Log;
public class SampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
net.kazyx.wirespider.Log.writer(new net.kazyx.wirespider.Log.Writer() {
@Override
public void v(String tag, String message) {
Log.v(tag, message);
}
@Override
public void d(String tag, String message) {
Log.d(tag, message);
}
@Override
public void e(String tag, String message) {
Log.e(tag, message);
}
@Override
public void printStackTrace(String tag, Throwable th) {
Log.wtf(tag, th);
}
});
net.kazyx.wirespider.Log.logLevel(net.kazyx.wirespider.Log.Level.VERBOSE);
}
}
|
Change long description to URL. | import os, sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def main():
setup(
name='stcrestclient',
version= '1.0.2',
author='Andrew Gillis',
author_email='[email protected]',
url='https://github.com/ajgillis/py-stcrestclient',
description='stcrestclient: Client modules for STC ReST API',
long_description = 'See https://github.com/ajgillis/py-stcrestclient#python-stc-rest-api-client-stcrestclient',
license='http://www.opensource.org/licenses/mit-license.php',
platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'],
keywords='Spirent TestCenter API',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3'],
packages=['stcrestclient'],
zip_safe=True,
)
if __name__ == '__main__':
main()
| import os, sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def main():
setup(
name='stcrestclient',
version= '1.0.2',
author='Andrew Gillis',
author_email='[email protected]',
url='https://github.com/ajgillis/py-stcrestclient',
description='stcrestclient: Client modules for STC ReST API',
long_description = open('README.md').read(),
license='http://www.opensource.org/licenses/mit-license.php',
platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'],
keywords='Spirent TestCenter API',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3'],
packages=['stcrestclient'],
zip_safe=True,
)
if __name__ == '__main__':
main()
|
Update thread query cache logic
- Move TTL to class constant
- Cast count to string instead of serializing | <?php
class SV_WordCountSearch_XenForo_Model_Thread extends XFCP_SV_WordCountSearch_XenForo_Model_Thread
{
/**
* The TTL for cached thread word count queries. Default is 4 hours.
*/
const WORD_COUNT_CACHE_TTL = 14400;
public function getThreadmarkWordCountByThread($threadId)
{
$cache = \XenForo_Application::getCache();
if ($cache)
{
$cacheKey = "SV_WordCountSearch_threadmarks_thread{$threadId}";
$wordCount = unserialize($cache->load($cacheKey));
if ($wordCount)
{
return $wordCount;
}
}
$posts = $this->_getDb()->fetchAll("
SELECT post_words.word_count
FROM threadmarks
INNER JOIN xf_post_words AS post_words ON
(post_words.post_id = threadmarks.post_id)
WHERE threadmarks.thread_id = ?
AND threadmarks.message_state = 'visible'
", $threadId);
$wordCount = 0;
foreach ($posts as $post)
{
$wordCount += $post['word_count'];
}
if ($cache)
{
$cache->save(
(string) $wordCount,
$cacheKey,
array(),
self::WORD_COUNT_CACHE_TTL
);
}
return $wordCount;
}
}
| <?php
class SV_WordCountSearch_XenForo_Model_Thread extends XFCP_SV_WordCountSearch_XenForo_Model_Thread
{
public function getThreadmarkWordCountByThread($threadId)
{
$cache = \XenForo_Application::getCache();
if ($cache)
{
$cacheKey = "SV_WordCountSearch_threadmarks_thread{$threadId}";
$wordCount = unserialize($cache->load($cacheKey));
if ($wordCount)
{
return $wordCount;
}
}
$posts = $this->_getDb()->fetchAll("
SELECT post_words.word_count
FROM threadmarks
INNER JOIN xf_post_words AS post_words ON
(post_words.post_id = threadmarks.post_id)
WHERE threadmarks.thread_id = ?
AND threadmarks.message_state = 'visible'
", $threadId);
$wordCount = 0;
foreach ($posts as $post)
{
$wordCount += $post['word_count'];
}
if ($cache)
{
$cache->save(serialize($wordCount), $cacheKey, array(), 14400);
}
return $wordCount;
}
}
|
Update Poll test to check members. | import unittest
from pollster.pollster import Pollster, Chart
class TestBasic(unittest.TestCase):
def test_basic_setup(self):
p = Pollster()
self.assertIsNotNone(p)
def test_charts(self):
c = Pollster().charts()
self.assertIsNotNone(c)
self.assertIsInstance(c, list)
self.assertGreater(len(c), 0)
def test_chart(self):
c = Pollster().charts()[0]
self.assertIsInstance(c, Chart)
cc = Pollster().chart(c.slug)
self.assertEqual(c.slug, cc.slug)
for attr in ['last_updated',
'title',
'url',
'estimates',
'poll_count',
'topic',
'state',
'slug', ]:
self.assertIsNotNone(getattr(c, attr))
self.assertIsNotNone(getattr(cc, attr))
self.assertEqual(getattr(c, attr), getattr(cc, attr))
self.assertIsInstance(c.estimates_by_date(), list)
def test_polls(self):
polls = Pollster().polls(topic='2016-president')
self.assertGreater(len(polls), 0)
poll = polls[0]
for attr in ['id',
'pollster',
'start_date',
'end_date',
'method',
'source',
'questions',
'survey_houses',
'sponsors',
'partisan',
'affiliation']:
self.assertIsNotNone(getattr(poll, attr))
| import unittest
from pollster.pollster import Pollster, Chart
class TestBasic(unittest.TestCase):
def test_basic_setup(self):
p = Pollster()
self.assertIsNotNone(p)
def test_charts(self):
c = Pollster().charts()
self.assertIsNotNone(c)
self.assertIsInstance(c, list)
self.assertGreater(len(c), 0)
def test_chart(self):
c = Pollster().charts()[0]
self.assertIsInstance(c, Chart)
cc = Pollster().chart(c.slug)
self.assertEqual(c.slug, cc.slug)
for attr in ['last_updated',
'title',
'url',
'estimates',
'poll_count',
'topic',
'state',
'slug', ]:
self.assertIsNotNone(getattr(c, attr))
self.assertIsNotNone(getattr(cc, attr))
self.assertEqual(getattr(c, attr), getattr(cc, attr))
self.assertIsInstance(c.estimates_by_date(), list)
def test_polls(self):
polls = Pollster().polls(topic='2016-president')
self.assertGreater(len(polls), 0)
|
Add moons admin link to global navigation. | <div class="user">
<img src="{{ $user->avatar }}" class="avatar" alt="{{ $user->name }}">
<div class="user-name">{{ $user->name }}</div>
<a href="/logout">Logout</a>
</div>
<ul>
<li>
<a href="/">
<i class="icon-home"></i>
Home
</a>
</li>
<li>
<a href="/miners">
<i class="icon-users"></i>
Miners
</a>
</li>
<li>
<a href="/moonadmin">
<i class="icon-">☽</i>
Moons
</a>
</li>
<li>
<a href="/renters">
<i class="icon-rocket"></i>
Renters
</a>
</li>
<li>
<a href="/reports">
<i class="icon-stats-dots"></i>
Reports
</a>
</li>
<li>
<a href="/timers">
<i class="icon-calendar"></i>
Timers
</a>
</li>
<li>
<a href="/taxes">
<i class="icon-coin-dollar"></i>
Taxes
</a>
</li>
<li>
<a href="/emails">
<i class="icon-envelop"></i>
Manage Emails
</a>
</li>
<li>
<a href="/access">
<i class="icon-cog"></i>
Settings
</a>
</li>
</ul>
| <div class="user">
<img src="{{ $user->avatar }}" class="avatar" alt="{{ $user->name }}">
<div class="user-name">{{ $user->name }}</div>
<a href="/logout">Logout</a>
</div>
<ul>
<li>
<a href="/">
<i class="icon-home"></i>
Home
</a>
</li>
<li>
<a href="/miners">
<i class="icon-users"></i>
Miners
</a>
</li>
<li>
<a href="/renters">
<i class="icon-rocket"></i>
Renters
</a>
</li>
<li>
<a href="/reports">
<i class="icon-stats-dots"></i>
Reports
</a>
</li>
<li>
<a href="/timers">
<i class="icon-calendar"></i>
Timers
</a>
</li>
<li>
<a href="/taxes">
<i class="icon-coin-dollar"></i>
Taxes
</a>
</li>
<li>
<a href="/emails">
<i class="icon-envelop"></i>
Manage Emails
</a>
</li>
<li>
<a href="/access">
<i class="icon-cog"></i>
Settings
</a>
</li>
</ul>
|
CRM-1322: Add mapping settings entity
- remove unused constant | <?php
namespace Oro\Bundle\IntegrationBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
class IntegrationConfiguration implements ConfigurationInterface
{
const ROOT_NODE_NAME = 'oro_integration';
const FORM_NODE_NAME = 'form';
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root(self::ROOT_NODE_NAME);
$root
->children()
->append($this->getFormTree())
->end();
return $treeBuilder;
}
/**
* @return ArrayNodeDefinition
*/
protected function getFormTree()
{
$builder = new TreeBuilder();
$node = $builder->root(self::FORM_NODE_NAME)
->useAttributeAsKey('name')
->prototype('array')
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('type')->isRequired()->end()
->arrayNode('options')
->prototype('variable')->end()
->end()
->integerNode('priority')->end()
->arrayNode('applicable')
->beforeNormalization()
->ifString()
->then(
function ($v) {
return [$v];
}
)
->end()
->prototype('scalar')
->cannotBeEmpty()
->end()
->end()
->end()
->end()
->end();
return $node;
}
}
| <?php
namespace Oro\Bundle\IntegrationBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
class IntegrationConfiguration implements ConfigurationInterface
{
const ROOT_NODE_NAME = 'oro_integration';
const SYNC_SETTING_ROOT_NODE = 'synchronization_settings';
const FORM_NODE_NAME = 'form';
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root(self::ROOT_NODE_NAME);
$root
->children()
->append($this->getFormTree())
->end();
return $treeBuilder;
}
/**
* @return ArrayNodeDefinition
*/
protected function getFormTree()
{
$builder = new TreeBuilder();
$node = $builder->root(self::FORM_NODE_NAME)
->useAttributeAsKey('name')
->prototype('array')
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('type')->isRequired()->end()
->arrayNode('options')
->prototype('variable')->end()
->end()
->integerNode('priority')->end()
->arrayNode('applicable')
->beforeNormalization()
->ifString()
->then(
function ($v) {
return [$v];
}
)
->end()
->prototype('scalar')
->cannotBeEmpty()
->end()
->end()
->end()
->end()
->end();
return $node;
}
}
|
Fix non existing useragents shortcut | import os
import random
try:
import json
except ImportError:
import simplejson as json
from fake_useragent import settings
from fake_useragent.build import build_db
class UserAgent(object):
def __init__(self):
super(UserAgent, self).__init__()
# check db json file exists
if not os.path.isfile(settings.DB):
build_db()
# no codecs\with for python 2.5
f = open(settings.DB, 'r')
self.data = json.loads(f.read())
f.close()
def __getattr__(self, attr):
attr = attr.replace(' ', '').replace('_', '').lower()
if attr == 'random':
attr = self.data['randomize'][
str(random.randint(0, self.data['max_random'] - 1))
]
elif attr == 'ie':
attr = 'internetexplorer'
elif attr == 'msie':
attr = 'internetexplorer'
elif attr == 'google':
attr = 'chrome'
elif attr == 'ff':
attr = 'firefox'
try:
return self.data['browsers'][attr][
random.randint(0, settings.BROWSERS_COUNT_LIMIT - 1)
]
except KeyError:
return None
| import os
import random
try:
import json
except ImportError:
import simplejson as json
from fake_useragent import settings
from fake_useragent.build import build_db
class UserAgent(object):
def __init__(self):
super(UserAgent, self).__init__()
# check db json file exists
if not os.path.isfile(settings.DB):
build_db()
# no codecs\with for python 2.5
f = open(settings.DB, 'r')
self.data = json.loads(f.read())
f.close()
def __getattr__(self, attr):
attr = attr.replace(' ', '').replace('_', '').lower()
if attr == 'random':
attr = self.data['randomize'][
str(random.randint(0, self.data['max_random'] - 1))
]
elif attr == 'ie':
attr = 'internetexplorer'
elif attr == 'msie':
attr = 'internetexplorer'
elif attr == 'google':
attr = 'chrome'
elif attr == 'ff':
attr = 'firefox'
return self.data['browsers'][attr][
random.randint(0, settings.BROWSERS_COUNT_LIMIT - 1)
]
|
Make the profile link inactive when needed. | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ trans('messages.project-name') }}</title>
<style>
body {
padding-top: 80px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.2/slate/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/admin/dashboard">
{{ trans('messages.project-name') }}
</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href="/">{{ trans('messages.back-to-site') }}</a></li>
@if (Request::path() == 'admin/profile')
<li class="active"><a href="#">{{ trans('messages.profile') }}</a></li>
@else
<li><a href="/admin/profile">{{ trans('messages.profile') }}</a></li>
@endif
<li><a href="/admin/logout">{{ trans('messages.logout') }}</a></li>
</ul>
</div>
</nav>
<div class="container">
@yield('body')
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ trans('messages.project-name') }}</title>
<style>
body {
padding-top: 80px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.2/slate/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/admin/dashboard">
{{ trans('messages.project-name') }}
</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href="/">{{ trans('messages.back-to-site') }}</a></li>
<li><a href="/admin/profile">{{ trans('messages.profile') }}</a></li>
<li><a href="/admin/logout">{{ trans('messages.logout') }}</a></li>
</ul>
</div>
</nav>
<div class="container">
@yield('body')
</div>
</body>
</html>
|
Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <[email protected]>
Reviewed-by: Pavel Paulau <[email protected]> | from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
| from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
|
Use SG slug for event filtering | from django_filters import FilterSet, CharFilter, IsoDateTimeFilter, BooleanFilter, ModelChoiceFilter
from falmer.events.models import Curator
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
'student_group',
'from_time',
'to_time',
'audience_just_for_pgs',
'audience_suitable_kids_families',
'audience_good_to_meet_people',
'is_over_18_only',
'cost',
'alcohol',
'type',
'ticket_level',
'curated_by'
)
title = CharFilter(lookup_expr='icontains')
brand = CharFilter(field_name='brand__slug')
bundle = CharFilter(field_name='bundle__slug')
student_group = CharFilter(field_name='student_group__slug')
to_time = IsoDateTimeFilter(field_name='start_time', lookup_expr='lte')
from_time = IsoDateTimeFilter(field_name='end_time', lookup_expr='gte')
uncurated = BooleanFilter(field_name='curated_by', lookup_expr='isnull')
curated_by = ModelChoiceFilter(queryset=Curator.objects.all(), field_name='curated_by')
#
# class BrandingPeriodFilerSet(FilterSet):
# class Meta:
# model = BrandingPeriod
| from django_filters import FilterSet, CharFilter, IsoDateTimeFilter, BooleanFilter, ModelChoiceFilter
from falmer.events.models import Curator
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
'student_group',
'from_time',
'to_time',
'audience_just_for_pgs',
'audience_suitable_kids_families',
'audience_good_to_meet_people',
'is_over_18_only',
'cost',
'alcohol',
'type',
'ticket_level',
'curated_by'
)
title = CharFilter(lookup_expr='icontains')
brand = CharFilter(field_name='brand__slug')
bundle = CharFilter(field_name='bundle__slug')
to_time = IsoDateTimeFilter(field_name='start_time', lookup_expr='lte')
from_time = IsoDateTimeFilter(field_name='end_time', lookup_expr='gte')
uncurated = BooleanFilter(field_name='curated_by', lookup_expr='isnull')
curated_by = ModelChoiceFilter(queryset=Curator.objects.all(), field_name='curated_by')
#
# class BrandingPeriodFilerSet(FilterSet):
# class Meta:
# model = BrandingPeriod
|
Use react key list container | 'use strict'
import 'normalize.css'
import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import '../fonts/work-sans/WorkSans.css!'
import '../styles/felony.css!'
import colors from '../styles/variables/colors'
import EncryptKeyListContainer from '../containers/EncryptKeyListContainer'
import FloatingButtonToggle from './floating-button/FloatingButtonToggle'
import Header from './header/Header'
export class Felony extends Component {
classes() {
return {
'default': {
app: {
absolute: '0 0 0 0',
background: colors.bgLight,
},
header: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
},
encryptKeyList: {
position: 'fixed',
top: 78,
left: 0,
right: 0,
bottom: 0,
overflowY: 'scroll', // TODO: elastic scroll
},
},
}
}
render() {
return (
<div is="app">
<div is="header">
<Header />
</div>
<div is="encryptKeyList">
<EncryptKeyListContainer />
</div>
<FloatingButtonToggle />
</div>
)
}
}
export default ReactCSS(Felony)
| 'use strict';
import React, { Component } from 'react';
import ReactCSS from 'reactcss';
import colors from '../styles/variables/colors';
import 'normalize.css';
import '../fonts/work-sans/WorkSans.css!';
import '../styles/felony.css!';
import Header from './header/Header';
import EncryptKeyList from './encrypt/EncryptKeyList';
import FloatingButtonToggle from './floating-button/FloatingButtonToggle';
export class Felony extends Component {
classes() {
return {
'default': {
app: {
Absolute: '0 0 0 0',
background: colors.bgLight,
},
header: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
},
encryptKeyList: {
position: 'fixed',
top: 78,
left: 0,
right: 0,
bottom: 0,
overflowY: 'scroll', // TODO: elastic scroll
},
},
};
}
render() {
return (
<div is="app">
<div is="header">
<Header />
</div>
<div is="encryptKeyList">
<EncryptKeyList />
</div>
<FloatingButtonToggle />
</div>
);
}
}
export default ReactCSS(Felony);
|
Use a more specific event selector in SelectDatasetView | import View from '../view';
import SelectDatasetPageTemplate from './selectDatasetPage.pug';
// View for a collection of datasets in a select tag. When user selects a
// dataset, a 'changed' event is triggered with the selected dataset as a
// parameter.
const SelectDatasetView = View.extend({
events: {
'change #isic-select-dataset-select': 'datasetChanged'
},
/**
* @param {DatasetCollection} settings.collection
*/
initialize: function (settings) {
this.listenTo(this.collection, 'reset', this.render);
this.render();
},
datasetChanged: function () {
const datasetId = this.$('select').val();
const dataset = this.collection.get(datasetId);
dataset.fetch()
.done(() => {
this.trigger('changed', dataset);
});
},
render: function () {
// Destroy previous select2
let select = this.$('#isic-select-dataset-select');
select.select2('destroy');
this.$el.html(SelectDatasetPageTemplate({
models: this.collection.toArray()
}));
// Set up select box
let placeholder = 'Select a dataset...';
if (!this.collection.isEmpty()) {
placeholder += ` (${this.collection.length} available)`;
}
select = this.$('#isic-select-dataset-select');
select.select2({
placeholder: placeholder,
dropdownParent: this.$el
});
select.focus();
return this;
}
});
export default SelectDatasetView;
| import View from '../view';
import SelectDatasetPageTemplate from './selectDatasetPage.pug';
// View for a collection of datasets in a select tag. When user selects a
// dataset, a 'changed' event is triggered with the selected dataset as a
// parameter.
const SelectDatasetView = View.extend({
events: {
'change': 'datasetChanged'
},
/**
* @param {DatasetCollection} settings.collection
*/
initialize: function (settings) {
this.listenTo(this.collection, 'reset', this.render);
this.render();
},
datasetChanged: function () {
const datasetId = this.$('select').val();
const dataset = this.collection.get(datasetId);
dataset.fetch()
.done(() => {
this.trigger('changed', dataset);
});
},
render: function () {
// Destroy previous select2
let select = this.$('#isic-select-dataset-select');
select.select2('destroy');
this.$el.html(SelectDatasetPageTemplate({
models: this.collection.toArray()
}));
// Set up select box
let placeholder = 'Select a dataset...';
if (!this.collection.isEmpty()) {
placeholder += ` (${this.collection.length} available)`;
}
select = this.$('#isic-select-dataset-select');
select.select2({
placeholder: placeholder,
dropdownParent: this.$el
});
select.focus();
return this;
}
});
export default SelectDatasetView;
|
Update question about computer access | from django import forms
from studygroups.models import Application
from studygroups.models import Reminder
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
def clean(self):
cleaned_data = super(ApplicationForm, self).clean()
contact_method = cleaned_data.get("contact_method")
if contact_method == Application.EMAIL and not cleaned_data.get('email'):
self.add_error('email', "Please enter your email address or change your preferred contact method.")
elif contact_method == Application.TEXT and not cleaned_data.get('mobile'):
self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.")
class Meta:
model = Application
labels = {
'mobile': 'What is your mobile number?',
'contact_method': 'Preferred Method of Contact.',
'computer_access': 'Can you bring your own laptop to the Learning Circle?',
'goals': 'In one sentence, please explain your goals for taking this course.',
'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?',
}
exclude = ['accepted_at']
widgets = {'study_group': forms.HiddenInput}
class MessageForm(forms.ModelForm):
class Meta:
model = Reminder
exclude = ['meeting_time', 'created_at', 'sent_at']
widgets = {'study_group': forms.HiddenInput}
| from django import forms
from studygroups.models import Application
from studygroups.models import Reminder
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
def clean(self):
cleaned_data = super(ApplicationForm, self).clean()
contact_method = cleaned_data.get("contact_method")
if contact_method == Application.EMAIL and not cleaned_data.get('email'):
self.add_error('email', "Please enter your email address or change your preferred contact method.")
elif contact_method == Application.TEXT and not cleaned_data.get('mobile'):
self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.")
class Meta:
model = Application
labels = {
'mobile': 'What is your mobile number?',
'contact_method': 'Preferred Method of Contact.',
'computer_access': 'Do you have access to a computer outside of the library?',
'goals': 'In one sentence, please explain your goals for taking this course.',
'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?',
}
exclude = ['accepted_at']
widgets = {'study_group': forms.HiddenInput}
class MessageForm(forms.ModelForm):
class Meta:
model = Reminder
exclude = ['meeting_time', 'created_at', 'sent_at']
widgets = {'study_group': forms.HiddenInput}
|
Move @private to the end of the jsdoc | /*global define*/
define([], function() {
"use strict";
/**
* Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
* a dictionary.
*
* @exports parseResponseHeaders
*
* @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
* described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
* @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
* is that header's value.
*
* @private
*/
var parseResponseHeaders = function(headerString) {
var headers = {};
if (!headerString) {
return headers;
}
var headerPairs = headerString.split('\u000d\u000a');
for (var i = 0; i < headerPairs.length; ++i) {
var headerPair = headerPairs[i];
// Can't use split() here because it does the wrong thing
// if the header value has the string ": " in it.
var index = headerPair.indexOf('\u003a\u0020');
if (index > 0) {
var key = headerPair.substring(0, index);
var val = headerPair.substring(index + 2);
headers[key] = val;
}
}
return headers;
};
return parseResponseHeaders;
});
| /*global define*/
define([], function() {
"use strict";
/**
* @private
*
* Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
* a dictionary.
*
* @exports parseResponseHeaders
*
* @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
* described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
* @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
* is that header's value.
*/
var parseResponseHeaders = function(headerString) {
var headers = {};
if (!headerString) {
return headers;
}
var headerPairs = headerString.split('\u000d\u000a');
for (var i = 0; i < headerPairs.length; ++i) {
var headerPair = headerPairs[i];
// Can't use split() here because it does the wrong thing
// if the header value has the string ": " in it.
var index = headerPair.indexOf('\u003a\u0020');
if (index > 0) {
var key = headerPair.substring(0, index);
var val = headerPair.substring(index + 2);
headers[key] = val;
}
}
return headers;
};
return parseResponseHeaders;
}); |
Set the docs no matter if we run the test on this platform or not | #!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from users import UsersCollector
import sys
################################################################################
class TestUsersCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('UsersCollector', {
'utmp': self.getFixturePath('utmp.centos6'),
})
self.collector = UsersCollector(config, None)
@patch.object(Collector, 'publish')
def test_should_work_with_real_data(self, publish_mock):
metrics = {
'kormoc': 2,
'root': 3,
'total': 5,
}
self.setDocExample(self.collector.__class__.__name__, metrics)
# Because of the compiled nature of pyutmp, we can't actually test
# different operating system versions then the currently running
# one
if sys.platform.startswith('linux'):
self.collector.collect()
self.assertPublishedMany(publish_mock, metrics)
################################################################################
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from users import UsersCollector
import sys
################################################################################
class TestUsersCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('UsersCollector', {
'utmp': self.getFixturePath('utmp.centos6'),
})
self.collector = UsersCollector(config, None)
@patch.object(Collector, 'publish')
def test_should_work_with_real_data(self, publish_mock):
# Because of the compiled nature of pyutmp, we can't actually test
# different operating system versions then the currently running
# one
if sys.platform.startswith('linux'):
self.collector.collect()
metrics = {
'kormoc': 2,
'root': 3,
'total': 5,
}
self.setDocExample(self.collector.__class__.__name__, metrics)
self.assertPublishedMany(publish_mock, metrics)
################################################################################
if __name__ == "__main__":
unittest.main()
|
Change error message text for invite friends page. | /* global graphql */
import React from 'react'
import {QueryRenderer} from 'react-relay/compat'
import environment from '../../../../relay-env'
import ProfileInviteFriend from './ProfileInviteFriendContainer'
import FullScreenProgress from 'general/FullScreenProgress'
import AuthUserComponent from 'general/AuthUserComponent'
import ErrorMessage from 'general/ErrorMessage'
class ProfileInviteFriendView extends React.Component {
render () {
return (
<AuthUserComponent>
<QueryRenderer
environment={environment}
query={graphql`
query ProfileInviteFriendViewQuery($userId: String!) {
user(userId: $userId) {
...ProfileInviteFriendContainer_user
}
}
`}
render={({error, props}) => {
if (error) {
console.error(error, error.source)
const errMsg = 'We had a problem loading this page :('
return <ErrorMessage message={errMsg} />
}
if (props) {
const showError = this.props.showError
return (
<ProfileInviteFriend
user={props.user}
showError={showError} />
)
} else {
return (<FullScreenProgress />)
}
}} />
</AuthUserComponent>
)
}
}
export default ProfileInviteFriendView
| /* global graphql */
import React from 'react'
import {QueryRenderer} from 'react-relay/compat'
import environment from '../../../../relay-env'
import ProfileInviteFriend from './ProfileInviteFriendContainer'
import FullScreenProgress from 'general/FullScreenProgress'
import AuthUserComponent from 'general/AuthUserComponent'
import ErrorMessage from 'general/ErrorMessage'
class ProfileInviteFriendView extends React.Component {
render () {
return (
<AuthUserComponent>
<QueryRenderer
environment={environment}
query={graphql`
query ProfileInviteFriendViewQuery($userId: String!) {
user(userId: $userId) {
...ProfileInviteFriendContainer_user
}
}
`}
render={({error, props}) => {
if (error) {
console.error(error, error.source)
const errMsg = 'We had a problem loading your stats :('
return <ErrorMessage message={errMsg} />
}
if (props) {
const showError = this.props.showError
return (
<ProfileInviteFriend
user={props.user}
showError={showError} />
)
} else {
return (<FullScreenProgress />)
}
}} />
</AuthUserComponent>
)
}
}
export default ProfileInviteFriendView
|
Add domain detect and show bold font of domain | define(function (require) {
'use strict';
var store = require('store');
var items = new Vue({
el: 'body',
data: {
items: [],
domains: store.fetch(),
domain: ''
},
ready: function () {
var timer,
that = this;
this.$watch('domains', function (domains) {
store.save(domains);
});
this.$watch('domain', function (value) {
that.items = [];
for (var i = 0; i < that.domains.length && value; i++) {
if (that.domains[i].name.indexOf(value) === 0) {
that.items.push(that.domains[i]);
}
}
});
},
methods: {
onRemove: function (item) {
this.domains.$remove(item.$data);
this.domain = '';
},
onHandle: function (e) {
var data,
value = this.domain.trim();
function parse(input) {
var regex = /((?:https?:\/\/)?(?:[^\.]*\.)*?)([^\.]*\.\w+)(\/.*)?$/;
return input.replace(regex, function (match, p1, p2, p3) {
p1 = p1 || '';
p2 = p2 || '';
p3 = p3 || '';
return p1 + p2.bold() + p3;
});
}
if (e.keyCode === 13) {
this.domains.push({
name: value,
active: true
});
this.domain = '';
} else if (e.keyCode === 27) {
this.domain = value = '';
} else {
//this.domain = parse(value);
}
},
domainFilter: function (self) {
return self.name.indexOf(this.domain) === 0;
}
}
});
});
| define(function (require) {
'use strict';
var store = require('store');
var items = new Vue({
el: 'body',
data: {
items: [],
domains: store.fetch(),
domain: ''
},
ready: function () {
var timer,
that = this;
this.$watch('domains', function (domains) {
store.save(domains);
});
this.$watch('domain', function (value) {
that.items = [];
for (var i = 0; i < that.domains.length && value; i++) {
if (that.domains[i].name.indexOf(value) === 0) {
that.items.push(that.domains[i]);
}
}
});
},
methods: {
onRemove: function (item) {
this.domains.$remove(item.$data);
this.domain = '';
},
onHandle: function (e) {
var data,
value = this.domain.trim();
if (e.keyCode === 13) {
this.domains.push({
name: value,
active: true
});
this.domain = '';
}
if (e.keyCode === 27) {
this.domain = value = '';
}
},
domainFilter: function (self) {
return self.name.indexOf(this.domain) === 0;
}
}
});
});
|
Sort test results according to version | 'use strict';
function TestResults(dataTable) {
var Cucumber = require('cucumber');
var TestResult = require('./testResult');
var maximums = [0, 0, 0, 0];
var testCollection = Cucumber.Type.Collection();
(function rowToTestResult() {
var rows = dataTable.getRows();
rows = rows.sort(function(a, b) {
return (a.raw()[1]) < (b.raw()[1]);
});
rows.syncForEach(function(row) {
var testResult = new TestResult(row.raw()[0], row.raw()[1], row.raw()[2], row.raw()[3]);
testCollection.add(testResult);
row.raw().forEach(function(element, index) {
if (maximums[index] < element.length) {
maximums[index] = element.length;
}
});
});
})();
var self = {
getTestResults: function getTestResults() {
var newTests = Cucumber.Type.Collection();
testCollection.syncForEach(function(test) {
newTests.add(test);
});
return newTests;
},
attachTest: function attachTest(test) {
testCollection.add(test);
},
getMaximums: function getMaximums() {
return maximums;
},
raw: function raw() {
var rawTests = [];
testCollection.syncForEach(function(test) {
rawTests.push(test.raw());
});
return rawTests;
}
};
return self;
}
module.exports = TestResults;
| 'use strict';
function TestResults(dataTable) {
var Cucumber = require('cucumber');
var TestResult = require('./testResult');
var maximums = [0, 0, 0, 0];
var testCollection = Cucumber.Type.Collection();
(function rowToTestResult() {
dataTable.getRows().syncForEach(function(row) {
var testResult = new TestResult(row.raw()[0], row.raw()[1], row.raw()[2], row.raw()[3]);
testCollection.add(testResult);
row.raw().forEach(function(element, index) {
if (maximums[index] < element.length) {
maximums[index] = element.length;
}
});
});
})();
var self = {
getTestResults: function getTestResults() {
var newTests = Cucumber.Type.Collection();
testCollection.syncForEach(function(test) {
newTests.add(test);
});
return newTests;
},
attachTest: function attachTest(test) {
testCollection.add(test);
},
getMaximums: function getMaximums() {
return maximums;
},
raw: function raw() {
var rawTests = [];
testCollection.syncForEach(function(test) {
rawTests.push(test.raw());
});
return rawTests;
}
};
return self;
}
module.exports = TestResults;
|
Use cleaner method for checking if template ends with .gshkl | 'use strict';
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
class Greshunkel {
constructor(options) {
this.options = {
directory: process.cwd()
};
_.extend(this.options, options);
}
compile(template) {
return new Promise((resolve, reject) => {
this._loadTemplate(template).then((content) => {
return resolve(content);
}).catch((err) => {
return reject(err);
});
});
}
_loadTemplate(template) {
return new Promise((resolve, reject) => {
template = template.endsWith('.gshkl') ? template : template + '.gshkl';
let templatePath = path.join(this.options.directory, template);
let reader = fs.createReadStream(templatePath, 'utf-8');
let content = '';
reader.on('data', (data) => {
content += data;
});
reader.on('close', () => {
return resolve(content);
});
reader.on('error', (err) => {
return reject(err);
});
});
}
}
let instance = new Greshunkel();
module.exports = {
Greshunkel: Greshunkel,
compile: instance.compile
};
| 'use strict';
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
class Greshunkel {
constructor(options) {
this.options = {
directory: process.cwd()
};
_.extend(this.options, options);
}
compile(template) {
return new Promise((resolve, reject) => {
this._loadTemplate(template).then((content) => {
return resolve(content);
}).catch((err) => {
return reject(err);
});
});
}
_loadTemplate(template) {
return new Promise((resolve, reject) => {
template = template.indexOf('.gshkl') !== -1 ? template : template + '.gshkl';
let templatePath = path.join(this.options.directory, template);
let reader = fs.createReadStream(templatePath, 'utf-8');
let content = '';
reader.on('data', (data) => {
content += data;
});
reader.on('close', () => {
return resolve(content);
});
reader.on('error', (err) => {
return reject(err);
});
});
}
}
let instance = new Greshunkel();
module.exports = {
Greshunkel: Greshunkel,
compile: instance.compile
};
|
Fix ajax URL check to run on page load | $(document).ready(function(){
$('#title_inc').tagsInput({'defaultText': '…'});
$('#title_exc').tagsInput({'defaultText': '…'});
$('#link_inc').tagsInput({'defaultText': '…'});
$('#link_exc').tagsInput({'defaultText': '…'});
set_submit(false)
$('#rss_url').blur(check_url)
check_url()
})
set_feedback = function (value) {
feedback = $('#url_feedback')
fieldset = $('#rss_url_fieldset')
if ( value ) {
fieldset.addClass('has-success').removeClass('has-error')
feedback.show().addClass('glyphicon-ok').removeClass('glyphicon-remove')
set_submit(true)
} else {
fieldset.addClass('has-error').removeClass('has-success')
feedback.show().addClass('glyphicon-remove').removeClass('glyphicon-ok')
set_submit(false)
}
}
set_submit = function (value) {
btn = $('#submit_btn')
if ( value ) {
btn.removeAttr('disabled')
} else {
btn.attr('disabled', 'disabled')
}
}
check_url = function () {
url = $('#rss_url').val()
$.get( "/check_url?&url=" + escape(url), function( data ) {
if (data == 'False') {
set_feedback(false)
} else {
set_feedback(true)
if (data != 'True') {
$('#rss_url').val(data)
}
}
});
} | $(document).ready(function(){
$('#title_inc').tagsInput({'defaultText': '…'});
$('#title_exc').tagsInput({'defaultText': '…'});
$('#link_inc').tagsInput({'defaultText': '…'});
$('#link_exc').tagsInput({'defaultText': '…'});
set_submit(false)
$('#rss_url').blur(function(){
url = $(this).val()
$.get( "/check_url?&url=" + escape(url), function( data ) {
if (data == 'False') {
set_feedback(false)
} else {
set_feedback(true)
if (data != 'True') {
$('#rss_url').val(data)
}
}
});
})
})
set_feedback = function (value) {
feedback = $('#url_feedback')
fieldset = $('#rss_url_fieldset')
if ( value ) {
fieldset.addClass('has-success').removeClass('has-error')
feedback.show().addClass('glyphicon-ok').removeClass('glyphicon-remove')
set_submit(true)
} else {
fieldset.addClass('has-error').removeClass('has-success')
feedback.show().addClass('glyphicon-remove').removeClass('glyphicon-ok')
set_submit(false)
}
}
set_submit = function (value) {
btn = $('#submit_btn')
if ( value ) {
btn.removeAttr('disabled')
} else {
btn.attr('disabled', 'disabled')
}
} |
Store the correct payment method | (function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway != 'paypal_express') {
return;
}
var order = {
products: storejs.get('grav-shoppingcart-basket-data'),
address: storejs.get('grav-shoppingcart-person-address'),
shipping: storejs.get('grav-shoppingcart-shipping-method'),
payment: 'paypal',
token: storejs.get('grav-shoppingcart-order-token').token,
amount: ShoppingCart.totalOrderPrice.toString(),
gateway: ShoppingCart.gateway
};
jQuery.ajax({
url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.saveOrderURL + '?task=preparePayment',
data: order,
type: 'POST'
})
.success(function(redirectUrl) {
ShoppingCart.clearCart();
window.location = redirectUrl;
})
.error(function() {
alert('Payment not successful. Please contact us.');
});
});
});
})();
| (function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway != 'paypal_express') {
return;
}
var order = {
products: storejs.get('grav-shoppingcart-basket-data'),
address: storejs.get('grav-shoppingcart-person-address'),
shipping: storejs.get('grav-shoppingcart-shipping-method'),
payment: storejs.get('grav-shoppingcart-payment-method'),
token: storejs.get('grav-shoppingcart-order-token').token,
amount: ShoppingCart.totalOrderPrice.toString(),
gateway: ShoppingCart.gateway
};
jQuery.ajax({
url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.saveOrderURL + '?task=preparePayment',
data: order,
type: 'POST'
})
.success(function(redirectUrl) {
ShoppingCart.clearCart();
window.location = redirectUrl;
})
.error(function() {
alert('Payment not successful. Please contact us.');
});
});
});
})();
|
Use ResizeFactor parameter instead of hardcoded integer | package com.yahoo.sketches.tuple;
import com.yahoo.sketches.ResizeFactor;
import java.util.function.Predicate;
/**
* Class for filtering values from a {@link Sketch} given a {@link Summary}
*
* @param <T> Summary type against to which apply the {@link Predicate}
*/
public class Filter<T extends Summary> {
private Predicate<T> predicate;
/**
* Filter constructor with a {@link Predicate}
* @param predicate Predicate to use in this filter. If the Predicate returns False, the element is discarded.
* If the Predicate returns True, then the element is kept in the {@link Sketch}
*
*/
public Filter(Predicate<T> predicate) {
this.predicate = predicate;
}
/**
* Filters elements on the provided {@link Sketch}
*
* @param sketchIn The sketch against to which apply the {@link Predicate}
* @return A new Sketch with some of the elements filtered based on the {@link Predicate}
*/
public CompactSketch<T> filter(Sketch<T> sketchIn) {
QuickSelectSketch<T> sketch = new QuickSelectSketch<>(sketchIn.getRetainedEntries(), ResizeFactor.X1.lg(), null);
boolean empty = true;
final SketchIterator<T> it = sketchIn.iterator();
while (it.next()) {
final T summary = it.getSummary();
if (predicate.test(summary)) {
sketch.insert(it.getKey(), summary.copy());
empty = false;
}
}
sketch.setThetaLong(sketchIn.getThetaLong());
if (!empty)
sketch.setNotEmpty();
return sketch.compact();
}
}
| package com.yahoo.sketches.tuple;
import java.util.function.Predicate;
/**
* Class for filtering values from a {@link Sketch} given a {@link Summary}
*
* @param <T> Summary type against to which apply the {@link Predicate}
*/
public class Filter<T extends Summary> {
private Predicate<T> predicate;
/**
* Filter constructor with a {@link Predicate}
* @param predicate Predicate to use in this filter. If the Predicate returns False, the element is discarded.
* If the Predicate returns True, then the element is kept in the {@link Sketch}
*
*/
public Filter(Predicate<T> predicate) {
this.predicate = predicate;
}
/**
* Filters elements on the provided {@link Sketch}
*
* @param sketchIn The sketch against to which apply the {@link Predicate}
* @return A new Sketch with some of the elements filtered based on the {@link Predicate}
*/
public CompactSketch<T> filter(Sketch<T> sketchIn) {
QuickSelectSketch<T> sketch = new QuickSelectSketch<>(sketchIn.getRetainedEntries(), 0, null);
boolean empty = true;
final SketchIterator<T> it = sketchIn.iterator();
while (it.next()) {
final T summary = it.getSummary();
if (predicate.test(summary)) {
sketch.insert(it.getKey(), summary.copy());
empty = false;
}
}
sketch.setThetaLong(sketchIn.getThetaLong());
if (!empty)
sketch.setNotEmpty();
return sketch.compact();
}
}
|
Add all directories under lib to eslint config | #!/usr/bin/env node
require('shelljs/global');
require('colors');
var async = require('async'),
ESLintCLIEngine = require('eslint').CLIEngine,
LINT_SOURCE_DIRS = [
'./lib',
'./test/system',
'./test/unit',
'./test/integration',
'./npm/*.js',
'./index.js'
];
module.exports = function (exit) {
// banner line
console.log('\nLinting files using eslint...'.yellow.bold);
async.waterfall([
// execute the CLI engine
function (next) {
next(null, (new ESLintCLIEngine()).executeOnFiles(LINT_SOURCE_DIRS));
},
// output results
function (report, next) {
var errorReport = ESLintCLIEngine.getErrorResults(report.results);
// log the result to CLI
console.log(ESLintCLIEngine.getFormatter()(report.results));
// log the success of the parser if it has no errors
(errorReport && !errorReport.length) && console.log('eslint ok!'.green);
// ensure that the exit code is non zero in case there was an error
next(Number(errorReport && errorReport.length) || 0);
}
], exit);
};
// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
| #!/usr/bin/env node
require('shelljs/global');
require('colors');
var async = require('async'),
ESLintCLIEngine = require('eslint').CLIEngine,
LINT_SOURCE_DIRS = [
'./lib/runner',
'./lib/authorizer',
'./lib/uvm/*.js',
'./lib/backpack',
'./test/system',
'./test/unit',
'./test/integration',
'./npm/*.js',
'./index.js'
];
module.exports = function (exit) {
// banner line
console.log('\nLinting files using eslint...'.yellow.bold);
async.waterfall([
// execute the CLI engine
function (next) {
next(null, (new ESLintCLIEngine()).executeOnFiles(LINT_SOURCE_DIRS));
},
// output results
function (report, next) {
var errorReport = ESLintCLIEngine.getErrorResults(report.results);
// log the result to CLI
console.log(ESLintCLIEngine.getFormatter()(report.results));
// log the success of the parser if it has no errors
(errorReport && !errorReport.length) && console.log('eslint ok!'.green);
// ensure that the exit code is non zero in case there was an error
next(Number(errorReport && errorReport.length) || 0);
}
], exit);
};
// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
|
Fix the calls to loadMigrators() | package org.jboss.loom.migrators;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jboss.loom.migrators._ext.MigratorDefinition;
import org.jboss.loom.spi.IMigrator;
/**
* Filters migrators - used to filter out migrators based on user input and config.
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public interface IMigratorFilter {
boolean filterDefinition( MigratorDefinition def );
boolean filterInstance( IMigrator def );
/**
* Takes any migrator.
*/
public static class All implements IMigratorFilter {
@Override public boolean filterDefinition( MigratorDefinition def ) { return true; }
@Override public boolean filterInstance( IMigrator def ) { return true; }
}
/**
* Looks for an exact match in the set of names it keeps.
* Only works with definitions; returns true for all instances.
*/
public static class ByNames implements IMigratorFilter {
private final Set<String> names = new HashSet();
public ByNames( List<String> onlyMigrators ) {
this.names.addAll( onlyMigrators );
}
public Set<String> getNames() {
return names;
}
@Override
public boolean filterDefinition( MigratorDefinition def ) {
return names.contains( def.getName() );
}
@Override
public boolean filterInstance( IMigrator def ) {
return true;
}
}
// Wildcards?
}// class
| package org.jboss.loom.migrators;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jboss.loom.migrators._ext.MigratorDefinition;
import org.jboss.loom.spi.IMigrator;
/**
* Filters migrators - used to filter out migrators based on user input and config.
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public interface IMigratorFilter {
boolean filterDefinition( MigratorDefinition def );
boolean filterInstance( IMigrator def );
/**
* Looks for an exact match in the set of names it keeps.
* Only works with definitions; returns true for all instances.
*/
public static class ByNames implements IMigratorFilter {
private final Set<String> names = new HashSet();
public ByNames( List<String> onlyMigrators ) {
this.names.addAll( onlyMigrators );
}
public Set<String> getNames() {
return names;
}
@Override
public boolean filterDefinition( MigratorDefinition def ) {
return names.contains( def.getName() );
}
@Override
public boolean filterInstance( IMigrator def ) {
return true;
}
}
// Wildcards?
}// class
|
Add prepare-release task for consistency | var bower = require('bower'),
eventStream = require('event-stream'),
gulp = require('gulp'),
chmod = require('gulp-chmod'),
zip = require('gulp-zip'),
tar = require('gulp-tar'),
gzip = require('gulp-gzip');
// Installs bower dependencies
gulp.task('bower', function(callback) {
bower.commands.install([], {}, {})
.on('error', function(error) {
callback(error);
})
.on('end', function() {
callback();
});
});
gulp.task('prepare-release', ['bower'], function() {
var version = require('./package.json').version;
return eventStream.merge(
getSources()
.pipe(zip('emoji-plugin-' + version + '.zip')),
getSources()
.pipe(tar('emoji-plugin-' + version + '.tar'))
.pipe(gzip())
)
.pipe(chmod(0644))
.pipe(gulp.dest('release'));
});
// Builds and packs plugins sources
gulp.task('default', ['prepare-release'], function() {
// The "default" task is just an alias for "prepare-release" task.
});
/**
* Returns files stream with the plugin sources.
*
* @returns {Object} Stream with VinylFS files.
*/
var getSources = function() {
return gulp.src([
'Plugin.php',
'README.md',
'LICENSE',
'js/*',
'css/*',
'components/emoji-images/emoji-images.js',
'components/emoji-images/readme.md',
'components/emoji-images/pngs/*'
],
{base: './'}
);
}
| var bower = require('bower'),
eventStream = require('event-stream'),
gulp = require('gulp'),
chmod = require('gulp-chmod'),
zip = require('gulp-zip'),
tar = require('gulp-tar'),
gzip = require('gulp-gzip');
// Installs bower dependencies
gulp.task('bower', function(callback) {
bower.commands.install([], {}, {})
.on('error', function(error) {
callback(error);
})
.on('end', function() {
callback();
});
});
// Builds and packs plugins sources
gulp.task('default', ['bower'], function() {
var version = require('./package.json').version;
return eventStream.merge(
getSources()
.pipe(zip('emoji-plugin-' + version + '.zip')),
getSources()
.pipe(tar('emoji-plugin-' + version + '.tar'))
.pipe(gzip())
)
.pipe(chmod(0644))
.pipe(gulp.dest('release'));
});
/**
* Returns files stream with the plugin sources.
*
* @returns {Object} Stream with VinylFS files.
*/
var getSources = function() {
return gulp.src([
'Plugin.php',
'README.md',
'LICENSE',
'js/*',
'css/*',
'components/emoji-images/emoji-images.js',
'components/emoji-images/readme.md',
'components/emoji-images/pngs/*'
],
{base: './'}
);
}
|
Update ldap3 1.0.3 => 1.0.4 | import sys
from setuptools import find_packages, setup
with open('VERSION') as version_fp:
VERSION = version_fp.read().strip()
install_requires = [
'django-local-settings>=1.0a13',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.4',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
with open('VERSION') as version_fp:
VERSION = version_fp.read().strip()
install_requires = [
'django-local-settings>=1.0a13',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Replace native w/ _.isObject function. | var klass = require('klass')
, _ = require('lodash')
, obligator = klass({
initialize: function() {
this._params = {};
this._collection = {};
}
})
.methods({
setCollection: function(collection) {
if ( !collection )
throw Error("collection is empty or missing!");
var parameters = Object.getOwnPropertyNames(this)
, i;
for(i in parameters){
if(!_.isObject(this[parameters[i]])){
this._params[parameters[i]] = this[parameters[i]];
delete this[parameters[i]];
}
}
this._collection = _.isString(collection) ? JSON.parse(collection) : collection;
},
validate: function(){
var params = this._params
, missingParams = []
, property = "";
for(property in params) {
if( params[property] != false && (_.isUndefined(this._collection[property]))) {
missingParams.push(property);
}
}
if( missingParams.length > 0)
throw Error("Missing Parameter(s): " + missingParams);
return true;
},
reset: function() {
this._collection = {};
this._params = {};
},
count: function() {
var count = 0;
for (var p in this._params)
++count;
return count;
},
});
exports.newFactoryInstance = function() {
return new obligator;
}
| var klass = require('klass')
, _ = require('lodash')
, obligator = klass({
initialize: function() {
this._params = {};
this._collection = {};
}
})
.methods({
setCollection: function(collection) {
if ( !collection )
throw Error("collection is empty or missing!");
var parameters = Object.getOwnPropertyNames(this)
, i;
for(i in parameters){
if(typeof(this[parameters[i]]) != "object"){
this._params[parameters[i]] = this[parameters[i]];
delete this[parameters[i]];
}
}
this._collection = _.isString(collection) ? JSON.parse(collection) : collection;
},
validate: function(){
var params = this._params
, missingParams = []
, property = "";
for(property in params) {
if( params[property] != false && (_.isUndefined(this._collection[property]))) {
missingParams.push(property);
}
}
if( missingParams.length > 0)
throw Error("Missing Parameter(s): " + missingParams);
return true;
},
reset: function() {
this._collection = {};
this._params = {};
},
count: function() {
var count = 0;
for (var p in this._params)
++count;
return count;
},
});
exports.newFactoryInstance = function() {
return new obligator;
}
|
Fix autofocus in user login dialog | /* Directives */
angular.module('myApp.directives')
.directive('ngVisible', function() {
return function(scope, elem, attr) {
scope.$watch(attr.ngVisible, function(value) {
elem.css('visibility', value ? 'visible' : 'hidden');
});
};
})
.directive('ngKeyup', function() {
return function(scope, elem, attrs) {
elem.bind('keyup', function() {
scope.$apply(attrs.ngKeyup);
});
};
})
.directive('gimsLinkNew', function($routeParams) {
return {
restrict: "E",
replace: true,
scope: {
content: '='
},
link: function(scope, element, attrs) {
var returnUrl = '';
if (attrs.origin) {
returnUrl = sprintf('?returnUrl=/admin/%s/edit/%s&%s=%s',
attrs.origin,
$routeParams.id,
attrs.origin,
$routeParams.id
);
}
var html = sprintf('<a class="link-new list-inline btn btn-default" href="/admin/%s/new%s"><i class="fa fa-plus-circle"></i> new %s</a>',
attrs.target,
returnUrl,
attrs.target
);
element.html(html).show();
}
};
})
.directive('gimsFocus', function($timeout) {
return {
link: function(scope, element) {
$timeout(function() {
element.focus();
}, 100);
}
};
});
| /* Directives */
angular.module('myApp.directives')
.directive('ngVisible', function() {
return function(scope, elem, attr) {
scope.$watch(attr.ngVisible, function(value) {
elem.css('visibility', value ? 'visible' : 'hidden');
});
};
})
.directive('ngKeyup', function() {
return function(scope, elem, attrs) {
elem.bind('keyup', function() {
scope.$apply(attrs.ngKeyup);
});
};
})
.directive('gimsLinkNew', function($routeParams) {
return {
restrict: "E",
replace: true,
scope: {
content: '='
},
link: function(scope, element, attrs) {
var returnUrl = '';
if (attrs.origin) {
returnUrl = sprintf('?returnUrl=/admin/%s/edit/%s&%s=%s',
attrs.origin,
$routeParams.id,
attrs.origin,
$routeParams.id
);
}
var html = sprintf('<a class="link-new list-inline btn btn-default" href="/admin/%s/new%s"><i class="fa fa-plus-circle"></i> new %s</a>',
attrs.target,
returnUrl,
attrs.target
);
element.html(html).show();
}
};
})
.directive('gimsFocus', function($timeout) {
return {
link: function(element) {
$timeout(function() {
element.focus();
});
}
};
});
|
Add future import for Py2. | """Generate publication-quality data acquisition methods section from BIDS dataset.
"""
from __future__ import print_function
from collections import Counter
from bids.reports import utils
class BIDSReport(object):
"""
Generates publication-quality data acquisition methods section from BIDS
dataset.
"""
def __init__(self, layout):
self.layout = layout
def generate(self, task_converter=None):
"""Generate the methods section.
"""
if task_converter is None:
task_converter = {}
descriptions = []
sessions = self.layout.get_sessions()
if sessions:
for ses in sessions:
subjs = self.layout.get_subjects(session=ses)
for sid in subjs:
description = utils.report(self.layout, subj=sid, ses=ses,
task_converter=task_converter)
descriptions.append(description)
else:
subjs = self.layout.get_subjects()
for sid in subjs:
description = utils.report(self.layout, subj=sid, ses=None,
task_converter=task_converter)
descriptions.append(description)
counter = Counter(descriptions)
print('Number of patterns detected: {0}'.format(len(counter.keys())))
return counter
| """Generate publication-quality data acquisition methods section from BIDS dataset.
"""
from collections import Counter
from bids.reports import utils
class BIDSReport(object):
"""
Generates publication-quality data acquisition methods section from BIDS
dataset.
"""
def __init__(self, layout):
self.layout = layout
def generate(self, task_converter=None):
"""Generate the methods section.
"""
if task_converter is None:
task_converter = {}
descriptions = []
sessions = self.layout.get_sessions()
if sessions:
for ses in sessions:
subjs = self.layout.get_subjects(session=ses)
for sid in subjs:
description = utils.report(self.layout, subj=sid, ses=ses,
task_converter=task_converter)
descriptions.append(description)
else:
subjs = self.layout.get_subjects()
for sid in subjs:
description = utils.report(self.layout, subj=sid, ses=None,
task_converter=task_converter)
descriptions.append(description)
counter = Counter(descriptions)
print('Number of patterns detected: {0}'.format(len(counter.keys())))
return counter
|
Use bytes instead of strings | // Copyright 2015 Andrew E. Bruno. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gofasta
import (
"os"
"bufio"
"bytes"
)
type SeqRecord struct {
Id string
Seq string
}
func SimpleParser(file *os.File) chan *SeqRecord {
c := make(chan *SeqRecord)
go func() {
defer close(c)
reader := bufio.NewReader(file)
// skip bytes until the first record
_, err := reader.ReadBytes('>')
if err != nil {
return
}
id, err := reader.ReadBytes('\n')
if err != nil {
return
}
var seqbuf bytes.Buffer
for ;; {
line, err := reader.ReadBytes('\n')
if err != nil || len(line) == 0 {
break
}
if line[0] == '>' {
c <- &SeqRecord{Id: string(bytes.TrimSpace(id)), Seq: seqbuf.String()}
id = line[1:]
seqbuf.Reset()
continue
}
seqbuf.Write(line[:len(line)-1])
}
c <- &SeqRecord{Id: string(bytes.TrimSpace(id)), Seq: seqbuf.String()}
}();
return c
}
| // Copyright 2015 Andrew E. Bruno. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gofasta
import (
"strings"
"os"
"bufio"
"bytes"
)
type SeqRecord struct {
Id string
Seq string
}
func SimpleParser(file *os.File) chan *SeqRecord {
c := make(chan *SeqRecord)
go func() {
defer close(c)
reader := bufio.NewReader(file)
// skip bytes until the first record
_, err := reader.ReadBytes('>')
if err != nil {
return
}
id, err := reader.ReadString('\n')
if err != nil {
return
}
var seqbuf bytes.Buffer
for ;; {
line, err := reader.ReadString('\n')
if err != nil || line == "" {
break
}
if line[0] == '>' {
c <- &SeqRecord{Id: strings.TrimSpace(id), Seq: seqbuf.String()}
id = line[1:]
seqbuf.Reset()
continue
}
seqbuf.WriteString(strings.TrimSpace(line))
}
c <- &SeqRecord{Id: strings.TrimSpace(id), Seq: seqbuf.String()}
}();
return c
}
|
Add a stub for fts_updates
Change-Id: Ieb48f98a0072dcd27de0b50027ff6c5f3ecc1513
Reviewed-on: http://review.couchbase.org/70413
Tested-by: buildbot <[email protected]>
Reviewed-by: Pavel Paulau <[email protected]> | from urlparse import urlparse
from logger import logger
class WorkloadSettings(object):
def __init__(self, options):
self.creates = options.creates
self.reads = options.reads
self.updates = options.updates
self.deletes = options.deletes
self.cases = 0 # Stub for library compatibility
self.ops = options.ops
self.throughput = options.throughput
self.doc_gen = options.generator
self.size = options.size
self.items = options.items
self.expiration = options.expiration
self.working_set = options.working_set
self.working_set_access = options.working_set_access
self.async = options.async
self.workers = options.workers
# Stubs for library compatibility
self.query_workers = 0
self.subdoc_workers = 0
self.n1ql_workers = 0
self.operations = False
self.fts_config = None
self.fts_updates = 0
self.index_type = None
self.ddocs = {}
self.qparams = {}
class TargetSettings(object):
def __init__(self, target_uri, prefix):
params = urlparse(target_uri)
if not params.hostname or not params.port or not params.path:
logger.interrupt('Invalid connection URI')
self.node = '{}:{}'.format(params.hostname, params.port)
self.bucket = params.path[1:]
self.password = params.password or ''
self.prefix = prefix
| from urlparse import urlparse
from logger import logger
class WorkloadSettings(object):
def __init__(self, options):
self.creates = options.creates
self.reads = options.reads
self.updates = options.updates
self.deletes = options.deletes
self.cases = 0 # Stub for library compatibility
self.ops = options.ops
self.throughput = options.throughput
self.doc_gen = options.generator
self.size = options.size
self.items = options.items
self.expiration = options.expiration
self.working_set = options.working_set
self.working_set_access = options.working_set_access
self.async = options.async
self.workers = options.workers
# Stubs for library compatibility
self.query_workers = 0
self.subdoc_workers = 0
self.n1ql_workers = 0
self.operations = False
self.fts_config = None
self.index_type = None
self.ddocs = {}
self.qparams = {}
class TargetSettings(object):
def __init__(self, target_uri, prefix):
params = urlparse(target_uri)
if not params.hostname or not params.port or not params.path:
logger.interrupt('Invalid connection URI')
self.node = '{}:{}'.format(params.hostname, params.port)
self.bucket = params.path[1:]
self.password = params.password or ''
self.prefix = prefix
|
[MySQL] Use the default number of queries | package sqlancer.dbms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.Test;
import sqlancer.Main;
public class TestMySQL {
String mysqlAvailable = System.getenv("MYSQL_AVAILABLE");
boolean mysqlIsAvailable = mysqlAvailable != null && mysqlAvailable.equalsIgnoreCase("true");
@Test
public void testPQS() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--num-threads", "4", "--random-string-generation", "ALPHANUMERIC", "--database-prefix",
"pqsdb" /* Workaround for connections not being closed */, "--num-queries",
TestConfig.NUM_QUERIES, "mysql", "--oracle", "PQS" }));
}
@Test
public void testMySQL() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--max-expression-depth", "1", "--num-threads", "4", "--num-queries", TestConfig.NUM_QUERIES,
"mysql" }));
}
}
| package sqlancer.dbms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.Test;
import sqlancer.Main;
public class TestMySQL {
String mysqlAvailable = System.getenv("MYSQL_AVAILABLE");
boolean mysqlIsAvailable = mysqlAvailable != null && mysqlAvailable.equalsIgnoreCase("true");
@Test
public void testMySQL() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--max-expression-depth", "1", "--num-threads", "4", "--num-queries", TestConfig.NUM_QUERIES,
"mysql" }));
}
@Test
public void testPQS() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--num-threads", "4", "--random-string-generation", "ALPHANUMERIC", "--database-prefix",
"pqsdb" /* Workaround for connections not being closed */, "--num-queries", "100000", "mysql",
"--oracle", "PQS" }));
}
}
|
Include qualifiers on reference generation | define(['rules/rules.module'
],
function() {
angular.module('rules').factory('references',
['ast',
function(ast) {
function generateReference(query) {
var bindings = {};
angular.forEach(query.bindings, function(binding) {
if (('id' in binding) && ('name' in binding)) {
bindings[binding.name] = binding.id;
}
});
angular.forEach(ast.variables(query.rule.head), function(variable) {
var name = variable.name;
bindings[name] = { id: query.bindings[name].id,
type: query.bindings[name].type,
qualifiers: query.bindings[name].qualifiers
};
});
var info = { rule: query.rule,
query: query.query,
bindings: bindings,
constraints: query.constraints
};
var url = ('#/rules/explain?inference=' +
encodeURIComponent(angular.toJson(info, false)));
var reference = { P854: [{ datatype: 'url',
datavalue: { type: 'string',
value: url,
__sqid_display_string_override__: '(explain inference)'
},
snaktype: 'value',
property: 'P854'
}]
};
return [{ snaks: reference,
'snaks-order': ['P854']
}];
}
return { generateReference: generateReference
};
}]);
return {};
});
| define(['rules/rules.module'
],
function() {
angular.module('rules').factory('references',
[
function() {
function generateReference(query) {
var bindings = {};
angular.forEach(query.bindings, function(binding) {
if (('id' in binding) && ('name' in binding)) {
bindings[binding.name] = binding.id;
});
var info = { rule: query.rule,
query: query.query,
bindings: bindings,
constraints: query.constraints
};
var url = ('#/rules/explain?inference=' +
encodeURIComponent(angular.toJson(info, false)));
var reference = { P854: [{ datatype: 'url',
datavalue: { type: 'string',
value: url,
__sqid_display_string_override__: '(explain inference)'
},
snaktype: 'value',
property: 'P854'
}]
};
return [{ snaks: reference,
'snaks-order': ['P854']
}];
}
return { generateReference: generateReference
};
}]);
return {};
});
|
fix(kakao): Handle case where email is not present | from allauth.account.models import EmailAddress
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class KakaoAccount(ProviderAccount):
@property
def properties(self):
return self.account.extra_data['properties']
def get_avatar_url(self):
return self.properties['profile_image']
def to_str(self):
dflt = super(KakaoAccount, self).to_str()
return self.properties['nickname'] or dflt
class KakaoProvider(OAuth2Provider):
id = 'kakao'
name = 'Kakao'
account_class = KakaoAccount
def extract_uid(self, data):
return str(data['id'])
def extract_common_fields(self, data):
email = data.get("kaccount_email")
return dict(email=email)
def extract_email_addresses(self, data):
ret = []
email = data.get("kaccount_email")
if email:
verified = data.get("kaccount_email_verified")
# data["kaccount_email_verified"] imply the email address is
# verified
ret.append(EmailAddress(email=email,
verified=verified,
primary=True))
return ret
provider_classes = [KakaoProvider]
| from allauth.account.models import EmailAddress
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class KakaoAccount(ProviderAccount):
@property
def properties(self):
return self.account.extra_data['properties']
def get_avatar_url(self):
return self.properties['profile_image']
def to_str(self):
dflt = super(KakaoAccount, self).to_str()
return self.properties['nickname'] or dflt
class KakaoProvider(OAuth2Provider):
id = 'kakao'
name = 'Kakao'
account_class = KakaoAccount
def extract_uid(self, data):
return str(data['id'])
def extract_common_fields(self, data):
email = data.get("kaccount_email")
return dict(email=email)
def extract_email_addresses(self, data):
ret = []
email = data.get("kaccount_email")
verified = data.get("kaccount_email_verified")
# data["kaccount_email_verified"] imply the email address is
# verified
ret.append(EmailAddress(email=email,
verified=verified,
primary=True))
return ret
provider_classes = [KakaoProvider]
|
Fix: Use assertSame() instead of assertEquals() | <?php
/*
* This file is part of sebastian/phpunit-framework-constraint.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
class DirectoryExistsTest extends TestCase
{
public function testDefaults()
{
$constraint = new DirectoryExists();
$this->assertCount(1, $constraint);
$this->assertSame('directory exists', $constraint->toString());
}
public function testEvaluateReturnsFalseWhenDirectoryDoesNotExist()
{
$directory = __DIR__ . '/NonExistentDirectory';
$constraint = new DirectoryExists();
$this->assertFalse($constraint->evaluate($directory, '', true));
}
public function testEvaluateReturnsTrueWhenDirectoryExists()
{
$directory = __DIR__;
$constraint = new DirectoryExists();
$this->assertTrue($constraint->evaluate($directory, '', true));
}
public function testEvaluateThrowsExpectationFailedExceptionWhenDirectoryDoesNotExist()
{
$directory = __DIR__ . '/NonExistentDirectory';
$constraint = new DirectoryExists();
try {
$constraint->evaluate($directory);
} catch (ExpectationFailedException $e) {
$this->assertSame(
<<<PHP
Failed asserting that directory "$directory" exists.
PHP
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}
| <?php
/*
* This file is part of sebastian/phpunit-framework-constraint.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
class DirectoryExistsTest extends TestCase
{
public function testDefaults()
{
$constraint = new DirectoryExists();
$this->assertCount(1, $constraint);
$this->assertEquals('directory exists', $constraint->toString());
}
public function testEvaluateReturnsFalseWhenDirectoryDoesNotExist()
{
$directory = __DIR__ . '/NonExistentDirectory';
$constraint = new DirectoryExists();
$this->assertFalse($constraint->evaluate($directory, '', true));
}
public function testEvaluateReturnsTrueWhenDirectoryExists()
{
$directory = __DIR__;
$constraint = new DirectoryExists();
$this->assertTrue($constraint->evaluate($directory, '', true));
}
public function testEvaluateThrowsExpectationFailedExceptionWhenDirectoryDoesNotExist()
{
$directory = __DIR__ . '/NonExistentDirectory';
$constraint = new DirectoryExists();
try {
$constraint->evaluate($directory);
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<PHP
Failed asserting that directory "$directory" exists.
PHP
,
TestFailure::exceptionToString($e)
);
return;
}
$this->fail();
}
}
|
Use class name instead of object to reference constant (compile error fix on some versions of php) | <?
// callback controller
class Bitpay_Bitcoins_IndexController extends Mage_Core_Controller_Front_Action {
// bitpay's IPN lands here
public function indexAction() {
require 'lib/bitpay/bp_lib.php';
$apiKey = Mage::getStoreConfig('payment/Bitcoins/api_key');
$invoice = bpVerifyNotification($apiKey);
if (is_string($invoice))
Mage::log("bitpay callback error: $invoice");
else {
// get the order
if (isset($invoice['posData']['quoteId'])) {
$quoteId = $invoice['posData']['quoteId'];
$order = Mage::getModel('sales/order')->load($quoteId, 'quote_id');
}
else {
$orderId = $invoice['posData']['orderId'];
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
}
// save the ipn so that we can find it when the user clicks "Place Order"
Mage::getModel('Bitcoins/ipn')->Record($invoice);
// update the order if it exists already
if ($order->getId())
switch($invoice['status']) {
case 'confirmed':
case 'complete':
foreach($order->getInvoiceCollection() as $i)
$i->pay()
->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)
->save();
break;
}
}
}
}
?> | <?
// callback controller
class Bitpay_Bitcoins_IndexController extends Mage_Core_Controller_Front_Action {
// bitpay's IPN lands here
public function indexAction() {
require 'lib/bitpay/bp_lib.php';
$apiKey = Mage::getStoreConfig('payment/Bitcoins/api_key');
$invoice = bpVerifyNotification($apiKey);
if (is_string($invoice))
Mage::log("bitpay callback error: $invoice");
else {
// get the order
if (isset($invoice['posData']['quoteId'])) {
$quoteId = $invoice['posData']['quoteId'];
$order = Mage::getModel('sales/order')->load($quoteId, 'quote_id');
}
else {
$orderId = $invoice['posData']['orderId'];
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
}
// save the ipn so that we can find it when the user clicks "Place Order"
Mage::getModel('Bitcoins/ipn')->Record($invoice);
// update the order if it exists already
if ($order->getId())
switch($invoice['status']) {
case 'confirmed':
case 'complete':
foreach($order->getInvoiceCollection() as $i)
$i->pay()
->save();
$order->setState($order::STATE_PROCESSING, true)
->save();
break;
}
}
}
}
?> |
Fix selection not occurring on compact select+expand | (function(bitflux) {
'use strict';
angular.module('openfin.showcase')
.directive('showcase', ['quandlService', 'configService', (quandlService, configService) => {
return {
restrict: 'E',
templateUrl: 'showcase/showcase.html',
scope: {
selection: '&'
},
link: (scope, element) => {
var chart = bitflux.app().quandlApiKey(quandlService.apiKey()),
firstRun = true;
chart.periodsOfDataToFetch(configService.getBitfluxStockAmount());
chart.proportionOfDataToDisplayByDefault(configService.getInitialBitfluxProportion());
// If there's already a selection, run the chart and use that.
// This occurs when the user selects a stock in compact view
// and it expands.
if (scope.selection && scope.selection()) {
firstRun = false;
chart.run(element[0].children[0]);
chart.changeQuandlProduct(scope.selection());
}
scope.$watch('selection()', (newSelection, previousSelection) => {
if (newSelection !== '') {
if (firstRun) {
firstRun = false;
chart.run(element[0].children[0]);
}
if (newSelection !== previousSelection) {
chart.changeQuandlProduct(newSelection);
}
}
});
}
};
}]);
}(bitflux));
| (function(bitflux) {
'use strict';
angular.module('openfin.showcase')
.directive('showcase', ['quandlService', 'configService', (quandlService, configService) => {
return {
restrict: 'E',
templateUrl: 'showcase/showcase.html',
scope: {
selection: '&'
},
link: (scope, element) => {
var chart = bitflux.app().quandlApiKey(quandlService.apiKey()),
firstRun = true;
chart.periodsOfDataToFetch(configService.getBitfluxStockAmount());
chart.proportionOfDataToDisplayByDefault(configService.getInitialBitfluxProportion());
scope.$watch('selection()', (newSelection, previousSelection) => {
if (newSelection !== '') {
if (firstRun) {
firstRun = false;
chart.run(element[0].children[0]);
}
if (newSelection !== previousSelection) {
chart.changeQuandlProduct(newSelection);
}
}
});
}
};
}]);
}(bitflux));
|
Fix for test failure introduced by basic auth changes | from e2e_framework.page_object import PageObject
from ..lms import BASE_URL
class InfoPage(PageObject):
"""
Info pages for the main site.
These are basically static pages, so we use one page
object to represent them all.
"""
# Dictionary mapping section names to URL paths
SECTION_PATH = {
'about': '/about',
'faq': '/faq',
'press': '/press',
'contact': '/contact',
'terms': '/tos',
'privacy': '/privacy',
'honor': '/honor',
}
# Dictionary mapping URLs to expected css selector
EXPECTED_CSS = {
'/about': 'section.vision',
'/faq': 'section.faq',
'/press': 'section.press',
'/contact': 'section.contact',
'/tos': 'section.tos',
'/privacy': 'section.privacy-policy',
'/honor': 'section.honor-code',
}
@property
def name(self):
return "lms.info"
@property
def requirejs(self):
return []
@property
def js_globals(self):
return []
def url(self, section=None):
return BASE_URL + self.SECTION_PATH[section]
def is_browser_on_page(self):
# Find the appropriate css based on the URL
for url_path, css_sel in self.EXPECTED_CSS.iteritems():
if self.browser.url.endswith(url_path):
return self.is_css_present(css_sel)
# Could not find the CSS based on the URL
return False
@classmethod
def sections(cls):
return cls.SECTION_PATH.keys()
| from e2e_framework.page_object import PageObject
from ..lms import BASE_URL
class InfoPage(PageObject):
"""
Info pages for the main site.
These are basically static pages, so we use one page
object to represent them all.
"""
# Dictionary mapping section names to URL paths
SECTION_PATH = {
'about': '/about',
'faq': '/faq',
'press': '/press',
'contact': '/contact',
'terms': '/tos',
'privacy': '/privacy',
'honor': '/honor',
}
# Dictionary mapping URLs to expected css selector
EXPECTED_CSS = {
'/about': 'section.vision',
'/faq': 'section.faq',
'/press': 'section.press',
'/contact': 'section.contact',
'/tos': 'section.tos',
'/privacy': 'section.privacy-policy',
'/honor': 'section.honor-code',
}
@property
def name(self):
return "lms.info"
@property
def requirejs(self):
return []
@property
def js_globals(self):
return []
def url(self, section=None):
return BASE_URL + self.SECTION_PATH[section]
def is_browser_on_page(self):
stripped_url = self.browser.url.replace(BASE_URL, "")
css_sel = self.EXPECTED_CSS[stripped_url]
return self.is_css_present(css_sel)
@classmethod
def sections(cls):
return cls.SECTION_PATH.keys()
|
Add message_type as CharField in form | import time
from django import forms
from .models import Message
from .utils import timestamp_to_datetime, datetime_to_timestamp
class MessageForm(forms.Form):
text = forms.CharField(widget=forms.Textarea)
typing = forms.BooleanField(required=False)
message_type = forms.CharField(widget=forms.Textarea)
class MessageCreationForm(MessageForm):
username = forms.CharField(max_length=20)
datetime_start = forms.IntegerField()
def clean_datetime_start(self):
now = int(round(time.time() * 1000))
timestamp = int(self.data['datetime_start'])
if now < timestamp:
timestamp = now
self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)
def save(self):
self.clean_datetime_start()
message = Message.objects.create(channel=self.channel, **self.cleaned_data)
if not message.typing:
message.datetime_sent = message.datetime_start
message.save()
return message;
class MessagePatchForm(MessageForm):
datetime_sent = forms.IntegerField()
def save(self, message):
timestamp_start = datetime_to_timestamp(message.datetime_start)
timestamp_sent = int(self.cleaned_data['datetime_sent'])
if timestamp_sent < timestamp_start:
timestamp_sent = timestamp_start
message.datetime_sent = timestamp_to_datetime(timestamp_sent)
message.text = self.cleaned_data['text']
message.typing = self.cleaned_data.get('typing', False)
message.save()
| import time
from django import forms
from .models import Message
from .utils import timestamp_to_datetime, datetime_to_timestamp
class MessageForm(forms.Form):
text = forms.CharField(widget=forms.Textarea)
typing = forms.BooleanField(required=False)
class MessageCreationForm(MessageForm):
username = forms.CharField(max_length=20)
datetime_start = forms.IntegerField()
def clean_datetime_start(self):
now = int(round(time.time() * 1000))
timestamp = int(self.data['datetime_start'])
if now < timestamp:
timestamp = now
self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)
def save(self):
self.clean_datetime_start()
message = Message.objects.create(channel=self.channel, **self.cleaned_data)
if not message.typing:
message.datetime_sent = message.datetime_start
message.save()
return message;
class MessagePatchForm(MessageForm):
datetime_sent = forms.IntegerField()
def save(self, message):
timestamp_start = datetime_to_timestamp(message.datetime_start)
timestamp_sent = int(self.cleaned_data['datetime_sent'])
if timestamp_sent < timestamp_start:
timestamp_sent = timestamp_start
message.datetime_sent = timestamp_to_datetime(timestamp_sent)
message.text = self.cleaned_data['text']
message.typing = self.cleaned_data.get('typing', False)
message.save()
|
Add unit test for masking key:value of YAML | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from salt.ext.six import text_type as text
# Import Salt Libs
from salt.utils.sanitizers import clean, mask_args_value
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.mock import NO_MOCK, NO_MOCK_REASON
@skipIf(NO_MOCK, NO_MOCK_REASON)
class SanitizersTestCase(TestCase):
'''
TestCase for sanitizers
'''
def test_sanitized_trim(self):
'''
Test sanitized input for trimming
'''
value = ' sample '
response = clean.trim(value)
assert response == 'sample'
assert type(response) == text
def test_sanitized_filename(self):
'''
Test sanitized input for filename
'''
value = '/absolute/path/to/the/file.txt'
response = clean.filename(value)
assert response == 'file.txt'
value = '../relative/path/to/the/file.txt'
response = clean.filename(value)
assert response == 'file.txt'
def test_sanitized_hostname(self):
'''
Test sanitized input for hostname (id)
'''
value = ' ../ ../some/dubious/hostname '
response = clean.hostname(value)
assert response == 'somedubioushostname'
test_sanitized_id = test_sanitized_hostname
def test_value_masked(self):
'''
Test if the values are masked.
:return:
'''
out = mask_args_value('quantum: fluctuations', 'quant*')
assert out == 'quantum: ** hidden **'
| # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
from salt.ext.six import text_type as text
# Import Salt Libs
from salt.utils.sanitizers import clean
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.mock import NO_MOCK, NO_MOCK_REASON
@skipIf(NO_MOCK, NO_MOCK_REASON)
class SanitizersTestCase(TestCase):
'''
TestCase for sanitizers
'''
def test_sanitized_trim(self):
'''
Test sanitized input for trimming
'''
value = ' sample '
response = clean.trim(value)
assert response == 'sample'
assert type(response) == text
def test_sanitized_filename(self):
'''
Test sanitized input for filename
'''
value = '/absolute/path/to/the/file.txt'
response = clean.filename(value)
assert response == 'file.txt'
value = '../relative/path/to/the/file.txt'
response = clean.filename(value)
assert response == 'file.txt'
def test_sanitized_hostname(self):
'''
Test sanitized input for hostname (id)
'''
value = ' ../ ../some/dubious/hostname '
response = clean.hostname(value)
assert response == 'somedubioushostname'
test_sanitized_id = test_sanitized_hostname
|
Fix reading the package version
This hack was broken by b4cad7631bd284df553bbc0fcd4c811bb4182509. | #!/usr/bin/env python
from setuptools import setup
long_description = open('README.rst').read()
# very convoluted way of reading version from the module without importing it
version = (
[l for l in open('flask_injector.py') if '__version__ = ' in l][0]
.split('=')[-1]
.strip().strip('\'')
)
if __name__ == '__main__':
setup(
name='Flask-Injector',
version=version,
url='https://github.com/alecthomas/flask_injector',
license='BSD',
author='Alec Thomas',
author_email='[email protected]',
description='Adds Injector, a Dependency Injection framework, support to Flask.',
long_description=long_description,
py_modules=['flask_injector'],
zip_safe=True,
platforms='any',
install_requires=['Flask', 'injector>=0.10.0', 'typing'],
keywords=['Dependency Injection', 'Flask'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Framework :: Flask',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
)
| #!/usr/bin/env python
from setuptools import setup
long_description = open('README.rst').read()
# very convoluted way of reading version from the module without importing it
version = (
[l for l in open('flask_injector.py') if '__version__' in l][0]
.split('=')[-1]
.strip().strip('\'')
)
if __name__ == '__main__':
setup(
name='Flask-Injector',
version=version,
url='https://github.com/alecthomas/flask_injector',
license='BSD',
author='Alec Thomas',
author_email='[email protected]',
description='Adds Injector, a Dependency Injection framework, support to Flask.',
long_description=long_description,
py_modules=['flask_injector'],
zip_safe=True,
platforms='any',
install_requires=['Flask', 'injector>=0.10.0', 'typing'],
keywords=['Dependency Injection', 'Flask'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Framework :: Flask',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.