text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Remove Emulation logs directory one time at the beggining of the test suite+ Fix system call | <?php
namespace Ivory\LuceneSearchBundle\Tests\Emulation;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;
/**
* Web test case
*
* @author GeLo <[email protected]>
*/
class WebTestCase extends BaseWebTestCase
{
/**
* @var boolean TRUE if the web test case has been initialized else FALSE
*/
protected static $initialize = array();
/**
* Remove emulation cache & logs directories for the given environment
*
* @param string $environment
*/
protected static function initialize($environment)
{
if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
{
$filesystem = new Filesystem();
$filesystem->remove(__DIR__.'/cache/'.$environment);
if(empty(self::$initialize))
$filesystem->remove(__DIR__.'/logs');
self::$initialize[$environment] = true;
}
}
/**
*@override
*/
protected static function getKernelClass()
{
$kernelClass = 'AppKernel';
require_once __DIR__.DIRECTORY_SEPARATOR.$kernelClass.'.php';
return $kernelClass;
}
/**
* Gets the kernel container
*
* @return Symfony\Component\DependencyInjection\ContainerInterface
*/
public static function createContainer(array $options = array('environment' => 'default'))
{
self::initialize($options['environment']);
$kernel = self::createKernel($options);
$kernel->boot();
return $kernel->getContainer();
}
}
| <?php
namespace Ivory\LuceneSearchBundle\Tests\Emulation;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;
/**
* Web test case
*
* @author GeLo <[email protected]>
*/
class WebTestCase extends BaseWebTestCase
{
/**
* @var boolean TRUE if the web test case has been initialized else FALSE
*/
protected static $initialize = array();
/**
* Remove emulation cache & logs directories
*/
protected static function initialize($environment)
{
if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
{
$filesystem = new Filesystem();
$filesystem->remove(__DIR__.'/cache/'.$environment);
$filesystem->remove(__DIR__.'/logs');
self::$initialize[$environment] = true;
}
}
/**
*@override
*/
protected static function getKernelClass()
{
$kernelClass = 'AppKernel';
require_once __DIR__.DIRECTORY_SEPARATOR.$kernelClass.'.php';
return $kernelClass;
}
/**
* Gets the kernel container
*
* @return Symfony\Component\DependencyInjection\ContainerInterface
*/
public static function createContainer(array $options = array('environment' => 'default'))
{
self::initialize($options['environment']);
$kernel = self::createKernel($options);
$kernel->boot();
return $kernel->getContainer();
}
}
|
Expand example to use done() |
var async = require('async');
var timetree = require('../');
var util = require('util');
function somethingSynchronous() {
var i = 100000, numbers = [];
while (i--) {
numbers.push(i);
}
return numbers.reduce(function(a,b) { return a * b; })
}
function databaseLookup(id, callback) {
setTimeout(function() {
callback(null, {
id: id,
data: 'Some Data about ' + id
});
}, 30 + Math.random() * 50)
}
var timer = timetree('example');
return async.waterfall(
[
function(callback) {
var subTimer = timer.split('task1');
return setTimeout(subTimer.done(callback), 40);
},
function(callback) {
var subTimer = timer.split('task2');
somethingSynchronous();
subTimer.end();
return callback();
},
function(callback) {
var subTimer = timer.split('task3');
return async.map(
[1, 2, 3],
function(item, next) {
var itemTimer = subTimer.split('item' + item);
databaseLookup(item, itemTimer.done(next));
},
function(err, results) {
subTimer.end();
var data = results.map(function(a) { return a.data; });
return callback(err, data);
}
);
}
],
function(err, data) {
timer.end();
console.log(util.inspect(timer.getResult(), false, 4));
}
);
|
var async = require('async');
var timetree = require('../');
var util = require('util');
var timer = timetree('example');
return async.waterfall(
[
function(callback) {
var subTimer = timer.split('task1');
return setTimeout(function() {
subTimer.end();
return callback();
}, 40);
},
function(callback) {
var subTimer = timer.split('task2');
return setTimeout(function() {
subTimer.end();
return callback();
}, 40);
},
function(callback) {
var subTimer = timer.split('task3');
return async.each([1, 2, 3],
function(item, callback) {
var itemTimer = subTimer.split('item' + item);
setTimeout(function() {
itemTimer.end();
return callback();
}, 10);
},
function() {
subTimer.end();
return callback();
}
);
}
],
function() {
timer.end();
console.log(util.inspect(timer.getResult(), false, 4));
}
); |
Use POST instead of GET | /* Global variables to cache the user and tweet data. */
var user;
var tweet_data;
function submit_username() {
var val = $('#usernamefield').val();
/* We can use the cache and return. */
if (user == val) {
generate_tweet(tweet_data);
return false;
}
user = val;
$('#tweet').html('Getting tweets...');
set_user(user);
$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + user + '&count=200&trim_user=1&callback=?',
function(j) {
tweet_data = $.toJSON(j);
generate_tweet(tweet_data);
}
);
return false;
}
function set_user(u) {
$('#user').html('Getting user...');
$('#usernamefield').val(u);
$.getJSON('http://api.twitter.com/1/users/show.json?screen_name=' + u + '&callback=?',
function(j) {
$('#user').html('Processing user...');
$.post('user/', {data: $.toJSON(j)}, function(h) {
$('#user').html(h);
});
}
);
}
function generate_tweet(d) {
$('#tweet').html('Generating tweet...');
$.post('tweet/', {data: d, user: user}, function(h) {
$('#tweet').html(h);
});
}
| /* Global variables to cache the user and tweet data. */
var user;
var tweet_data;
function submit_username() {
var val = $('#usernamefield').val();
/* We can use the cache and return. */
if (user == val) {
generate_tweet(tweet_data);
return false;
}
user = val;
$('#tweet').html('Getting tweets...');
set_user(user);
$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + user + '&count=200&trim_user=1&callback=?',
function(j) {
tweet_data = $.toJSON(j);
generate_tweet(tweet_data);
}
);
return false;
}
function set_user(u) {
$('#user').html('Getting user...');
$('#usernamefield').val(u);
$.getJSON('http://api.twitter.com/1/users/show.json?screen_name=' + u + '&callback=?',
function(j) {
$('#user').html('Processing user...');
$.get('user/', {data: $.toJSON(j)}, function(h) {
$('#user').html(h);
});
}
);
}
function generate_tweet(d) {
$('#tweet').html('Generating tweet...');
$.get('tweet/', {data: d, user: user}, function(h) {
$('#tweet').html(h);
});
}
|
Use T attribute to get transpose | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = np.transpose(0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5)
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
|
Fix can not read property of undefined error | var once = require('once');
module.exports = function () {
var collections = [].slice.call(arguments);
if(!Array.isArray(collections[0])) {
collections = [ collections ];
}
return Promise.all(
collections.map(function(plugins) {
var i = -1;
return new Promise(function(resolve, reject){
var next = function(data) {
var result, done;
if (++i < plugins.length) {
done = once(function(err, data){
if(err) {
reject(err);
}
else {
next(data);
}
});
result = plugins[i](data, done);
if(result && typeof result.then == 'function') {
result.then(function(data){
done(null, data);
}, done);
}
}
else {
resolve(data);
}
};
next([]);
});
})
);
};
| var once = require('once');
module.exports = function () {
var collections = [].slice.call(arguments);
if(!Array.isArray(collections[0])) {
collections = [ collections ];
}
return Promise.all(
collections.map(function(plugins) {
var i = -1;
return new Promise(function(resolve, reject){
var next = function(data) {
var result, done;
if (++i < plugins.length) {
done = once(function(err, data){
if(err) {
reject(err);
}
else {
next(data);
}
});
result = plugins[i](data, done);
if(typeof result.then == 'function') {
result.then(function(data){
done(null, data);
}, done);
}
}
else {
resolve(data);
}
};
next([]);
});
})
);
};
|
Fix indentation on single file | "use strict";
module.exports = function(connection, parsed, data, callback) {
if (!parsed.attributes ||
parsed.attributes.length !== 1 ||
!parsed.attributes[0] ||
["STRING", "LITERAL", "ATOM"].indexOf(parsed.attributes[0].type) < 0
) {
connection.send({
tag: parsed.tag,
command: "BAD",
attributes: [{
type: "TEXT",
value: "SUBSCRIBE expects mailbox name"
}]
}, "INVALID COMMAND", parsed, data);
return callback();
}
if (["Authenticated", "Selected"].indexOf(connection.state) < 0) {
connection.send({
tag: parsed.tag,
command: "BAD",
attributes: [{
type: "TEXT",
value: "Log in first"
}]
}, "SUBSCRIBE FAILED", parsed, data);
return callback();
}
var path = parsed.attributes[0].value;
connection.subscribeFolder(path,function (err) {
if (err) {
connection.send({
tag: parsed.tag,
command: "BAD",
attributes: [{
type: "TEXT",
value: "Invalid mailbox name"
}]
}, "SUBSCRIBE FAILED", parsed, data);
return callback();
}
connection.send({
tag: parsed.tag,
command: "OK",
attributes: [{
type: "TEXT",
value: "Status completed"
}]
}, "SUBSCRIBE", parsed, data);
return callback();
});
};
| "use strict";
module.exports = function(connection, parsed, data, callback) {
if (!parsed.attributes ||
parsed.attributes.length !== 1 ||
!parsed.attributes[0] ||
["STRING", "LITERAL", "ATOM"].indexOf(parsed.attributes[0].type) < 0
) {
connection.send({
tag: parsed.tag,
command: "BAD",
attributes: [{
type: "TEXT",
value: "SUBSCRIBE expects mailbox name"
}]
}, "INVALID COMMAND", parsed, data);
return callback();
}
if (["Authenticated", "Selected"].indexOf(connection.state) < 0) {
connection.send({
tag: parsed.tag,
command: "BAD",
attributes: [{
type: "TEXT",
value: "Log in first"
}]
}, "SUBSCRIBE FAILED", parsed, data);
return callback();
}
var path = parsed.attributes[0].value;
connection.subscribeFolder(path,function (err) {
if (err) {
connection.send({
tag: parsed.tag,
command: "BAD",
attributes: [{
type: "TEXT",
value: "Invalid mailbox name"
}]
}, "SUBSCRIBE FAILED", parsed, data);
return callback();
}
connection.send({
tag: parsed.tag,
command: "OK",
attributes: [{
type: "TEXT",
value: "Status completed"
}]
}, "SUBSCRIBE", parsed, data);
return callback();
});
}; |
ref: Disable select for update on build mutation | from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
# def select_resource_for_update(self) -> bool:
# return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
| from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
def select_resource_for_update(self) -> bool:
return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
|
Add missing commands to default help prompt | import backend.Core;
import java.io.IOException;
import parse.GreetParser;
import parse.StepParser;
public class App {
public String getGreeting() {
return "Hello world.";
}
/**
* Main entry point to G2Tutorial.
*
* @param args commandline arguments
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Available commands:\n\tgreet, init, step");
System.exit(1);
}
if (args[0].equals("greet")) {
// Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
} else if (args[0].equals("init")) {
// Initializes an empty git repo
try {
Core.initCore();
} catch (IOException e) {
System.err.println("Could not init g2t");
e.printStackTrace();
}
System.exit(0);
} else if (args[0].equals("step")) {
// Commits the current changes as a step and starts a new step
Core c = null;
try {
c = new Core();
} catch (IOException e) {
System.err.println("g2t is not initialized");
e.printStackTrace();
}
StepParser p = new StepParser(args, c);
p.parse();
} else {
System.out.println("Available commands:\n"
+ "\tgreet, init, step");
System.exit(1);
}
}
}
| import backend.Core;
import java.io.IOException;
import parse.GreetParser;
import parse.StepParser;
public class App {
public String getGreeting() {
return "Hello world.";
}
/**
* Main entry point to G2Tutorial.
*
* @param args commandline arguments
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Available commands:\n\tgreet");
System.exit(1);
}
if (args[0].equals("greet")) {
// Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
} else if (args[0].equals("init")) {
// Initializes an empty git repo
try {
Core.initCore();
} catch (IOException e) {
System.err.println("Could not init g2t");
e.printStackTrace();
}
System.exit(0);
} else if (args[0].equals("step")) {
// Commits the current changes as a step and starts a new step
Core c = null;
try {
c = new Core();
} catch (IOException e) {
System.err.println("g2t is not initialized");
e.printStackTrace();
}
StepParser p = new StepParser(args, c);
p.parse();
} else {
System.out.println("Available commands:\n"
+ "\tgreet, init, step");
System.exit(1);
}
}
}
|
Update registry class and interface references | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\PricingBundle\Calculator;
use Sylius\Bundle\PricingBundle\Model\PriceableInterface;
use Sylius\Component\Registry\ServiceRegistryInterface;
/**
* This class delegates the calculation of charge for particular subject
* to a correct calculator instance, based on the type defined on the priceable.
*
* @author Paweł Jędrzejewski <[email protected]>
*/
class DelegatingCalculator implements DelegatingCalculatorInterface
{
/**
* Calculator registry.
*
* @var ServiceRegistryInterface
*/
protected $registry;
/**
* Constructor.
*
* @param ServiceRegistryInterface $registry
*/
public function __construct(ServiceRegistryInterface $registry)
{
$this->registry = $registry;
}
/**
* {@inheritdoc}
*/
public function calculate(PriceableInterface $subject, array $context = array())
{
if (null === $type = $subject->getPricingCalculator()) {
throw new \InvalidArgumentException('Cannot calculate the price for PriceableInterface instance without calculator defined.');
}
$calculator = $this->registry->get($type);
return $calculator->calculate($subject, $subject->getPricingConfiguration(), $context);
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\PricingBundle\Calculator;
use Sylius\Bundle\PricingBundle\Model\PriceableInterface;
use Sylius\Bundle\ResourceBundle\Registry\ServiceRegistryInterface;
/**
* This class delegates the calculation of charge for particular subject
* to a correct calculator instance, based on the type defined on the priceable.
*
* @author Paweł Jędrzejewski <[email protected]>
*/
class DelegatingCalculator implements DelegatingCalculatorInterface
{
/**
* Calculator registry.
*
* @var ServiceRegistryInterface
*/
protected $registry;
/**
* Constructor.
*
* @param ServiceRegistryInterface $registry
*/
public function __construct(ServiceRegistryInterface $registry)
{
$this->registry = $registry;
}
/**
* {@inheritdoc}
*/
public function calculate(PriceableInterface $subject, array $context = array())
{
if (null === $type = $subject->getPricingCalculator()) {
throw new \InvalidArgumentException('Cannot calculate the price for PriceableInterface instance without calculator defined.');
}
$calculator = $this->registry->get($type);
return $calculator->calculate($subject, $subject->getPricingConfiguration(), $context);
}
}
|
Allow karma to load plugins automatically | var webpack = require('webpack');
// TODO: use BowerWebpackPlugin
// var BowerWebpackPlugin = require('bower-webpack-plugin');
var webpackCommon = require('./webpack.common.config.js');
// Put in separate file?
var webpackTestConfig = {
devtool: 'inline-source-map',
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
}),
],
resolve: webpackCommon.resolve,
module: {
loaders: [
// Assume test files are ES6
{test: /\.test\.js$/, loader: 'babel-loader'},
]
}
};
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['mocha', 'sinon'],
files: [
// Only need to target one file, which will load all files in tests/ that
// match *.test.js
'website/static/js/tests/tests.webpack.js',
],
reporters: ['spec'],
preprocessors: {
// add webpack as preprocessor
'website/static/js/tests/tests.webpack.js': ['webpack', 'sourcemap'],
},
webpack: webpackTestConfig,
webpackServer: {
noInfo: true // don't spam the console
}
});
};
| var webpack = require('webpack');
// TODO: use BowerWebpackPlugin
// var BowerWebpackPlugin = require('bower-webpack-plugin');
var webpackCommon = require('./webpack.common.config.js');
// Put in separate file?
var webpackTestConfig = {
devtool: 'inline-source-map',
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
}),
],
resolve: webpackCommon.resolve,
module: {
loaders: [
{test: /\.test\.js$/, loader: 'babel-loader'},
]
}
};
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['mocha', 'sinon'],
files: [
// Only need to target one file, which will load all files in tests/ that
// match *.test.js
'website/static/js/tests/tests.webpack.js',
],
reporters: ['spec'],
preprocessors: {
// add webpack as preprocessor
'website/static/js/tests/tests.webpack.js': ['webpack', 'sourcemap'],
},
webpack: webpackTestConfig,
webpackServer: {
noInfo: true // don't spam the console
},
plugins: [
require('karma-webpack'),
require('karma-mocha'),
require('karma-sourcemap-loader'),
require('karma-chrome-launcher'),
require('karma-spec-reporter'),
require('karma-sinon')
]
});
};
|
Fix for MPLY-8221. Survey now handle a null survey url and urls that don't start with http or https. Buddy: Vimmy | // Copyright eeGeo Ltd (2012-2016), All Rights Reserved
package com.eegeo.surveys;
import com.eegeo.entrypointinfrastructure.MainActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
public class SurveyView {
private MainActivity m_activity = null;
private static AlertDialog m_options = null;
public SurveyView(MainActivity activity) {
m_activity = activity;
}
protected void startUxCallback(String timerSurveyUrl)
{
AlertDialog.Builder builder = new AlertDialog.Builder(m_activity);
builder.setTitle("Want to help us improve our map?");
builder.setMessage("Just a few quick questions - honest!");
builder.setPositiveButton("Yes", showSurvey(timerSurveyUrl));
builder.setNegativeButton("No", null);
builder.setCancelable(false);
m_options = builder.show();
}
private DialogInterface.OnClickListener showSurvey(final String timerSurveyUrl)
{
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String prefixedUrl = "";
if (!timerSurveyUrl.isEmpty())
{
if (!timerSurveyUrl.startsWith("https://") && !timerSurveyUrl.startsWith("http://")) {
prefixedUrl = "http://" + timerSurveyUrl;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(prefixedUrl));
m_activity.startActivity(browserIntent);
}
m_options = null;
}
};
}
}
| // Copyright eeGeo Ltd (2012-2016), All Rights Reserved
package com.eegeo.surveys;
import com.eegeo.entrypointinfrastructure.MainActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
public class SurveyView {
private MainActivity m_activity = null;
private static AlertDialog m_options = null;
public SurveyView(MainActivity activity) {
m_activity = activity;
}
protected void startUxCallback(String timerSurveyUrl)
{
AlertDialog.Builder builder = new AlertDialog.Builder(m_activity);
builder.setTitle("Want to help us improve our map?");
builder.setMessage("Just a few quick questions - honest!");
builder.setPositiveButton("Yes", showSurvey(timerSurveyUrl));
builder.setNegativeButton("No", null);
builder.setCancelable(false);
m_options = builder.show();
}
private DialogInterface.OnClickListener showSurvey(final String timerSurveyUrl)
{
return new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(timerSurveyUrl));
m_activity.startActivity(browserIntent);
m_options = null;
}
};
}
}
|
Fix "import star" feature support
`dict.keys()` returns `dict_keys` object in py3,
which does not support indexing. | import sys
from functools import partial, update_wrapper
from django.utils import six
def proxy(attr, default):
def wrapper(self):
# It has to be most recent,
# to override settings in tests
from django.conf import settings
value = getattr(settings, attr, default)
if callable(value):
func = partial(value, self)
return update_wrapper(func, value)
elif isinstance(value, property):
return value.__get__(self)
return value
return property(wrapper)
class ConfMeta(type):
def __new__(mcs, name, bases, attrs):
prefix = attrs.get('__prefix__', name.upper()) + '_'
fields = {
key: proxy(prefix + key, value)
for key, value in attrs.items()
if not key.startswith('__')
}
attrs.update(fields, __all__=tuple(fields))
# Ready to build
cls = super(ConfMeta, mcs).__new__(mcs, name, bases, attrs)
# Sets non-abstract conf as module
abstract = attrs.get('__abstract__', False)
if not abstract:
# http://mail.python.org/pipermail/python-ideas/2012-May/
# 014969.html
ins = cls()
ins.__name__ = ins.__module__
sys.modules[ins.__module__] = ins
return cls
class Conf(six.with_metaclass(ConfMeta)):
__abstract__ = True
| import sys
from functools import partial, update_wrapper
from django.utils import six
def proxy(attr, default):
def wrapper(self):
# It has to be most recent,
# to override settings in tests
from django.conf import settings
value = getattr(settings, attr, default)
if callable(value):
func = partial(value, self)
return update_wrapper(func, value)
elif isinstance(value, property):
return value.__get__(self)
return value
return property(wrapper)
class ConfMeta(type):
def __new__(mcs, name, bases, attrs):
prefix = attrs.get('__prefix__', name.upper()) + '_'
fields = {
key: proxy(prefix + key, value)
for key, value in attrs.items()
if not key.startswith('__')
}
attrs.update(fields, __all__=fields.keys())
# Ready to build
cls = super(ConfMeta, mcs).__new__(mcs, name, bases, attrs)
# Sets non-abstract conf as module
abstract = attrs.get('__abstract__', False)
if not abstract:
# http://mail.python.org/pipermail/python-ideas/2012-May/
# 014969.html
ins = cls()
ins.__name__ = ins.__module__
sys.modules[ins.__module__] = ins
return cls
class Conf(six.with_metaclass(ConfMeta)):
__abstract__ = True
|
Add entry point for generating reports | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup, find_packages
PACKAGE_VERSION = '0.1'
deps = [
'flask',
'Jinja2',
'manifestparser',
'mongoengine',
'mozfile',
'mozillapulse',
'mozlog',
]
setup(name='test-informant',
version=PACKAGE_VERSION,
description='A web service for monitoring and reporting the state of test manifests.',
long_description='See https://github.com/ahal/test-informant',
classifiers=['Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords='mozilla',
author='Andrew Halberstadt',
author_email='[email protected]',
url='https://github.com/ahal/test-informant',
license='MPL 2.0',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points="""
[console_scripts]
test-informant = informant.pulse_listener:run
generate-informant-report = tools.generate_report:cli
""")
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup, find_packages
PACKAGE_VERSION = '0.1'
deps = [
'flask',
'Jinja2',
'manifestparser',
'mongoengine',
'mozfile',
'mozillapulse',
'mozlog',
]
setup(name='test-informant',
version=PACKAGE_VERSION,
description='A web service for monitoring and reporting the state of test manifests.',
long_description='See https://github.com/ahal/test-informant',
classifiers=['Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords='mozilla',
author='Andrew Halberstadt',
author_email='[email protected]',
url='https://github.com/ahal/test-informant',
license='MPL 2.0',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points="""
[console_scripts]
test-informant = informant.pulse_listener:run
""")
|
BAP-457: Delete user error
- fix bug | /**
* Delete action with confirm dialog, triggers REST DELETE request
*
* @class OroApp.DatagridActionDelete
* @extends OroApp.DatagridAction
*/
OroApp.DatagridActionDelete = OroApp.DatagridAction.extend({
/** @property Backbone.BootstrapModal */
errorModal: undefined,
/** @property Backbone.BootstrapModal */
confirmModal: undefined,
/**
* Execute delete model
*/
execute: function() {
this.getConfirmDialog().open();
},
/**
* Confirm delete item
*/
doDelete: function() {
var self = this;
this.model.destroy({
url: this.getLink(),
wait: true,
error: function() {
self.getErrorDialog().open();
}
});
},
/**
* Get view for confirm modal
*
* @return {Backbone.BootstrapModal}
*/
getConfirmDialog: function() {
if (!this.confirmModal) {
this.confirmModal = new Backbone.BootstrapModal({
title: 'Delete Confirmation',
content: 'Are you sure you want to delete this item?'
});
this.confirmModal.on('ok', _.bind(this.doDelete, this));
}
return this.confirmModal;
},
/**
* Get view for error modal
*
* @return {Backbone.BootstrapModal}
*/
getErrorDialog: function() {
if (!this.errorModal) {
this.confirmModal = new Backbone.BootstrapModal({
title: 'Delete Error',
content: 'Cannot delete item.',
cancelText: false
});
}
return this.confirmModal;
}
});
| /**
* Delete action with confirm dialog, triggers REST DELETE request
*
* @class OroApp.DatagridActionDelete
* @extends OroApp.DatagridAction
*/
OroApp.DatagridActionDelete = OroApp.DatagridAction.extend({
/** @property Backbone.BootstrapModal */
errorModal: undefined,
/** @property Backbone.BootstrapModal */
confirmModal: undefined,
/**
* Execute delete model
*/
execute: function() {
this.getConfirmDialog().open($.proxy(this.doDelete, this));
},
/**
* Confirm delete item
*/
doDelete: function() {
var self = this;
this.model.destroy({
url: this.getLink(),
wait: true,
error: function() {
self.getErrorDialog().open();
}
});
},
/**
* Get view for confirm modal
*
* @return {Backbone.BootstrapModal}
*/
getConfirmDialog: function() {
if (!this.confirmModal) {
this.confirmModal = new Backbone.BootstrapModal({
title: 'Delete Confirmation',
content: 'Are you sure you want to delete this item?'
});
}
return this.confirmModal;
},
/**
* Get view for error modal
*
* @return {Backbone.BootstrapModal}
*/
getErrorDialog: function() {
if (!this.errorModal) {
this.confirmModal = new Backbone.BootstrapModal({
title: 'Delete Error',
content: 'Cannot delete item.',
cancelText: false
});
}
return this.confirmModal;
}
});
|
Use the same name for the servers for the memcached and memcache service providers | <?php
namespace GeekCache\Cache;
class MemcachedServiceProvider
{
public function __construct($container)
{
$this->container = $container;
}
public function register()
{
$this->container['geekcache.memcached'] = $this->container->share(function ($c) {
$memcached = new \Memcached();
$servers = isset($c['geekcache.memcache.servers'])
? $c['geekcache.memcache.servers']
: array('localhost' => array(11211));
foreach ($servers as $ip => $ports) {
foreach ($ports as $port) {
$flatServers[] = array($ip, (int)$port);
}
};
$memcached->addServers($flatServers);
return $memcached;
});
$this->container['geekcache.persistentincrementablecache.unnamespaced'] = $this->container->share(function ($c) {
return new IncrementableMemcachedCache($c['geekcache.memcached']);
});
$this->container['geekcache.persistentcache.unnamespaced'] = $this->container->share(function ($c) {
return new MemcachedCache($c['geekcache.memcached']);
});
}
}
| <?php
namespace GeekCache\Cache;
class MemcachedServiceProvider
{
public function __construct($container)
{
$this->container = $container;
}
public function register()
{
$this->container['geekcache.memcached'] = $this->container->share(function ($c) {
$memcached = new \Memcached();
$servers = isset($c['geekcache.memcached.servers'])
? $c['geekcache.memcached.servers']
: array('localhost' => array(11211));
foreach ($servers as $ip => $ports) {
foreach ($ports as $port) {
$flatServers[] = array($ip, (int)$port);
}
};
$memcached->addServers($flatServers);
return $memcached;
});
$this->container['geekcache.persistentincrementablecache.unnamespaced'] = $this->container->share(function ($c) {
return new IncrementableMemcachedCache($c['geekcache.memcached']);
});
$this->container['geekcache.persistentcache.unnamespaced'] = $this->container->share(function ($c) {
return new MemcachedCache($c['geekcache.memcached']);
});
}
}
|
FIX - override ngModel.$isEmpty to work as in input type checkbox. | /**
* @author xialei <[email protected]>
*/
angular.module('angular-icheck', [])
.directive('iCheck', [function () {
return {
restrict: 'EA',
transclude: true,
require: 'ngModel',
replace: true,
template: '<div class="angular-icheck">\n <div class="checkbox"></div>\n <div class="label" ng-transclude></div>\n</div>',
link: function (scope, ele, attrs, ctrl) {
var box = angular.element(ele[0].querySelector('.checkbox'));
ele.bind("click", function () {
box.toggleClass("checked");
ctrl.$setViewValue(box.hasClass("checked"));
});
ctrl.$render = function () {
if (ctrl.$viewValue) {
box.addClass("checked");
} else {
box.removeClass("checked");
}
};
// https://github.com/angular/angular.js/issues/2594
// override $isEmpty method
ctrl.$isEmpty = function(value) {
return value === false;
};
ctrl.$setViewValue(box.hasClass("checked"));
ctrl.$validate();
}
}
}]); | /**
* @author xialei <[email protected]>
*/
angular.module('angular-icheck', [])
.directive('iCheck', [function () {
return {
restrict: 'EA',
transclude: true,
require: 'ngModel',
replace: true,
template: '<div class="angular-icheck">\n <div class="checkbox"></div>\n <div class="label" ng-transclude></div>\n</div>',
link: function (scope, ele, attrs, ctrl) {
var box = angular.element(ele[0].querySelector('.checkbox'));
ele.bind("click", function () {
box.toggleClass("checked");
ctrl.$setViewValue(box.hasClass("checked"));
});
ctrl.$render = function () {
if (ctrl.$viewValue) {
box.addClass("checked");
}else{
box.removeClass("checked");
}
};
}
}
}]); |
Add SSL to cx-freeze packages | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
| import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
|
Return proper result for Q012 | 'use strict';
var Transmittal = require('../models/transmittal');
module.exports = {
isValidTimestamp: function(activityYear, respondentID, timestamp, callback) {
Transmittal.findOne({'activity_year': activityYear - 1, 'respondent_id': respondentID}, function(err, data) {
if (err) {
return callback(err, null);
}
var result = {result: false};
if (data !== null) {
var year = timestamp.substring(0,4),
month = timestamp.substring(4,6),
day = timestamp.substring(6,8),
hour = timestamp.substring(8,10),
minute = timestamp.substring(10,12);
var timestampDate = new Date(year, month - 1, day - 1, hour, minute);
if (timestampDate > data.timestamp) {
result.result = true;
}
}
return callback(null, result);
});
},
isTaxIDTheSameAsLastYear: function(activityYear, respondentID, taxID, callback) {
Transmittal.findOne({'activity_year': activityYear - 1, 'respondent_id': respondentID}, function(err, data) {
if (err) {
return callback(err, null);
}
var result = {
'Current Year Tax ID': taxID,
'Previous Year Tax ID': '',
'result': false
};
if (data !== null) {
result['Previous Year Tax ID'] = data.tax_id;
if (data.tax_id === taxID) {
result.result = true;
}
}
return callback(null, result);
});
}
};
| 'use strict';
var Transmittal = require('../models/transmittal');
module.exports = {
isValidTimestamp: function(activityYear, respondentID, timestamp, callback) {
Transmittal.findOne({'activity_year': activityYear - 1, 'respondent_id': respondentID}, function(err, data) {
if (err) {
return callback(err, null);
}
var result = {result: false};
if (data !== null) {
var year = timestamp.substring(0,4),
month = timestamp.substring(4,6),
day = timestamp.substring(6,8),
hour = timestamp.substring(8,10),
minute = timestamp.substring(10,12);
var timestampDate = new Date(year, month - 1, day - 1, hour, minute);
if (timestampDate > data.timestamp) {
result.result = true;
}
}
return callback(null, result);
});
},
isTaxIDTheSameAsLastYear: function(activityYear, respondentID, taxID, callback) {
Transmittal.findOne({'activity_year': activityYear - 1, 'respondent_id': respondentID, 'tax_id': taxID}, function(err, data) {
if (err) {
return callback(err, null);
}
if (data !== null) {
return callback(null, {'result': true});
}
return callback(null, {'result': false});
});
}
};
|
Add the URL to the exception messsage. | <?php
namespace CommerceGuys\Platform\Cli\Api;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Service\Client;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Common\Exception\ExceptionCollection;
class PlatformClient extends Client
{
/**
* @{inheritdoc}
*
* Catch ClientErrorResponseException to alter the message.
*/
public function send($requests)
{
if (!($requests instanceof RequestInterface)) {
return $this->sendMultiple($requests);
}
try {
try {
/** @var $requests RequestInterface */
$this->getCurlMulti()
->add($requests)
->send();
return $requests->getResponse();
} catch (ExceptionCollection $e) {
throw $e->getFirst();
}
}
catch (ClientErrorResponseException $e) {
$response = $e->getResponse();
if ($response && ($json = $response->json())) {
$url = $e->getRequest()->getUrl();
$reason = $response->getReasonPhrase();
$code = $json['code'];
$message = $json['message'];
if (!empty($json['detail'])) {
$message .= "\n " . $json['detail'];
}
throw new \RuntimeException("The Platform.sh API call failed.\nURL: $url\nError: $code $reason\nMessage:\n $message");
}
throw $e;
}
}
}
| <?php
namespace CommerceGuys\Platform\Cli\Api;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Service\Client;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Common\Exception\ExceptionCollection;
class PlatformClient extends Client
{
/**
* @{inheritdoc}
*
* Catch ClientErrorResponseException to alter the message.
*/
public function send($requests)
{
if (!($requests instanceof RequestInterface)) {
return $this->sendMultiple($requests);
}
try {
try {
/** @var $requests RequestInterface */
$this->getCurlMulti()
->add($requests)
->send();
return $requests->getResponse();
} catch (ExceptionCollection $e) {
throw $e->getFirst();
}
}
catch (ClientErrorResponseException $e) {
$response = $e->getResponse();
if ($response && ($json = $response->json())) {
$reason = $response->getReasonPhrase();
$code = $json['code'];
$message = $json['message'];
if (!empty($json['detail'])) {
$message .= "\n " . $json['detail'];
}
throw new \RuntimeException("The Platform.sh API call failed.\nError: $code $reason\nMessage:\n $message");
}
throw $e;
}
}
}
|
Call Experiment.publish in run method | import traceback
from laboratory.observation import Observation, Test
from laboratory import exceptions
class Experiment(object):
def __init__(self, name='Experiment', raise_on_mismatch=False):
self.name = name
self.raise_on_mismatch = raise_on_mismatch
self._control = None
self.observations = []
def control(self):
self._control = Observation('Control')
return Test('Control', True, self._control)
def candidate(self, name='Candidate'):
observation = Observation(name)
self.observations.append(observation)
return Test(name, False, observation)
def run(self):
control = self._control
if control is None:
raise exceptions.LaboratoryException(
'Your experiment must record a control case'
)
match = self.compare(control, *self.observations)
self.publish(match)
return control.value
def compare(self, control, *candidates):
for observation in candidates:
if observation.failure or control.value != observation.value:
return self._comparison_mismatch(control, observation)
return True
def _comparison_mismatch(self, control, observation):
if self.raise_on_mismatch:
if observation.failure:
msg = '%s raised an exception:\n%s' % (
observation.name, traceback.format_exc(observation.exception)
)
else:
msg = '%s does not match control value (%s != %s)' % (
observation.name, control.value, observation.value
)
raise exceptions.MismatchException(msg)
return False
def publish(self, match):
return
| import traceback
from laboratory.observation import Observation, Test
from laboratory import exceptions
class Experiment(object):
def __init__(self, name='Experiment', raise_on_mismatch=False):
self.name = name
self.raise_on_mismatch = raise_on_mismatch
self._control = None
self.observations = []
def control(self):
self._control = Observation('Control')
return Test('Control', True, self._control)
def candidate(self, name='Candidate'):
observation = Observation(name)
self.observations.append(observation)
return Test(name, False, observation)
def run(self):
control = self._control
if control is None:
raise exceptions.LaboratoryException(
'Your experiment must record a control case'
)
match = self.compare(control, *self.observations)
return control.value
def compare(self, control, *candidates):
for observation in candidates:
if observation.failure or control.value != observation.value:
return self._comparison_mismatch(control, observation)
return True
def _comparison_mismatch(self, control, observation):
if self.raise_on_mismatch:
if observation.failure:
msg = '%s raised an exception:\n%s' % (
observation.name, traceback.format_exc(observation.exception)
)
else:
msg = '%s does not match control value (%s != %s)' % (
observation.name, control.value, observation.value
)
raise exceptions.MismatchException(msg)
return False
def publish(self):
raise NotImplementedError
|
Make entity manager available to all entity services | <?php
namespace SimplyTestable\ApiBundle\Services;
use Doctrine\ORM\EntityManager;
use SimplyTestable\ApiBundle\Entity\WebSite;
use webignition\NormalisedUrl\NormalisedUrl;
abstract class EntityService {
/**
*
* @var \Doctrine\ORM\EntityManager
*/
protected $entityManager;
/**
*
* @var \Doctrine\ORM\EntityRepository
*/
private $entityRepository;
/**
*
* @param \Doctrine\ORM\EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager) {
$this->entityManager = $entityManager;
}
abstract protected function getEntityName();
/**
*
* @param string $entityName
*/
public function setEntityName($entityName) {
$this->entityName = $entityName;
}
/**
*
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager() {
return $this->entityManager;
}
/**
*
* @return \Doctrine\ORM\EntityRepository
*/
public function getEntityRepository() {
if (is_null($this->entityRepository)) {
$this->entityRepository = $this->entityManager->getRepository($this->getEntityName());
}
return $this->entityRepository;
}
} | <?php
namespace SimplyTestable\ApiBundle\Services;
use Doctrine\ORM\EntityManager;
use SimplyTestable\ApiBundle\Entity\WebSite;
use webignition\NormalisedUrl\NormalisedUrl;
abstract class EntityService {
/**
*
* @var \Doctrine\ORM\EntityManager
*/
private $entityManager;
/**
*
* @var \Doctrine\ORM\EntityRepository
*/
private $entityRepository;
/**
*
* @param \Doctrine\ORM\EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager) {
$this->entityManager = $entityManager;
}
abstract protected function getEntityName();
/**
*
* @param string $entityName
*/
public function setEntityName($entityName) {
$this->entityName = $entityName;
}
/**
*
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager() {
return $this->entityManager;
}
/**
*
* @return \Doctrine\ORM\EntityRepository
*/
public function getEntityRepository() {
if (is_null($this->entityRepository)) {
$this->entityRepository = $this->entityManager->getRepository($this->getEntityName());
}
return $this->entityRepository;
}
} |
Change User to use Django's AbstractBaseUser | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
date_joined = models.DateTimeField(
auto_now_add=True,
help_text=("The date the user joined")
)
is_active = models.BooleanField(
default=True,
help_text=("The user active state")
)
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
password = models.CharField(
max_length=100,
help_text=("The user's password.")
)
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
cookie = models.CharField(
default='',
max_length=100,
db_index=True,
help_text=("The user's active cookie.")
)
|
Change mapping to avoid warning | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.OneToOneField(
User, related_name="metadata", on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager"
| from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.ForeignKey(
User, related_name="metadata", unique=True, on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager"
|
Add unit test for valid blacklist | #!/usr/bin/env python3
import argparse
from passgen import make_parser, sanitize_input
import unittest
class PassGenTestCase(unittest.TestCase):
def setUp(self):
self.parse_args = make_parser().parse_args
def test_duplicate_flags(self):
for duplicate_flag in ['dd', 'll', 'uu', 'pp', 'ss']:
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-f', duplicate_flag]))
def test_no_valid_flags(self):
for invalid_flag in ['a', 'b', 'c']:
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-f', invalid_flag]))
def test_limit_lower_bound(self):
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-i', '0']))
def test_limit_upper_bound(self):
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-i', '9']))
def test_valid_flags(self):
for valid_flag in ['dl', 'du', 'dp', 'ds', 'dlu', 'dlup', 'dlups']:
dictionary = sanitize_input(self.parse_args(['-f', valid_flag]))
self.assertIsInstance(dictionary, argparse.Namespace)
def test_valid_blacklist(self):
dictionary = sanitize_input(self.parse_args(['-f', 'd', '-b', '012345678']))
self.assertIsInstance(dictionary, argparse.Namespace)
if __name__ == '__main__':
unittest.main(buffer=True)
| #!/usr/bin/env python3
import argparse
from passgen import make_parser, sanitize_input
import unittest
class PassGenTestCase(unittest.TestCase):
def setUp(self):
self.parse_args = make_parser().parse_args
def test_duplicate_flags(self):
for duplicate_flag in ['dd', 'll', 'uu', 'pp', 'ss']:
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-f', duplicate_flag]))
def test_no_valid_flags(self):
for invalid_flag in ['a', 'b', 'c']:
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-f', invalid_flag]))
def test_limit_lower_bound(self):
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-i', '0']))
def test_limit_upper_bound(self):
with self.assertRaises(ValueError):
sanitize_input(self.parse_args(['-i', '9']))
def test_valid_flags(self):
for valid_flag in ['dl', 'du', 'dp', 'ds', 'dlu', 'dlup', 'dlups']:
dictionary = sanitize_input(self.parse_args(['-f', valid_flag]))
self.assertIsInstance(dictionary, argparse.Namespace)
if __name__ == '__main__':
unittest.main(buffer=True)
|
[WEB-465] Fix typo in "powerful apps" | import React from 'react';
import Helmet from 'react-helmet';
import Hero from './Hero';
const LandingPageHero = ({ title, headline }, { modals }) => {
return (
<div>
<Helmet title={title} />
<Hero
headline={headline}
textline={`Increase your productivity, focus on new features, and scale beyond millions of users without
managing servers.`}
image={
<img
src={require('../pages/home/build-powerful-apps-in-half-the-time.svg')}
alt="serverless app platform"
/>
}
>
<div className="hero__text__button-container">
<span
className="button button--large button--featured"
onClick={modals.signUp.open}
>
Get Started for Free
</span>
<p className="hero__text__button-description">
6 months free • No credit card required
</p>
</div>
</Hero>
</div>
);
};
LandingPageHero.defaultProps = {
title: 'Build powerful apps in half the time | Syncano',
headline: <span>Build powerful apps<br />in half the time</span>
};
LandingPageHero.contextTypes = {
modals: React.PropTypes.object
};
export default LandingPageHero;
| import React from 'react';
import Helmet from 'react-helmet';
import Hero from './Hero';
const LandingPageHero = ({ title, headline }, { modals }) => {
return (
<div>
<Helmet title={title} />
<Hero
headline={headline}
textline={`Increase your productivity, focus on new features, and scale beyond millions of users without
managing servers.`}
image={
<img
src={require('../pages/home/build-powerful-apps-in-half-the-time.svg')}
alt="serverless app platform"
/>
}
>
<div className="hero__text__button-container">
<span
className="button button--large button--featured"
onClick={modals.signUp.open}
>
Get Started for Free
</span>
<p className="hero__text__button-description">
6 months free • No credit card required
</p>
</div>
</Hero>
</div>
);
};
LandingPageHero.defaultProps = {
title: 'Build powerful apps in half the time | Syncano',
headline: <span>Build powerfulapps<br />in half the time</span>
};
LandingPageHero.contextTypes = {
modals: React.PropTypes.object
};
export default LandingPageHero;
|
Fix double error message when "tour" is missing | 'use strict';
angular.module('alienUiApp').factory('restTechnicalErrorInterceptor', ['$rootScope', '$q', '$window', 'toaster', '$translate',
function($rootScope, $q, $window, toaster, $translate) {
var extractErrorMessage = function(rejection) {
if (UTILS.isDefinedAndNotNull(rejection.data)) {
if (UTILS.isDefinedAndNotNull(rejection.data.error)) {
var error = rejection.data.error;
// Redirect to homepage when the user is not authenticated
if (error.code === 100) {
$window.location.href = '/';
} else {
return {
status: rejection.status,
data: 'ERRORS.' + error.code
};
}
} else {
// Error not defined ==> return the data part
return {
status: rejection.status,
data: rejection.data
};
}
} else {
// rejection.data not defined ==> unknown error
return {
status: rejection.status,
data: 'ERRORS.UNKNOWN'
};
}
};
return {
'responseError': function(rejection) {
var error = extractErrorMessage(rejection);
// Display the toaster message on top with 4000 ms display timeout
// Don't shot toaster for "tour" guides
if (rejection.config.url.indexOf('data/guides') < 0) {
toaster.pop('error', $translate('ERRORS.INTERNAL') + ' - ' + error.status, $translate(error.data), 4000, 'trustedHtml', null);
}
return $q.reject(rejection);
}
};
}
]);
| 'use strict';
angular.module('alienUiApp').factory('restTechnicalErrorInterceptor', ['$rootScope', '$q', '$window', 'toaster', '$translate',
function($rootScope, $q, $window, toaster, $translate) {
var extractErrorMessage = function(rejection) {
if (UTILS.isDefinedAndNotNull(rejection.data)) {
if (UTILS.isDefinedAndNotNull(rejection.data.error)) {
var error = rejection.data.error;
// Redirect to homepage when the user is not authenticated
if (error.code === 100) {
$window.location.href = '/';
} else {
return {
status: rejection.status,
data: 'ERRORS.' + error.code
};
}
} else {
// Error not defined ==> return the data part
return {
status: rejection.status,
data: rejection.data
};
}
} else {
// rejection.data not defined ==> unknown error
return {
status: rejection.status,
data: 'ERRORS.UNKNOWN'
};
}
};
return {
'responseError': function(rejection) {
var error = extractErrorMessage(rejection);
// Display the toaster message on top with 4000 ms display timeout
// Don't shot toaster for "tour" guides
if (error.data.indexOf('/data/guides') < 0) {
toaster.pop('error', $translate('ERRORS.INTERNAL') + ' - ' + error.status, $translate(error.data), 4000, 'trustedHtml', null);
}
return $q.reject(rejection);
}
};
}
]);
|
Update test case for new version of IUCN | <?php
namespace Tests\AppBundle\API\Listing;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class TraitsTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$service = $this->webservice->factory('listing', 'traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => '')),
null
);
$expected = array(
array(
"name" => "Plant Habit",
"trait_type_id" => 1,
"frequency" => 48842
),
array(
"name" => "IUCN Threat Status",
"trait_type_id" => 3,
"frequency" => 23185
),
array(
"name" => "Plant Life Cycle Habit",
"trait_type_id" => 2,
"frequency" => 16819
)
);
$this->assertEquals($expected, $results, 'Search without term and limit, result should be a list of all traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => 'SomethingThatWillNeverBeATraitType')),
null
);
$expected = array();
$this->assertEquals($expected, $results, 'Search term does not hit, result should be an empty array');
}
}
| <?php
namespace Tests\AppBundle\API\Listing;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class TraitsTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$service = $this->webservice->factory('listing', 'traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => '')),
null
);
$expected = array(
array(
"name" => "Plant Habit",
"trait_type_id" => 1,
"frequency" => 48842
),
array(
"name" => "IUCN Threat Status",
"trait_type_id" => 3,
"frequency" => 23194
),
array(
"name" => "Plant Life Cycle Habit",
"trait_type_id" => 2,
"frequency" => 16819
)
);
$this->assertEquals($expected, $results, 'Search without term and limit, result should be a list of all traits');
$results = $service->execute(
new ParameterBag(array('dbversion' => $default_db, 'search' => 'SomethingThatWillNeverBeATraitType')),
null
);
$expected = array();
$this->assertEquals($expected, $results, 'Search term does not hit, result should be an empty array');
}
}
|
Use separate variable names for Visual Studio config/platform. | # -*- coding: utf-8 -*-
from nimp.commands._command import *
from nimp.utilities.build import *
#-------------------------------------------------------------------------------
class VsBuildCommand(Command):
def __init__(self):
Command.__init__(self, 'vs-build', 'Builds a Visual Studio project')
#---------------------------------------------------------------------------
def configure_arguments(self, env, parser):
parser.add_argument('solution',
help = 'Solution file',
metavar = '<FILE>')
parser.add_argument('project',
help = 'Project',
metavar = '<FILE>',
default = 'None')
parser.add_argument('--target',
help = 'Target',
metavar = '<TARGET>',
default = 'Build')
parser.add_argument('-c',
'--vs-configuration',
help = 'configuration to build',
metavar = '<vs-configuration>',
default = 'release')
parser.add_argument('-p',
'--vs-platform',
help = 'platform to build',
metavar = '<vs-platform>',
default = 'Win64')
parser.add_argument('--vs-version',
help = 'VS version to use',
metavar = '<VERSION>',
default = '12')
return True
#---------------------------------------------------------------------------
def run(self, env):
return vsbuild(env.solution, env.vs_platform, env.vs_configuration, env.project, env.vs_version, env.target)
| # -*- coding: utf-8 -*-
from nimp.commands._command import *
from nimp.utilities.build import *
#-------------------------------------------------------------------------------
class VsBuildCommand(Command):
def __init__(self):
Command.__init__(self, 'vs-build', 'Builds a Visual Studio project')
#---------------------------------------------------------------------------
def configure_arguments(self, env, parser):
parser.add_argument('solution',
help = 'Solution file',
metavar = '<FILE>')
parser.add_argument('project',
help = 'Project',
metavar = '<FILE>',
default = 'None')
parser.add_argument('--target',
help = 'Target',
metavar = '<TARGET>',
default = 'Build')
parser.add_argument('-c',
'--configuration',
help = 'configuration to build',
metavar = '<configuration>',
default = 'release')
parser.add_argument('-p',
'--platform',
help = 'platform to build',
metavar = '<platform>',
default = 'Win64')
parser.add_argument('--vs-version',
help = 'VS version to use',
metavar = '<VERSION>',
default = '12')
return True
#---------------------------------------------------------------------------
def run(self, env):
return vsbuild(env.solution, env.platform, env.configuration, env.project, env.vs_version, env.target)
|
Make sure we match the original API for reporter use | 'use strict';
var fs = require('fs'),
jshintPlugin = require('gulp-jshint'),
cache = require('gulp-cache');
var jshintVersion = '0.2.4';
// Add on to the original plugin
jshintPlugin.cached = function (opt) {
var jshintOpts;
if (typeof opt === 'string') {
jshintOpts = fs.readFileSync(opt);
} else {
jshintOpts = JSON.stringify(opt);
}
return cache.proxy('jshint', {
task: jshintPlugin(opt),
key: function (file) {
return [file.contents.toString('utf8'), jshintVersion, jshintOpts].join('');
},
success: function (jshintedFile) {
return jshintedFile.jshint.success;
},
value: function (jshintedFile) {
var result = {
jshint: {
success: jshintedFile.jshint.success,
cached: true
}
};
return result;
}
});
};
// Allow the fileCache to be modified externally
jshintPlugin.cached.fileCache = cache.fileCache;
module.exports = jshintPlugin; | 'use strict';
var fs = require('fs'),
jshintPlugin = require('gulp-jshint'),
cache = require('gulp-cache');
var jshintVersion = '0.2.4';
var task = {
// Allow the original if needed.
original: jshintPlugin,
// Or, the cached version
cached: function (opt) {
var jshintOpts;
if (typeof opt === 'string') {
jshintOpts = fs.readFileSync(opt);
} else {
jshintOpts = JSON.stringify(opt);
}
return cache.proxy('jshint', {
task: jshintPlugin(opt),
key: function (file) {
return [file.contents.toString('utf8'), jshintVersion, jshintOpts].join('');
},
success: function (jshintedFile) {
return jshintedFile.jshint.success;
},
value: function (jshintedFile) {
var result = {
jshint: {
success: jshintedFile.jshint.success,
cached: true
}
};
return result;
}
});
}
};
// Allow the fileCache to be modified externally
task.cached.fileCache = cache.fileCache;
module.exports = task; |
Add bidict to required packages | from setuptools import setup, find_packages
setup(
name='ssbio',
version='0.1',
author='Nathan Mih',
author_email='[email protected]',
license='MIT',
url='http://github.com/nmih/ssbio',
description='Various tools and functions to enable structural systems biology',
packages=find_packages(),
package_dir={'ssbio': 'ssbio'},
package_data={'ssbio': ['ssbio/etc/*']},
scripts = ['ssbio/scripts/cleanpdb', 'ssbio/scripts/aggprop', 'ssbio/scripts/thermostability', 'ssbio/structure/mutatepdb.py', 'ssbio/structure/tleap.py',
'ssbio/databases/drugbank.py', 'ssbio/structure/properties/msmsprops.py',
'ssbio/dock/dock.py'],
long_description=open('README.md').read(),
install_requires=['biopython',
'numpy',
'tqdm',
'pandas',
'requests',
'cachetools',
'bioservices',
'prody',
'xmltodict',
'bidict']
) | from setuptools import setup, find_packages
setup(
name='ssbio',
version='0.1',
author='Nathan Mih',
author_email='[email protected]',
license='MIT',
url='http://github.com/nmih/ssbio',
description='Various tools and functions to enable structural systems biology',
packages=find_packages(),
package_dir={'ssbio': 'ssbio'},
package_data={'ssbio': ['ssbio/etc/*']},
scripts = ['ssbio/scripts/cleanpdb', 'ssbio/scripts/aggprop', 'ssbio/scripts/thermostability', 'ssbio/structure/mutatepdb.py', 'ssbio/structure/tleap.py',
'ssbio/databases/drugbank.py', 'ssbio/structure/properties/msmsprops.py',
'ssbio/dock/dock.py'],
long_description=open('README.md').read(),
install_requires=['biopython',
'numpy',
'tqdm',
'pandas',
'requests',
'cachetools',
'bioservices',
'prody',
'xmltodict']
) |
Fix Thread CPU time metric name. | package com.ea.orbit.metrics.jvm;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricSet;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.Map;
/**
* Created by jefft on 9/21/2015.
*/
public class ThreadCPUUsageSet implements MetricSet
{
private final ThreadMXBean threads;
public ThreadCPUUsageSet()
{
this(ManagementFactory.getThreadMXBean());
}
public ThreadCPUUsageSet(ThreadMXBean threads)
{
this.threads = threads;
}
@Override
public Map<String, Metric> getMetrics()
{
final Map<String, Metric> gauges = new HashMap<String, Metric>();
ThreadInfo[] threadInfos = threads.getThreadInfo(threads.getAllThreadIds());
for (final ThreadInfo info : threadInfos)
{
gauges.put("Thread." + info.getThreadName() + ".cputime", new Gauge<Long>()
{
@Override
public Long getValue()
{
return threads.getThreadCpuTime(info.getThreadId());
}
});
}
return gauges;
}
}
| package com.ea.orbit.metrics.jvm;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricSet;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.Map;
/**
* Created by jefft on 9/21/2015.
*/
public class ThreadCPUUsageSet implements MetricSet
{
private final ThreadMXBean threads;
public ThreadCPUUsageSet()
{
this(ManagementFactory.getThreadMXBean());
}
public ThreadCPUUsageSet(ThreadMXBean threads)
{
this.threads = threads;
}
@Override
public Map<String, Metric> getMetrics()
{
final Map<String, Metric> gauges = new HashMap<String, Metric>();
ThreadInfo[] threadInfos = threads.getThreadInfo(threads.getAllThreadIds());
for (final ThreadInfo info : threadInfos)
{
gauges.put("Thread." + info.getThreadName(), new Gauge<Long>()
{
@Override
public Long getValue()
{
return threads.getThreadCpuTime(info.getThreadId());
}
});
}
return gauges;
}
}
|
Remove history from long description | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
setup(
name='gnsq',
version='1.0.0',
description='A gevent based python client for NSQ.',
long_description=readme,
long_description_content_type='text/x-rst',
author='Trevor Olson',
author_email='[email protected]',
url='https://github.com/wtolson/gnsq',
packages=[
'gnsq',
'gnsq.contrib',
'gnsq.stream',
],
package_dir={'gnsq': 'gnsq'},
include_package_data=True,
install_requires=[
'blinker',
'gevent',
'six',
'urllib3',
],
extras_require={
'snappy': ['python-snappy'],
},
license="BSD",
zip_safe=False,
keywords='gnsq',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
setup(
name='gnsq',
version='1.0.0',
description='A gevent based python client for NSQ.',
long_description=readme + '\n\n' + history,
author='Trevor Olson',
author_email='[email protected]',
url='https://github.com/wtolson/gnsq',
packages=[
'gnsq',
'gnsq.contrib',
'gnsq.stream',
],
package_dir={'gnsq': 'gnsq'},
include_package_data=True,
install_requires=[
'blinker',
'gevent',
'six',
'urllib3',
],
extras_require={
'snappy': ['python-snappy'],
},
license="BSD",
zip_safe=False,
keywords='gnsq',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
]
)
|
Set the AMD module name in the UMD build | import path from 'path';
const projectRoot = path.join(__dirname, '..');
export default {
cache: true,
entry: [
path.join(projectRoot, 'src', 'hibp.js'),
],
output: {
library: 'hibp',
libraryTarget: 'umd',
umdNamedDefine: true,
path: path.join(projectRoot, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.join(projectRoot, 'src'),
],
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
cacheDirectory: true,
plugins: [
'add-module-exports',
],
presets: [
[
'env',
{
targets: {
browsers: [
'> 1%',
'last 2 versions',
],
},
},
],
],
},
},
],
},
],
},
node: {
fs: 'empty',
module: 'empty',
Buffer: false, // axios 0.16.1
},
};
| import path from 'path';
const projectRoot = path.join(__dirname, '..');
export default {
cache: true,
entry: [
path.join(projectRoot, 'src', 'hibp.js'),
],
output: {
library: 'hibp',
libraryTarget: 'umd',
path: path.join(projectRoot, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.join(projectRoot, 'src'),
],
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
cacheDirectory: true,
plugins: [
'add-module-exports',
],
presets: [
[
'env',
{
targets: {
browsers: [
'> 1%',
'last 2 versions',
],
},
},
],
],
},
},
],
},
],
},
node: {
fs: 'empty',
module: 'empty',
Buffer: false, // axios 0.16.1
},
};
|
Modify error message log UI | import React, { PropTypes } from 'react';
import VarOneStore from '../../stores/varOne-store';
import connectToStores from 'alt/utils/connectToStores';
@connectToStores
export default class VarOneLogModal extends React.Component {
static propTypes = {
msg: PropTypes.string,
port: PropTypes.string,
inputPort: PropTypes.string,
failMessage: PropTypes.string
}
static getStores() {
return [ VarOneStore ];
}
static getPropsFromStores() {
return VarOneStore.getState();
}
render() {
const failResultMessage = this.props.failMessage;
return (
<div id='varOneLogModal' className='modal fade' tabIndex='-1' role='dialog'>
<div className='modal-dialog modal-lg' role='document'>
<div className='modal-content'>
<div className='modal-header'>
<button type='button' className='close' data-dismiss='modal'>×</button>
<h4 className='modal-title'>varOne Error Message</h4>
</div>
<div className='modal-body'>
<textarea ref='textFailMessage'
rows='35' cols='90' value={ failResultMessage }>
</textarea>
</div>
</div>
</div>
</div>
);
}
}
| import React, { PropTypes } from 'react';
import VarOneStore from '../../stores/varOne-store';
import connectToStores from 'alt/utils/connectToStores';
@connectToStores
export default class VarOneLogModal extends React.Component {
static propTypes = {
msg: PropTypes.string,
port: PropTypes.string,
inputPort: PropTypes.string,
failMessage: PropTypes.string
}
static getStores() {
return [ VarOneStore ];
}
static getPropsFromStores() {
return VarOneStore.getState();
}
render() {
const failResultMessage = this.props.failMessage;
return (
<div id='varOneLogModal' className='modal fade'>
<div className='modal-dialog modal-lg'>
<div className='modal-content'>
<div className='modal-header'>
<button type='button' className='close' data-dismiss='modal'>×</button>
<h4 className='modal-title'>varOne Log Message</h4>
</div>
<div className='modal-body'>
<textarea ref='textFailMessage' rows='10' cols='90' value={ failResultMessage }>
</textarea>
</div>
<div className='modal-footer'>
</div>
</div>
</div>
</div>
);
}
}
|
Add prefix 'wi' to database table name. | <?php
namespace WiContactAPI\V1\Rest\Contact;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="WiContactAPI\V1\Rest\Contact\ContactCollection")
* @ORM\Table(name="wi_contacts")
*/
class ContactEntity
{
/**
*
* @var int @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
*
* @var string @ORM\Column(type="string", nullable=true)
*/
protected $name;
/**
*
* @return the $id
*/
public function getId()
{
return $this->id;
}
/**
*
* @return the $name
*/
public function getName()
{
return $this->name;
}
/**
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
// @todo: Add phones support
// @todo: Add Gedmo Annotations support
/**
*
* @see Zend\\Stdlib\\Hydrator\\ArraySerializable::extract expects the provided object to implement getArrayCopy()
* @return multitype
*/
public function getArrayCopy()
{
return get_object_vars($this);
}
} | <?php
namespace WiContactAPI\V1\Rest\Contact;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="WiContactAPI\V1\Rest\Contact\ContactCollection")
* @ORM\Table(name="contacts")
*/
class ContactEntity
{
/**
*
* @var int @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
*
* @var string @ORM\Column(type="string", nullable=true)
*/
protected $name;
/**
*
* @return the $id
*/
public function getId()
{
return $this->id;
}
/**
*
* @return the $name
*/
public function getName()
{
return $this->name;
}
/**
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
// @todo: Add phones support
// @todo: Add Gedmo Annotations support
/**
*
* @see Zend\\Stdlib\\Hydrator\\ArraySerializable::extract expects the provided object to implement getArrayCopy()
* @return multitype
*/
public function getArrayCopy()
{
return get_object_vars($this);
}
} |
Change the interface layout to reflect the changes we spoke about in icq
git-svn-id: 00f83033766efed07e2b0af284f6d6b8c92b3c53@408254 13f79535-47bb-0310-9956-ffa450edef68 | /***********************************************************************
* Copyright (c) 1999-2006 The Apache Software Foundation. *
* All rights reserved. *
* ------------------------------------------------------------------- *
* Licensed under the Apache License, Version 2.0 (the "License"); you *
* may not use this file except in compliance with the License. You *
* may obtain a copy of the License at: *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. See the License for the specific language governing *
* permissions and limitations under the License. *
***********************************************************************/
package org.apache.spf.mechanismn;
import org.apache.spf.IPAddr;
import org.apache.spf.SPF1Data;
public interface GenericMechanismn {
/**
* Run the mechanismn
* @return result
*/
public int run();
/**
*
* @param spfData The SPF1Data
* @param mechanismPrefix The mechanismPrefix
* @param checkAddress The ipAddress to check
* @param domainName The domainName
* @param maskLenght The maskLength
*/
public void init(SPF1Data spfData,String mechanismPrefix,IPAddr checkAddress, String domainName, int maskLenght);
}
| /***********************************************************************
* Copyright (c) 1999-2006 The Apache Software Foundation. *
* All rights reserved. *
* ------------------------------------------------------------------- *
* Licensed under the Apache License, Version 2.0 (the "License"); you *
* may not use this file except in compliance with the License. You *
* may obtain a copy of the License at: *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. See the License for the specific language governing *
* permissions and limitations under the License. *
***********************************************************************/
package org.apache.spf.mechanismn;
import org.apache.spf.IPAddr;
import org.apache.spf.SPF1Data;
public interface GenericMechanismn {
/**
* Run the mechanismn
* @return result
*/
public int checkMechanismn(IPAddr checkAddress, String domainName, int maskLenght);
/**
* Init the SPF1Data
* @param spfData The current SPF1Data container
*/
public void initSPF1Data(SPF1Data spfData);
}
|
Return shipping methods with ordered keys | <?php
/**
* @author Krzysztof Gzocha <[email protected]>
*/
namespace Team3\Order;
/**
* Class ShippingMethodCollection
* @package Team3\Order
*/
class ShippingMethodCollection implements ShippingMethodCollectionInterface
{
/**
* @var ShippingMethodInterface[]
*/
protected $shippingMethods;
/**
* @param ShippingMethodInterface[] $shippingMethod
*/
public function __construct(array $shippingMethod = [])
{
$this->shippingMethods = $shippingMethod;
}
/**
* @return ShippingMethodInterface[]
*/
public function getShippingMethods()
{
return array_values($this->shippingMethods);
}
/**
* @inheritdoc
*/
public function addShippingMethod(ShippingMethodInterface $shippingMethod)
{
$this->shippingMethods[] = $shippingMethod;
return $this;
}
/**
* @param ShippingMethodInterface[] $shippingMethods
*
* @return ShippingMethodCollection
*/
public function setShippingMethods(array $shippingMethods)
{
$this->shippingMethods = $shippingMethods;
return $this;
}
/**
* @inheritdoc
*/
public function getIterator()
{
return new \ArrayIterator($this->getShippingMethods());
}
/**
* @inheritdoc
*/
public function count()
{
return count($this->getShippingMethods());
}
}
| <?php
/**
* @author Krzysztof Gzocha <[email protected]>
*/
namespace Team3\Order;
/**
* Class ShippingMethodCollection
* @package Team3\Order
*/
class ShippingMethodCollection implements ShippingMethodCollectionInterface
{
/**
* @var ShippingMethodInterface[]
*/
protected $shippingMethods;
/**
* @param ShippingMethodInterface[] $shippingMethod
*/
public function __construct(array $shippingMethod = [])
{
$this->shippingMethods = $shippingMethod;
}
/**
* @return ShippingMethodInterface[]
*/
public function getShippingMethods()
{
return $this->shippingMethods;
}
/**
* @inheritdoc
*/
public function addShippingMethod(ShippingMethodInterface $shippingMethod)
{
$this->shippingMethods[] = $shippingMethod;
return $this;
}
/**
* @param ShippingMethodInterface[] $shippingMethods
*
* @return ShippingMethodCollection
*/
public function setShippingMethods(array $shippingMethods)
{
$this->shippingMethods = $shippingMethods;
return $this;
}
/**
* @inheritdoc
*/
public function getIterator()
{
return new \ArrayIterator($this->getShippingMethods());
}
/**
* @inheritdoc
*/
public function count()
{
return count($this->getShippingMethods());
}
}
|
Fix unused import which could creates crashes | import os
import socket
import time
from RAXA.settings import PROJECT_ROOT
from backend.io.connector import Connector
class Tellstick(Connector):
TYPE = 'Tellstick'
def is_usable(self):
return self.connector.version.startswith('RAXA')
def update(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9001))
s.send('get_ip' + self.connector.code+'\n')
ip = s.recv(2048)
s.close()
path = os.path.join(PROJECT_ROOT, 'other', 'connector.tellstick', 'TellStickNet.hex')
if ip is not None:
print 'atftp -p -l %s --tftp-timeout 1 %s' % (path, ip)
os.system('atftp -p -l %s --tftp-timeout 1 %s' % (path, ip))
time.sleep(10)
def send(self, string):
string = '{%s,"tellstick":"%s"}' % (string, self.connector.code)
print string
self._send('send%s' % string)
def scan(self):
self._send('broadcastD')
def _send(self, message):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9001))
s.send(message)
s.close() | import os
import socket
import tftpy
import time
from RAXA.settings import PROJECT_ROOT
from backend.io.connector import Connector
class Tellstick(Connector):
TYPE = 'Tellstick'
def is_usable(self):
return self.connector.version.startswith('RAXA')
def update(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9001))
s.send('get_ip' + self.connector.code+'\n')
ip = s.recv(2048)
s.close()
path = os.path.join(PROJECT_ROOT, 'other', 'connector.tellstick', 'TellStickNet.hex')
if ip is not None:
print 'atftp -p -l %s --tftp-timeout 1 %s' % (path, ip)
os.system('atftp -p -l %s --tftp-timeout 1 %s' % (path, ip))
time.sleep(10)
def send(self, string):
string = '{%s,"tellstick":"%s"}' % (string, self.connector.code)
print string
self._send('send%s' % string)
def scan(self):
self._send('broadcastD')
def _send(self, message):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9001))
s.send(message)
s.close() |
Fix file size prop warning | import React from "react";
import PropTypes from "prop-types";
import { Col, Row } from "react-bootstrap";
import { byteSize } from "../../utils";
import { Icon, ListGroupItem, RelativeTime } from "../../base";
export default class File extends React.Component {
static propTypes = {
id: PropTypes.string,
name: PropTypes.string,
size: PropTypes.object,
file: PropTypes.object,
uploaded_at: PropTypes.string,
user: PropTypes.object,
onRemove: PropTypes.func
};
handleRemove = () => {
this.props.onRemove(this.props.id);
};
render () {
const { name, size, uploaded_at, user } = this.props;
let creation;
if (user === null) {
creation = (
<span>
Retrieved <RelativeTime time={uploaded_at} />
</span>
);
} else {
creation = (
<span>
Uploaded <RelativeTime time={uploaded_at} /> by {user.id}
</span>
);
}
return (
<ListGroupItem className="spaced">
<Row>
<Col md={5}>
<strong>{name}</strong>
</Col>
<Col md={2}>
{byteSize(size.size)}
</Col>
<Col md={4}>
{creation}
</Col>
<Col md={1}>
<Icon
name="trash"
bsStyle="danger"
style={{fontSize: "17px"}}
onClick={this.handleRemove}
pullRight
/>
</Col>
</Row>
</ListGroupItem>
);
}
}
| import React from "react";
import PropTypes from "prop-types";
import { Col, Row } from "react-bootstrap";
import { byteSize } from "../../utils";
import { Icon, ListGroupItem, RelativeTime } from "../../base";
export default class File extends React.Component {
static propTypes = {
id: PropTypes.string,
name: PropTypes.string,
size: PropTypes.number,
file: PropTypes.object,
uploaded_at: PropTypes.string,
user: PropTypes.object,
onRemove: PropTypes.func
};
handleRemove = () => {
this.props.onRemove(this.props.id);
};
render () {
const { name, size, uploaded_at, user } = this.props;
let creation;
if (user === null) {
creation = (
<span>
Retrieved <RelativeTime time={uploaded_at} />
</span>
);
} else {
creation = (
<span>
Uploaded <RelativeTime time={uploaded_at} /> by {user.id}
</span>
);
}
return (
<ListGroupItem className="spaced">
<Row>
<Col md={5}>
<strong>{name}</strong>
</Col>
<Col md={2}>
{byteSize(size)}
</Col>
<Col md={4}>
{creation}
</Col>
<Col md={1}>
<Icon
name="trash"
bsStyle="danger"
style={{fontSize: "17px"}}
onClick={this.handleRemove}
pullRight
/>
</Col>
</Row>
</ListGroupItem>
);
}
}
|
Fix translations not loaded in test | <?php
namespace Backend\Modules\Error\Tests\Action;
use Backend\Core\Language\Language;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\HttpFoundation\Response;
class IndexTest extends BackendWebTestCase
{
public function testAuthenticationIsNotNeeded(Client $client): void
{
$this->logout($client);
self::assertHttpStatusCode($client, '/private/en/error/index', Response::HTTP_BAD_REQUEST);
self::assertCurrentUrlEndsWith($client, '/private/en/error/index');
}
public function testModuleNotAllowed(Client $client): void
{
self::assertPageLoadedCorrectly(
$client,
'/private/en/error/index?type=module-not-allowed',
[
'You have insufficient rights for this module.',
],
Response::HTTP_FORBIDDEN
);
}
public function testActionNotAllowed(Client $client): void
{
self::assertPageLoadedCorrectly(
$client,
'/private/en/error/index?type=action-not-allowed',
[
'You have insufficient rights for this action.',
],
Response::HTTP_FORBIDDEN
);
}
public function testNotFound(Client $client): void
{
Language::setLocale('en');
self::assertPageLoadedCorrectly(
$client,
'/private/en/error/index?type=not-found',
[
Language::err('NotFound', 'Error'),
],
Response::HTTP_NOT_FOUND
);
}
}
| <?php
namespace Backend\Modules\Error\Tests\Action;
use Backend\Core\Language\Language;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\HttpFoundation\Response;
class IndexTest extends BackendWebTestCase
{
public function testAuthenticationIsNotNeeded(Client $client): void
{
$this->logout($client);
self::assertHttpStatusCode($client, '/private/en/error/index', Response::HTTP_BAD_REQUEST);
self::assertCurrentUrlEndsWith($client, '/private/en/error/index');
}
public function testModuleNotAllowed(Client $client): void
{
self::assertPageLoadedCorrectly(
$client,
'/private/en/error/index?type=module-not-allowed',
[
'You have insufficient rights for this module.',
],
Response::HTTP_FORBIDDEN
);
}
public function testActionNotAllowed(Client $client): void
{
self::assertPageLoadedCorrectly(
$client,
'/private/en/error/index?type=action-not-allowed',
[
'You have insufficient rights for this action.',
],
Response::HTTP_FORBIDDEN
);
}
public function testNotFound(Client $client): void
{
self::assertPageLoadedCorrectly(
$client,
'/private/en/error/index?type=not-found',
[
Language::err('NotFound', 'Error'),
],
Response::HTTP_NOT_FOUND
);
}
}
|
Clean only volumes of type host_path | """.. Ignore pydocstyle D400.
====================
Clean test directory
====================
Command to run on local machine::
./manage.py cleantestdir
"""
import re
import shutil
from itertools import chain
from pathlib import Path
from django.core.management.base import BaseCommand
from resolwe.storage import settings as storage_settings
from resolwe.storage.connectors import connectors
TEST_DIR_REGEX = r"^test_.*_\d+$"
class Command(BaseCommand):
"""Cleanup files created during testing."""
help = "Cleanup files created during testing."
def handle(self, *args, **kwargs):
"""Cleanup files created during testing."""
directories = [
Path(connector.path)
for connector in chain(
connectors.for_storage("data"), connectors.for_storage("upload")
)
if connector.mountable
]
directories += [
Path(volume_config["config"]["path"])
for volume_name, volume_config in storage_settings.FLOW_VOLUMES.items()
if not volume_config["config"].get("read_only", False)
and volume_config["type"] == "host_path"
]
for directory in directories:
directory = directory.resolve()
for test_dir in directory.iterdir():
if not test_dir.is_dir():
continue
if not re.match(TEST_DIR_REGEX, test_dir.name):
continue
shutil.rmtree(test_dir)
| """.. Ignore pydocstyle D400.
====================
Clean test directory
====================
Command to run on local machine::
./manage.py cleantestdir
"""
import re
import shutil
from itertools import chain
from pathlib import Path
from django.core.management.base import BaseCommand
from resolwe.storage import settings as storage_settings
from resolwe.storage.connectors import connectors
TEST_DIR_REGEX = r"^test_.*_\d+$"
class Command(BaseCommand):
"""Cleanup files created during testing."""
help = "Cleanup files created during testing."
def handle(self, *args, **kwargs):
"""Cleanup files created during testing."""
directories = [
Path(connector.path)
for connector in chain(
connectors.for_storage("data"), connectors.for_storage("upload")
)
if connector.mountable
]
directories += [
Path(volume_config["config"]["path"])
for volume_name, volume_config in storage_settings.FLOW_VOLUMES.items()
if volume_config["config"].get("read_only", False) == False
]
for directory in directories:
directory = directory.resolve()
for test_dir in directory.iterdir():
if not test_dir.is_dir():
continue
if not re.match(TEST_DIR_REGEX, test_dir.name):
continue
shutil.rmtree(test_dir)
|
Use docs as project homepage | import re
from setuptools import find_packages, setup
with open('netsgiro/__init__.py') as fh:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read()))
with open('README.rst') as fh:
long_description = fh.read()
setup(
name='netsgiro',
version=metadata['version'],
description='File parsers for Nets AvtaleGiro and OCR Giro',
long_description=long_description,
url='https://netsgiro.readthedocs.io/',
author='Otovo AS',
author_email='[email protected]',
license='Apache License, Version 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='avtalegiro ocr giro',
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=[
'attrs',
'typing', # Needed for Python 3.4
],
extras_require={
'dev': [
'check-manifest',
'flake8',
'flake8-import-order',
'mypy',
'pytest',
'pytest-xdist',
'sphinx',
'sphinx_rtd_theme',
'tox',
],
},
)
| import re
from setuptools import find_packages, setup
with open('netsgiro/__init__.py') as fh:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read()))
with open('README.rst') as fh:
long_description = fh.read()
setup(
name='netsgiro',
version=metadata['version'],
description='File parsers for Nets AvtaleGiro and OCR Giro',
long_description=long_description,
url='https://github.com/otovo/python-netsgiro',
author='Otovo AS',
author_email='[email protected]',
license='Apache License, Version 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='avtalegiro ocr giro',
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=[
'attrs',
'typing', # Needed for Python 3.4
],
extras_require={
'dev': [
'check-manifest',
'flake8',
'flake8-import-order',
'mypy',
'pytest',
'pytest-xdist',
'sphinx',
'sphinx_rtd_theme',
'tox',
],
},
)
|
Allow query without table to run | import collections
from collections import namedtuple
from six import string_types
from aq.errors import QueryParsingError
from aq.select_parser import select_stmt, ParseException
TableId = namedtuple('TableId', ('database', 'table', 'alias'))
QueryMetadata = namedtuple('QueryMetadata', ('tables',))
class SelectParser(object):
def __init__(self, options):
self.options = options
@staticmethod
def parse_query(query):
try:
parse_result = select_stmt.parseString(query, parseAll=True)
except ParseException as e:
raise QueryParsingError(e)
tables = [parse_table_id(tid) for tid in parse_result.table_ids]
parsed_query = concat(parse_result)
return parsed_query, QueryMetadata(tables=tables)
def parse_table_id(table_id):
database = table_id.database[0] if table_id.database else None
table = table_id.table[0] if table_id.table else None
alias = table_id.alias[0] if table_id.alias else None
return TableId(database, table, alias)
def flatten(nested_list):
for item in nested_list:
if isinstance(item, collections.Iterable) and not isinstance(item, string_types):
for nested_item in flatten(item):
yield nested_item
else:
yield item
def concat(tokens):
return ' '.join(flatten(tokens))
| from collections import namedtuple
import collections
from six import string_types
from aq.errors import QueryParsingError
from aq.select_parser import select_stmt, ParseException
TableId = namedtuple('TableId', ('database', 'table', 'alias'))
QueryMetadata = namedtuple('QueryMetadata', ('tables',))
class SelectParser(object):
def __init__(self, options):
self.options = options
@staticmethod
def parse_query(query):
try:
parse_result = select_stmt.parseString(query, parseAll=True)
except ParseException as e:
raise QueryParsingError(e)
if not parse_result.table:
raise QueryParsingError('No table specified in query')
tables = [parse_table_id(tid) for tid in parse_result.table_ids]
parsed_query = concat(parse_result)
return parsed_query, QueryMetadata(tables=tables)
def parse_table_id(table_id):
database = table_id.database[0] if table_id.database else None
table = table_id.table[0] if table_id.table else None
alias = table_id.alias[0] if table_id.alias else None
return TableId(database, table, alias)
def flatten(nested_list):
for item in nested_list:
if isinstance(item, collections.Iterable) and not isinstance(item, string_types):
for nested_item in flatten(item):
yield nested_item
else:
yield item
def concat(tokens):
return ' '.join(flatten(tokens))
|
Return url root when no id exists | "use strict";
/**
* Model for individual books.
*/
define([
"underscore",
"backbone"
], function(_, Backbone) {
var Book = Backbone.Model.extend({
idAttribute: "_id",
defaults: {
'type': 'book',
'public': true
},
url: function(){
var urlPrefix = '_rewrite/data/';
if (this.isNew()) {
// Do not include non-existent server ID.
return urlPrefix;
} else {
return urlPrefix + this.get(this.idAttribute);
}
},
/**
* Because CouchDB returns id & rev for some calls, and _id and _rev for others,
* handle those special cases here.
**/
parse: function(response, options) {
if (_.has(response, "id") && _.has(response, "rev")) {
response["_id"] = response["id"];
response["_rev"] = response["rev"];
delete response["id"];
delete response["rev"];
// Also get rid of "ok" key.
if (_.has(response, "ok")) {
delete response["ok"];
}
}
return response;
}
});
return Book;
});
| "use strict";
/**
* Model for individual books.
*/
define([
"underscore",
"backbone"
], function(_, Backbone) {
var Book = Backbone.Model.extend({
idAttribute: "_id",
defaults: {
'type': 'book',
'public': true
},
url: function(){
return '_rewrite/data/' + this.get('id');
/**
* Because CouchDB returns id & rev for some calls, and _id and _rev for others,
* handle those special cases here.
**/
parse: function(response, options) {
if (_.has(response, "id") && _.has(response, "rev")) {
response["_id"] = response["id"];
response["_rev"] = response["rev"];
delete response["id"];
delete response["rev"];
// Also get rid of "ok" key.
if (_.has(response, "ok")) {
delete response["ok"];
}
}
return response;
}
});
return Book;
});
|
Update factory name to ngCrypto | /**
* Angular crypto-js
* https://github.com/janppires/angular-crypto-js.git
**/
(function(angular, CryptoJS){
'use strict';
angular
.module('angular-crypto-js', [])
.factory('ngCrypto', [ngCrypto]);
function ngCrypto(){
return {
md5Hex : md5Hex,
sha1Hex : sha1Hex,
sha256Hex: sha256Hex,
sha224Hex: sha224Hex,
sha512Hex: sha512Hex,
sha384Hex: sha384Hex,
sha3Hex: sha3Hex,
}
function md5Hex(message){
return toHex(CryptoJS.MD5, message);
}
function sha1Hex(message){
return toHex(CryptoJS.SHA1, message);
}
function sha256Hex(message){
return toHex(CryptoJS.SHA256, message);
}
function sha224Hex(message){
return toHex(CryptoJS.SHA224, message);
}
function sha512Hex(message){
return toHex(CryptoJS.SHA512, message);
}
function sha384Hex(message){
return toHex(CryptoJS.SHA384, message);
}
function sha3Hex(message){
return toHex(CryptoJS.SHA3, message);
}
function toHex(hasher, message){
return hasher(message).toString(CryptoJS.enc.Hex);
}
}
})(window.angular, window.CryptoJS);
| /**
* Angular crypto-js
* https://github.com/janppires/angular-crypto-js.git
**/
(function(angular, CryptoJS){
'use strict';
angular
.module('angular-crypto-js', [])
.factory('cryptoJs', [cryptoJs]);
function cryptoJs(){
return {
md5Hex : md5Hex,
sha1Hex : sha1Hex,
sha256Hex: sha256Hex,
sha224Hex: sha224Hex,
sha512Hex: sha512Hex,
sha384Hex: sha384Hex,
sha3Hex: sha3Hex,
}
function md5Hex(message){
return toHex(CryptoJS.MD5, message);
}
function sha1Hex(message){
return toHex(CryptoJS.SHA1, message);
}
function sha256Hex(message){
return toHex(CryptoJS.SHA256, message);
}
function sha224Hex(message){
return toHex(CryptoJS.SHA224, message);
}
function sha512Hex(message){
return toHex(CryptoJS.SHA512, message);
}
function sha384Hex(message){
return toHex(CryptoJS.SHA384, message);
}
function sha3Hex(message){
return toHex(CryptoJS.SHA3, message);
}
function toHex(hasher, message){
return hasher(message).toString(CryptoJS.enc.Hex);
}
}
})(window.angular, window.CryptoJS);
|
Set title to 4line, change fontsize to 17px | (function (env) {
"use strict";
env.ddg_spice_wikinews = function(api_result){
if (api_result.error) {
return Spice.failed('wikinews');
}
DDG.require('moment.js', function(){
Spice.add({
id: "wikinews",
name: "Wikinews",
data: api_result.query.categorymembers,
meta: {
total: api_result.query.categorymembers.length,
sourceName: 'Wikinews articles',
sourceUrl: "https://en.wikinews.org/wiki/Main_Page",
itemType: "Latest Wikinews articles"
},
normalize: function(item) {
var timestamp = new Date(item.timestamp).getTime();
return {
title: item.title,
url: "https:///en.wikinews.org/?curid=" + item.pageid,
post_domain: "wikinews.org",
date_from: moment(timestamp).fromNow()
};
},
templates: {
group: 'text',
options: {
footer: Spice.wikinews.footer
},
detail: false,
item_detail: false,
variants: {
tileTitle: "4line",
},
elClass: {
tileTitle: 'tx--17'
}
}
});
});
};
}(this));
| (function (env) {
"use strict";
env.ddg_spice_wikinews = function(api_result){
if (api_result.error) {
return Spice.failed('wikinews');
}
DDG.require('moment.js', function(){
Spice.add({
id: "wikinews",
name: "Wikinews",
data: api_result.query.categorymembers,
meta: {
total: api_result.query.categorymembers.length,
sourceName: 'Wikinews articles',
sourceUrl: "https://en.wikinews.org/wiki/Main_Page",
itemType: "Latest Wikinews articles"
},
normalize: function(item) {
var timestamp = new Date(item.timestamp).getTime();
return {
title: item.title,
url: "https:///en.wikinews.org/?curid=" + item.pageid,
post_domain: "wikinews.org",
date_from: moment(timestamp).fromNow()
};
},
templates: {
group: 'text',
options: {
footer: Spice.wikinews.footer
},
detail: false,
item_detail: false,
variants: {
tileTitle: "3line-small",
}
}
});
});
};
}(this));
|
Fix for request timer not always working. | from time import time
from logging import getLogger
# From: https://djangosnippets.org/snippets/1866/
def sizify(value):
"""
Simple kb/mb/gb size snippet
"""
#value = ing(value)
if value < 512:
ext = 'B'
elif value < 512000:
value = value / 1024.0
ext = 'kB'
elif value < 4194304000:
value = value / 1048576.0
ext = 'MB'
else:
value = value / 1073741824.0
ext = 'GB'
return '%s %s' % (str(round(value, 2)), ext)
class LoggingMiddleware(object):
def __init__(self):
# arguably poor taste to use django's logger
self.logger = getLogger('django')
def process_request(self, request):
request.timer = time()
return None
def process_response(self, request, response):
if not hasattr(request, 'timer'):
request.timer = time()
self.logger.info(
'%s %s %s %s [%s] (%.0f ms)',
request.META["SERVER_PROTOCOL"],
request.method,
request.get_full_path(),
response.status_code,
sizify(len(response.content)),
(time() - request.timer) * 1000.
)
return response | from time import time
from logging import getLogger
# From: https://djangosnippets.org/snippets/1866/
def sizify(value):
"""
Simple kb/mb/gb size snippet
"""
#value = ing(value)
if value < 512:
ext = 'B'
elif value < 512000:
value = value / 1024.0
ext = 'kB'
elif value < 4194304000:
value = value / 1048576.0
ext = 'MB'
else:
value = value / 1073741824.0
ext = 'GB'
return '%s %s' % (str(round(value, 2)), ext)
class LoggingMiddleware(object):
def __init__(self):
# arguably poor taste to use django's logger
self.logger = getLogger('django')
def process_request(self, request):
request.timer = time()
return None
def process_response(self, request, response):
self.logger.info(
'%s %s %s %s [%s] (%.0f ms)',
request.META["SERVER_PROTOCOL"],
request.method,
request.get_full_path(),
response.status_code,
sizify(len(response.content)),
(time() - request.timer) * 1000.
)
return response |
Throw error when selector is not unique | var Browser = require('../interfaces/browser.js');
var objectAssign = require('object-assign');
/**
* An adapter of WebdriverIO for use with Mugshot
*
* @implements {Browser}
* @class
*
* @param webdriverioInstance - An instance of WebdriverIO
*/
function WebDriverIOAdaptor(webdriverioInstance) {
this._webdriverio = webdriverioInstance;
}
WebDriverIOAdaptor.prototype = objectAssign({}, Browser, {
takeScreenshot: function(callback) {
this._webdriverio.saveScreenshot()
.then(function(screenshot) {
callback(null, screenshot);
})
.catch(function(error) {
callback(error);
});
},
getBoundingClientRect: function(selector, callback) {
var webdriverio = this._webdriverio;
webdriverio.getElementSize(selector)
.then(function(size) {
if (size instanceof Array) {
throw new Error('The selector ' + selector + ' is not unique.');
}
webdriverio.getLocation(selector)
.then(function(location) {
var rect = {
width: size.width,
height: size.height,
top: location.y,
left: location.x,
bottom: location.y + size.height,
right: location.x + size.width
};
callback(null, rect);
})
.catch(function(error) {
callback(error);
});
})
.catch(function(error) {
callback(error);
});
}
});
module.exports = WebDriverIOAdaptor;
| var Browser = require('../interfaces/browser.js');
var objectAssign = require('object-assign');
/**
* An adapter of WebdriverIO for use with Mugshot
*
* @implements {Browser}
* @class
*
* @param webdriverioInstance - An instance of WebdriverIO
*/
function WebDriverIOAdaptor(webdriverioInstance) {
this._webdriverio = webdriverioInstance;
}
WebDriverIOAdaptor.prototype = objectAssign({}, Browser, {
takeScreenshot: function(callback) {
this._webdriverio.saveScreenshot()
.then(function(screenshot) {
callback(null, screenshot);
})
.catch(function(error) {
callback(error);
});
},
getBoundingClientRect: function(selector, callback) {
var webdriverio = this._webdriverio;
webdriverio.getElementSize(selector)
.then(function(size) {
webdriverio.getLocation(selector)
.then(function(location) {
var rect = {
width: size.width,
height: size.height,
top: location.y,
left: location.x,
bottom: location.y + size.height,
right: location.x + size.width
};
callback(null, rect);
})
.catch(function(error) {
callback(error);
});
})
.catch(function(error) {
callback(error);
});
}
});
module.exports = WebDriverIOAdaptor;
|
Use a context manager for reading README.md. | import io
import os
from setuptools import setup
version_txt = os.path.join(os.path.dirname(__file__), 'aghasher', 'version.txt')
with open(version_txt, 'r') as f:
version = f.read().strip()
with io.open('README.md', encoding='utf8') as f:
long_description = f.read()
setup(
author='Daniel Steinberg',
author_email='[email protected]',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Scientific/Engineering :: Information Analysis',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6'
],
description='An implementation of Anchor Graph Hashing',
install_requires=['numpy', 'scipy'],
keywords=['anchor-graph-hashing', 'hashing', 'locality-sensitive-hashing', 'machine-learning'],
license='MIT',
long_description=long_description,
long_description_content_type='text/markdown',
name='aghasher',
package_data={'aghasher': ['version.txt']},
packages=['aghasher'],
url='https://github.com/dstein64/aghasher',
version=version,
)
| import io
import os
from setuptools import setup
version_txt = os.path.join(os.path.dirname(__file__), 'aghasher', 'version.txt')
with open(version_txt, 'r') as f:
version = f.read().strip()
setup(
author='Daniel Steinberg',
author_email='[email protected]',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Scientific/Engineering :: Information Analysis',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6'
],
description='An implementation of Anchor Graph Hashing',
install_requires=['numpy', 'scipy'],
keywords=['anchor-graph-hashing', 'hashing', 'locality-sensitive-hashing', 'machine-learning'],
license='MIT',
long_description=io.open('README.md', encoding='utf8').read(),
long_description_content_type='text/markdown',
name='aghasher',
package_data={'aghasher': ['version.txt']},
packages=['aghasher'],
url='https://github.com/dstein64/aghasher',
version=version,
)
|
Handle App::abort() no longer exist.
Signed-off-by: crynobone <[email protected]> | <?php namespace Orchestra\Support\Traits;
use Illuminate\Support\Facades\App;
use Orchestra\Support\Facades\Messages;
use Illuminate\Support\Facades\Redirect;
use Symfony\Component\HttpKernel\Exception\HttpException
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException
trait ControllerResponseTrait
{
/**
* Queue notification and redirect.
*
* @param string $to
* @param string $message
* @param string $type
* @return mixed
*/
public function redirectWithMessage($to, $message = null, $type = 'success')
{
! is_null($message) && Messages::add($type, $message);
return $this->redirect($to);
}
/**
* Queue notification and redirect.
*
* @param string $to
* @param mixed $errors
* @return mixed
*/
public function redirectWithErrors($to, $errors)
{
return $this->redirect($to)->withInput()->withErrors($errors);
}
/**
* Redirect.
*
* @param string $to
* @return mixed
*/
public function redirect($to)
{
return Redirect::to($to);
}
/**
* Halt current request using App::abort().
*
* @param int $code
* @return void
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function suspend($code)
{
if ($status == 404) {
throw new NotFoundHttpException('');
}
throw new HttpException($code, '', null, []);
}
}
| <?php namespace Orchestra\Support\Traits;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Redirect;
use Orchestra\Support\Facades\Messages;
trait ControllerResponseTrait
{
/**
* Queue notification and redirect.
*
* @param string $to
* @param string $message
* @param string $type
* @return Response
*/
public function redirectWithMessage($to, $message = null, $type = 'success')
{
! is_null($message) && Messages::add($type, $message);
return $this->redirect($to);
}
/**
* Queue notification and redirect.
*
* @param string $to
* @param mixed $errors
* @return Response
*/
public function redirectWithErrors($to, $errors)
{
return $this->redirect($to)->withInput()->withErrors($errors);
}
/**
* Redirect.
*
* @param string $to
* @param string $message
* @param string $type
* @return Response
*/
public function redirect($to)
{
return Redirect::to($to);
}
/**
* Halt current request using App::abort().
*
* @param integer $status
* @return Response
*/
public function suspend($status)
{
return App::abort($status);
}
}
|
Add padding to button item | import Item from './item';
export default class ButtonItem extends Item {
constructor() {
super();
this._root
.classed('button', true)
.styles({
'background': '#FFF',
'cursor': 'pointer',
'height': '3em',
'justify-content': 'center',
'padding': '0.5em 0'
});
this._text = this._root
.append('button')
.attrs({
'tabindex': -1,
'type': 'button'
})
.styles({
'background': 'none',
'border': '1px solid transparent',
'color': 'inherit',
'cursor': 'inherit',
'line-height': '2em',
'margin': 0,
'padding': '0 0.25em'
});
this._padding.styles({
'display': 'none'
});
}
tabindex(value = null) {
if (value === null) {
return this._text.attr('tabindex');
}
this._text.attr('tabindex', value);
return this;
}
text(value = null) {
if (value === null) {
return this._text;
}
this._text.text(value);
return this;
}
_click() {
if (this._disabled === false && this._model) {
this._model.set(this._name, this._value);
}
}
}
| import { select } from 'd3';
import Item from './item';
export default class ButtonItem extends Item {
constructor() {
super();
this._root
.classed('button', true)
.styles({
'background': '#FFF',
'cursor': 'pointer',
'height': '3em',
'justify-content': 'center'
});
this._text = this._root
.append('button')
.attrs({
'tabindex': -1,
'type': 'button'
})
.styles({
'background': 'none',
'border': '1px solid transparent',
'color': 'inherit',
'cursor': 'inherit',
'line-height': '2em',
'margin': 0,
'padding': '0 0.25em'
});
this._padding.styles({
'display': 'none'
});
}
tabindex(value = null) {
if (value === null) {
return this._text.attr('tabindex');
}
this._text.attr('tabindex', value);
return this;
}
text(value = null) {
if (value === null) {
return this._text;
}
this._text.text(value);
return this;
}
_click() {
if (this._disabled === false && this._model) {
this._model.set(this._name, this._value);
}
}
}
|
Refresh page after user creation
Former-commit-id: 375fb1e0b2c00dd37d17c20ce9a7abb68163176f | function viewUsers(view) {
getUsers(
success = function (data) {
//console.log(data);
populateUsersTable(data);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateUsersTable(data) {
var usersHtml = templates.userList(data);
var isEditor = false;
$('.section').html(usersHtml);
$('.collections-select-table tbody tr').click(function () {
$('.collections-select-table tbody tr').removeClass('selected');
$(this).addClass('selected');
var userId = $(this).attr('data-id');
viewUserDetails(userId);
});
$('.radioBtnDiv').change(function () {
if($('input:checked').val() === 'publisher') {
isEditor = true;
} else {
isEditor = false;
}
});
$('.form-create-user').submit(function (e) {
e.preventDefault();
var username = $('#create-user-username').val();
var email = $('#create-user-email').val();
var password = $('#create-user-password').val();
if (username.length < 1) {
sweetAlert("Please enter the users name.");
return;
}
if (email.length < 1) {
sweetAlert("Please enter the users name.");
return;
}
if (password.length < 1) {
sweetAlert("Please enter the users password.");
return;
}
postUser(username, email, password, isEditor);
viewUsers();
});
}
}
| function viewUsers(view) {
getUsers(
success = function (data) {
//console.log(data);
populateUsersTable(data);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateUsersTable(data) {
var usersHtml = templates.userList(data);
var isEditor = false;
$('.section').html(usersHtml);
$('.collections-select-table tbody tr').click(function () {
$('.collections-select-table tbody tr').removeClass('selected');
$(this).addClass('selected');
var userId = $(this).attr('data-id');
viewUserDetails(userId);
});
$('.radioBtnDiv').change(function () {
if($('input:checked').val() === 'publisher') {
isEditor = true;
alert(isEditor);
} else {
isEditor = false;
alert(isEditor);
}
});
$('.form-create-user').submit(function (e) {
e.preventDefault();
var username = $('#create-user-username').val();
var email = $('#create-user-email').val();
var password = $('#create-user-password').val();
if (username.length < 1) {
sweetAlert("Please enter the users name.");
return;
}
if (email.length < 1) {
sweetAlert("Please enter the users name.");
return;
}
if (password.length < 1) {
sweetAlert("Please enter the users password.");
return;
}
postUser(username, email, password, isEditor);
});
}
}
|
Remove unnecessary checks for V2 tokens | /* global btoa */
const V2TOKEN_ABORT_TIMEOUT = 3000
export function getAccessToken () {
return new Promise(function (resolve, reject) {
if (typeof window === 'undefined') {
return reject(new Error('getV2Token should be used in browser'))
} else if (!window.parent) {
return reject(new Error('getV2Token should be used in iframe'))
} else if (!window.parent.postMessage) {
return reject(new Error('getV2Token should be used in modern browser'))
}
const origin = window.location.origin
const intent = {action: 'getToken'}
let timeout = null
const receiver = function (event) {
let token
try {
token = new AccessToken({
appName: event.data.appName,
token: event.data.token
})
} catch (e) {
reject(e)
return
}
window.removeEventListener('message', receiver)
clearTimeout(timeout)
resolve({ client: null, token })
}
window.addEventListener('message', receiver, false)
window.parent.postMessage(intent, origin)
timeout = setTimeout(() => {
reject(new Error('No response from parent iframe after 3s'))
}, V2TOKEN_ABORT_TIMEOUT)
})
}
export class AccessToken {
constructor (opts) {
this.appName = opts.appName || ''
this.token = opts.token || ''
}
toAuthHeader () {
return 'Basic ' + btoa(`${this.appName}:${this.token}`)
}
}
| /* global btoa */
const V2TOKEN_ABORT_TIMEOUT = 3000
export function getAccessToken () {
return new Promise(function (resolve, reject) {
if (typeof window === 'undefined') {
return reject(new Error('getV2Token should be used in browser'))
} else if (!window.parent) {
return reject(new Error('getV2Token should be used in iframe'))
} else if (!window.parent.postMessage) {
return reject(new Error('getV2Token should be used in modern browser'))
}
const origin = window.location.origin
const intent = {action: 'getToken'}
let timeout = null
const receiver = function (event) {
let token
try {
token = new AccessToken({
appName: event.data.appName,
token: event.data.token
})
} catch (e) {
reject(e)
return
}
window.removeEventListener('message', receiver)
clearTimeout(timeout)
resolve({ client: null, token })
}
window.addEventListener('message', receiver, false)
window.parent.postMessage(intent, origin)
timeout = setTimeout(() => {
reject(new Error('No response from parent iframe after 3s'))
}, V2TOKEN_ABORT_TIMEOUT)
})
}
export class AccessToken {
constructor (opts) {
this.appName = opts.appName || ''
this.token = opts.token || ''
if (this.appName === '') {
throw new Error('Missing appName parameter')
}
if (this.token === '') {
throw new Error('Missing token parameter')
}
}
toAuthHeader () {
return 'Basic ' + btoa(`${this.appName}:${this.token}`)
}
}
|
Make API read-only and publically available. | from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models import Build
from projects.models import Project
class UserResource(ModelResource):
class Meta:
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
#allowed_methods = ['get', 'post', 'put']
allowed_methods = ['get']
queryset = User.objects.all()
fields = ['username', 'first_name',
'last_name', 'last_login',
'id']
filtering = {
"username": ('exact', 'startswith'),
}
class ProjectResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
allowed_methods = ['get']
queryset = Project.objects.all()
filtering = {
"slug": ('exact', 'startswith'),
}
excludes = ['build_pdf', 'path', 'skip', 'featured']
class BuildResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
class Meta:
allowed_methods = ['get']
queryset = Build.objects.all()
filtering = {
"project": ALL,
}
| from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models import Build
from projects.models import Project
class UserResource(ModelResource):
class Meta:
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
allowed_methods = ['get', 'post', 'put']
queryset = User.objects.all()
fields = ['username', 'first_name',
'last_name', 'last_login',
'id']
filtering = {
"username": ('exact', 'startswith'),
}
class ProjectResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
allowed_methods = ['get', 'post', 'put']
queryset = Project.objects.all()
filtering = {
"slug": ('exact', 'startswith'),
}
excludes = ['build_pdf', 'path', 'skip', 'featured']
class BuildResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
class Meta:
allowed_methods = ['get']
queryset = Build.objects.all()
filtering = {
"project": ALL,
}
|
Increase soft keyboard launch delay | package co.smartreceipts.android.widget;
import android.content.Context;
import android.content.res.Configuration;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class ShowSoftKeyboardOnFocusChangeListener implements View.OnFocusChangeListener {
/**
* After we resume Smart Receipts after using the camera, the input manager isn't quite ready yet to actually
* show the keyboard for some reason (as opposed to using a text receipt). I wasn't able to find any checks
* for why this fails, so I built in a hacky hardcoded delay to help resolve this
*/
private static final int DELAY_TO_SHOW_KEYBOARD_MILLIS = 400;
@Override
public void onFocusChange(final View view, final boolean hasFocus) {
if (hasFocus && view != null) {
if (view.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
// Try both immediately
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
view.postDelayed(new Runnable() {
@Override
public void run() {
// And delayed
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}, DELAY_TO_SHOW_KEYBOARD_MILLIS);
}
}
}
}
}
| package co.smartreceipts.android.widget;
import android.content.Context;
import android.content.res.Configuration;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class ShowSoftKeyboardOnFocusChangeListener implements View.OnFocusChangeListener {
/**
* After we resume Smart Receipts after using the camera, the input manager isn't quite ready yet to actually
* show the keyboard for some reason (as opposed to using a text receipt). I wasn't able to find any checks
* for why this fails programtically, so I built in a hacky hardcoded delay to help resolve this
*/
private static final int DELAY_TO_SHOW_KEYBOARD_MILLIS = 250;
@Override
public void onFocusChange(final View view, final boolean hasFocus) {
if (hasFocus && view != null) {
if (view.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
// Try both immediately
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
view.postDelayed(new Runnable() {
@Override
public void run() {
// And delayed
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}, DELAY_TO_SHOW_KEYBOARD_MILLIS);
}
}
}
}
}
|
Add get registration count to service | <?php
namespace Shaygan\AffiliateBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ReferralRegistrationRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ReferralRegistrationRepository extends EntityRepository
{
public function getRegistrationByUser($user)
{
return $this->_em
->createQuery('SELECT rr,r FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'JOIN rr.referrer r '
. 'WHERE r.id=:id '
. 'ORDER BY rr.id DESC ')
->setParameter("id", $user->getId())
;
}
public function getRegistrationCountByUser($user)
{
return $this->_em
->createQuery('SELECT COUNT(*) FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'JOIN rr.referrer r '
. 'WHERE r.id=:id ')
->setParameter("id", $user->getId())
->getSingleScalarResult()
;
}
}
| <?php
namespace Shaygan\AffiliateBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ReferralRegistrationRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ReferralRegistrationRepository extends EntityRepository
{
public function getRegistrationByUser($user)
{
return $this->_em
->createQuery('SELECT rr,r FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'JOIN rr.referrer r '
. 'WHERE r.id=:id '
. 'ORDER BY rr.id DESC ')
->setParameter("id", $user->getId())
;
}
public function getRegistrationCountByUser($user)
{
return $this->_em
->createQuery('SELECT COUNT(*) FROM ShayganAffiliateBundle:ReferralRegistration rr '
. 'WHERE r.id=:id ')
->setParameter("id", $user->getId())
->getSingleScalarResult()
;
}
}
|
Add additional assertions around objectcontroller errors | describe('lib/rules/disallow-objectcontroller', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowObjectController: undefined});
}).to.throws(/requires a true value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowObjectController: {}});
}).to.throws(/requires a true value/i);
});
});
describe('with true', function() {
checker.rules({disallowObjectController: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report',
code: function() {
Ember.Controller.extend({
});
}
}, {
it: 'should not report',
code: function() {
var foo = Ember.ObjectController;
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
Ember.ObjectController.extend({
});
},
errors: [{
column: 6, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
message: 'ObjectController is deprecated in Ember 1.11'
}]
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
var foo = Ember.ObjectController.create({
});
},
errors: [{
column: 16, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
message: 'ObjectController is deprecated in Ember 1.11'
}]
}
/* jshint ignore:end */
]);
});
});
| describe('lib/rules/disallow-objectcontroller', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowObjectController: undefined});
}).to.throws(/requires a true value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowObjectController: {}});
}).to.throws(/requires a true value/i);
});
});
describe('with true', function() {
checker.rules({disallowObjectController: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report',
code: function() {
Ember.Controller.extend({
});
}
}, {
it: 'should not report',
code: function() {
var foo = Ember.ObjectController;
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
Ember.ObjectController.extend({
});
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
var foo = Ember.ObjectController.create({
});
}
}
/* jshint ignore:end */
]);
});
});
|
Mark snapshots as inactive if any are not valid | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
def get(self, image_id):
image = SnapshotImage.query.get(image_id)
if image is None:
return '', 404
return self.respond(image)
def post(self, image_id):
image = SnapshotImage.query.get(image_id)
if image is None:
return '', 404
args = self.parser.parse_args()
if args.status:
image.status = SnapshotStatus[args.status]
db.session.add(image)
db.session.flush()
if image.status == SnapshotStatus.active:
snapshot = image.snapshot
inactive_image_query = SnapshotImage.query.filter(
SnapshotImage.status != SnapshotStatus.active,
SnapshotImage.snapshot_id == snapshot.id,
).exists()
if not db.session.query(inactive_image_query).scalar():
snapshot.status = SnapshotStatus.active
db.session.add(snapshot)
elif snapshot.status == SnapshotStatus.active:
snapshot.status = SnapshotStatus.inactive
db.session.add(snapshot)
db.session.commit()
return self.respond(image)
| from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
def get(self, image_id):
image = SnapshotImage.query.get(image_id)
if image is None:
return '', 404
return self.respond(image)
def post(self, image_id):
image = SnapshotImage.query.get(image_id)
if image is None:
return '', 404
args = self.parser.parse_args()
if args.status:
image.status = SnapshotStatus[args.status]
db.session.add(image)
db.session.flush()
if image.status == SnapshotStatus.active:
snapshot = image.snapshot
inactive_image_query = SnapshotImage.query.filter(
SnapshotImage.status != SnapshotStatus.active,
SnapshotImage.snapshot_id == snapshot.id,
).exists()
if not db.session.query(inactive_image_query).scalar():
snapshot.status = SnapshotStatus.active
db.session.add(snapshot)
db.session.commit()
return self.respond(image)
|
Fix exception handling in integrity decorator | import functools
import logging
from weblib.error import ResponseNotValid
def integrity(integrity_func, integrity_errors=(ResponseNotValid,),
ignore_errors=()):
"""
Args:
:param integrity_func: couldb callable or string contains name of
method to call
"""
def build_decorator(func):
@functools.wraps(func)
def func_wrapper(self, grab, task):
if isinstance(integrity_func, (list, tuple)):
int_funcs = integrity_func
else:
int_funcs = [integrity_func]
try:
for int_func in int_funcs:
if isinstance(int_func, str):
getattr(self, int_func)(grab)
else:
int_func(grab)
except ignore_errors as ex:
self.stat.inc(ex.__class__.__name__)
grab.meta['integrity_error'] = ex
result = func(self, grab, task)
if result is not None:
for event in result:
yield event
except integrity_errors as ex:
yield task.clone(refresh_cache=True)
self.stat.inc(ex.__class__.__name__)
#logging.error(ex)
except Exception as ex:
raise
else:
grab.meta['integrity_error'] = None
result = func(self, grab, task)
if result is not None:
for event in result:
yield event
return func_wrapper
return build_decorator
| import functools
import logging
from weblib.error import ResponseNotValid
def integrity(integrity_func, integrity_errors=(ResponseNotValid,),
ignore_errors=()):
"""
Args:
:param integrity_func: couldb callable or string contains name of
method to call
"""
def build_decorator(func):
@functools.wraps(func)
def func_wrapper(self, grab, task):
if isinstance(integrity_func, (list, tuple)):
int_funcs = integrity_func
else:
int_funcs = [integrity_func]
try:
for int_func in int_funcs:
if isinstance(int_func, str):
getattr(self, int_func)(grab)
else:
int_func(grab)
except ignore_errors as ex:
self.stat.inc(ex.__class__.__name__)
grab.meta['integrity_error'] = ex
result = func(self, grab, task)
if result is not None:
for event in result:
yield event
except integrity_errors as ex:
yield task.clone(refresh_cache=True)
self.stat.inc(ex.__class__.__name__)
#logging.error(ex)
else:
grab.meta['integrity_error'] = None
result = func(self, grab, task)
if result is not None:
for event in result:
yield event
return func_wrapper
return build_decorator
|
Revert "Move DocSearch styles before headComponents"
This reverts commit 1232ccbc0ff6c5d9e80de65cefb352c404973e2f. | import React from 'react'
import PropTypes from 'prop-types'
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{props.headComponents}
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css"
/>
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<noscript key="noscript" id="gatsby-noscript">
This app works best with JavaScript enabled.
</noscript>
<div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: props.body }} />
{props.postBodyComponents}
</body>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"
/>
</html>
)
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
| import React from 'react'
import PropTypes from 'prop-types'
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css"
/>
{props.headComponents}
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<noscript key="noscript" id="gatsby-noscript">
This app works best with JavaScript enabled.
</noscript>
<div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: props.body }} />
{props.postBodyComponents}
</body>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"
/>
</html>
)
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
|
Update basic app to reflect change in api | window.addEvent("domready", function() {
var BasicApp = new Class({
Extends: App,
initialize: function(element, options) {
this.parent(element, options);
this.renderer = new BasicRenderer();
this.camera = new Camera();
this.camera.perspective(45, this.options.width/this.options.height,
0.1, 100);
this.camera.lookAt([0, 0, 5],
[0, 0, 0],
[0, 1, 0]);
this.triangle = new Mesh(3, gl.TRIANGLES, gl.STATIC_DRAW,
gl.STATIC_DRAW);
this.triangle.vertexBuffer.setValues([ 0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0]);
this.triangle.colorBuffer.setValues([1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0]);
},
draw: function() {
this.clear();
this.renderer.render([this.triangle], this.camera);
}
});
var app = new BasicApp(document.body);
app.run();
});
| window.addEvent("domready", function() {
var BasicApp = new Class({
Extends: App,
initialize: function(element, options) {
this.parent(element, options);
this.renderer = new BasicRenderer();
this.camera = new Camera();
this.camera.perspective(45, this.options.width/this.options.height,
0.1, 100);
this.camera.lookAt([0, 0, 5],
[0, 0, 0],
[0, 1, 0]);
this.triangle = new Mesh(3, gl.TRIANGLES, gl.STATIC_DRAW,
gl.STATIC_DRAW, gl.STATIC_DRAW);
this.triangle.vertexBuffer.setValues([ 0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0]);
this.triangle.colorBuffer.setValues([1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0]);
},
draw: function() {
this.clear();
this.renderer.renderMesh(this.triangle, this.camera);
}
});
var app = new BasicApp(document.body);
app.run();
});
|
Enforce other tasks to ran after init | /*
* grunt-browser-sync
* https://github.com/shakyshane/grunt-browser-sync
*
* Copyright (c) 2013 Shane Osbourne
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
grunt.registerMultiTask("browserSync", "Keep your browsers in sync", function () {
var done = this.async();
var options = this.options();
var patterns;
if (this.data && this.data.bsFiles && this.data.bsFiles.src) {
patterns = this.data.bsFiles.src;
if (typeof patterns === "string") {
patterns = [patterns];
}
}
if (!patterns) {
if (this.data.src) {
patterns = this.data.src;
if (typeof this.data.src === "string") {
patterns = [this.data.src];
}
}
}
if (!patterns) {
if (this.filesSrc.length) {
patterns = this.filesSrc;
}
}
var browserSync = require("browser-sync");
browserSync.init(patterns, options);
//noinspection JSUnresolvedVariable
if (options.watchTask || options.watchtask || options.background) {
// Wait until browserSync fully initializes
browserSync.emitter.on('init', function() {
done(); // Allow Watch task to run after
});
}
});
};
| /*
* grunt-browser-sync
* https://github.com/shakyshane/grunt-browser-sync
*
* Copyright (c) 2013 Shane Osbourne
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
grunt.registerMultiTask("browserSync", "Keep your browsers in sync", function () {
var done = this.async();
var options = this.options();
var patterns;
if (this.data && this.data.bsFiles && this.data.bsFiles.src) {
patterns = this.data.bsFiles.src;
if (typeof patterns === "string") {
patterns = [patterns];
}
}
if (!patterns) {
if (this.data.src) {
patterns = this.data.src;
if (typeof this.data.src === "string") {
patterns = [this.data.src];
}
}
}
if (!patterns) {
if (this.filesSrc.length) {
patterns = this.filesSrc;
}
}
var browserSync = require("browser-sync");
browserSync.init(patterns, options);
//noinspection JSUnresolvedVariable
if (options.watchTask || options.watchtask || options.background) {
done(); // Allow Watch task to run after
}
});
};
|
Revert "first attempt to improve performance" | package com.ideaheap;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class StreamsBasedCalculator {
public Map<String, String> getStringTransition(
final Set<String> stringSet,
final Map<String, Double> stringCosts) {
return stringCosts.keySet().parallelStream().collect(
Collectors.toConcurrentMap(
(state) -> state,
(state) -> stringTransitionCost(state, stringSet, stringCosts)
)
);
}
private String stringTransitionCost(
final String state,
final Set<String> stringSet,
final Map<String, Double> expectedUtilities) {
return stringSet.stream().max(
Comparator.comparing(
act -> calculateExpectedUtility(state, act, expectedUtilities)
)
).get();
}
private Double calculateExpectedUtility(
String state,
String act,
Map<String, Double> expectedUtilities) {
return expectedUtilities
.entrySet()
.stream()
.mapToDouble(
n -> getStateProbability(state, act, n.getKey()) * n.getValue()
).sum();
}
private Double getStateProbability(String state, String act, String key) {
return 5.0;
}
} | package com.ideaheap;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class StreamsBasedCalculator {
public Map<String, String> getStringTransition(
final Set<String> stringSet,
final Map<String, Double> stringCosts) {
return stringCosts.keySet().parallelStream().collect(
Collectors.toConcurrentMap(
(state) -> state,
(state) -> stringTransitionCost(state, stringSet, stringCosts)
)
);
}
private String stringTransitionCost(
final String state,
final Set<String> stringSet,
final Map<String, Double> expectedUtilities) {
return Double.toString(stringSet
.stream()
.mapToDouble(act -> calculateExpectedUtility(state, act, expectedUtilities))
.max()
.getAsDouble());
}
//
private Double calculateExpectedUtility(
String state,
String act,
Map<String, Double> expectedUtilities) {
return expectedUtilities
.entrySet()
.stream()
.mapToDouble(
n -> getStateProbability(state, act, n.getKey()) * n.getValue()
).sum();
}
private Double getStateProbability(String state, String act, String key) {
return 5.0;
}
}
|
Allow looser version of nose
TravisCI provides `nose` already installed:
- http://docs.travis-ci.com/user/languages/python/#Pre-installed-packages
However it's now at a later version and causes our tests to fail:
pkg_resources.VersionConflict: (nose 1.3.4 (/home/travis/virtualenv/python2.7.8/lib/python2.7/site-packages), Requirement.parse('nose==1.3.1')) | #!/usr/bin/env python2
import os
from setuptools import setup, find_packages
from plugins import __version__
repo_directory = os.path.dirname(__file__)
try:
long_description = open(os.path.join(repo_directory, 'README.rst')).read()
except:
long_description = None
setup(
name='gds-nagios-plugins',
version=__version__,
packages=find_packages(exclude=['test*']),
author='Tom Booth',
author_email='[email protected]',
maintainer='Government Digital Service',
url='https://github.com/alphagov/nagios-plugins',
description='nagios-plugins: a set of useful nagios plugins',
long_description=long_description,
license='MIT',
keywords='',
setup_requires=['setuptools-pep8'],
install_requires=[
"nagioscheck==0.1.6"
],
tests_require=[
"nose >=1.3, <1.4",
"freezegun==0.1.11"
],
test_suite='nose.collector',
entry_points={
'console_scripts': [
'check_apt_security_updates='
'plugins.command.check_apt_security_updates:main',
'check_reboot_required=plugins.command.check_reboot_required:main',
'check_elasticsearch=plugins.command.check_elasticsearch:main'
]
}
)
| #!/usr/bin/env python2
import os
from setuptools import setup, find_packages
from plugins import __version__
repo_directory = os.path.dirname(__file__)
try:
long_description = open(os.path.join(repo_directory, 'README.rst')).read()
except:
long_description = None
setup(
name='gds-nagios-plugins',
version=__version__,
packages=find_packages(exclude=['test*']),
author='Tom Booth',
author_email='[email protected]',
maintainer='Government Digital Service',
url='https://github.com/alphagov/nagios-plugins',
description='nagios-plugins: a set of useful nagios plugins',
long_description=long_description,
license='MIT',
keywords='',
setup_requires=['setuptools-pep8'],
install_requires=[
"nagioscheck==0.1.6"
],
tests_require=[
"nose==1.3.1",
"freezegun==0.1.11"
],
test_suite='nose.collector',
entry_points={
'console_scripts': [
'check_apt_security_updates='
'plugins.command.check_apt_security_updates:main',
'check_reboot_required=plugins.command.check_reboot_required:main',
'check_elasticsearch=plugins.command.check_elasticsearch:main'
]
}
)
|
Allow data=None, even though the spec doesn't allow it | import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid)
if data:
doc.update(data=bson.Binary(data))
doc.update(content)
self.librarypaste.pastes.save(doc)
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.librarypaste.pastes.update(query, update)
def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
return self.librarypaste.pastes.find_one(query)
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = dict(time=pymongo.DESCENDING)
recs = self.librarypaste.pastes.find(query).order(order).limit(1)
try:
return next(recs)['uid']
except StopIteration:
pass
def _lookupUid(self, shortid):
query = dict(shortid=shortid)
rec = self.librarypaste.pastes.find_one(query)
return rec['uid']
| import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid, data=bson.Binary(data))
doc.update(content)
self.librarypaste.pastes.save(doc)
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.librarypaste.pastes.update(query, update)
def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
return self.librarypaste.pastes.find_one(query)
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = dict(time=pymongo.DESCENDING)
recs = self.librarypaste.pastes.find(query).order(order).limit(1)
try:
return next(recs)['uid']
except StopIteration:
pass
def _lookupUid(self, shortid):
query = dict(shortid=shortid)
rec = self.librarypaste.pastes.find_one(query)
return rec['uid']
|
Hide groups the user is already member of in user add group form. | <?php
namespace User\Form;
use App\Entity\User;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AddGroupType extends AbstractType
{
private $user;
function __construct(User $user)
{
$this->user = $user;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->user;
$builder
->add('group', 'entity', array(
'property'=>'displayName',
'class' => 'App\Entity\Group',
'query_builder'=>function (EntityRepository $repo) use($user) {
$qb = $repo->createQueryBuilder('g')
->where('g.noUsers = false AND g.userJoinable = true');
if($user->getGroups()->count() == 0)
return $qb;
return $qb->andWhere('g NOT IN(:groups)')
->setParameter('groups', $user->getGroups());
},
'required'=>true,
'multiple'=>false,
))
->add('submit', 'submit', array(
'label' => 'Join group',
'attr' => array(
'class' => 'btn-sm',
)
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
));
}
/**
* @return string
*/
public function getName()
{
return 'usr_group_add';
}
}
| <?php
namespace User\Form;
use App\Entity\User;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AddGroupType extends AbstractType
{
private $user;
function __construct(User $user)
{
$this->user = $user;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->user;
$builder
->add('group', 'entity', array(
'property'=>'displayName',
'class' => 'App\Entity\Group',
'query_builder'=>function (EntityRepository $repo) {
return $repo->createQueryBuilder('g')
->where('g.noUsers = false AND g.userJoinable = true');
},
'required'=>true,
'multiple'=>false,
))
->add('submit', 'submit', array(
'label' => 'Join group',
'attr' => array(
'class' => 'btn-sm',
)
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
));
}
/**
* @return string
*/
public function getName()
{
return 'usr_group_add';
}
}
|
Change buttons state for color and color picker after a click. | var session = null;
// instead of windows.onload
$(document).ready( function() {
// hide iphone/ipad URL bar
//setTimeout(function() { window.scrollTo(0, 1) }, 100);
$(".logout").click( function ( event ) {
if (!confirm("Leave Poietic Generator?")) {
return false;
}
return true;
});
// initialize zoness
sessionF = new Session(
SESSION_TYPE_DRAW,
function( session ) {
//console.log("page_draw/ready: session callback ok");
$(".username").text(session.user_name);
var board = new Board( session );
var editor = new Editor( session, board, 'session-editor' );
var color_picker = new ColorPicker( editor );
var chat = new Chat( session);
var viewer = new Viewer( session, board, 'session-viewer', color_picker );
//console.log("page_draw/ready: prepicker");
$("#brush").click( function( event ){
event.preventDefault();
if ( true === color_picker.is_visible() ) {
color_picker.hide( this );
$(this).removeClass( "ui-btn-active" );
return false;
} else {
color_picker.show( this );
return true;
}
});
$("#picker").click( function ( event ) {
event.preventDefault();
viewer.toggle_color_picker();
return $(this).toggleClass( "ui-btn-active" ).hasClass( "ui-btn-active" );
});
}
);
});
| var session = null;
// instead of windows.onload
$(document).ready( function() {
// hide iphone/ipad URL bar
//setTimeout(function() { window.scrollTo(0, 1) }, 100);
$(".logout").click( function ( event ) {
if (!confirm("Leave Poietic Generator?")) {
return false;
}
return true;
});
// initialize zoness
sessionF = new Session(
SESSION_TYPE_DRAW,
function( session ) {
//console.log("page_draw/ready: session callback ok");
$(".username").text(session.user_name);
var board = new Board( session );
var editor = new Editor( session, board, 'session-editor' );
var color_picker = new ColorPicker( editor );
var chat = new Chat( session);
var viewer = new Viewer( session, board, 'session-viewer', color_picker );
//console.log("page_draw/ready: prepicker");
$("#brush").click( function( event ){
event.preventDefault();
if ( true === color_picker.is_visible() ) {
color_picker.hide(this);
} else {
color_picker.show(this);
}
});
$("#picker").click( function ( event ) {
event.preventDefault();
viewer.toggle_color_picker();
});
}
);
});
|
Add Trip and Step ModelForms | from django.contrib.auth.forms import AuthenticationForm
from django import forms
from django.core.validators import MinLengthValidator
from .models import PoolingUser, Trip, Step
from users.forms import UserCreationForm
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control',
}))
class SearchTrip(forms.Form):
"""
Pay attention that id fields are meant to be hidden, since we suppose they come from
an autocomplete AJAX request via an another CharField.
"""
origin_id = forms.IntegerField()
destination_id = forms.IntegerField()
datetime = forms.DateTimeField()
class PoolingUserForm(forms.ModelForm):
class Meta:
model = PoolingUser
# Exclude the one-to-one relation with User
fields = ['birth_date', 'driving_license', 'cellphone_number']
class TripForm(forms.ModelForm):
class Meta:
model = Trip
fields = ['date_origin', 'max_num_passengers']
class StepForm(forms.ModelForm):
class Meta:
model = Step
fields = ['origin', 'destination', 'hour_origin', 'hour_destination', 'max_price']
class UserForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
fields = ('email', 'first_name', 'last_name')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name in self.Meta.fields:
self[field_name].field.required = True
self['password1'].field.validators = [MinLengthValidator(6)]
| from django.contrib.auth.forms import AuthenticationForm
from django import forms
from django.core.validators import MinLengthValidator
from .models import PoolingUser
from users.forms import UserCreationForm
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control',
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control',
}))
class SearchTrip(forms.Form):
"""
Pay attention that id fields are meant to be hidden, since we suppose they come from
an autocomplete AJAX request via an another CharField.
"""
origin_id = forms.IntegerField()
destination_id = forms.IntegerField()
datetime = forms.DateTimeField()
class PoolingUserForm(forms.ModelForm):
class Meta:
model = PoolingUser
# Exclude the one-to-one relation with User
fields = ['birth_date', 'driving_license', 'cellphone_number']
class UserForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
fields = ('email', 'first_name', 'last_name')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name in self.Meta.fields:
self[field_name].field.required = True
self['password1'].field.validators = [MinLengthValidator(6)]
|
Increase startup attempts from 1 to 3 in MongoDB container | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.plugin.mongodb;
import com.google.common.net.HostAndPort;
import org.testcontainers.containers.MongoDBContainer;
import java.io.Closeable;
public class MongoServer
implements Closeable
{
private static final int MONGO_PORT = 27017;
private final MongoDBContainer dockerContainer;
public MongoServer()
{
this("3.4.0");
}
public MongoServer(String mongoVersion)
{
this.dockerContainer = new MongoDBContainer("mongo:" + mongoVersion)
.withStartupAttempts(3)
.withEnv("MONGO_INITDB_DATABASE", "tpch")
.withCommand("--bind_ip 0.0.0.0");
this.dockerContainer.start();
}
public HostAndPort getAddress()
{
return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT));
}
@Override
public void close()
{
dockerContainer.close();
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.plugin.mongodb;
import com.google.common.net.HostAndPort;
import org.testcontainers.containers.MongoDBContainer;
import java.io.Closeable;
public class MongoServer
implements Closeable
{
private static final int MONGO_PORT = 27017;
private final MongoDBContainer dockerContainer;
public MongoServer()
{
this("3.4.0");
}
public MongoServer(String mongoVersion)
{
this.dockerContainer = new MongoDBContainer("mongo:" + mongoVersion)
.withEnv("MONGO_INITDB_DATABASE", "tpch")
.withCommand("--bind_ip 0.0.0.0");
this.dockerContainer.start();
}
public HostAndPort getAddress()
{
return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(MONGO_PORT));
}
@Override
public void close()
{
dockerContainer.close();
}
}
|
Use invokeLater for ui build | package com.izforge.izpack.installer.base;
import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.installer.manager.PanelManager;
import javax.swing.*;
/**
* Installer frame controller
*
* @author Anthonin Bonnefoy
*/
public class InstallerController
{
private InstallerFrame installerFrame;
private PanelManager panelManager;
private AutomatedInstallData automatedInstallData;
public InstallerController(PanelManager panelManager, InstallDataConfiguratorWithRules installDataRulesEngineManager, InstallerFrame installerFrame, AutomatedInstallData automatedInstallData)
{
this.panelManager = panelManager;
this.installerFrame = installerFrame;
this.automatedInstallData = automatedInstallData;
installDataRulesEngineManager.configureInstallData();
}
public InstallerController buildInstallation() throws Exception
{
panelManager.loadPanelsInContainer();
panelManager.instantiatePanels();
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
installerFrame.buildGUI();
installerFrame.sizeFrame();
}
});
return this;
}
public void launchInstallation()
{
activateFirstPanel();
}
private void activateFirstPanel()
{
int firstPanel = installerFrame.hasNavigateNext(-1, false);
if (firstPanel > -1)
{
installerFrame.setVisible(true);
automatedInstallData.setCurPanelNumber(firstPanel);
installerFrame.switchPanel(firstPanel);
}
}
}
| package com.izforge.izpack.installer.base;
import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.installer.manager.PanelManager;
/**
* Installer frame controller
*
* @author Anthonin Bonnefoy
*/
public class InstallerController
{
private InstallerFrame installerFrame;
private PanelManager panelManager;
private AutomatedInstallData automatedInstallData;
public InstallerController(PanelManager panelManager, InstallDataConfiguratorWithRules installDataRulesEngineManager, InstallerFrame installerFrame, AutomatedInstallData automatedInstallData)
{
this.panelManager = panelManager;
this.installerFrame = installerFrame;
this.automatedInstallData = automatedInstallData;
installDataRulesEngineManager.configureInstallData();
}
public InstallerController buildInstallation() throws Exception
{
panelManager.loadPanelsInContainer();
panelManager.instantiatePanels();
installerFrame.buildGUI();
installerFrame.sizeFrame();
return this;
}
public void launchInstallation()
{
activateFirstPanel();
}
private void activateFirstPanel()
{
int firstPanel = installerFrame.hasNavigateNext(-1, false);
if (firstPanel > -1)
{
installerFrame.setVisible(true);
automatedInstallData.setCurPanelNumber(firstPanel);
installerFrame.switchPanel(firstPanel);
}
}
}
|
Change docker-py dependency error to a warning, update fix command
Signed-off-by: Joffrey F <[email protected]> | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import sys
# Attempt to detect https://github.com/docker/compose/issues/4344
try:
# We don't try importing pip because it messes with package imports
# on some Linux distros (Ubuntu, Fedora)
# https://github.com/docker/compose/issues/4425
# https://github.com/docker/compose/issues/4481
# https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py
s_cmd = subprocess.Popen(
['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE
)
packages = s_cmd.communicate()[0].splitlines()
dockerpy_installed = len(
list(filter(lambda p: p.startswith(b'docker-py=='), packages))
) > 0
if dockerpy_installed:
from .colors import yellow
print(
yellow('WARNING:'),
"Dependency conflict: an older version of the 'docker-py' package "
"may be polluting the namespace. "
"If you're experiencing crashes, run the following command to remedy the issue:\n"
"pip uninstall docker-py; pip uninstall docker; pip install docker",
file=sys.stderr
)
except OSError:
# pip command is not available, which indicates it's probably the binary
# distribution of Compose which is not affected
pass
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import sys
# Attempt to detect https://github.com/docker/compose/issues/4344
try:
# We don't try importing pip because it messes with package imports
# on some Linux distros (Ubuntu, Fedora)
# https://github.com/docker/compose/issues/4425
# https://github.com/docker/compose/issues/4481
# https://github.com/pypa/pip/blob/master/pip/_vendor/__init__.py
s_cmd = subprocess.Popen(
['pip', 'freeze'], stderr=subprocess.PIPE, stdout=subprocess.PIPE
)
packages = s_cmd.communicate()[0].splitlines()
dockerpy_installed = len(
list(filter(lambda p: p.startswith(b'docker-py=='), packages))
) > 0
if dockerpy_installed:
from .colors import red
print(
red('ERROR:'),
"Dependency conflict: an older version of the 'docker-py' package "
"is polluting the namespace. "
"Run the following command to remedy the issue:\n"
"pip uninstall docker docker-py; pip install docker",
file=sys.stderr
)
sys.exit(1)
except OSError:
# pip command is not available, which indicates it's probably the binary
# distribution of Compose which is not affected
pass
|
Add check against missing library versions
@tomByrer, Please check your PR. Now it outputs just bootstrap library
for Bootstrap CDN. | 'use strict';
var fs = require('fs');
var path = require('path');
var sortVersions = require('../lib/sort_versions');
module.exports = function(output, target, scrape) {
return function(cb) {
console.log('Starting to update ' + target + ' data');
scrape(function(err, libraries) {
if(err) {
console.error('Failed to update ' + target + ' data!', err);
return cb(err);
}
var p = path.join(output, target + '.json');
libraries = libraries.map(function(library) {
library.versions = sortVersions(library.versions);
// skip if library is missing versions for some reason
if(!library.versions) {
console.warn('Failed to find versions for', library);
return;
}
library.lastversion = library.versions[0];
return library;
}).filter(id);
fs.writeFile(
p,
JSON.stringify(libraries),
function(err) {
if(err) {
console.error('Failed to write', p);
return cb(err);
}
console.log('Updated', target, 'data');
cb();
}
);
});
};
};
function id(a) {
return a;
}
| 'use strict';
var fs = require('fs');
var path = require('path');
var sortVersions = require('../lib/sort_versions');
module.exports = function(output, target, scrape) {
return function(cb) {
console.log('Starting to update ' + target + ' data');
scrape(function(err, libraries) {
if(err) {
console.error('Failed to update ' + target + ' data!', err);
return cb(err);
}
var p = path.join(output, target + '.json');
libraries = libraries.map(function(library) {
library.versions = sortVersions(library.versions);
library.lastversion = library.versions[0];
return library;
});
fs.writeFile(
p,
JSON.stringify(libraries),
function(err) {
if(err) {
console.error('Failed to write', p);
return cb(err);
}
console.log('Updated', target, 'data');
cb();
}
);
});
};
};
|
Remove `apollo-federation` and `apollo-gateway` from Jest module not-mapping. | const { defaults } = require("jest-config");
module.exports = {
testEnvironment: "node",
setupFiles: [
"<rootDir>/../apollo-server-env/dist/index.js"
],
preset: "ts-jest",
testMatch: null,
testRegex: "/__tests__/.*\\.test\\.(js|ts)$",
testPathIgnorePatterns: [
"/node_modules/",
"/dist/"
],
moduleFileExtensions: [...defaults.moduleFileExtensions, "ts", "tsx"],
moduleNameMapper: {
'^__mocks__/(.*)$': '<rootDir>/../../__mocks__/$1',
// This regex should match the packages that we want compiled from source
// through `ts-jest`, as opposed to loaded from their output files in
// `dist`.
// We don't want to match `apollo-server-env` and
// `apollo-engine-reporting-protobuf`, because these don't depend on
// compilation but need to be initialized from as parto of `prepare`.
'^(?!apollo-server-env|apollo-engine-reporting-protobuf)(apollo-(?:server|datasource|cache-control|tracing|engine)[^/]*|graphql-extensions)(?:/dist)?((?:/.*)|$)': '<rootDir>/../../packages/$1/src$2'
},
clearMocks: true,
globals: {
"ts-jest": {
tsConfig: "<rootDir>/src/__tests__/tsconfig.json",
diagnostics: false
}
}
};
| const { defaults } = require("jest-config");
module.exports = {
testEnvironment: "node",
setupFiles: [
"<rootDir>/../apollo-server-env/dist/index.js"
],
preset: "ts-jest",
testMatch: null,
testRegex: "/__tests__/.*\\.test\\.(js|ts)$",
testPathIgnorePatterns: [
"/node_modules/",
"/dist/"
],
moduleFileExtensions: [...defaults.moduleFileExtensions, "ts", "tsx"],
moduleNameMapper: {
'^__mocks__/(.*)$': '<rootDir>/../../__mocks__/$1',
// This regex should match the packages that we want compiled from source
// through `ts-jest`, as opposed to loaded from their output files in
// `dist`.
// We don't want to match `apollo-server-env` and
// `apollo-engine-reporting-protobuf`, because these don't depend on
// compilation but need to be initialized from as parto of `prepare`.
'^(?!apollo-server-env|apollo-engine-reporting-protobuf)(apollo-(?:federation|gateway|server|datasource|cache-control|tracing|engine)[^/]*|graphql-extensions)(?:/dist)?((?:/.*)|$)': '<rootDir>/../../packages/$1/src$2'
},
clearMocks: true,
globals: {
"ts-jest": {
tsConfig: "<rootDir>/src/__tests__/tsconfig.json",
diagnostics: false
}
}
};
|
Correct a mistake from 1ae32f5 | var jsdom = require("jsdom");
function assign (destination, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
return destination;
}
var jsdomBrowser = function (baseBrowserDecorator, config) {
baseBrowserDecorator(this);
this.name = "jsdom";
this._start = function (url) {
if (jsdom.JSDOM) { // Indicate jsdom >= 10.0.0 and a new API
var jsdomOptions = {
resources: "usable",
runScripts: "dangerously"
};
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.JSDOM.fromURL(url, jsdomOptions);
} else {
var jsdomOptions = {
url: url,
features : {
FetchExternalResources: ["script", "iframe"],
ProcessExternalResources: ["script"]
},
created: function (error, window) {
// Do nothing.
}
}
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.env(jsdomOptions);
}
};
};
jsdomBrowser.$inject = ["baseBrowserDecorator", "config.jsdomLauncher"];
module.exports = {
"launcher:jsdom": ["type", jsdomBrowser]
};
| var jsdom = require("jsdom");
function assign (destination, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
return destination;
}
var jsdomBrowser = function (baseBrowserDecorator, config) {
baseBrowserDecorator(this);
this.name = "jsdom";
this._start = function (url) {
if (jsdom.JSDOM) { // Indicate jsdom >= 10.0.0 and a new API
var jsdomOptions = {
resources: "usable",
runScripts: "dangerously",
virtualConsole: virtualConsole
};
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.JSDOM.fromURL(url, jsdomOptions);
} else {
var jsdomOptions = {
url: url,
features : {
FetchExternalResources: ["script", "iframe"],
ProcessExternalResources: ["script"]
},
created: function (error, window) {
// Do nothing.
}
}
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.env(jsdomOptions);
}
};
};
jsdomBrowser.$inject = ["baseBrowserDecorator", "config.jsdomLauncher"];
module.exports = {
"launcher:jsdom": ["type", jsdomBrowser]
};
|
Break line in an odd place to keep the build from breaking. | import decimal
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
price = settings.PAYMENTS_PLANS[plan]["price"]
if isinstance(price, decimal.Decimal):
amount = int(100 * price)
else:
amount = int(100 * decimal.Decimal(str(price)))
stripe.Plan.create(
amount=amount,
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency=settings.PAYMENTS_PLANS[plan]["currency"],
trial_period_days=settings.PAYMENTS_PLANS[plan].get(
"trial_period_days"),
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for {0}".format(plan)
| import decimal
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
price = settings.PAYMENTS_PLANS[plan]["price"]
if isinstance(price, decimal.Decimal):
amount = int(100 * price)
else:
amount = int(100 * decimal.Decimal(str(price)))
stripe.Plan.create(
amount=amount,
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency=settings.PAYMENTS_PLANS[plan]["currency"],
trial_period_days=settings.PAYMENTS_PLANS[plan].get("trial_period_days"),
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for {0}".format(plan)
|
Deploy should remember to generate markers | import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('generate_markers', lazy=True)
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
| import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
Remove stylint from gulp watch | var gulp = require('gulp');
var stylus = require('gulp-stylus');
var stylint = require('gulp-stylint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var stylFiles = './assets/styl/*.styl';
function bsjs(file) {
return './assets/bootstrap-stylus-5.0.2/js/' + file + '.js'
};
var bootstrapJsFiles = [bsjs('collapse'), bsjs('button'), bsjs('dropdown')];
gulp.task('stylus-lint', function() {
return gulp.src(stylFiles)
.pipe(stylint({
config: './assets/styl/.stylintrc'
}))
.pipe(stylint.reporter())
.pipe(stylint.reporter('fail'));
});
gulp.task('stylus-compile', function() {
return gulp.src(stylFiles)
.pipe(stylus({
compress: true
}))
.pipe(gulp.dest('./assets/css'))
});
gulp.task('stylus', ['stylus-lint', 'stylus-compile']);
gulp.task('bootstrap-js', function() {
return gulp.src(bootstrapJsFiles)
.pipe(concat('bootstrap.min.js'))
.pipe(uglify())
.pipe(gulp.dest('./assets/js'))
});
gulp.task('watch', function() {
gulp.watch([stylFiles, './assets/bootstrap-stylus-5.0.2/bootstrap/*.styl'], ['stylus-compile']);
});
gulp.task('default', ['stylus', 'bootstrap-js']); | var gulp = require('gulp');
var stylus = require('gulp-stylus');
var stylint = require('gulp-stylint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var stylFiles = './assets/styl/*.styl';
function bsjs(file) {
return './assets/bootstrap-stylus-5.0.2/js/' + file + '.js'
};
var bootstrapJsFiles = [bsjs('collapse'), bsjs('button'), bsjs('dropdown')];
gulp.task('stylus-lint', function() {
return gulp.src(stylFiles)
.pipe(stylint({
config: './assets/styl/.stylintrc'
}))
.pipe(stylint.reporter())
.pipe(stylint.reporter('fail'));
});
gulp.task('stylus-compile', function() {
return gulp.src(stylFiles)
.pipe(stylus({
compress: true
}))
.pipe(gulp.dest('./assets/css'))
});
gulp.task('stylus', ['stylus-lint', 'stylus-compile']);
gulp.task('bootstrap-js', function() {
return gulp.src(bootstrapJsFiles)
.pipe(concat('bootstrap.min.js'))
.pipe(uglify())
.pipe(gulp.dest('./assets/js'))
});
gulp.task('watch', function() {
gulp.watch([stylFiles, './assets/bootstrap-stylus-5.0.2/bootstrap/*.styl'], ['stylus']);
});
gulp.task('default', ['stylus', 'bootstrap-js']); |
Add archive description to validator and point to my repo for demo | /**
* This is the default configuration file for the Superdesk application. By default,
* the app will use the file with the name "superdesk.config.js" found in the current
* working directory, but other files may also be specified using relative paths with
* the SUPERDESK_CONFIG environment variable or the grunt --config flag.
*/
module.exports = function(grunt) {
return {
defaultRoute: '/workspace',
validatorMediaMetadata: {
headline: {
required: true
},
alt_text: {
required: true
},
archive_description: {
required: false
},
description_text: {
required: true
},
copyrightholder: {
required: false
},
byline: {
required: false
},
usageterms: {
required: false
},
copyrightnotice: {
required: false
}
},
features: {
swimlane: {columnsLimit: 4}
},
ingest: {
PROVIDER_DASHBOARD_DEFAULTS: {
show_log_messages: true,
show_ingest_count: true,
show_time: true,
log_messages: 'error',
show_status: true
},
DEFAULT_SCHEDULE: {minutes: 5, seconds: 0},
DEFAULT_IDLE_TIME: {hours: 0, minutes: 0},
}
};
};
| /**
* This is the default configuration file for the Superdesk application. By default,
* the app will use the file with the name "superdesk.config.js" found in the current
* working directory, but other files may also be specified using relative paths with
* the SUPERDESK_CONFIG environment variable or the grunt --config flag.
*/
module.exports = function(grunt) {
return {
defaultRoute: '/workspace',
validatorMediaMetadata: {
headline: {
required: true
},
alt_text: {
required: true
},
description_text: {
required: true
},
copyrightholder: {
required: false
},
byline: {
required: false
},
usageterms: {
required: false
},
copyrightnotice: {
required: false
}
},
features: {
swimlane: {columnsLimit: 4}
},
ingest: {
PROVIDER_DASHBOARD_DEFAULTS: {
show_log_messages: true,
show_ingest_count: true,
show_time: true,
log_messages: 'error',
show_status: true
},
DEFAULT_SCHEDULE: {minutes: 5, seconds: 0},
DEFAULT_IDLE_TIME: {hours: 0, minutes: 0},
}
};
};
|
Update project name from dejavu to PyDejavu | from setuptools import setup, find_packages
# import os, sys
def parse_requirements(requirements):
# load from requirements.txt
with open(requirements) as f:
lines = [l for l in f]
# remove spaces
stripped = map((lambda x: x.strip()), lines)
# remove comments
nocomments = filter((lambda x: not x.startswith('#')), stripped)
# remove empty lines
reqs = filter((lambda x: x), nocomments)
return reqs
PACKAGE_NAME = "PyDejavu"
PACKAGE_VERSION = "0.1"
SUMMARY = 'Dejavu Audio Fingerprinting'
DESCRIPTION = """Dejavu Audio Fingerprinting"""
REQUIREMENTS = parse_requirements("requirements.txt")
setup(
name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description=SUMMARY,
long_description=DESCRIPTION,
author='worldveil',
author_email='[email protected]',
url='http://github.com/tuxdna/dejavu',
license='Apache 2.0',
include_package_data=True,
packages=find_packages(),
platforms=['Any'],
install_requires=REQUIREMENTS,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from setuptools import setup, find_packages
# import os, sys
def parse_requirements(requirements):
# load from requirements.txt
with open(requirements) as f:
lines = [l for l in f]
# remove spaces
stripped = map((lambda x: x.strip()), lines)
# remove comments
nocomments = filter((lambda x: not x.startswith('#')), stripped)
# remove empty lines
reqs = filter((lambda x: x), nocomments)
return reqs
PACKAGE_NAME = "dejavu"
PACKAGE_VERSION = "0.1"
SUMMARY = 'Dejavu Audio Fingerprinting'
DESCRIPTION = """Dejavu Audio Fingerprinting"""
REQUIREMENTS = parse_requirements("requirements.txt")
setup(
name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description=SUMMARY,
long_description=DESCRIPTION,
author='worldveil',
author_email='[email protected]',
url='http://github.com/tuxdna/dejavu',
license='Apache 2.0',
include_package_data=True,
packages=find_packages(),
platforms=['Any'],
install_requires=REQUIREMENTS,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Increment minor version number for new release (v0.02). | from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.02',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='[email protected]',
url='http://wiki.creativecommons.org/CcLicense',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
#package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work
data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf',
'license.rdf/rdf/selectors.rdf',
'license.rdf/rdf/jurisdictions.rdf']),
('cc/license/xml', ['license.rdf/xml/questions.xml'])],
zip_safe=False,
test_suite='nose.collector',
install_requires=[
'setuptools',
'zope.interface',
'nose',
'Genshi',
'pylons', # XXX why does nose throw a RuntimeWarning without this?
],
setup_requires=['setuptools-git',],
entry_points="""
# -*- Entry points: -*-
[nose.plugins]
pylons = pylons.test:PylonsPlugin
""",
)
| from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.01',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='[email protected]',
url='http://wiki.creativecommons.org/CcLicense',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
#package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work
data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf',
'license.rdf/rdf/selectors.rdf',
'license.rdf/rdf/jurisdictions.rdf']),
('cc/license/xml', ['license.rdf/xml/questions.xml'])],
zip_safe=False,
test_suite='nose.collector',
install_requires=[
'setuptools',
'zope.interface',
'nose',
'Genshi',
'pylons', # XXX why does nose throw a RuntimeWarning without this?
],
setup_requires=['setuptools-git',],
entry_points="""
# -*- Entry points: -*-
[nose.plugins]
pylons = pylons.test:PylonsPlugin
""",
)
|
Use only the height to decide whether to zoom in or out. | # Sample extension: zoom a window to maximum height
import re
import sys
class ZoomHeight:
menudefs = [
('windows', [
('_Zoom Height', '<<zoom-height>>'),
])
]
windows_keydefs = {
'<<zoom-height>>': ['<Alt-F2>'],
}
unix_keydefs = {
'<<zoom-height>>': ['<Control-x><Control-z>'],
}
def __init__(self, editwin):
self.editwin = editwin
def zoom_height_event(self, event):
top = self.editwin.top
geom = top.wm_geometry()
m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
if not m:
top.bell()
return
width, height, x, y = map(int, m.groups())
newheight = top.winfo_screenheight()
if sys.platform == 'win32':
newy = 0
newheight = newheight - 72
else:
newy = 24
newheight = newheight - 96
if height >= newheight:
newgeom = ""
else:
newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy)
top.wm_geometry(newgeom)
| # Sample extension: zoom a window to maximum height
import re
import sys
class ZoomHeight:
menudefs = [
('windows', [
('_Zoom Height', '<<zoom-height>>'),
])
]
windows_keydefs = {
'<<zoom-height>>': ['<Alt-F2>'],
}
unix_keydefs = {
'<<zoom-height>>': ['<Control-x><Control-z>'],
}
def __init__(self, editwin):
self.editwin = editwin
def zoom_height_event(self, event):
top = self.editwin.top
geom = top.wm_geometry()
m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
if not m:
top.bell()
return
width, height, x, y = map(int, m.groups())
height = top.winfo_screenheight()
if sys.platform == 'win32':
y = 0
height = height - 72
else:
y = 24
height = height - 96
newgeom = "%dx%d+%d+%d" % (width, height, x, y)
if geom == newgeom:
newgeom = ""
top.wm_geometry(newgeom)
|
Handle no roles on users table | import React, {PropTypes} from 'react'
const UsersTable = ({users}) => (
<div className="panel panel-minimal">
<div className="panel-body">
<table className="table v-center">
<thead>
<tr>
<th>User</th>
<th>Roles</th>
<th>Permissions</th>
</tr>
</thead>
<tbody>
{
users.length ? users.map((user) => (
<tr key={user.name}>
<td>{user.name}</td>
<td>{users.roles && user.roles.map((r) => r.name).join(', ')}</td>
<td>{user.permissions.map((p) => p.scope).join(', ')}</td>
</tr>
)) : (() => (
<tr className="table-empty-state">
<th colSpan="5">
<p>You don't have any Users,<br/>why not create one?</p>
</th>
</tr>
))()
}
</tbody>
</table>
</div>
</div>
)
const {
arrayOf,
shape,
string,
} = PropTypes
UsersTable.propTypes = {
users: arrayOf(shape({
name: string.isRequired,
roles: arrayOf(shape({
name: string,
})),
permissions: arrayOf(shape({
name: string,
scope: string.isRequired,
})),
})),
}
export default UsersTable
| import React, {PropTypes} from 'react'
const UsersTable = ({users}) => (
<div className="panel panel-minimal">
<div className="panel-body">
<table className="table v-center">
<thead>
<tr>
<th>User</th>
<th>Roles</th>
<th>Permissions</th>
</tr>
</thead>
<tbody>
{
users.length ? users.map((user) => (
<tr key={user.name}>
<td>{user.name}</td>
<td>{user.roles.map((r) => r.name).join(', ')}</td>
<td>{user.permissions.map((p) => p.scope).join(', ')}</td>
</tr>
)) : (() => (
<tr className="table-empty-state">
<th colSpan="5">
<p>You don't have any Users,<br/>why not create one?</p>
</th>
</tr>
))()
}
</tbody>
</table>
</div>
</div>
)
const {
arrayOf,
shape,
string,
} = PropTypes
UsersTable.propTypes = {
users: arrayOf(shape({
name: string.isRequired,
roles: arrayOf(shape({
name: string,
})),
permissions: arrayOf(shape({
name: string,
scope: string.isRequired,
})),
})),
}
export default UsersTable
|
Remove references to gulpish git | var gulp = require('gulp');
var chug = require('gulp-chug');
var clean = require('gulp-clean');
var jshint = require('gulp-jshint');
gulp.task('watch', function () {
gulp.watch('./src/**/*.js');
gulp.watch([
'./src/template/decode/**/*',
'!./src/template/decode/build{,/**}'
], ['decode']);
});
gulp.task('classes', function () {
return gulp.src('./src/base/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest('./lib/base'));
});
gulp.task('decode', ['buildDecode', 'classes'], function () {
return gulp.src([
'./src/template/decode/build/**/*.js',
'./src/decode/**/*.js'
])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest('./lib/decode'));
});
gulp.task('buildDecode', function () {
return gulp.src('./src/template/decode/gulpfile.js', { read : false })
.pipe(chug({ tasks : ['build'] }))
});
gulp.task('ci', function () {
return gulp.src('./src/template/decode/gulpfile.js', { read : false })
.pipe(chug({ tasks : ['ci'] }));
});
gulp.task('clean', function () {
return gulp.src('./decode/**/*')
.pipe(clean());
});
| var gulp = require('gulp');
var bump = require('gulp-bump');
var chug = require('gulp-chug');
var clean = require('gulp-clean');
var git = require('gulp-git');
var jshint = require('gulp-jshint');
gulp.task('watch', function () {
gulp.watch('./src/**/*.js');
gulp.watch([
'./src/template/decode/**/*',
'!./src/template/decode/build{,/**}'
], ['decode']);
});
gulp.task('classes', function () {
return gulp.src('./src/base/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest('./lib/base'));
});
gulp.task('decode', ['buildDecode', 'classes'], function () {
return gulp.src([
'./src/template/decode/build/**/*.js',
'./src/decode/**/*.js'
])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest('./lib/decode'));
});
gulp.task('buildDecode', function () {
return gulp.src('./src/template/decode/gulpfile.js', { read : false })
.pipe(chug({ tasks : ['build'] }))
});
gulp.task('ci', function () {
return gulp.src('./src/template/decode/gulpfile.js', { read : false })
.pipe(chug({ tasks : ['ci'] }));
});
gulp.task('clean', function () {
return gulp.src('./decode/**/*')
.pipe(clean());
});
|
Add 'password' to comment on required credentials | 'use strict';
// Bitazza uses Alphapoint, also used by ndax
// In order to use private endpoints, the following are required:
// - 'apiKey'
// - 'secret',
// - 'uid' (userId in the api info)
// - 'login' (the email address used to log into the UI)
// - 'password' (the password used to log into the UI)
const ndax = require ('./ndax.js');
// ---------------------------------------------------------------------------
module.exports = class bitazza extends ndax {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitazza',
'name': 'Bitazza',
'countries': [ 'THA' ],
'certified': false,
'pro': false,
'urls': {
'test': undefined,
'api': {
'public': 'https://apexapi.bitazza.com:8443/AP',
'private': 'https://apexapi.bitazza.com:8443/AP',
},
'www': 'https://bitazza.com/',
'referral': '',
'fees': 'https://bitazza.com/fees.html',
'doc': [
'https://api-doc.bitazza.com/',
],
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0025'),
'maker': this.parseNumber ('0.0025'),
},
},
});
}
};
| 'use strict';
// Bitazza uses Alphapoint, also used by ndax
// In order to use private endpoints, the following are required:
// - 'apiKey'
// - 'secret',
// - 'uid' (userId in the api info)
// - 'login' (the email address used to log into the UI)
const ndax = require ('./ndax.js');
// ---------------------------------------------------------------------------
module.exports = class bitazza extends ndax {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitazza',
'name': 'Bitazza',
'countries': [ 'THA' ],
'certified': false,
'pro': false,
'urls': {
'test': undefined,
'api': {
'public': 'https://apexapi.bitazza.com:8443/AP',
'private': 'https://apexapi.bitazza.com:8443/AP',
},
'www': 'https://bitazza.com/',
'referral': '',
'fees': 'https://bitazza.com/fees.html',
'doc': [
'https://api-doc.bitazza.com/',
],
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0025'),
'maker': this.parseNumber ('0.0025'),
},
},
});
}
};
|
Fix test customer collection find | package me.pagarme;
import me.pagar.model.Address;
import me.pagar.model.Customer;
import me.pagar.model.PagarMeException;
import me.pagar.model.Phone;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
public class CustomerTest extends BaseTest {
private Customer customer;
@Before
public void setUp() {
super.setUp();
customer = new Customer();
}
@Test
public void testCreateCustomer() {
Customer customer = this.customerCreateCommon();
try {
customer.save();
Address customerAddress = customer.getAddress();
Phone customerPhone = customer.getPhone();
this.assertCustomer(customer, customerAddress, customerPhone);
} catch (PagarMeException ex) {
throw new UnsupportedOperationException(ex);
}
}
@Test
public void testCustomerFind() {
Customer customer = this.customerCreateCommon();
try {
customer.save();
Integer customerId = customer.getId();
customer.find(customerId);
Address customerAddress = customer.getAddress();
Phone customerPhone = customer.getPhone();
this.assertCustomer(customer, customerAddress, customerPhone);
} catch (PagarMeException ex) {
throw new UnsupportedOperationException(ex);
}
}
} | package me.pagarme;
import me.pagar.model.Address;
import me.pagar.model.Customer;
import me.pagar.model.PagarMeException;
import me.pagar.model.Phone;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
public class CustomerTest extends BaseTest {
private Customer customer;
@Before
public void setUp() {
super.setUp();
customer = new Customer();
}
@Test
public void testCreateCustomer() {
Customer customer = this.customerCreateCommon();
try {
customer.save();
Address customerAddress = customer.getAddress();
Phone customerPhone = customer.getPhone();
this.assertCustomer(customer, customerAddress, customerPhone);
} catch (PagarMeException ex) {
throw new UnsupportedOperationException(ex);
}
}
@Test
public void testCustomerFind() {
Customer customer = this.customerCreateCommon();
try {
customer.save();
Integer customerId = customer.getId();
customer.find(customerId);
Address customerAddress = customer.getAddress();
Phone customerPhone = customer.getPhone();
this.assertCustomer(customer, customerAddress, customerPhone);
} catch (PagarMeException ex) {
throw new UnsupportedOperationException(ex);
}
}
@Test
public void testCustomerCollectionFind() {
Customer createCustomer = this.customerCreateCommon();
try {
createCustomer.save();
Collection<Customer> customerCollection = customer.findCollection(1,0);
Assert.assertEquals(customerCollection.size(), 1);
} catch (PagarMeException ex) {
throw new UnsupportedOperationException(ex);
}
}
} |
Improve API to colorize an icon
Move the details to this library. Usage example:
icons.colorize(myButton, ["#FF0000", "#00FF00"]); | define(function () {
icons = {};
icons.load = function (iconInfo, callback) {
if ("uri" in iconInfo) {
source = iconInfo.uri;
}
else if ("name" in iconInfo) {
source = "lib/sugar-html-graphics/icons/" + iconInfo.name + ".svg";
}
fillColor = iconInfo.fillColor;
strokeColor = iconInfo.strokeColor;
client = new XMLHttpRequest();
client.onload = function () {
var iconData = this.responseText;
var re;
if (fillColor) {
re = /(<!ENTITY fill_color ")(.*)(">)/;
iconData = iconData.replace(re, "$1" + fillColor + "$3");
}
if (strokeColor) {
re = /(<!ENTITY stroke_color ")(.*)(">)/;
iconData = iconData.replace(re, "$1" + strokeColor + "$3");
}
callback("data:image/svg+xml," + escape(iconData));
};
client.open("GET", source);
client.send();
};
function getBackgroundURL(elem) {
var style = elem.currentStyle || window.getComputedStyle(elem, '');
// Remove prefix 'url(' and suffix ')' before return
return style.backgroundImage.slice(4, -1);
}
function setBackgroundURL(elem, url) {
elem.style.backgroundImage = "url('" + url + "')";
}
icons.colorize = function(elem, colors) {
var iconInfo = {
"uri": getBackgroundURL(elem),
"strokeColor": colors[0],
"fillColor": colors[1]
};
icons.load(iconInfo, function (url) {
setBackgroundURL(elem, url);
});
};
return icons;
});
| define(function () {
icons = {};
icons.load = function (iconInfo, callback) {
if ("uri" in iconInfo) {
source = iconInfo.uri;
}
else if ("name" in iconInfo) {
source = "lib/sugar-html-graphics/icons/" + iconInfo.name + ".svg";
}
fillColor = iconInfo.fillColor;
strokeColor = iconInfo.strokeColor;
client = new XMLHttpRequest();
client.onload = function () {
var iconData = this.responseText;
var re;
if (fillColor) {
re = /(<!ENTITY fill_color ")(.*)(">)/;
iconData = iconData.replace(re, "$1" + fillColor + "$3");
}
if (strokeColor) {
re = /(<!ENTITY stroke_color ")(.*)(">)/;
iconData = iconData.replace(re, "$1" + strokeColor + "$3");
}
callback("data:image/svg+xml," + escape(iconData));
};
client.open("GET", source);
client.send();
};
return icons;
});
|
Use nodejs native crypto module | import mongo from '../db'
import utils from '../utils'
import crypto from 'crypto'
/**
* User :: {
* id: String,
* username: String,
* password: String,
* createdAt: String
* }
*/
/** String -> String -> User */
function createUser(username, password) {
return {
"id": utils.UUID(),
"username": username,
"password": crypto.createHmac('sha256', password).update(password).digest('base64'),
"createdAt": Date.now()
}
}
/** String -> Promise(Boolean, Error) */
function userExist(username) {
return mongo.connect()
.then(db => db.collection('users').findOne({ username })
.then(mongo.close(db)))
.then(user => user != null)
}
/** User -> Promise(User, Error) */
function saveUser(user) {
return mongo.connect()
.then(db => db.collection('users').insertOne(user)
.then(mongo.close(db)))
.then(() => user)
}
/** String -> String -> Promise({id, username, token : String}, Error) */
export function register(username, password) {
userExist(username)
.then(exist => exist ?
Promise.reject("The user already exist") :
Promise.resolve(createUser(username, password)))
.then(saveUser)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user)
}))
}
| import mongo from '../db'
import utils from '../utils'
/**
* User :: {
* id: String,
* username: String,
* password: String,
* createdAt: String
* }
*/
/** String -> String -> User */
function createUser(username, password) {
return {
"id": utils.UUID(),
"username": username,
"password": utils.HMAC256(password, password),
"createdAt": Date.now()
}
}
/** String -> Promise(Boolean, Error) */
function userExist(username) {
return mongo.connect()
.then(db => db.collection('users').findOne({ username })
.then(mongo.close(db)))
.then(user => user != null)
}
/** User -> Promise(User, Error) */
function saveUser(user) {
return mongo.connect()
.then(db => db.collection('users').insertOne(user)
.then(mongo.close(db)))
.then(() => user)
}
/** String -> String -> Promise({id, username, token : String}, Error) */
export function register(username, password) {
userExist(username)
.then(exist => exist ?
Promise.reject("The user already exist") :
Promise.resolve(createUser(username, password)))
.then(saveUser)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user)
}))
}
|
Use an update view instead of form view | from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.utils.datastructures import MultiValueDictKeyError
from django.views.generic import TemplateView, UpdateView
from incuna.utils import get_class_from_path
from profiles.models import Profile
from profiles.utils import class_view_decorator
try:
ProfileForm = get_class_from_path(settings.PROFILE_FORM_CLASS)
except AttributeError:
from forms import ProfileForm
@class_view_decorator(login_required)
class ProfileView(TemplateView):
template_name = 'profiles/profile.html'
@class_view_decorator(login_required)
class ProfileEdit(UpdateView):
form_class = ProfileForm
template_name = 'profiles/profile_form.html'
def form_valid(self, form):
instance = super(ProfileEdit, self).form_valid(form)
self.request.user.message_set.create(message='Your profile has been updated.')
return instance
def get_context_data(self, **kwargs):
context = super(ProfileEdit, self).get_context_data(**kwargs)
context['site'] = Site.objects.get_current()
return context
def get_object(self):
if isinstance(self.request.user, Profile):
return self.request.user
return self.request.user.profile
def get_success_url(self):
try:
return self.request.GET['next']
except MultiValueDictKeyError:
return reverse('profile')
| from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.views.generic import FormView, TemplateView
from django.utils.datastructures import MultiValueDictKeyError
from incuna.utils import get_class_from_path
from profiles.models import Profile
from profiles.utils import class_view_decorator
try:
ProfileForm = get_class_from_path(settings.PROFILE_FORM_CLASS)
except AttributeError:
from forms import ProfileForm
@class_view_decorator(login_required)
class ProfileView(TemplateView):
template_name = 'profiles/profile.html'
@class_view_decorator(login_required)
class ProfileEdit(FormView):
form_class = ProfileForm
template_name = 'profiles/profile_form.html'
def form_valid(self, form):
instance = super(ProfileEdit, self).form_valid(form)
self.request.user.message_set.create(message='Your profile has been updated.')
return instance
def get_context_data(self, **kwargs):
context = super(ProfileEdit, self).get_context_data(**kwargs)
context['site'] = Site.objects.get_current()
return context
def get_object(self):
if isinstance(self.request.user, Profile):
return self.request.user
return self.request.user.profile
def get_success_url(self):
try:
return self.request.GET['next']
except MultiValueDictKeyError:
return reverse('profile')
|
Change deprecated call to res.json(status, body)
Fixes #74 | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
ExperimentSchema = mongoose.model('ExperimentSchema');
/**
* List of Experiment schemas
*/
exports.list = function(req, res) {
ExperimentSchema.find({}, function(err, schemas) {
if (err) {
res.json(500, {error: err.message});
} else {
res.json(200, schemas);
}
});
};
/**
* Build a random experiment from a random ExperimentSchema
*/
exports.random = function(req, res) {
function errorHandler(err) {
res.json(500, {error: err.message});
}
ExperimentSchema.count({}, function(err, count) {
if (err) {
return errorHandler(err);
} else if (count < 1) {
return errorHandler(new Error('No experiment schemas in' +
' database.'));
} else {
// Get a random number from [0, number of schema)
var rand = Math.floor(Math.random() * count);
// Get a random schema
ExperimentSchema.find({})
.skip(rand)
.limit(1)
.populate('mediaPool', 'artist title label')
.exec(function(err, schema) {
if (err) {
return errorHandler(err);
}
// Using the controller, build an experiment from this
// schema
schema[0].buildExperiment(function(err, builtExperiment) {
// Send the response
res.status(200).json(builtExperiment);
});
});
}
});
}; | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
ExperimentSchema = mongoose.model('ExperimentSchema');
/**
* List of Experiment schemas
*/
exports.list = function(req, res) {
ExperimentSchema.find({}, function(err, schemas) {
if (err) {
res.json(500, {error: err.message});
} else {
res.json(200, schemas);
}
});
};
/**
* Build a random experiment from a random ExperimentSchema
*/
exports.random = function(req, res) {
function errorHandler(err) {
res.json(500, {error: err.message});
}
ExperimentSchema.count({}, function(err, count) {
if (err) {
return errorHandler(err);
} else if (count < 1) {
return errorHandler(new Error('No experiment schemas in' +
' database.'));
} else {
// Get a random number from [0, number of schema)
var rand = Math.floor(Math.random() * count);
// Get a random schema
ExperimentSchema.find({})
.skip(rand)
.limit(1)
.populate('mediaPool', 'artist title label')
.exec(function(err, schema) {
if (err) {
return errorHandler(err);
}
// Using the controller, build an experiment from this
// schema
schema[0].buildExperiment(function(err, builtExperiment) {
// Send the response
res.json(200, builtExperiment);
});
});
}
});
}; |
Add missingParam method to exception class. | <?php
namespace Telegram\Bot\Exceptions;
/**
* Class CouldNotUploadInputFile.
*/
class CouldNotUploadInputFile extends TelegramSDKException
{
/**
* @param $file
*
* @return CouldNotUploadInputFile
*/
public static function fileDoesNotExistOrNotReadable($file): CouldNotUploadInputFile
{
return new static("File: `{$file}` does not exist or is not readable!");
}
/**
* @param $path
*
* @return CouldNotUploadInputFile
*/
public static function filenameNotProvided($path): CouldNotUploadInputFile
{
$file = is_string($path) ? $path : "the resource that you're trying to upload";
return new static(
"Filename not provided for {$file}. " .
'Remote or Resource file uploads require a filename. Refer Docs for more information.'
);
}
/**
* @param $path
*
* @return CouldNotUploadInputFile
*/
public static function couldNotOpenResource($path): CouldNotUploadInputFile
{
return new static("Failed to create InputFile entity. Unable to open resource: {$path}.");
}
/**
* @param $property
*
* @return CouldNotUploadInputFile
*/
public static function resourceShouldBeInputFileEntity($property): CouldNotUploadInputFile
{
return new static("Resource file should be uploaded using `Telegram\Bot\FileUpload\InputFile::create(\$resourceOrRemoteUrl, \$filename)` for `{$property}` property.");
}
/**
* @param $inputFileField
*
* @return CouldNotUploadInputFile
*/
public static function missingParam($inputFileField): CouldNotUploadInputFile
{
return new static("Input field [{$inputFileField}] is missing in your params. Please make sure it exists and is an `Telegram\Bot\FileUpload\InputFile` entity.");
}
}
| <?php
namespace Telegram\Bot\Exceptions;
/**
* Class CouldNotUploadInputFile.
*/
class CouldNotUploadInputFile extends TelegramSDKException
{
/**
* @param $file
*
* @return CouldNotUploadInputFile
*/
public static function fileDoesNotExistOrNotReadable($file): CouldNotUploadInputFile
{
return new static("File: `{$file}` does not exist or is not readable!");
}
/**
* @param $path
*
* @return CouldNotUploadInputFile
*/
public static function filenameNotProvided($path): CouldNotUploadInputFile
{
$file = is_string($path) ? $path : "the resource that you're trying to upload";
return new static(
"Filename not provided for {$file}. " .
'Remote or Resource file uploads require a filename. Refer Docs for more information.'
);
}
/**
* @param $path
*
* @return CouldNotUploadInputFile
*/
public static function couldNotOpenResource($path): CouldNotUploadInputFile
{
return new static("Failed to create InputFile entity. Unable to open resource: {$path}.");
}
/**
* @param $property
*
* @return CouldNotUploadInputFile
*/
public static function resourceShouldBeInputFileEntity($property): CouldNotUploadInputFile
{
return new static("Resource file should be uploaded using `Telegram\Bot\FileUpload\InputFile::create(\$resourceOrRemoteUrl, \$filename)` for `{$property}` property.");
}
}
|
Fix class BadFunctionCallException not found | <?php
namespace Eris\Generator;
use BadFunctionCallException;
use Eris\Generator;
use ReverseRegex\Lexer;
use ReverseRegex\Random\SimpleRandom;
use ReverseRegex\Parser;
use ReverseRegex\Generator\Scope;
/**
* Note * and + modifiers cause an unbounded number of character to be generated (up to plus infinity) and as such they are not supported.
* Please use {1,N} and {0,N} instead of + and *.
*
* @param string $expression
* @return Generator\Regex
*/
function regex($expression)
{
return new Regex($expression);
}
class Regex implements Generator
{
private $expression;
public function __construct($expression)
{
if (!class_exists("ReverseRegex\Parser")) {
throw new BadFunctionCallException("Please install the suggested dependency icomefromthenet/reverse-regex to run this Generator.");
}
$this->expression = $expression;
}
public function __invoke()
{
$lexer = new Lexer($this->expression);
$gen = new SimpleRandom(rand());
$result = null;
$parser = new Parser($lexer,new Scope(),new Scope());
$parser->parse()->getResult()->generate($result,$gen);
return $result;
}
public function shrink($value)
{
return $value;
}
public function contains($value)
{
return is_string($value)
&& (bool) preg_match("/{$this->expression}/", $value);
}
}
| <?php
namespace Eris\Generator;
use Eris\Generator;
use ReverseRegex\Lexer;
use ReverseRegex\Random\SimpleRandom;
use ReverseRegex\Parser;
use ReverseRegex\Generator\Scope;
/**
* Note * and + modifiers cause an unbounded number of character to be generated (up to plus infinity) and as such they are not supported.
* Please use {1,N} and {0,N} instead of + and *.
*
* @param string $expression
* @return Generator\Regex
*/
function regex($expression)
{
return new Regex($expression);
}
class Regex implements Generator
{
private $expression;
public function __construct($expression)
{
if (!class_exists("ReverseRegex\Parser")) {
throw new BadFunctionCallException("Please install the suggested dependency icomefromthenet/reverse-regex to run this Generator.");
}
$this->expression = $expression;
}
public function __invoke()
{
$lexer = new Lexer($this->expression);
$gen = new SimpleRandom(rand());
$result = null;
$parser = new Parser($lexer,new Scope(),new Scope());
$parser->parse()->getResult()->generate($result,$gen);
return $result;
}
public function shrink($value)
{
return $value;
}
public function contains($value)
{
return is_string($value)
&& (bool) preg_match("/{$this->expression}/", $value);
}
}
|
Make the window in the pyglet example larger. | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import pyglet
from pyglet import gl
import imgui
from imgui.integrations.pyglet import PygletRenderer
def main():
window = pyglet.window.Window(width=1280, height=720, resizable=True)
gl.glClearColor(1, 1, 1, 1)
renderer = PygletRenderer(window)
def update(dt):
imgui.new_frame()
if imgui.begin_main_menu_bar():
if imgui.begin_menu("File", True):
clicked_quit, selected_quit = imgui.menu_item(
"Quit", 'Cmd+Q', False, True
)
if clicked_quit:
exit(1)
imgui.end_menu()
imgui.end_main_menu_bar()
imgui.show_test_window()
imgui.begin("Custom window", True)
imgui.text("Bar")
imgui.text_colored("Eggs", 0.2, 1., 0.)
imgui.end()
@window.event
def on_draw():
update(1/60.0)
window.clear()
imgui.render()
renderer.render(imgui.get_draw_data())
pyglet.app.run()
renderer.shutdown()
if __name__ == "__main__":
main()
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
import pyglet
from pyglet import gl
import imgui
from imgui.integrations.pyglet import PygletRenderer
def main():
window = pyglet.window.Window(width=800, height=600, resizable=True)
gl.glClearColor(1, 1, 1, 1)
renderer = PygletRenderer(window)
def update(dt):
imgui.new_frame()
if imgui.begin_main_menu_bar():
if imgui.begin_menu("File", True):
clicked_quit, selected_quit = imgui.menu_item(
"Quit", 'Cmd+Q', False, True
)
if clicked_quit:
exit(1)
imgui.end_menu()
imgui.end_main_menu_bar()
imgui.show_test_window()
imgui.begin("Custom window", True)
imgui.text("Bar")
imgui.text_colored("Eggs", 0.2, 1., 0.)
imgui.end()
@window.event
def on_draw():
update(1/60.0)
window.clear()
imgui.render()
renderer.render(imgui.get_draw_data())
pyglet.app.run()
renderer.shutdown()
if __name__ == "__main__":
main()
|
CRM-4904: Refactor email body sync
- Refactor migration | <?php
namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_20;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\MigrationBundle\Migration\SqlMigrationQuery;
class OroEmailBundle implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
self::oroEmailTable($schema);
$this->deleteBodySyncProcess($queries);
}
/**
* @param Schema $schema
*/
public static function oroEmailTable(Schema $schema)
{
$table = $schema->getTable('oro_email');
if (!$table->hasColumn('body_synced')) {
$table->addColumn('body_synced', 'boolean', ['notnull' => false, 'default' => false]);
}
}
/**
* Delete sync_email_body_after_email_synchronize process definition
*
* @param QueryBag $queries
*/
protected function deleteBodySyncProcess(QueryBag $queries)
{
$queries->addQuery(
new ParametrizedSqlMigrationQuery(
'DELETE FROM oro_process_definition WHERE name = :processName',
['processName' => 'sync_email_body_after_email_synchronize']
)
);
}
}
| <?php
namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_20;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\MigrationBundle\Migration\SqlMigrationQuery;
class OroEmailBundle implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
self::oroEmailTable($schema);
$this->deleteBodySyncProcess($queries);
}
/**
* @param Schema $schema
*/
public static function oroEmailTable(Schema $schema)
{
$table = $schema->getTable('oro_email');
if (!$table->hasColumn('body_synced')) {
$table->addColumn('body_synced', 'boolean', ['notnull' => false, 'default' => false]);
}
}
/**
* Delete sync_email_body_after_email_synchronize process definition
*
* @param QueryBag $queries
*/
protected function deleteBodySyncProcess(QueryBag $queries)
{
$sql = <<<SQL
DELETE
FROM
oro_process_definition
WHERE name = 'sync_email_body_after_email_synchronize'
SQL;
$queries->addPostQuery(new SqlMigrationQuery($sql));
}
}
|
Add 'app' option as alias | #! /usr/bin/env node
/**
* Created by garusis on 31/01/17.
*/
import yargs from "yargs"
const argv = yargs
.usage("lb-migration <cmd> [args]")
.command('migrate [--ds] [--models]', 'Migrate models in datasources', {
d: {
demand: false,
alias: ["ds", "datasource"],
default: [],
describe: "Datasources that will be migrated. If empty or not present, all datasources will be migrates.",
type: "array"
},
m: {
demand: false,
alias: "model",
default: [],
describe: "Models in the selected datasources that will be migrated. If empty or not present, all models in all selected datasources will be migrates. Selected Models not presents in selected datasources will be not migrated.",
type: "array"
}
}, function (argv) {
console.log('migrate', argv)
})
.command('seed [--src]', 'Starts to seed your loopback application models', {
s: {
demand: false,
alias: ["src", "sources"],
default: ["./seeds/*.js"],
describe: "File globs to your seeders files.",
type: "array"
}
}, function (argv) {
console.log('seed', argv)
})
.options({
a: {
demand: false,
alias: ["app", "loopback-app"],
default: "./server/server.js",
describe: "Path to your loopback application main file.",
type: "string"
}
})
.help()
.argv | #! /usr/bin/env node
/**
* Created by garusis on 31/01/17.
*/
import yargs from "yargs"
const argv = yargs
.usage("lb-migration <cmd> [args]")
.command('migrate [--ds] [--models]', 'Migrate models in datasources', {
d: {
demand: false,
alias: ["ds", "datasource"],
default: [],
describe: "Datasources that will be migrated. If empty or not present, all datasources will be migrates.",
type: "array"
},
m: {
demand: false,
alias: "model",
default: [],
describe: "Models in the selected datasources that will be migrated. If empty or not present, all models in all selected datasources will be migrates. Selected Models not presents in selected datasources will be not migrated.",
type: "array"
}
}, function (argv) {
console.log('migrate', argv)
})
.command('seed [--src]', 'Starts to seed your loopback application models', {
s: {
demand: false,
alias: ["src", "sources"],
default: ["./seeds/*.js"],
describe: "File globs to your seeders files.",
type: "array"
}
}, function (argv) {
console.log('seed', argv)
})
.options({
app: {
demand: false,
alias: "loopback-app",
default: "./server/server.js",
describe: "Path to your loopback application main file.",
type: "string"
}
})
.help()
.argv |
Change error message in Property. | const Errors = use("core/errors");
class PropertyPrototype {
constructor() {
this._validators = new Set();
this._outputModifications = new Set();
}
_addValidator(validateFunction) {
this._validators.add(validateFunction);
}
_addOutputModification(outputSetter) {
this._outputModifications.add(outputSetter);
}
_inputModification(value) {
return value;
}
_validate(value, propertyName, modelName) {
try {
this._validators.forEach(validator => validator.call(this, value, propertyName, modelName));
}
catch (error) {
if (error instanceof Errors.Validation) {
throw new Errors.Validation(`In ${modelName} model ` + error.message);
} else {
throw error;
}
}
}
_output(outputObject, propertyName) {
this._outputModifications.forEach(outputSetter => outputSetter(outputObject, propertyName));
}
}
class DefaultProperty extends PropertyPrototype {
required() {
this._addValidator((value, propertyName) => {
if (typeof value === 'undefined' || value === null) {
throw new Errors.Validation(`property ${propertyName} is required, but does not exists`);
}
});
return this;
}
private() {
this._addOutputModification((outputObject, propertyName) => {
delete outputObject[propertyName];
});
return this;
}
}
module.exports = DefaultProperty; | const Errors = use("core/errors");
class PropertyPrototype {
constructor() {
this._validators = new Set();
this._outputModifications = new Set();
}
_addValidator(validateFunction) {
this._validators.add(validateFunction);
}
_addOutputModification(outputSetter) {
this._outputModifications.add(outputSetter);
}
_inputModification(value) {
return value;
}
_validate(value, propertyName, modelName) {
try {
this._validators.forEach(validator => validator.call(this, value, propertyName, modelName));
}
catch (error) {
if (error instanceof Errors.Validation) {
throw new Errors.Validation(`In model ${modelName} ` + error.message);
} else {
throw error;
}
}
}
_output(outputObject, propertyName) {
this._outputModifications.forEach(outputSetter => outputSetter(outputObject, propertyName));
}
}
class DefaultProperty extends PropertyPrototype {
required() {
this._addValidator((value, propertyName) => {
if (typeof value === 'undefined' || value === null) {
throw new Errors.Validation(`property ${propertyName} is required, but does not exists`);
}
});
return this;
}
private() {
this._addOutputModification((outputObject, propertyName) => {
delete outputObject[propertyName];
});
return this;
}
}
module.exports = DefaultProperty; |
Use `self.stdout.write` instead of `print` | from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity == '2' or verbosity == '3'
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
| from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity == '2' or verbosity == '3'
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
print resp
|
Use describe instead of describe.only | goog.provide('ol.test.coordinate');
describe('ol.coordinate', function() {
describe('#closestOnSegment', function() {
it('can handle points where the foot of the perpendicular is closest',
function() {
var point = [2, 5];
var segment = [[-5, 0], [10, 0]];
expect(ol.coordinate.closestOnSegment(point, segment))
.to.eql([2, 0]);
});
it('can handle points where the foot of the perpendicular is not closest',
function() {
var point = [0, -6];
var segment = [[-5, 0], [0, -1]];
expect(ol.coordinate.closestOnSegment(point, segment))
.to.eql([0, -1]);
});
});
describe('#squaredDistanceToSegment', function() {
it('can handle points where the foot of the perpendicular is closest',
function() {
var point = [2, 5];
var segment = [[-5, 0], [10, 0]];
expect(ol.coordinate.squaredDistanceToSegment(point, segment))
.to.eql(25);
});
it('can handle points where the foot of the perpendicular is not closest',
function() {
var point = [0, -6];
var segment = [[-5, 0], [0, -1]];
expect(ol.coordinate.squaredDistanceToSegment(point, segment))
.to.eql(25);
});
});
});
goog.require('ol.coordinate');
| goog.provide('ol.test.coordinate');
describe.only('ol.coordinate', function() {
describe('#closestOnSegment', function() {
it('can handle points where the foot of the perpendicular is closest',
function() {
var point = [2, 5];
var segment = [[-5, 0], [10, 0]];
expect(ol.coordinate.closestOnSegment(point, segment))
.to.eql([2, 0]);
});
it('can handle points where the foot of the perpendicular is not closest',
function() {
var point = [0, -6];
var segment = [[-5, 0], [0, -1]];
expect(ol.coordinate.closestOnSegment(point, segment))
.to.eql([0, -1]);
});
});
describe('#squaredDistanceToSegment', function() {
it('can handle points where the foot of the perpendicular is closest',
function() {
var point = [2, 5];
var segment = [[-5, 0], [10, 0]];
expect(ol.coordinate.squaredDistanceToSegment(point, segment))
.to.eql(25);
});
it('can handle points where the foot of the perpendicular is not closest',
function() {
var point = [0, -6];
var segment = [[-5, 0], [0, -1]];
expect(ol.coordinate.squaredDistanceToSegment(point, segment))
.to.eql(25);
});
});
});
goog.require('ol.coordinate');
|
Add `JSON_PARTIAL_OUTPUT_ON_ERROR` flag when encoding JSON responses in the exception handler
This fixes the scenario when json_encode() would fail and the default PHP exception handler takes over and returns something else than JSON | <?php namespace Nord\Lumen\Core\App\Exception;
use Illuminate\Http\Exception\HttpResponseException;
use Illuminate\Http\JsonResponse;
class ApiExceptionHandler
{
/**
* @var bool
*/
private $debug;
/**
* ApiExceptionHandler constructor.
*
* @param bool $debug
*/
public function __construct($debug)
{
$this->debug = $debug;
}
/**
* @param \Exception $exception
*
* @return JsonResponse
*/
public function createResponse(\Exception $exception)
{
if ($this->debug) {
$data = [
'exception' => get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTrace(),
];
} else {
$data = ['message' => trans('errors.something_went_wrong')];
}
$status = $exception instanceof HttpResponseException ? $exception->getStatusCode() : 500;
return new JsonResponse($data, $status, array(), JSON_PARTIAL_OUTPUT_ON_ERROR);
}
}
| <?php namespace Nord\Lumen\Core\App\Exception;
use Illuminate\Http\Exception\HttpResponseException;
use Illuminate\Http\JsonResponse;
class ApiExceptionHandler
{
/**
* @var bool
*/
private $debug;
/**
* ApiExceptionHandler constructor.
*
* @param bool $debug
*/
public function __construct($debug)
{
$this->debug = $debug;
}
/**
* @param \Exception $exception
*
* @return JsonResponse
*/
public function createResponse(\Exception $exception)
{
if ($this->debug) {
$data = [
'exception' => get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTrace(),
];
} else {
$data = ['message' => trans('errors.something_went_wrong')];
}
$status = $exception instanceof HttpResponseException ? $exception->getStatusCode() : 500;
return new JsonResponse($data, $status);
}
}
|
Remove test for use_setuptools, as it fails when running under pytest because the installed version of setuptools is already present. | import sys
import os
import tempfile
import unittest
import shutil
import copy
CURDIR = os.path.abspath(os.path.dirname(__file__))
TOPDIR = os.path.split(CURDIR)[0]
sys.path.insert(0, TOPDIR)
from ez_setup import _python_cmd, _install
import ez_setup
class TestSetup(unittest.TestCase):
def urlopen(self, url):
return open(self.tarball, 'rb')
def setUp(self):
self.old_sys_path = copy.copy(sys.path)
self.cwd = os.getcwd()
self.tmpdir = tempfile.mkdtemp()
os.chdir(TOPDIR)
_python_cmd("setup.py", "-q", "egg_info", "-RDb", "", "sdist",
"--formats", "zip", "--dist-dir", self.tmpdir)
zipball = os.listdir(self.tmpdir)[0]
self.zipball = os.path.join(self.tmpdir, zipball)
from setuptools.compat import urllib2
urllib2.urlopen = self.urlopen
def tearDown(self):
shutil.rmtree(self.tmpdir)
os.chdir(self.cwd)
sys.path = copy.copy(self.old_sys_path)
def test_install(self):
def _faked(*args):
return True
ez_setup._python_cmd = _faked
_install(self.zipball)
if __name__ == '__main__':
unittest.main()
| import sys
import os
import tempfile
import unittest
import shutil
import copy
CURDIR = os.path.abspath(os.path.dirname(__file__))
TOPDIR = os.path.split(CURDIR)[0]
sys.path.insert(0, TOPDIR)
from ez_setup import (use_setuptools, _python_cmd, _install)
import ez_setup
class TestSetup(unittest.TestCase):
def urlopen(self, url):
return open(self.tarball, 'rb')
def setUp(self):
self.old_sys_path = copy.copy(sys.path)
self.cwd = os.getcwd()
self.tmpdir = tempfile.mkdtemp()
os.chdir(TOPDIR)
_python_cmd("setup.py", "-q", "egg_info", "-RDb", "", "sdist",
"--formats", "zip", "--dist-dir", self.tmpdir)
zipball = os.listdir(self.tmpdir)[0]
self.zipball = os.path.join(self.tmpdir, zipball)
from setuptools.compat import urllib2
urllib2.urlopen = self.urlopen
def tearDown(self):
shutil.rmtree(self.tmpdir)
os.chdir(self.cwd)
sys.path = copy.copy(self.old_sys_path)
def test_install(self):
def _faked(*args):
return True
ez_setup._python_cmd = _faked
_install(self.zipball)
def test_use_setuptools(self):
self.assertEqual(use_setuptools(), None)
if __name__ == '__main__':
unittest.main()
|
Change logInstructions to allow users to copy import codes | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var path = require('path');
module.exports = yeoman.Base.extend({
constructor: function () {
yeoman.Base.apply(this, arguments);
this.argument('name', {type: String, required: true});
},
initializing: {
paths: function() {
this.destinationRoot(path.join(this.config.get('modulesPath'), this.name));
}
},
writing: {
boilerplate: function() {
this.fs.copy([
this.templatePath('**/*'),
'!**/*.ejs'
],
this.destinationRoot()
);
},
constantsJS: function() {
this.fs.copyTpl(
this.templatePath('constants.js.ejs'),
this.destinationPath('constants.js'),
{ name: this.name }
)
},
selectorsJS: function() {
this.fs.copyTpl(
this.templatePath('selectors.js.ejs'),
this.destinationPath('selectors.js'),
{ name: this.name }
)
}
},
end: {
logInstructions: function() {
this.log('');
this.log('Great, now import the module generated into your root reducer in src/reducer.js:');
this.log('');
this.log(chalk.green("import " + this.name + " from './modules/" + this.name + "'"));
this.log('');
this.log('and add the reducer as part of the combineReducers: ');
this.log('');
this.log(chalk.green("[" + this.name + ".constants.NAME]: " + this.name + ".reducer"));
}
}
});
| 'use strict';
var yeoman = require('yeoman-generator');
var path = require('path');
module.exports = yeoman.Base.extend({
constructor: function () {
yeoman.Base.apply(this, arguments);
this.argument('name', {type: String, required: true});
},
initializing: {
paths: function() {
this.destinationRoot(path.join(this.config.get('modulesPath'), this.name));
}
},
writing: {
boilerplate: function() {
this.fs.copy([
this.templatePath('**/*'),
'!**/*.ejs'
],
this.destinationRoot()
);
},
constantsJS: function() {
this.fs.copyTpl(
this.templatePath('constants.js.ejs'),
this.destinationPath('constants.js'),
{ name: this.name }
)
},
selectorsJS: function() {
this.fs.copyTpl(
this.templatePath('selectors.js.ejs'),
this.destinationPath('selectors.js'),
{ name: this.name }
)
}
},
end: {
logInstructions: function() {
this.log('');
this.log('You have created your ' + this.name + ' module successfully \n');
this.log('Make sure to add this module to your rootReducer');
this.log('');
}
}
});
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.