text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Use imported views instead of lazy import | from django.conf.urls import patterns, url
try:
from account.decorators import login_required
except ImportError:
from django.contrib.auth.decorators import login_required
from .views import (
CancelView,
ChangeCardView,
ChangePlanView,
HistoryView,
SubscribeView,
webhook,
subscribe,
change_card,
change_plan,
cancel
)
urlpatterns = patterns(
"",
url(r"^webhook/$", webhook, name="payments_webhook"),
url(r"^a/subscribe/$", subscribe, name="payments_ajax_subscribe"),
url(r"^a/change/card/$", change_card, name="payments_ajax_change_card"),
url(r"^a/change/plan/$", change_plan, name="payments_ajax_change_plan"),
url(r"^a/cancel/$", cancel, name="payments_ajax_cancel"),
url(
r"^subscribe/$",
login_required(SubscribeView.as_view()),
name="payments_subscribe"
),
url(
r"^change/card/$",
login_required(ChangeCardView.as_view()),
name="payments_change_card"
),
url(
r"^change/plan/$",
login_required(ChangePlanView.as_view()),
name="payments_change_plan"
),
url(
r"^cancel/$",
login_required(CancelView.as_view()),
name="payments_cancel"
),
url(
r"^history/$",
login_required(HistoryView.as_view()),
name="payments_history"
),
)
| from django.conf.urls import patterns, url
try:
from account.decorators import login_required
except ImportError:
from django.contrib.auth.decorators import login_required
from .views import (
CancelView,
ChangeCardView,
ChangePlanView,
HistoryView,
SubscribeView
)
urlpatterns = patterns(
"payments.views",
url(r"^webhook/$", "webhook", name="payments_webhook"),
url(r"^a/subscribe/$", "subscribe", name="payments_ajax_subscribe"),
url(r"^a/change/card/$", "change_card", name="payments_ajax_change_card"),
url(r"^a/change/plan/$", "change_plan", name="payments_ajax_change_plan"),
url(r"^a/cancel/$", "cancel", name="payments_ajax_cancel"),
url(
r"^subscribe/$",
login_required(SubscribeView.as_view()),
name="payments_subscribe"
),
url(
r"^change/card/$",
login_required(ChangeCardView.as_view()),
name="payments_change_card"
),
url(
r"^change/plan/$",
login_required(ChangePlanView.as_view()),
name="payments_change_plan"
),
url(
r"^cancel/$",
login_required(CancelView.as_view()),
name="payments_cancel"
),
url(
r"^history/$",
login_required(HistoryView.as_view()),
name="payments_history"
),
)
|
Fix the logo component in Symfony 5 | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Components\Logo;
use function class_exists;
use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Components\AbstractComponentProvider;
/**
* @internal
*/
final class Provider extends AbstractComponentProvider
{
/**
* {@inheritdoc}
*/
public function isAvailable(): bool
{
return class_exists(\Laminas\Text\Figlet\Figlet::class)
&& is_array($this->app['config']->get('logo', false));
}
/**
* {@inheritdoc}
*/
public function register(): void
{
$config = $this->app['config'];
if ($config->get('logo.enabled', false)) {
Artisan::starting(
function ($artisan) use ($config) {
$artisan->setName(
(string) new FigletString($config->get('app.name'), $config->get('logo', []))
);
}
);
}
}
}
| <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Components\Logo;
use function class_exists;
use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Components\AbstractComponentProvider;
/**
* @internal
*/
final class Provider extends AbstractComponentProvider
{
/**
* {@inheritdoc}
*/
public function isAvailable(): bool
{
return class_exists(\Laminas\Text\Figlet\Figlet::class)
&& is_array($this->app['config']->get('logo', false));
}
/**
* {@inheritdoc}
*/
public function register(): void
{
$config = $this->app['config'];
if ($config->get('logo.enabled', false)) {
Artisan::starting(
function ($artisan) use ($config) {
$artisan->setName(
new FigletString($config->get('app.name'), $config->get('logo', []))
);
}
);
}
}
}
|
Make sure the remember token is set | <?php
namespace Adldap\Laravel\Tests;
use Mockery as m;
use Adldap\Laravel\Auth\ResolverInterface;
use Adldap\Laravel\Middleware\WindowsAuthenticate;
class WindowsAuthenticateTest extends DatabaseTestCase
{
public function test_handle()
{
$request = app('request');
$request->server->set('AUTH_USER', 'jdoe');
$middleware = app(WindowsAuthenticate::class);
$user = $this->makeLdapUser([
'cn' => 'John Doe',
'userprincipalname' => '[email protected]',
'samaccountname' => 'jdoe',
]);
$resolver = m::mock(ResolverInterface::class);
$resolver
->shouldReceive('query')->once()->andReturn($resolver)
->shouldReceive('where')->once()->withArgs([['samaccountname' => 'jdoe']])->andReturn($resolver)
->shouldReceive('firstOrFail')->once()->andReturn($user)
->shouldReceive('getEloquentUsername')->once()->andReturn('email')
->shouldReceive('getLdapUsername')->once()->andReturn('userprincipalname');
$middleware->setResolver($resolver);
$middleware->handle($request, function () {});
$authenticated = auth()->user();
$this->assertEquals('John Doe', $authenticated->name);
$this->assertEquals('[email protected]', $authenticated->email);
$this->assertNotEmpty($authenticated->remember_token);
}
}
| <?php
namespace Adldap\Laravel\Tests;
use Mockery as m;
use Adldap\Laravel\Auth\ResolverInterface;
use Adldap\Laravel\Middleware\WindowsAuthenticate;
class WindowsAuthenticateTest extends DatabaseTestCase
{
public function test_handle()
{
$request = app('request');
$request->server->set('AUTH_USER', 'jdoe');
$middleware = app(WindowsAuthenticate::class);
$user = $this->makeLdapUser([
'cn' => 'John Doe',
'userprincipalname' => '[email protected]',
'samaccountname' => 'jdoe',
]);
$resolver = m::mock(ResolverInterface::class);
$resolver
->shouldReceive('query')->once()->andReturn($resolver)
->shouldReceive('where')->once()->withArgs([['samaccountname' => 'jdoe']])->andReturn($resolver)
->shouldReceive('firstOrFail')->once()->andReturn($user)
->shouldReceive('getEloquentUsername')->once()->andReturn('email')
->shouldReceive('getLdapUsername')->once()->andReturn('userprincipalname');
$middleware->setResolver($resolver);
$middleware->handle($request, function () {});
$authenticated = auth()->user();
$this->assertEquals('John Doe', $authenticated->name);
$this->assertEquals('[email protected]', $authenticated->email);
}
}
|
Fix error in site alias files conditional if | <?php
// Grab the "Global" settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['datastorePort']['value'];
$host = $result['datastoreHost']['value'];
$webroot = $result['webrootDir']['value'];
// I'm not sure why but if you keep $result populated you get ghost aliases who
// values are the same as the $result array elelment names
$result = array();
$aliases = array();
$dir_handle = new DirectoryIterator($path);
while($dir_handle->valid()) {
if($dir_handle->isDir() && !$dir_handle->isDot()) {
$basename = $dir_handle->getBasename();
$root = $dir_handle->getPathname();
$root = $webroot != "" ? $root : $root . $webroot;
$aliases[$basename] = array(
'uri' => 'http://localhost/' . $basename,
'root' => $root,
'databases' => array(
'default' => array(
'default' => array(
'driver' => $driver,
'username' => $user,
'password' => $pass,
'port' => $port,
'host' => $host,
'database' => $basename,
),
),
),
);
}
$dir_handle->next();
}
| <?php
// Grab the "Global" settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['datastorePort']['value'];
$host = $result['datastoreHost']['value'];
$webroot = $result['webrootDir']['value'];
// I'm not sure why but if you keep $result populated you get ghost aliases who
// values are the same as the $result array elelment names
$result = array();
$aliases = array();
$dir_handle = new DirectoryIterator($path);
while($dir_handle->valid()) {
if($dir_handle->isDir() && !$dir_handle->isDot()) {
$basename = $dir_handle->getBasename();
$root = $dir_handle->getPathname();
$root = $webroot = "" ? $root : $root . $webroot;
$aliases[$basename] = array(
'uri' => 'http://localhost/' . $basename,
'root' => $root,
'databases' => array(
'default' => array(
'default' => array(
'driver' => $driver,
'username' => $user,
'password' => $pass,
'port' => $port,
'host' => $host,
'database' => $basename,
),
),
),
);
}
$dir_handle->next();
}
|
FIX: Use a string in `q` instead of an object because special characters in the values of each key of an object are now escaped as expected. | // Dependencies
var nock = require('nock'),
solr = require('./../main'),
vows = require('vows'),
assert = require('assert'),
mocks = require('./mocks'),
fs = require('fs');
// Load configuration file
var config = JSON.parse(fs.readFileSync(__dirname + '/config.json'));
if(config.mocked){
//nock.recorder.rec();
mocks.facet(nock);
}
// Suite Test
var suite = vows.describe('Solr Client API: facet');
suite.addBatch({
'Create a facet' : {
'with the following options: `field`, `prefix`, `query`, `limit`, `offset`, `sort`, `limit`, `mincount`, `missing`, `method`' : {
topic : function(){
var client = solr.createClient();
var query = client.createQuery()
.q('*:*')
.rows(0)
.facet({
field : 'title',
prefix : 'Ipa',
query : 'title:Ipad',
limit : 20,
offset : 0,
sort : 'count',
mincount : 0,
missing : false,
method : 'fc' ,
});
client.search(query,this.callback);
},
'should return a correct response without error' :function(err,res) {
assertCorrectResponse(err,res)
}
}
}
}).export(module);
// Macro
function assertCorrectResponse(err,data){
assert.isNull(err);
assert.isObject(data);
assert.equal(data.responseHeader.status,0);
}
| // Dependencies
var nock = require('nock'),
solr = require('./../main'),
vows = require('vows'),
assert = require('assert'),
mocks = require('./mocks'),
fs = require('fs');
// Load configuration file
var config = JSON.parse(fs.readFileSync(__dirname + '/config.json'));
if(config.mocked){
//nock.recorder.rec();
mocks.facet(nock);
}
// Suite Test
var suite = vows.describe('Solr Client API: facet');
suite.addBatch({
'Create a facet' : {
'with the following options: `field`, `prefix`, `query`, `limit`, `offset`, `sort`, `limit`, `mincount`, `missing`, `method`' : {
topic : function(){
var client = solr.createClient();
var query = client.createQuery()
.q({'*' : '*'})
.rows(0)
.facet({
field : 'title',
prefix : 'Ipa',
query : 'title:Ipad',
limit : 20,
offset : 0,
sort : 'count',
mincount : 0,
missing : false,
method : 'fc' ,
});
client.search(query,this.callback);
},
'should return a correct response without error' :function(err,res) {
assertCorrectResponse(err,res)
}
}
}
}).export(module);
// Macro
function assertCorrectResponse(err,data){
assert.isNull(err);
assert.isObject(data);
assert.equal(data.responseHeader.status,0);
}
|
Send network data on start | var
util = require('util')
, stream = require('stream')
, os = require('os')
;
function network(opts, app) {
var
self = this
, initialize = function(cloud) {
self.log.debug("Initializing network module")
self.cloud = cloud;
self.emit('register', self);
process.nextTick(function bump() {
var networkInterfaces = os.networkInterfaces();
var DA = {
result : networkInterfaces
, error : null
, id : da.id
};
self.emit('data', JSON.stringify(DA));
});
}
;
this.log = app.log;
this.readable = true;
this.writeable = true;
this.V = 0;
this.D = 1005;
this.G = "0";
app.on('client::up', initialize);
};
util.inherits(network, stream);
network.prototype.write = function(data) {
var cloud = this.cloud;
try {
var da = JSON.parse(data);
}
catch(err) {
this.log.debug("network: Invalid command");
return false;
}
switch (da.method) {
case 'SCAN':
this.log.debug('network: Scanning interfaces...');
var networkInterfaces = os.networkInterfaces();
var DA = {
result : networkInterfaces
, error : null
, id : da.id
};
this.emit('data', JSON.stringify(DA));
break;
}
return true;
};
network.prototype.end = function() {
};
network.prototype.close = function() {
};
module.exports = network; | var
util = require('util')
, stream = require('stream')
, os = require('os')
;
function network(opts, app) {
var
self = this
, initialize = function(cloud) {
self.log.debug("Initializing network module")
self.cloud = cloud;
self.emit('register', self);
process.nextTick(function bump() {
self.emit('data', '{}');
});
}
;
this.log = app.log;
this.readable = true;
this.writeable = true;
this.V = 0;
this.D = 1005;
this.G = "0";
app.on('client::up', initialize);
};
util.inherits(network, stream);
network.prototype.write = function(data) {
var cloud = this.cloud;
try {
var da = JSON.parse(data);
}
catch(err) {
this.log.debug("network: Invalid command");
return false;
}
switch (da.method) {
case 'SCAN':
this.log.debug('network: Scanning interfaces...');
var networkInterfaces = os.networkInterfaces();
var DA = {
result : networkInterfaces
, error : null
, id : da.id
};
this.emit('data', JSON.stringify(DA));
break;
}
return true;
};
network.prototype.end = function() {
};
network.prototype.close = function() {
};
module.exports = network; |
Fix for ambiguous suburbs that have brackets and screw some things up. | <?php
namespace SimpleQuiz\Utils;
class Location {
protected $_suburb = null;
protected $_district = null;
protected $_region = null;
protected $_state = null;
public function __construct($suburb) {
$this->loadBySuburb($suburb);
}
public function loadBySuburb($suburb) {
$location = \ORM::for_table('location')->where('suburb', $suburb)->find_one();
$this->_suburb = trim(strpos($suburb, " (") !== -1 ? substr($suburb, 0, strpos($suburb, " (")) : $suburb);
$this->_district = $location["district"];
$this->_region = $location["region"];
$this->_state = $location["state"];
}
public function getSuburb() {
return $this->_suburb;
}
public function getDistrict() {
return $this->_district;
}
public function getRegion() {
return $this->_region;
}
public function getState() {
return $this->_state;
}
public function getLowestLevelLocation() {
if ($this->_suburb) {
return $this->_suburb;
}
else if ($this->_district) {
return $this->_district;
}
else if ($this->_region) {
return $this->_region;
}
else {
return $this->_state;
}
}
}
| <?php
namespace SimpleQuiz\Utils;
class Location {
protected $_suburb = null;
protected $_district = null;
protected $_region = null;
protected $_state = null;
public function __construct($suburb) {
$this->loadBySuburb($suburb);
}
public function loadBySuburb($suburb) {
$this->_suburb = $suburb;
$location = \ORM::for_table('location')->where('suburb', $suburb)->find_one();
$this->_district = $location["district"];
$this->_region = $location["region"];
$this->_state = $location["state"];
}
public function getSuburb() {
return $this->_suburb;
}
public function getDistrict() {
return $this->_district;
}
public function getRegion() {
return $this->_region;
}
public function getState() {
return $this->_state;
}
public function getLowestLevelLocation() {
if ($this->_suburb) {
return $this->_suburb;
}
else if ($this->_district) {
return $this->_district;
}
else if ($this->_region) {
return $this->_region;
}
else {
return $this->_state;
}
}
}
|
Mark TimeStampedMixin.modified as an onupdate FetchedValue | from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue())
| from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, server_default=func.now(), nullable=False)
modified = db.Column(db.DateTime, server_default=func.now(), nullable=False)
|
Define user earlier so it can be used more | <?php
class BotController extends AuthenticatedController {
public function update( $boturl = '' ) {
$this->requireLogin();
require_once 'models/grader/bot.php';
if ( empty( $boturl ) ) {
go( 'bot', 'update', [ 'boturl_empty' => true ] );
}
if ( !filter_var( $boturl, FILTER_VALIDATE_URL ) ) {
go( 'bot', 'update', [ 'boturl_invalid' => true ] );
}
$user = $_SESSION[ 'user' ];
try {
$user->setBoturl( $boturl );
}
catch ( ModelValidationException $e ) {
go( 'bot', 'update', [ 'bot_fail' => true, 'errorid' => $e->error ] );
}
go( 'bot', 'update' );
}
public function updateView( $boturl_empty, $boturl_invalid, $bot_fail, $errorid = false ) {
require_once 'models/error.php';
$this->requireLogin();
$user = $_SESSION[ 'user' ];
if ( $errorid !== false ) {
$error = new Error( $errorid );
if ( $error->user->id !== $user->id ) {
throw new HTTPUnauthorizedException();
}
}
require_once 'models/grader/bot.php';
require_once 'views/bot/update.php';
}
}
?>
| <?php
class BotController extends AuthenticatedController {
public function update( $boturl = '' ) {
$this->requireLogin();
require_once 'models/grader/bot.php';
if ( empty( $boturl ) ) {
go( 'bot', 'update', [ 'boturl_empty' => true ] );
}
if ( !filter_var( $boturl, FILTER_VALIDATE_URL ) ) {
go( 'bot', 'update', [ 'boturl_invalid' => true ] );
}
$user = $_SESSION[ 'user' ];
try {
$user->setBoturl( $boturl );
}
catch ( ModelValidationException $e ) {
go( 'bot', 'update', [ 'bot_fail' => true, 'errorid' => $e->error ] );
}
go( 'bot', 'update' );
}
public function updateView( $boturl_empty, $boturl_invalid, $bot_fail, $errorid = false ) {
require_once 'models/error.php';
$this->requireLogin();
if ( $errorid !== false ) {
$error = new Error( $errorid );
if ( $error->user->id !== $_SESSION[ 'user' ]->id ) {
throw new HTTPUnauthorizedException();
}
}
$user = $_SESSION[ 'user' ];
require_once 'models/grader/bot.php';
require_once 'views/bot/update.php';
}
}
?>
|
Add clearTitleSegments method to seo helper
Former-commit-id: 7eaed8690b7c184f477a748e87ea13cb89bb9ef8
Former-commit-id: 52e068afc53274320ccd396396bb64f1c71343d0 | <?php
namespace Concrete\Core\Html\Service;
class Seo
{
private $siteName = '';
private $titleSegments = array();
private $titleSegmentSeparator = ' :: ';
private $titleFormat = '%1$s :: %2$s';
private $hasCustomTitle = false;
public function setSiteName($name)
{
$this->siteName = $name;
}
public function hasCustomTitle()
{
return $this->hasCustomTitle;
}
public function setCustomTitle($title)
{
$this->hasCustomTitle = true;
$this->clearTitleSegments();
$this->addTitleSegmentBefore($title);
return $this;
}
public function addTitleSegment($segment)
{
array_push($this->titleSegments, $segment);
return $this;
}
public function addTitleSegmentBefore($segment)
{
array_unshift($this->titleSegments, $segment);
return $this;
}
public function clearTitleSegments()
{
$this->titleSegments = array();
}
public function setTitleFormat($format)
{
$this->titleFormat = $format;
return $this;
}
public function setTitleSegmentSeparator($separator)
{
$this->titleSegmentSeparator = $separator;
return $this;
}
public function getTitle()
{
$segments = '';
if (count($this->titleSegments) > 0) {
$segments = implode($this->titleSegmentSeparator, $this->titleSegments);
}
return sprintf($this->titleFormat, $this->siteName, $segments);
}
}
| <?php
namespace Concrete\Core\Html\Service;
class Seo
{
private $siteName = '';
private $titleSegments = array();
private $titleSegmentSeparator = ' :: ';
private $titleFormat = '%1$s :: %2$s';
private $hasCustomTitle = false;
public function setSiteName($name)
{
$this->siteName = $name;
}
public function hasCustomTitle()
{
return $this->hasCustomTitle;
}
public function setCustomTitle($title)
{
$this->hasCustomTitle = true;
$this->titleSegments = array();
$this->addTitleSegmentBefore($title);
return $this;
}
public function addTitleSegment($segment)
{
array_push($this->titleSegments, $segment);
return $this;
}
public function addTitleSegmentBefore($segment)
{
array_unshift($this->titleSegments, $segment);
return $this;
}
public function setTitleFormat($format)
{
$this->titleFormat = $format;
return $this;
}
public function setTitleSegmentSeparator($separator)
{
$this->titleSegmentSeparator = $separator;
return $this;
}
public function getTitle()
{
$segments = '';
if (count($this->titleSegments) > 0) {
$segments = implode($this->titleSegmentSeparator, $this->titleSegments);
}
return sprintf($this->titleFormat, $this->siteName, $segments);
}
}
|
Update default grunt task to run unit tests and cssmin | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
options: {
"sub": true
},
all: ['src/**/*.js']
},
connect: {
server: {
options: {
port: 8000,
hostname: '127.0.0.1',
base: '../../'
}
}
},
jasmine: {
src: ['src/**/*.js'],
options: {
specs: 'tests/**/*.spec.js',
host: 'http://127.0.0.1:8000/products/argos-saleslogix/',
template: 'GruntRunner.tmpl'
}
},
cssmin: {
combine: {
files: {
'min/css/app.min.css': ['content/css/toggle.css', 'content/css/app.css']
}
}
},
csslint: {
options: {
csslintrc: '.csslintrc',
formatters: [
{ id: 'junit-xml', dest: 'report/junit.xml' }
]
},
lax: {
src: ['content/**/*.css']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.registerTask('test', ['connect', 'jasmine']);
grunt.registerTask('default', ['test', 'cssmin']);
};
| module.exports = function(grunt) {
grunt.initConfig({
jshint: {
options: {
"sub": true
},
all: ['src/**/*.js']
},
connect: {
server: {
options: {
port: 8000,
hostname: '127.0.0.1',
base: '../../'
}
}
},
jasmine: {
src: ['src/**/*.js'],
options: {
specs: 'tests/**/*.spec.js',
host: 'http://127.0.0.1:8000/products/argos-saleslogix/',
template: 'GruntRunner.tmpl'
}
},
cssmin: {
combine: {
files: {
'min/css/app.min.css': ['content/css/toggle.css', 'content/css/app.css']
}
}
},
csslint: {
options: {
csslintrc: '.csslintrc',
formatters: [
{ id: 'junit-xml', dest: 'report/junit.xml' }
]
},
lax: {
src: ['content/**/*.css']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.registerTask('test', ['connect', 'jasmine']);
grunt.registerTask('default', ['test']);
};
|
Make feature_file_paths have no duplicates | import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.update(feature_candidates)
return feature_candidates
| import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.extend(feature_candidates)
return feature_candidates
|
Make the Entry class static
So we don't to instantiate it. Was getting weird errors :/
Found on SO somewhere. | import java.util.*;
public class Table {
public static class Entry {
public Integer iface;
public IPAddress destinationIP;
public IPAddress nextHop;
public Entry(String d, String n, Integer i) {
iface = i;
destinationIP = new IPAddress(d);
nextHop = new IPAddress(n);
}
}
HashMap<IPAddress, Entry> table;
public Table() {
table = new HashMap<IPAddress, Entry>();
}
public void add(String destinationIP, String nextHop, Integer iface) {
table.put(new IPAddress(destinationIP), new Entry(destinationIP, nextHop, iface));
}
public boolean isEmpty() {
return table.size() == 0;
}
public void print() {
System.out.println("-------------------------------------------------");
System.out.println("| Destination | Next Hop | Interface |");
System.out.println("-------------------------------------------------");
for (Map.Entry<IPAddress, Entry> item : table.entrySet()) {
Entry e = item.getValue();
System.out.printf("| %15s | %15s | %5d |\n", e.destinationIP, e.nextHop, e.iface);
}
System.out.println("-------------------------------------------------\n");
}
public Entry findDestinationIP(IPAddress ip) {
if (table.containsKey(ip)) {
return table.get(ip);
}
}
}
| import java.util.*;
public class Table {
public class Entry {
public Integer iface;
public IPAddress destinationIP;
public IPAddress nextHop;
public Entry(String d, String n, Integer i) {
iface = i;
destinationIP = new IPAddress(d);
nextHop = new IPAddress(n);
}
}
HashMap<IPAddress, Entry> table;
public Table() {
table = new HashMap<IPAddress, Entry>();
}
public void add(String destinationIP, String nextHop, Integer iface) {
table.put(new IPAddress(destinationIP), new Entry(destinationIP, nextHop, iface));
}
public boolean isEmpty() {
return table.size() == 0;
}
public void print() {
System.out.println("-------------------------------------------------");
System.out.println("| Destination | Next Hop | Interface |");
System.out.println("-------------------------------------------------");
for (Map.Entry<IPAddress, Entry> item : table.entrySet()) {
Entry e = item.getValue();
System.out.printf("| %15s | %15s | %5d |\n", e.destinationIP, e.nextHop, e.iface);
}
System.out.println("-------------------------------------------------\n");
}
public Entry findDestinationIP(IPAddress ip) {
if (table.containsKey(ip)) {
return table.get(ip);
}
}
}
|
Add compression and integrity checks | from msgpack import packb, unpackb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
from checksum import add_integrity, check_integrity
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
return packb(compress(add_integrity(packb(data, default=encode_btree))))
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
data = decompress(next(Unpacker(data)))
return unpackb(check_integrity(data), object_hook=decode_btree)
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()}
| from msgpack import packb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
return packb(data, default=encode_btree)
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
unpacker = Unpacker(data, object_hook=decode_btree)
return(next(unpacker))
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()}
|
Improve register error response from api to client | <?php
namespace App\Controllers;
class AuthController
{
public function login()
{
var_dump(input());
return $input;
}
public function register()
{
$inputs = input()->all(['email', 'password']);
if (!$this->isValid($inputs))
{
return 'form is not valid';
}
if ($this->isEmailExist($inputs['email']))
{
return 'email already used';
}
\Builder::table('users')->insert([
'email' => $inputs['email'],
'password' => sha1($inputs['email']),
'role' => 'student'
]);
return 'success';
}
private function isEmailExist($email)
{
return !is_null(\Builder::table('users')->where('email', '=', $email)->first());
}
/**
* Check if array has falsy values
*
* @param arrays $inputs
* @return boolean
*/
private function isValid($inputs)
{
return !in_array(false, $this->isEmpty($inputs));
}
/**
* Transform all values in array to (boolean) false depending
* on whether its empty or not. The element will be false if
* it is empty.
*
* @param array $arrays
* @return array
*/
private function isEmpty($arrays)
{
return array_map(
function ($value)
{
return !empty($value);
},
$arrays
);
}
} | <?php
namespace App\Controllers;
class AuthController
{
public function login()
{
var_dump(input());
return $input;
}
public function register()
{
$inputs = input()->all(['email', 'password']);
if (!$this->isValid($inputs) || $this->isEmailExist($inputs['email'])) {
return 'fail';
}
\Builder::table('users')->insert([
'email' => $inputs['email'],
'password' => sha1($inputs['email']),
'role' => 'student'
]);
return 'success';
}
private function isEmailExist($email)
{
return !is_null(\Builder::table('users')->where('email', '=', $email)->first());
}
/**
* Check if array has falsy values
*
* @param arrays $inputs
* @return boolean
*/
private function isValid($inputs)
{
return !in_array(false, $this->isEmpty($inputs));
}
/**
* Transform all values in array to (boolean) false depending
* on whether its empty or not. The element will be false if
* it is empty.
*
* @param array $arrays
* @return array
*/
private function isEmpty($arrays)
{
return array_map(
function ($value)
{
return !empty($value);
},
$arrays
);
}
} |
Add full_name field to API | from django.contrib.auth.models import User
from rest_framework import permissions, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
if hasattr(obj, 'profile'):
ret['department_name'] = obj.profile.department_name
if obj.first_name and obj.last_name:
ret['full_name'] = '%s %s' % (obj.first_name, obj.last_name)
return ret
class Meta:
fields = [
'last_login', 'username', 'email', 'date_joined',
'first_name', 'last_name'
]
model = User
# ViewSets define the view behavior.
class UserView(generics.RetrieveAPIView,
mixins.RetrieveModelMixin):
def get_queryset(self):
user = self.request.user
if user.is_superuser:
return self.queryset
else:
return self.queryset.filter(id=user.id)
def get_object(self):
username = self.kwargs.get('username', None)
if username:
qs = self.get_queryset()
obj = generics.get_object_or_404(qs, username=username)
else:
obj = self.request.user
return obj
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
#router = routers.DefaultRouter()
#router.register(r'users', UserViewSet)
| from django.contrib.auth.models import User
from rest_framework import permissions, routers, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
if hasattr(obj, 'profile'):
ret['department_name'] = obj.profile.department_name
return ret
class Meta:
fields = [
'last_login', 'username', 'email', 'date_joined',
'first_name', 'last_name'
]
model = User
# ViewSets define the view behavior.
class UserView(generics.RetrieveAPIView,
mixins.RetrieveModelMixin):
def get_queryset(self):
user = self.request.user
if user.is_superuser:
return self.queryset
else:
return self.queryset.filter(id=user.id)
def get_object(self):
username = self.kwargs.get('username', None)
if username:
qs = self.get_queryset()
obj = generics.get_object_or_404(qs, username=username)
else:
obj = self.request.user
return obj
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
#router = routers.DefaultRouter()
#router.register(r'users', UserViewSet)
|
Remove Yices test from RPC prover test | from cryptol import cryptoltypes
from cryptol.bitvector import BV
import saw
from saw.proofscript import *
import unittest
from pathlib import Path
def cry(exp):
return cryptoltypes.CryptolLiteral(exp)
class ProverTest(unittest.TestCase):
@classmethod
def setUpClass(self):
saw.connect(reset_server=True)
@classmethod
def tearDownClass(self):
saw.reset_server()
saw.disconnect()
def test_provers(self):
if __name__ == "__main__": saw.view(saw.LogResults())
simple_thm = cry('\(x:[8]) -> x != x+1')
self.assertTrue(saw.prove(simple_thm, ProofScript([abc])).is_valid())
self.assertTrue(saw.prove(simple_thm, ProofScript([z3([])])).is_valid())
self.assertTrue(saw.prove(simple_thm, ProofScript([Admit()])).is_valid())
self.assertTrue(saw.prove(cry('True'), ProofScript([Trivial()])).is_valid())
simple_non_thm = cry('\(x:[8]) -> x != 5')
pr = saw.prove(simple_non_thm, ProofScript([z3([])]))
self.assertFalse(pr.is_valid())
cex = pr.get_counterexample()
self.assertEqual(cex, [('x', BV(8, 0x05))])
if __name__ == "__main__":
unittest.main()
| from cryptol import cryptoltypes
from cryptol.bitvector import BV
import saw
from saw.proofscript import *
import unittest
from pathlib import Path
def cry(exp):
return cryptoltypes.CryptolLiteral(exp)
class ProverTest(unittest.TestCase):
@classmethod
def setUpClass(self):
saw.connect(reset_server=True)
@classmethod
def tearDownClass(self):
saw.reset_server()
saw.disconnect()
def test_provers(self):
if __name__ == "__main__": saw.view(saw.LogResults())
simple_thm = cry('\(x:[8]) -> x != x+1')
self.assertTrue(saw.prove(simple_thm, ProofScript([abc])).is_valid())
self.assertTrue(saw.prove(simple_thm, ProofScript([yices([])])).is_valid())
self.assertTrue(saw.prove(simple_thm, ProofScript([z3([])])).is_valid())
self.assertTrue(saw.prove(simple_thm, ProofScript([Admit()])).is_valid())
self.assertTrue(saw.prove(cry('True'), ProofScript([Trivial()])).is_valid())
simple_non_thm = cry('\(x:[8]) -> x != 5')
pr = saw.prove(simple_non_thm, ProofScript([z3([])]))
self.assertFalse(pr.is_valid())
cex = pr.get_counterexample()
self.assertEqual(cex, [('x', BV(8, 0x05))])
if __name__ == "__main__":
unittest.main()
|
Stop the server if MongoDB is not started | var mongoose = require('mongoose');
var config = require('config');
var semver = require('semver')
// configure mongodb
mongoose.connect(config.mongodb.connectionString || 'mongodb://' + config.mongodb.user + ':' + config.mongodb.password + '@' + config.mongodb.server +'/' + config.mongodb.database);
mongoose.connection.on('error', function (err) {
console.error('MongoDB error: ' + err.message);
console.error('Make sure a mongoDB server is running and accessible by this application');
process.exit(1);
});
mongoose.connection.on('open', function (err) {
mongoose.connection.db.admin().serverStatus(function(err, data) {
if (err) {
if (err.name === "MongoError" && err.errmsg === 'need to login') {
console.log('Forcing MongoDB authentication');
mongoose.connection.db.authenticate(config.mongodb.user, config.mongodb.password, function(err) {
if (!err) return;
console.error(err);
process.exit(1);
});
return;
} else {
console.error(err);
process.exit(1);
}
}
if (!semver.satisfies(data.version, '>=2.1.0')) {
console.error('Error: Uptime requires MongoDB v2.1 minimum. The current MongoDB server uses only '+ data.version);
process.exit(1);
};
});
});
module.exports = mongoose; | var mongoose = require('mongoose');
var config = require('config');
var semver = require('semver')
// configure mongodb
mongoose.connect(config.mongodb.connectionString || 'mongodb://' + config.mongodb.user + ':' + config.mongodb.password + '@' + config.mongodb.server +'/' + config.mongodb.database);
mongoose.connection.on('error', function (err) {
console.error('MongoDB error: ' + err.message);
console.error('Make sure a mongoDB server is running and accessible by this application')
});
mongoose.connection.on('open', function (err) {
mongoose.connection.db.admin().serverStatus(function(err, data) {
if (err) {
if (err.name === "MongoError" && err.errmsg === 'need to login') {
console.log('Forcing MongoDB authentication');
mongoose.connection.db.authenticate(config.mongodb.user, config.mongodb.password, function(err) {
if (!err) return;
console.error(err);
process.exit(1);
});
return;
} else {
console.error(err);
process.exit(1);
}
}
if (!semver.satisfies(data.version, '>=2.1.0')) {
console.error('Error: Uptime requires MongoDB v2.1 minimum. The current MongoDB server uses only '+ data.version);
process.exit(1);
};
});
});
module.exports = mongoose; |
Fix html wrapper linter issue | import React, { PropTypes } from 'react';
const HtmlWrapper = ({ children, state, head, scripts, stylesheets }) => {
// eslint-disable-next-line react/no-danger
const content = (<div id="root" dangerouslySetInnerHTML={{ __html: children }} />);
const htmlAttributes = head.htmlAttributes.toComponent();
return (
<html lang="en" {...htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{head.title.toComponent()}
{head.meta.toComponent()}
{head.link.toComponent()}
{
stylesheets.map(path => (
<link href={`/${path}`} rel="stylesheet" />
))
}
</head>
<body>
{ content }
<script
dangerouslySetInnerHTML={{__html: `window.__PRELOADED_STATE__ = ${JSON.stringify(state).replace(/</g, '\\u003c')};`}}
/>
{
scripts.map(path => (
<script src={`/${path}`} type="text/javascript"></script>
))
}
</body>
</html>
);
};
HtmlWrapper.propTypes = {
children: PropTypes.node.isRequired,
state: PropTypes.object.isRequired,
head: PropTypes.object.isRequired,
scripts: PropTypes.arrayOf(PropTypes.string),
stylesheets: PropTypes.arrayOf(PropTypes.string),
};
export default HtmlWrapper; | import React, { PropTypes } from 'react';
const HtmlWrapper = ({ children, state, head, scripts, stylesheets }) => {
// eslint-disable-next-line react/no-danger
const content = (<div id="root" dangerouslySetInnerHTML={{ __html: children }} />);
const htmlAttributes = head.htmlAttributes.toComponent();
return (
<html lang="en" {...htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{head.title.toComponent()}
{head.meta.toComponent()}
{head.link.toComponent()}
{
stylesheets.map(path => (
<link href={`/${path}`} rel="stylesheet" />
))
}
</head>
<body>
{ content }
<script
dangerouslySetInnerHTML={{__html: `window.__PRELOADED_STATE__ = ${JSON.stringify(state).replace(/</g, '\\u003c')};`}}
/>
</script>
{
scripts.map(path => (
<script src={`/${path}`} type="text/javascript"></script>
))
}
</body>
</html>
);
};
HtmlWrapper.propTypes = {
children: PropTypes.node.isRequired,
state: PropTypes.object.isRequired,
head: PropTypes.object.isRequired,
scripts: PropTypes.arrayOf(PropTypes.string),
stylesheets: PropTypes.arrayOf(PropTypes.string),
};
export default HtmlWrapper; |
Set limit for leaderboard to 10 | <?php
namespace Badger\UserBundle\Doctrine\Repository;
use Doctrine\ORM\EntityRepository;
use Badger\UserBundle\Repository\UserRepositoryInterface;
/**
* @author Adrien Pétremann <[email protected]>
*/
class UserRepository extends EntityRepository implements UserRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function countAll()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select($qb->expr()->count('u'))
->from('UserBundle:User', 'u');
$query = $qb->getQuery();
return $query->getSingleScalarResult();
}
/**
* {@inheritdoc}
*/
public function getSortedUserByUnlockedBadges($order = 'DESC', $limit = 10)
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('u AS user, COUNT(ub.id) AS nbUnlockedBadges')
->from('UserBundle:User', 'u')
->leftJoin('GameBundle:UnlockedBadge', 'ub')
->where('ub.user = u')
->setMaxResults($limit)
->orderBy('nbUnlockedBadges', $order)
->groupBy('u')
;
$query = $qb->getQuery();
return $query->getResult();
}
}
| <?php
namespace Badger\UserBundle\Doctrine\Repository;
use Doctrine\ORM\EntityRepository;
use Badger\UserBundle\Repository\UserRepositoryInterface;
/**
* @author Adrien Pétremann <[email protected]>
*/
class UserRepository extends EntityRepository implements UserRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function countAll()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select($qb->expr()->count('u'))
->from('UserBundle:User', 'u');
$query = $qb->getQuery();
return $query->getSingleScalarResult();
}
/**
* {@inheritdoc}
*/
public function getSortedUserByUnlockedBadges($order = 'DESC', $limit = 7)
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('u AS user, COUNT(ub.id) AS nbUnlockedBadges')
->from('UserBundle:User', 'u')
->leftJoin('GameBundle:UnlockedBadge', 'ub')
->where('ub.user = u')
->setMaxResults($limit)
->orderBy('nbUnlockedBadges', $order)
->groupBy('u')
;
$query = $qb->getQuery();
return $query->getResult();
}
}
|
Move highstock exporting before export-csv plugin | module.exports = {
all: {
options: {
format: 'json_flat',
pretty: true
},
files: [{
dest: 'dist/javascript.json',
src: [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/javascript/lib/highstock/highstock-exporting.js',
'src/javascript/lib/moment/moment.js',
'src/javascript/lib/**/*.js',
'src/javascript/autogenerated/idd_codes.js',
'src/javascript/autogenerated/texts.js',
'src/javascript/autogenerated/*.js',
'src/javascript/binary/base/*.js',
'src/javascript/binary/**/*.js'
]
},
{
dest: 'dist/lib.json',
src: [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/javascript/lib/moment/moment.js',
'src/javascript/lib/**/*.js'
]
},
{
dest: 'dist/binary.json', src: [
'src/javascript/binary/base/*.js',
'src/javascript/binary/**/*.js'
]
},
{
dest: 'dist/data.json', src: [
'src/javascript/autogenerated/idd_codes.js',
'src/javascript/autogenerated/texts.js',
'src/javascript/autogenerated/*.js'
]
}]
}
};
| module.exports = {
all: {
options: {
format: 'json_flat',
pretty: true
},
files: [{
dest: 'dist/javascript.json',
src: [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/javascript/lib/moment/moment.js',
'src/javascript/lib/**/*.js',
'src/javascript/autogenerated/idd_codes.js',
'src/javascript/autogenerated/texts.js',
'src/javascript/autogenerated/*.js',
'src/javascript/binary/base/*.js',
'src/javascript/binary/**/*.js'
]
},
{
dest: 'dist/lib.json',
src: [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/javascript/lib/moment/moment.js',
'src/javascript/lib/**/*.js'
]
},
{
dest: 'dist/binary.json', src: [
'src/javascript/binary/base/*.js',
'src/javascript/binary/**/*.js'
]
},
{
dest: 'dist/data.json', src: [
'src/javascript/autogenerated/idd_codes.js',
'src/javascript/autogenerated/texts.js',
'src/javascript/autogenerated/*.js'
]
}]
}
};
|
Change the failure status-code of the zen mock to a 503: Server is currently unavailable.
This is a more appropriate mock response. We then check for our app
issuing a: 502: Server received an invalid response from upstream server | <?php
class ZenTest extends Slim_Framework_TestCase {
// Use dependency injection to mock the Curl object.
public function testCanFetchZenFromGitHub() {
$expected = 'Never sniff a gift fish.';
$curl = $this->getMock('\Curl');
$curl->expects($this->any())
->method('get')
->will($this->returnValue((object) array(
'headers' => array('Status-Code' => 200),
'body' => $expected
)));
$this->app->curl = function ($c) use ($curl) {
return $curl;
};
$this->get('/zen');
$this->assertEquals(200, $this->response->status());
$this->assertEquals($expected, $this->response->body());
}
public function testZenResponseWhenGitHubFails() {
$curl = $this->getMock('\Curl');
$curl->expects($this->any())
->method('get')
->will($this->returnValue((object) array(
'headers' => array('Status-Code' => 503),
'body' => ''
)));
$this->app->curl = function ($c) use ($curl) {
return $curl;
};
$this->get('/zen');
$this->assertEquals(502, $this->response->status());
}
}
/* End of file ZenTest.php */
| <?php
class ZenTest extends Slim_Framework_TestCase {
// Use dependency injection to mock the Curl object.
public function testCanFetchZenFromGitHub() {
$expected = 'Never sniff a gift fish.';
$curl = $this->getMock('\Curl');
$curl->expects($this->any())
->method('get')
->will($this->returnValue((object) array(
'headers' => array('Status-Code' => 200),
'body' => $expected
)));
$this->app->curl = function ($c) use ($curl) {
return $curl;
};
$this->get('/zen');
$this->assertEquals(200, $this->response->status());
$this->assertEquals($expected, $this->response->body());
}
public function testZenResponseWhenGitHubFails() {
$curl = $this->getMock('\Curl');
$curl->expects($this->any())
->method('get')
->will($this->returnValue((object) array(
'headers' => array('Status-Code' => 502),
'body' => ''
)));
$this->app->curl = function ($c) use ($curl) {
return $curl;
};
$this->get('/zen');
$this->assertEquals(502, $this->response->status());
}
}
/* End of file ZenTest.php */
|
Rename of pre and elems to generic nodes | define([
'jquery', // src/jquery.js,
'defaults'
], function ($, defaults) {
function Crayon(element, options) {
console.error('construct');
this.element = element;
this.options = $.extend({}, defaults, options);
this.init();
}
// Define plugin
Crayon.prototype = {
nodes: null,
init: function () {
console.error('init');
this.nodes = this.query();
this.load(this.nodes);
},
query: function () {
return $(this.options.selector, this.element);
},
load: function (nodes) {
var me = this;
nodes.each(function (i, node) {
var atts = $(node).attr(me.options.attrSelector);
var parsedAtts = me.options.attrParser(atts);
node.crayon = {
atts: parsedAtts
};
console.log('atts', parsedAtts);
var output = me.parse(me.options.getValue(node), parsedAtts);
if (output && output.length) {
me.options.setValue(node, output);
}
console.log('output', output);
});
},
parse: function (value, atts) {
// TODO Load language, cache
// TODO Apply regex to code
// TODO Return output
console.log('value', value);
return value;
}
};
return Crayon;
});
| define([
'jquery', // src/jquery.js,
'defaults'
], function ($, defaults) {
function Crayon(element, options) {
console.error('construct');
this.element = element;
this.options = $.extend({}, defaults, options);
this.init();
}
// Define plugin
Crayon.prototype = {
elems: null,
init: function () {
console.error('init');
this.elems = this.query();
this.load(this.elems);
},
query: function () {
return $(this.options.selector, this.element);
},
load: function (elems) {
var me = this;
elems.each(function (i, pre) {
var atts = $(pre).attr(me.options.attrSelector);
var parsedAtts = me.options.attrParser(atts);
pre.crayon = {
atts: parsedAtts
};
console.log('atts', parsedAtts);
var output = me.parse(me.options.getValue(pre), parsedAtts);
if (output && output.length) {
me.options.setValue(pre, output);
}
console.log('output', output);
});
},
parse: function (value, atts) {
// TODO Load language, cache
// TODO Apply regex to code
// TODO Return output
console.log('value', value);
return value;
}
};
return Crayon;
});
|
Add setOption method to change default configuration | <?php
namespace Datatheke\Bundle\PagerBundle\DataGrid\Handler\Http;
use Symfony\Component\HttpFoundation\Request;
use Datatheke\Bundle\PagerBundle\DataGrid\HttpDataGridInterface;
use Datatheke\Bundle\PagerBundle\DataGrid\DataGridView;
use Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler as PagerViewHandler;
use Datatheke\Bundle\PagerBundle\Pager\PagerView;
class ViewHandler implements HttpHandlerInterface
{
protected $pagerHandler;
public function __construct($options = array())
{
if ($options instanceof PagerViewHandler) {
$this->pagerHandler = $options;
} elseif (is_array($options)) {
$this->pagerHandler = new PagerViewHandler($options);
} else {
throw new \Exception('ViewHandler::__construct() first agrument should be an array or a Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler object');
}
}
public function setOption($option, $value)
{
$this->pagerHandler->setOption($option, $value);
return $this;
}
public function handleRequest(HttpDataGridInterface $datagrid, Request $request)
{
$pager = $datagrid->getPager();
$this->pagerHandler->handleRequest($pager, $request);
return $this->createView($datagrid, $request);
}
protected function createView(HttpDataGridInterface $datagrid, Request $request)
{
return new DataGridView($datagrid, new PagerView($datagrid->getPager(), $this->pagerHandler));
}
}
| <?php
namespace Datatheke\Bundle\PagerBundle\DataGrid\Handler\Http;
use Symfony\Component\HttpFoundation\Request;
use Datatheke\Bundle\PagerBundle\DataGrid\HttpDataGridInterface;
use Datatheke\Bundle\PagerBundle\DataGrid\DataGridView;
use Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler as PagerViewHandler;
use Datatheke\Bundle\PagerBundle\Pager\PagerView;
class ViewHandler implements HttpHandlerInterface
{
protected $pagerHandler;
public function __construct($options = array())
{
if ($options instanceof PagerViewHandler) {
$this->pagerHandler = $options;
} elseif (is_array($options)) {
$this->pagerHandler = new PagerViewHandler($options);
} else {
throw new \Exception('ViewHandler::__construct() first agrument should be an array or a Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler object');
}
}
public function handleRequest(HttpDataGridInterface $datagrid, Request $request)
{
$pager = $datagrid->getPager();
$this->pagerHandler->handleRequest($pager, $request);
return $this->createView($datagrid, $request);
}
protected function createView(HttpDataGridInterface $datagrid, Request $request)
{
return new DataGridView($datagrid, new PagerView($datagrid->getPager(), $this->pagerHandler));
}
}
|
Change dot generate message to suggest PDF format. |
import click
from textx.metamodel import metamodel_from_file
from textx.lang import get_language
from textx.exceptions import TextXError
from txtools.vis import metamodel_export, model_export
@click.command()
@click.argument('model_file')
@click.option('-l', '--language', default='textx',
help='Registered language name. '
'Default is "textx" - for textX grammars.')
@click.option('-d', '--debug', default=False, is_flag=True,
help='run in debug mode')
def vis(model_file, language, debug):
"""
Visualize (meta)model using dot.
"""
try:
if language == 'textx':
mm = metamodel_from_file(model_file, debug=debug)
click.echo("Generating '%s.dot' file for meta-model." % model_file)
click.echo("To convert to PDF run 'dot -Tpdf -O %s.dot'"
% model_file)
metamodel_export(mm, "%s.dot" % model_file)
else:
mm = get_language(language)
model = mm.model_from_file(model_file, debug=debug)
click.echo("Generating '%s.dot' file for model." % model_file)
click.echo("To convert to PDF run 'dot -Tpdf -O %s.dot'"
% model_file)
model_export(model, "%s.dot" % model_file)
except TextXError as e:
click.echo(e)
|
import click
from textx.metamodel import metamodel_from_file
from textx.lang import get_language
from textx.exceptions import TextXError
from txtools.vis import metamodel_export, model_export
@click.command()
@click.argument('model_file')
@click.option('-l', '--language', default='textx',
help='Registered language name. '
'Default is "textx" - for textX grammars.')
@click.option('-d', '--debug', default=False, is_flag=True,
help='run in debug mode')
def vis(model_file, language, debug):
"""
Visualize (meta)model using dot.
"""
try:
if language == 'textx':
mm = metamodel_from_file(model_file, debug=debug)
click.echo("Generating '%s.dot' file for meta-model." % model_file)
click.echo("To convert to png run 'dot -Tpng -O %s.dot'"
% model_file)
metamodel_export(mm, "%s.dot" % model_file)
else:
mm = get_language(language)
model = mm.model_from_file(model_file, debug=debug)
click.echo("Generating '%s.dot' file for model." % model_file)
click.echo("To convert to png run 'dot -Tpng -O %s.dot'"
% model_file)
model_export(model, "%s.dot" % model_file)
except TextXError as e:
click.echo(e)
|
Add alt_text field for Media | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
| # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
|
Add readline support with vi keybindings | #!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s $ ' % os.getcwd()
def read_command():
line = input(prompt())
return line
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
return True
def run_builtin(cmd, cmd_text):
if shutil.which(cmd[0]):
os.system(cmd_text)
if cmd[0] == 'cd':
os.chdir(cmd[1])
elif cmd[0] == 'pwd':
print(os.getcwd())
elif cmd[0] == 'exit':
sys.exit()
if __name__ == "__main__":
while True:
try:
cmd_text = read_command()
cmd_text, cmd = parse_command(cmd_text)
record_command(cmd)
if cmd[0] in builtin_cmds:
run_builtin(cmd, cmd_text)
else:
#pid = subprocess.Popen(cmd_text, stdin=None, stdout=None, shell=True)
os.system(cmd_text)
except SystemExit:
break
except:
traceback.print_exc()
| #!/usr/bin/env python3
import os
import shutil
import sys
import traceback
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
print('%s $ ' % os.getcwd(), end='', flush=True)
def read_command():
return sys.stdin.readline()
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
print(command)
return True
def run_builtin(cmd, cmd_text):
if shutil.which(cmd[0]):
os.system(cmd_text)
if cmd[0] == 'cd':
os.chdir(cmd[1])
elif cmd[0] == 'pwd':
print(os.getcwd())
elif cmd[0] == 'exit':
sys.exit()
if __name__ == "__main__":
while True:
try:
prompt()
cmd_text = read_command()
cmd_text, cmd = parse_command(cmd_text)
record_command(cmd)
if cmd[0] in builtin_cmds:
run_builtin(cmd, cmd_text)
else:
#pid = subprocess.Popen(cmd_text, stdin=None, stdout=None, shell=True)
os.system(cmd_text)
except SystemExit:
break
except:
traceback.print_exc()
|
Add method to get current number of fetched items. | package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class ResultSet implements Iterable<Item> {
private final ResponseQueue responseQueue;
public ResultSet(final ResponseQueue responseQueue) {
this.responseQueue = responseQueue;
}
public boolean isFullyFetched() {
return responseQueue.getStatus() == ResponseQueue.Status.COMPLETE;
}
public int fetchedCount() {
return responseQueue.size();
}
public CompletableFuture<List<Item>> all() {
return CompletableFuture.supplyAsync(() -> {
final List<Item> list = new ArrayList<>();
while (!isFullyFetched() || fetchedCount() > 0) {
final ResponseMessage msg = responseQueue.poll();
if (msg != null)
list.add(new Item(msg.getResult()));
}
return list;
});
}
@Override
public Iterator<Item> iterator() {
return new Iterator<Item>() {
private Item current = null;
@Override
public boolean hasNext() {
final ResponseMessage msg = responseQueue.poll();
if (null == msg)
return false;
// todo: wait??
this.current = new Item(msg.getResult());
return true;
}
@Override
public Item next() {
return current;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
| package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class ResultSet implements Iterable<Item> {
private final ResponseQueue responseQueue;
public ResultSet(final ResponseQueue responseQueue) {
this.responseQueue = responseQueue;
}
public boolean isFullyFetched() {
return responseQueue.getStatus() == ResponseQueue.Status.COMPLETE;
}
public CompletableFuture<List<Item>> all() {
return CompletableFuture.supplyAsync(() -> {
final List<Item> list = new ArrayList<>();
while (!isFullyFetched() || responseQueue.size() > 0) {
final ResponseMessage msg = responseQueue.poll();
if (msg != null)
list.add(new Item(msg.getResult()));
}
return list;
});
}
@Override
public Iterator<Item> iterator() {
return new Iterator<Item>() {
private Item current = null;
@Override
public boolean hasNext() {
final ResponseMessage msg = responseQueue.poll();
if (null == msg)
return false;
// todo: wait??
this.current = new Item(msg.getResult());
return true;
}
@Override
public Item next() {
return current;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
|
Install six for Python 2 & 3 compatibility | #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="[email protected]",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/tarball/master",
url="http://github.com/mineo/sagbescheid",
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.7"],
description="systemd notification daemon",
long_description=open("README.rst").read(),
install_requires=["Twisted[tls]>=15.2.0",
"pyasn1",
"txdbus==1.1.0",
"automat==0.7.0",
"zope.interface==4.6.0",
"systemd-python==234",
"enum34==1.1.6;python_version<'3.4'",
"six==1.12.0"],
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "sagbescheid/version.py"},
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']
}
)
| #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="[email protected]",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/tarball/master",
url="http://github.com/mineo/sagbescheid",
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.7"],
description="systemd notification daemon",
long_description=open("README.rst").read(),
install_requires=["Twisted[tls]>=15.2.0",
"pyasn1",
"txdbus==1.1.0",
"automat==0.7.0",
"zope.interface==4.6.0",
"systemd-python==234",
"enum34==1.1.6;python_version<'3.4'"],
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "sagbescheid/version.py"},
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']
}
)
|
PATCH should 204 on success
Closes #8 | 'use strict';
const BaseHandler = require('./BaseHandler');
class PatchHandler extends BaseHandler {
/**
* Write data to the DataStore and return the new offset.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(req, res) {
const re = new RegExp('\\' + this.store.path + '\\/(\\w+)\/?'); // eslint-disable-line prefer-template
const match = req.url.match(re);
if (!match) {
return super.send(res, 404);
}
const file_name = match[1];
let offset = req.headers['upload-offset'];
// The request MUST include a Upload-Offset header
if (!offset) {
return super.send(res, 409);
}
offset = parseInt(offset, 10);
// The value MUST be a non-negative integer.
if (isNaN(offset) || offset < 0) {
return super.send(res, 400, { 'Content-Type': 'text/plain' }, 'Upload-Offset must be non-negative');
}
return this.store.write(req, file_name, offset).then((new_offset) => {
return super.send(res, 204, { 'Upload-Offset': new_offset });
})
.catch((error) => {
console.log(error);
super.send(res, 404);
});
}
}
module.exports = PatchHandler;
| 'use strict';
const BaseHandler = require('./BaseHandler');
class PatchHandler extends BaseHandler {
/**
* Write data to the DataStore and return the new offset.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(req, res) {
const re = new RegExp('\\' + this.store.path + '\\/(\\w+)\/?'); // eslint-disable-line prefer-template
const match = req.url.match(re);
if (!match) {
return super.send(res, 404);
}
const file_name = match[1];
let offset = req.headers['upload-offset'];
// The request MUST include a Upload-Offset header
if (!offset) {
return super.send(res, 409);
}
offset = parseInt(offset, 10);
// The value MUST be a non-negative integer.
if (isNaN(offset) || offset < 0) {
return super.send(res, 400, { 'Content-Type': 'text/plain' }, 'Upload-Offset must be non-negative');
}
return this.store.write(req, file_name, offset).then((new_offset) => {
return super.send(res, 201, { 'Upload-Offset': new_offset });
})
.catch((error) => {
console.log(error);
super.send(res, 404);
});
}
}
module.exports = PatchHandler;
|
Change patient visit table ordering to be latest to oldest | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.core.urlresolvers import reverse
class BillingCode(models.Model):
nr_rvus = models.FloatField()
creation_date = models.DateTimeField('date created', default=timezone.now)
ordering = models.IntegerField(blank=True, null=True)
code_name = models.CharField(max_length=200)
def __str__(self):
return "%s (%0.2f)" % (self.code_name, self.nr_rvus)
class Meta:
ordering = ('-ordering', 'code_name',)
class Provider(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
annual_rvu_goal = models.FloatField(default=0)
def __str__(self):
return "%s %s (%s)" % (self.user.first_name,
self.user.last_name,
self.user.email)
class Meta:
ordering = ('user',)
class PatientVisit(models.Model):
provider = models.ForeignKey(Provider, on_delete=models.CASCADE)
visit_date = models.DateTimeField('visit date')
code_billed = models.ForeignKey(BillingCode)
class Meta:
ordering = ('-visit_date',)
def get_absolute_url(self):
return reverse('patient-visit-detail', kwargs={'pk': self.pk})
def __str__(self):
return "%s:%s:%s" % (self.visit_date, self.provider, self.code_billed)
| from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.core.urlresolvers import reverse
class BillingCode(models.Model):
nr_rvus = models.FloatField()
creation_date = models.DateTimeField('date created', default=timezone.now)
ordering = models.IntegerField(blank=True, null=True)
code_name = models.CharField(max_length=200)
def __str__(self):
return "%s (%0.2f)" % (self.code_name, self.nr_rvus)
class Meta:
ordering = ('-ordering', 'code_name',)
class Provider(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
annual_rvu_goal = models.FloatField(default=0)
def __str__(self):
return "%s %s (%s)" % (self.user.first_name,
self.user.last_name,
self.user.email)
class Meta:
ordering = ('user',)
class PatientVisit(models.Model):
provider = models.ForeignKey(Provider, on_delete=models.CASCADE)
visit_date = models.DateTimeField('visit date')
code_billed = models.ForeignKey(BillingCode)
class Meta:
ordering = ('visit_date',)
def get_absolute_url(self):
return reverse('patient-visit-detail', kwargs={'pk': self.pk})
def __str__(self):
return "%s:%s:%s" % (self.visit_date, self.provider, self.code_billed)
|
Allow disabling the autocharging behavior of the bank transfer moocher | from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals import post_charge
class BankTransferMoocher(BaseMoocher):
identifier = 'banktransfer'
title = _('Pay by bank transfer')
def __init__(self, *, autocharge, **kw):
self.autocharge = autocharge
super(BankTransferMoocher, self).__init__(**kw)
def get_urls(self):
return [
url('^confirm/$', self.confirm_view, name='banktransfer_confirm'),
]
def payment_form(self, request, payment):
return render_to_string('mooch/banktransfer_payment_form.html', {
'payment': payment,
'moocher': self,
}, request=request)
@require_POST_m
def confirm_view(self, request):
instance = get_object_or_404(self.model, id=request.POST.get('id'))
instance.payment_service_provider = self.identifier
if self.autocharge:
instance.charged_at = timezone.now()
instance.transaction = repr(request.META.copy())
instance.save()
post_charge.send(
sender=self.__class__,
payment=instance,
request=request,
)
return http.HttpResponseRedirect(self.success_url)
| from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals import post_charge
class BankTransferMoocher(BaseMoocher):
identifier = 'banktransfer'
title = _('Pay by bank transfer')
def get_urls(self):
return [
url('^confirm/$', self.confirm_view, name='banktransfer_confirm'),
]
def payment_form(self, request, payment):
return render_to_string('mooch/banktransfer_payment_form.html', {
'payment': payment,
'moocher': self,
}, request=request)
@require_POST_m
def confirm_view(self, request):
instance = get_object_or_404(self.model, id=request.POST.get('id'))
instance.payment_service_provider = self.identifier
instance.charged_at = timezone.now()
instance.transaction = repr(request.META.copy())
instance.save()
post_charge.send(
sender=self.__class__,
payment=instance,
request=request,
)
return http.HttpResponseRedirect(self.success_url)
|
Allow local_site_reverse to take an actual LocalSite.
local_site_reverse was able to take a LocalSite's name, or a request
object, but if you actually had a LocalSite (or None), you'd have to
write your own conditional to extract the name and pass it.
Now, local_site_reverse can take a LocalSite. This saves a database
query, if one is already available, and simplifies calling code.
Reviewed at https://reviews.reviewboard.org/r/6302/ | from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
local_site=None, args=None, kwargs=None,
*func_args, **func_kwargs):
"""Reverses a URL name, returning a working URL.
This works much like Django's reverse(), but handles returning a
localsite version of a URL when invoked with a request within a localsite.
"""
assert not (local_site_name and local_site)
if request or local_site_name or local_site:
if local_site:
local_site_name = local_site.name
elif request and not local_site_name:
local_site_name = getattr(request, '_local_site_name', None)
if local_site_name:
if args:
new_args = [local_site_name] + args
new_kwargs = kwargs
else:
new_args = args
new_kwargs = {
'local_site_name': local_site_name,
}
if kwargs:
new_kwargs.update(kwargs)
try:
return reverse(viewname, args=new_args, kwargs=new_kwargs,
*func_args, **func_kwargs)
except NoReverseMatch:
# We'll try it again without those arguments.
pass
return reverse(viewname, args=args, kwargs=kwargs,
*func_args, **func_kwargs)
| from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
args=None, kwargs=None, *func_args, **func_kwargs):
"""Reverses a URL name, returning a working URL.
This works much like Django's reverse(), but handles returning a
localsite version of a URL when invoked with a request within a localsite.
"""
if request or local_site_name:
if request and not local_site_name:
local_site_name = getattr(request, '_local_site_name', None)
if local_site_name:
if args:
new_args = [local_site_name] + args
new_kwargs = kwargs
else:
new_args = args
new_kwargs = {
'local_site_name': local_site_name,
}
if kwargs:
new_kwargs.update(kwargs)
try:
return reverse(viewname, args=new_args, kwargs=new_kwargs,
*func_args, **func_kwargs)
except NoReverseMatch:
# We'll try it again without those arguments.
pass
return reverse(viewname, args=args, kwargs=kwargs,
*func_args, **func_kwargs)
|
Remove test with integer > Integer.MAX. Replaced it with negative number test | package strings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static strings.BaseConversion.baseConversion;
class BaseConversionTest {
private String expected;
private String input;
private int b1;
private int b2;
@Test
void baseConversion1() {
expected = "314F";
input = "12623";
b1 = 10;
b2 = 16;
test(expected, input, b1, b2);
}
@Test
void baseConversion2() {
expected = "-6CC2";
input = "-62543";
b1 = 7;
b2 = 13;
test(expected, input, b1, b2);
}
@Test
void baseConversion3() {
expected = "111";
input = "7";
b1 = 10;
b2 = 2;
test(expected, input, b1, b2);
}
@Test
void baseConversion4() {
expected = "33CD";
input = "10001100101001";
b1 = 2;
b2 = 14;
test(expected, input, b1, b2);
}
private void test(String expected, String input, int b1, int b2) {
assertEquals(expected, baseConversion(input, b1, b2));
}
} | package strings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static strings.BaseConversion.baseConversion;
class BaseConversionTest {
private String expected;
private String input;
private int b1;
private int b2;
@Test
void baseConversion1() {
expected = "314F";
input = "12623";
b1 = 10;
b2 = 16;
test(expected, input, b1, b2);
}
@Test
void baseConversion2() {
expected = "2C996B726";
input = "114152520463";
b1 = 7;
b2 = 13;
test(expected, input, b1, b2);
}
@Test
void baseConversion3() {
expected = "111";
input = "7";
b1 = 10;
b2 = 2;
test(expected, input, b1, b2);
}
@Test
void baseConversion4() {
expected = "33CD";
input = "10001100101001";
b1 = 2;
b2 = 14;
test(expected, input, b1, b2);
}
private void test(String expected, String input, int b1, int b2) {
assertEquals(expected, baseConversion(input, b1, b2));
}
} |
Allow to set the port in adhocracy.domain to make adhocracy work stand alone again. | import logging
from adhocracy import model
from pylons import config
log = logging.getLogger(__name__)
class InstanceDiscriminatorMiddleware(object):
def __init__(self, app, domain):
self.app = app
self.domain = domain
log.debug("Host name: %s." % domain)
def __call__(self, environ, start_response):
host = environ.get('HTTP_HOST', "")
environ['adhocracy.domain'] = self.domain
instance_key = config.get('adhocracy.instance')
if instance_key is None:
host = host.replace(self.domain, "")
host = host.split(':', 1)[0]
host = host.strip('.').strip()
instance_key = host
if len(instance_key):
instance = model.Instance.find(instance_key)
if instance is None:
log.debug("No such instance: %s, defaulting!" % instance_key)
else:
model.instance_filter.setup_thread(instance)
try:
return self.app(environ, start_response)
finally:
model.instance_filter.setup_thread(None)
def setup_discriminator(app, config):
domains = config.get('adhocracy.domain',
config.get('adhocracy.domains', ''))
domains = [d.strip() for d in domains.split(',')]
return InstanceDiscriminatorMiddleware(app, domains[0])
| import logging
from adhocracy import model
from pylons import config
log = logging.getLogger(__name__)
class InstanceDiscriminatorMiddleware(object):
def __init__(self, app, domain):
self.app = app
self.domain = domain
log.debug("Host name: %s." % domain)
def __call__(self, environ, start_response):
host = environ.get('HTTP_HOST', "")
environ['adhocracy.domain'] = self.domain
instance_key = config.get('adhocracy.instance')
if instance_key is None:
host = host.split(':', 1)[0]
host = host.replace(self.domain, "")
host = host.strip('.').strip()
instance_key = host
if len(instance_key):
instance = model.Instance.find(instance_key)
if instance is None:
log.debug("No such instance: %s, defaulting!" % instance_key)
else:
model.instance_filter.setup_thread(instance)
try:
return self.app(environ, start_response)
finally:
model.instance_filter.setup_thread(None)
def setup_discriminator(app, config):
domains = config.get('adhocracy.domain',
config.get('adhocracy.domains', ''))
domains = [d.strip() for d in domains.split(',')]
return InstanceDiscriminatorMiddleware(app, domains[0])
|
Handle the three get cases |
const getStorage = () => {
const data = window.localStorage.getItem('__chrome.storage.sync__')
if (data != null) {
return JSON.parse(data)
} else {
return {}
}
}
const setStorage = (storage) => {
const json = JSON.stringify(storage)
window.localStorage.setItem('__chrome.storage.sync__', json)
}
module.exports = {
sync: {
get (keys, callback) {
const storage = getStorage()
if (keys == null) return storage
let defaults = {}
switch (typeof keys) {
case 'string':
keys = [keys]
break
case 'object':
if (!Array.isArray(keys)) {
defaults = keys
keys = Object.keys(keys)
}
break;
}
if (keys.length === 0 ) return {}
let items = {}
keys.forEach(function (key) {
var value = storage[key]
if (value == null) value = defaults[key]
items[key] = value
})
setTimeout(function () {
callback(items)
})
},
set (items, callback) {
const storage = getStorage()
Object.keys(items).forEach(function (name) {
storage[name] = items[name]
})
setStorage(storage)
setTimeout(callback)
}
}
}
|
const getStorage = () => {
const data = window.localStorage.getItem('__chrome.storage.sync__')
if (data != null) {
return JSON.parse(data)
} else {
return {}
}
}
const setStorage = (storage) => {
const json = JSON.stringify(storage)
window.localStorage.setItem('__chrome.storage.sync__', json)
}
module.exports = {
sync: {
get (keys, callback) {
const storage = getStorage()
if (keys === {} || keys === []) return {}
if (keys === null) return storage
if (typeof keys === 'string') keys = [keys]
let items = {}
// ['foo'] or ['foo', 'bar'] or [{foo: 'bar'}]
keys.forEach(function (key) {
if (typeof key === 'string') {
items[key] = storage[key]
}
else {
const objKey = Object.keys(key)
if (!storage[objKey] || storage[objKey] === '') {
items[objKey] = key[objKey]
} else {
items[objKey] = storage[objKey]
}
}
})
setTimeout(function () {
callback(items)
})
},
set (items, callback) {
const storage = getStorage()
Object.keys(items).forEach(function (name) {
storage[name] = items[name]
})
setStorage(storage)
setTimeout(callback)
}
}
}
|
Increment version for 24-bit wav bug fix | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.4',
author='James Robert',
author_email='[email protected]',
description='Manipulate audio with an simple and easy high level interface',
license='MIT',
keywords='audio sound high-level',
url='http://pydub.com',
packages=['pydub'],
long_description=__doc__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Multimedia :: Sound/Audio :: Analysis",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Sound/Audio :: Editors",
"Topic :: Multimedia :: Sound/Audio :: Mixers",
"Topic :: Software Development :: Libraries",
'Topic :: Utilities',
]
)
| __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.3',
author='James Robert',
author_email='[email protected]',
description='Manipulate audio with an simple and easy high level interface',
license='MIT',
keywords='audio sound high-level',
url='http://pydub.com',
packages=['pydub'],
long_description=__doc__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Multimedia :: Sound/Audio :: Analysis",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Sound/Audio :: Editors",
"Topic :: Multimedia :: Sound/Audio :: Mixers",
"Topic :: Software Development :: Libraries",
'Topic :: Utilities',
]
)
|
Modify query to return vertex count | 'use strict';
function prepareQuery(sql) {
var affectedTableRegexCache = {
bbox: /!bbox!/g,
scale_denominator: /!scale_denominator!/g,
pixel_width: /!pixel_width!/g,
pixel_height: /!pixel_height!/g
};
return sql
.replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)')
.replace(affectedTableRegexCache.scale_denominator, '0')
.replace(affectedTableRegexCache.pixel_width, '1')
.replace(affectedTableRegexCache.pixel_height, '1');
}
module.exports.extractTableNames = function extractTableNames(query) {
return [
'SELECT * FROM CDB_QueryTablesText($windshaft$',
prepareQuery(query),
'$windshaft$) as tablenames'
].join('');
};
module.exports.getColumnNamesFromQuery = function extractTableNames(query) {
return [
'SELECT * FROM (',
prepareQuery(query),
') as columnNames limit 0'
].join('');
};
module.exports.getTableStats = function getTableStats(table, geomColumn) {
geomColumn = geomColumn || 'the_geom';
return [
'with feature_stats AS (',
' select (_postgis_stats(',
' \'' + table + '\'::regclass, \'' + geomColumn + '\'',
' )::json ->> \'table_features\')::numeric as features',
'),',
'vertex_stats as (',
' select sum(ST_NPoints(' + geomColumn + ')) as vertexes from ' + table,
')',
'select * from feature_stats, vertex_stats'
].join('\n');
};
| 'use strict';
function prepareQuery(sql) {
var affectedTableRegexCache = {
bbox: /!bbox!/g,
scale_denominator: /!scale_denominator!/g,
pixel_width: /!pixel_width!/g,
pixel_height: /!pixel_height!/g
};
return sql
.replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)')
.replace(affectedTableRegexCache.scale_denominator, '0')
.replace(affectedTableRegexCache.pixel_width, '1')
.replace(affectedTableRegexCache.pixel_height, '1');
}
module.exports.extractTableNames = function extractTableNames(query) {
return [
'SELECT * FROM CDB_QueryTablesText($windshaft$',
prepareQuery(query),
'$windshaft$) as tablenames'
].join('');
};
module.exports.getColumnNamesFromQuery = function extractTableNames(query) {
return [
'SELECT * FROM (',
prepareQuery(query),
') as columnNames limit 0'
].join('');
};
module.exports.getTableStats = function getTableStats(table, geomColumn) {
return [
'SELECT row_to_json(s) as result FROM(',
'select _postgis_stats(\'',
table,
'\'::regclass, \'',
(geomColumn || 'the_geom'),
'\') as stats) as s',
].join('');
};
|
Add GUI support for Travis | module.exports = function(config) {
var configuration = {
client: {
captureConsole: false
},
plugins: [
'karma-chai',
'karma-sinon',
'karma-mocha',
'karma-chrome-launcher'
],
frameworks: ['mocha', 'sinon', 'chai'],
files: [
//- lib
"lib/three.js/build/three.js",
"lib/ColladaLoader/index.js",
"lib/isMobile/isMobile.min.js",
"lib/detector/index.js",
//- app
"src/javascript/helpers/*.js",
"src/javascript/control/*.js",
"src/javascript/models/*.js",
"src/javascript/scene/*.js",
"src/javascript/simulator/*.js",
//- test
'test/utils/**/*.js',
'test/unit/**/*.js'
],
reporters: ['progress'],
browsers: ['Chrome'],
customLaunchers: {
chromeTravis: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
singleRun: false
}
if(process.env.TRAVIS){
configuration.browsers = ['chromeTravis'];
}
config.set(configuration);
}
| module.exports = function(config) {
var configuration = {
client: {
captureConsole: false
},
plugins: [
'karma-chai',
'karma-sinon',
'karma-mocha',
'karma-chrome-launcher'
],
frameworks: ['mocha', 'sinon', 'chai'],
files: [
//- lib
"lib/three.js/build/three.js",
"lib/ColladaLoader/index.js",
"lib/isMobile/isMobile.min.js",
"lib/detector/index.js",
//- app
"src/javascript/helpers/*.js",
"src/javascript/control/*.js",
"src/javascript/models/*.js",
"src/javascript/scene/*.js",
"src/javascript/simulator/*.js",
//- test
'test/utils/**/*.js',
'test/unit/**/*.js'
],
reporters: ['progress'],
browsers: ['Chrome'],
singleRun: false
}
if(process.env.TRAVIS){
configuration.browsers = ['Chrome_travis_ci'];
}
config.set(configuration);
}
|
Fix Conversation validation on recipients | <?php
namespace FD\PrivateMessageBundle\Validator;
use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Class ConversationValidator.
*/
class ConversationValidator
{
const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';
/**
* Entry point of the conversation's validation process.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
public static function validate(Conversation $conversation, ExecutionContextInterface $context)
{
self::validateRecipients($conversation, $context);
}
/**
* Make sure the author of the conversation is not sending a message to himself.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
{
// This could be NULL or array.
$recipients = $conversation->getRecipients();
if ($recipients->contains($conversation->getAuthor())) {
$context
->buildViolation(self::RECIPIENT_VIOLATION)
->atPath('recipients')
->addViolation();
}
}
}
| <?php
namespace FD\PrivateMessageBundle\Validator;
use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Class ConversationValidator.
*/
class ConversationValidator
{
const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';
/**
* Entry point of the conversation's validation process.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
public static function validate(Conversation $conversation, ExecutionContextInterface $context)
{
self::validateRecipients($conversation, $context);
}
/**
* Make sure the author of the conversation is not sending a message to himself.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
{
// This could be NULL or array.
$recipients = $conversation->getRecipients();
if (is_array($recipients) && in_array($conversation->getAuthor(), $recipients)) {
$context
->buildViolation(self::RECIPIENT_VIOLATION)
->atPath('recipients')
->addViolation();
}
}
}
|
Fix broken functional tests on windows
Something must have changed on the Appveyor side since this code
hasn't been touched recently. The issue was that a functional test
was referring to "/tmp" which is not valid on Windows. I'm surprised
this worked on Windows in the first place. | import os
import tempfile
import yaml
from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase
from test.functional.job_configs import BASIC_JOB
class TestMasterEndpoints(BaseFunctionalTestCase):
def setUp(self):
super().setUp()
self._project_dir = tempfile.TemporaryDirectory()
def _start_master_only_and_post_a_new_job(self):
master = self.cluster.start_master()
build_resp = master.post_new_build({
'type': 'directory',
'config': yaml.safe_load(BASIC_JOB.config[os.name])['BasicJob'],
'project_directory': self._project_dir.name,
})
build_id = build_resp['build_id']
return master, build_id
def test_cancel_build(self):
master, build_id = self._start_master_only_and_post_a_new_job()
master.cancel_build(build_id)
master.block_until_build_finished(build_id)
self.assert_build_has_canceled_status(build_id=build_id)
def test_get_artifact_before_it_is_ready(self):
master, build_id = self._start_master_only_and_post_a_new_job()
# Since we didn't start any slaves so the artifacts is actually not ready.
_, status_code = master.get_build_artifacts(build_id)
self.assertEqual(status_code, 202)
# Cancel the started build just to speed up teardown (avoid teardown timeout waiting for empty queue)
master.cancel_build(build_id)
| import os
import yaml
from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase
from test.functional.job_configs import BASIC_JOB
class TestMasterEndpoints(BaseFunctionalTestCase):
def _start_master_only_and_post_a_new_job(self):
master = self.cluster.start_master()
build_resp = master.post_new_build({
'type': 'directory',
'config': yaml.safe_load(BASIC_JOB.config[os.name])['BasicJob'],
'project_directory': '/tmp',
})
build_id = build_resp['build_id']
return master, build_id
def test_cancel_build(self):
master, build_id = self._start_master_only_and_post_a_new_job()
master.cancel_build(build_id)
master.block_until_build_finished(build_id)
self.assert_build_has_canceled_status(build_id=build_id)
def test_get_artifact_before_it_is_ready(self):
master, build_id = self._start_master_only_and_post_a_new_job()
# Since we didn't start any slaves so the artifacts is actually not ready.
_, status_code = master.get_build_artifacts(build_id)
self.assertEqual(status_code, 202)
# Cancel the started build just to speed up teardown (avoid teardown timeout waiting for empty queue)
master.cancel_build(build_id)
|
Add test injection in xml asserter | <?php
namespace mageekguy\atoum\xml;
use mageekguy\atoum;
use mageekguy\atoum\observable;
use mageekguy\atoum\runner;
use mageekguy\atoum\test;
class extension implements atoum\extension
{
public function __construct(atoum\configurator $configurator = null)
{
if ($configurator)
{
$parser = $configurator->getScript()->getArgumentsParser();
$handler = function($script, $argument, $values) {
$script->getRunner()->addTestsFromDirectory(dirname(__DIR__) . '/tests/units/classes');
};
$parser
->addHandler($handler, array('--test-ext'))
->addHandler($handler, array('--test-it'))
;
}
}
public function setRunner(runner $runner)
{
return $this;
}
public function setTest(test $test)
{
$asserter = null;
$test->getAssertionManager()
->setHandler(
'xml',
function($xml = null, $depth = null, $options = null) use ($test, & $asserter) {
if ($asserter === null)
{
$asserter = new atoum\xml\asserters\node($test->getAsserterGenerator());
}
if (null === $xml) {
return $asserter;
}
return $asserter
->setWithTest($test)
->setWith($xml, $depth, $options);
}
)
;
return $this;
}
public function handleEvent($event, observable $observable) {}
}
| <?php
namespace mageekguy\atoum\xml;
use mageekguy\atoum;
use mageekguy\atoum\observable;
use mageekguy\atoum\runner;
use mageekguy\atoum\test;
class extension implements atoum\extension
{
public function __construct(atoum\configurator $configurator = null)
{
if ($configurator)
{
$parser = $configurator->getScript()->getArgumentsParser();
$handler = function($script, $argument, $values) {
$script->getRunner()->addTestsFromDirectory(dirname(__DIR__) . '/tests/units/classes');
};
$parser
->addHandler($handler, array('--test-ext'))
->addHandler($handler, array('--test-it'))
;
}
}
public function setRunner(runner $runner)
{
return $this;
}
public function setTest(test $test)
{
$asserter = null;
$test->getAssertionManager()
->setHandler(
'xml',
function($xml = null, $depth = null, $options = null) use ($test, & $asserter) {
if ($asserter === null)
{
$asserter = new atoum\xml\asserters\node($test->getAsserterGenerator());
}
if (null === $xml) {
return $asserter;
}
return $asserter->setWith($xml, $depth, $options);
}
)
;
return $this;
}
public function handleEvent($event, observable $observable) {}
}
|
Print HTTP content in verbose mode | # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'
self.verbose = verbose
def _request(self, method, path, data=None, headers=None):
url = self.url + path
config = {}
if self.verbose is not None:
config['verbose'] = self.verbose
r = requests.request(method, url, data=data, headers=headers,
config=config, allow_redirects=True)
r.raise_for_status()
if not 'application/json' in r.headers['Content-Type']:
raise TypeError('No JSON in response')
content = r.content.strip()
if content:
if self.verbose is not None:
self.verbose.write(content + '\n')
return json.loads(content)
else:
return None
def resources(self):
"""Retrieve information about sub-resources."""
return self._request('GET', '/')
def shorten(self, full_url):
"""Create a new shortened URL."""
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = 'url=%s' % full_url
return self._request('POST', '/urls', data=data, headers=headers)
def metadata(self, url_id):
"""Retrieve available metadata of a shortened link."""
return self._request('GET', '/urls/%s' % url_id)
| # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'
self.config = {}
if verbose is not None:
self.config['verbose'] = verbose
def _request(self, method, path, data=None, headers=None):
url = self.url + path
r = requests.request(method, url, data=data, headers=headers,
config=self.config, allow_redirects=True)
r.raise_for_status()
if not 'application/json' in r.headers['Content-Type']:
raise TypeError('No JSON in response')
return json.loads(r.content) if r.content.strip() else None
def resources(self):
"""Retrieve information about sub-resources."""
return self._request('GET', '/')
def shorten(self, full_url):
"""Create a new shortened URL."""
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = 'url=%s' % full_url
return self._request('POST', '/urls', data=data, headers=headers)
def metadata(self, url_id):
"""Retrieve available metadata of a shortened link."""
return self._request('GET', '/urls/%s' % url_id)
|
Use the new child_process.spawn API |
var log = require("../utils/log")
module.exports = function exec (cmd, args, env, pipe, cb) {
if (!cb) cb = pipe, pipe = false
if (!cb) cb = env, env = process.env
log(cmd+" "+args.map(JSON.stringify).join(" "), "exec")
var stdio = process.binding("stdio")
, fds = [ stdio.stdinFD || 0
, stdio.stdoutFD || 1
, stdio.stderrFD || 2
]
, cp = require("child_process").spawn( cmd
, args
, { env : env
, customFDs : pipe ? null : fds
}
)
, stdout = ""
, stderr = ""
cp.stdout && cp.stdout.on("data", function (chunk) {
if (chunk) stdout += chunk
})
cp.stderr && cp.stderr.on("data", function (chunk) {
if (chunk) stderr += chunk
})
cp.on("exit", function (code) {
if (code) cb(new Error("`"+cmd+"` failed with "+code))
else cb(null, code, stdout, stderr)
})
return cp
}
|
var log = require("../utils/log")
module.exports = function exec (cmd, args, env, pipe, cb) {
if (!cb) cb = pipe, pipe = false
if (!cb) cb = env, env = process.env
log(cmd+" "+args.map(JSON.stringify).join(" "), "exec")
var stdio = process.binding("stdio")
, fds = [ stdio.stdinFD || 0
, stdio.stdoutFD || 1
, stdio.stderrFD || 2
]
, cp = require("child_process").spawn( cmd
, args
, env
, pipe ? null : fds
)
, stdout = ""
, stderr = ""
cp.stdout && cp.stdout.on("data", function (chunk) {
if (chunk) stdout += chunk
})
cp.stderr && cp.stderr.on("data", function (chunk) {
if (chunk) stderr += chunk
})
cp.on("exit", function (code) {
if (code) cb(new Error("`"+cmd+"` failed with "+code))
else cb(null, code, stdout, stderr)
})
return cp
}
|
Replace deprecated slave_ok for read_preference in pymongo.Connection
See: http://api.mongodb.org/python/current/api/pymongo/connection.html | try:
from numbers import Number
import pymongo
from pymongo import ReadPreference
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignored.
"""
def get_default_config(self):
"""
Returns the default collector settings
"""
return {
'path': 'mongo',
'host': 'localhost'
}
def collect(self):
"""Collect number values from db.serverStatus()"""
if Number is None:
self.log.error('Unable to import either Number or pymongo')
return {}
conn = pymongo.Connection(self.config['host'],read_preference=ReadPreference.SECONDARY)
data = conn.db.command('serverStatus')
for key in data:
self._publish_metrics([], key, data)
def _publish_metrics(self, prev_keys, key, data):
"""Recursively publish keys"""
value = data[key]
keys = prev_keys + [key]
if isinstance(value, dict):
for new_key in value:
self._publish_metrics(keys, new_key, value)
elif isinstance(value, Number):
self.publish('.'.join(keys), value)
| try:
from numbers import Number
import pymongo
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignored.
"""
def get_default_config(self):
"""
Returns the default collector settings
"""
return {
'path': 'mongo',
'host': 'localhost'
}
def collect(self):
"""Collect number values from db.serverStatus()"""
if Number is None:
self.log.error('Unable to import either Number or pymongo')
return {}
conn = pymongo.Connection(self.config['host'],slave_okay=True)
data = conn.db.command('serverStatus')
for key in data:
self._publish_metrics([], key, data)
def _publish_metrics(self, prev_keys, key, data):
"""Recursively publish keys"""
value = data[key]
keys = prev_keys + [key]
if isinstance(value, dict):
for new_key in value:
self._publish_metrics(keys, new_key, value)
elif isinstance(value, Number):
self.publish('.'.join(keys), value)
|
Fix help messages for commands | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(entry_point, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
|
Debug .vue files in browserify | var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir.config.js.browserify.options.debug=true;
elixir(function(mix) {
/* PixboPlayer */
mix
.sass('PixboPlayer.scss')
.scripts(
[
'jquery-2.1.3.min.js',
'vegas.min.js',
'jquery.ticker.js',
'../PixboPlayer.js'
],
'public/js/PixboPlayer.js',
'resources/assets/js/vendor'
);
/* Fonts */
mix
.copy( 'resources/assets/fonts', 'public/fonts' )
/* Admin GUI */
mix
.sass('app.scss')
.scripts(
[
'jquery-2.1.4.min.js',
'../../../../node_modules/moment/min/moment-with-locales.min.js',
'../../../../node_modules/bootstrap-select/dist/js/bootstrap-select.js',
'bootstrap-datetimepicker.min.js',
'dropzone.js'
],
'public/js/vendor.js',
'resources/assets/js/vendor'
)
.browserify('index.js');
}); | var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix
/* PixboPlayer */
.sass('PixboPlayer.scss')
.scripts(
[
'jquery-2.1.3.min.js',
'vegas.min.js',
'jquery.ticker.js',
'../PixboPlayer.js'
],
'public/js/PixboPlayer.js',
'resources/assets/js/vendor'
)
/* Fonts */
.copy( 'resources/assets/fonts', 'public/fonts' )
/* Admin GUI */
.sass('app.scss')
.scripts(
[
'jquery-2.1.4.min.js',
'../../../../node_modules/moment/min/moment-with-locales.min.js',
'../../../../node_modules/bootstrap-select/dist/js/bootstrap-select.js',
'bootstrap-datetimepicker.min.js',
'dropzone.js'
],
'public/js/vendor.js',
'resources/assets/js/vendor'
)
.browserify('index.js');
}); |
Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch | import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION
# Warning: it doesn't happen in tests but it's useful, do not remove!
auth_header = {}
if 'Authorization' in request.META:
auth_header = {'Authorization': request.META['Authorization']}
elif 'HTTP_AUTHORIZATION' in request.META:
auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
headers=auth_header,
parameters=dict(request.REQUEST.items()),
query_string=request.environ.get('QUERY_STRING', ''))
if oauth_request:
oauth_server = oauth.OAuthServer(DataStore(oauth_request))
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
else:
oauth_server = None
return oauth_server, oauth_request
def send_oauth_error(err=None):
"""Shortcut for sending an error."""
# send a 401 error
response = HttpResponse(err.message.encode('utf-8'), mimetype="text/plain")
response.status_code = 401
# return the authenticate header
realm = getattr(settings, OAUTH_REALM_KEY_NAME, '')
header = oauth.build_authenticate_header(realm=realm)
for k, v in header.iteritems():
response[k] = v
return response
| import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
oauth_request = oauth.OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
headers=request.META,
parameters=dict(request.REQUEST.items()),
query_string=request.environ.get('QUERY_STRING', ''))
if oauth_request:
oauth_server = oauth.OAuthServer(DataStore(oauth_request))
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
else:
oauth_server = None
return oauth_server, oauth_request
def send_oauth_error(err=None):
"""Shortcut for sending an error."""
# send a 401 error
response = HttpResponse(err.message.encode('utf-8'), mimetype="text/plain")
response.status_code = 401
# return the authenticate header
realm = getattr(settings, OAUTH_REALM_KEY_NAME, '')
header = oauth.build_authenticate_header(realm=realm)
for k, v in header.iteritems():
response[k] = v
return response
|
Fix status bar on analysis page | import { List as list } from 'immutable';
import { connect } from 'react-redux';
import { aBlockClicked } from '../../../actions/analysis.actions';
import { aContentBlockHovered } from '../../../actions/content.actions';
import React from 'react';
import PropTypes from 'prop-types';
import BlockPacker from '../../../components/block-packer';
export function Blocks({ pageIndex, active, blocks, deep, status, onClick, onHover }) {
return <BlockPacker
pageIndex={pageIndex}
activeBlock={active}
blocks={blocks}
deepBlock={deep}
status={status}
onClick={onClick}
onHover={onHover} />
}
Blocks.propTypes = {
pageIndex: PropTypes.number.isRequired,
blocks: PropTypes.instanceOf(list),
status: PropTypes.string,
active: PropTypes.array,
deep: PropTypes.string,
onClick: PropTypes.func.isRequired,
onHover: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
active: state.getIn(['other', 'blockView', 'active']),
blocks: state.getIn(['other', 'blockView', 'blocks']),
deep: state.getIn(['other', 'blockView', 'deep']),
status: state.getIn(['other', 'blockView', 'status'])
});
const mapDispatchToProps = dispatch => ({
onClick: req => dispatch(aBlockClicked(req)),
onHover: (block, subBlock) => dispatch(aContentBlockHovered({ block, subBlock }))
});
export default connect(mapStateToProps, mapDispatchToProps)(Blocks);
| import { List as list } from 'immutable';
import { connect } from 'react-redux';
import { aBlockClicked } from '../../../actions/analysis.actions';
import { aContentBlockHovered } from '../../../actions/content.actions';
import React from 'react';
import PropTypes from 'prop-types';
import BlockPacker from '../../../components/block-packer';
export function Blocks({ pageIndex, active, blocks, deep, status, onClick, onHover }) {
return <BlockPacker
pageIndex={pageIndex}
activeBlock={active}
blocks={blocks}
deepBlock={deep}
status={status}
onClick={onClick}
onHover={onHover} />
}
Blocks.propTypes = {
pageIndex: PropTypes.number.isRequired,
blocks: PropTypes.instanceOf(list),
status: PropTypes.string,
active: PropTypes.array,
deep: PropTypes.string,
onClick: PropTypes.func.isRequired,
onHover: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
active: state.getIn(['other', 'blockView', 'active']),
blocks: state.getIn(['other', 'blockView', 'blocks']),
deep: state.getIn(['other', 'blockView', 'deep']),
blockStatus: state.getIn(['other', 'blockView', 'status'])
});
const mapDispatchToProps = dispatch => ({
onClick: req => dispatch(aBlockClicked(req)),
onHover: (block, subBlock) => dispatch(aContentBlockHovered({ block, subBlock }))
});
export default connect(mapStateToProps, mapDispatchToProps)(Blocks);
|
Fix pattern scenario loader test | package website.automate.jwebrobot.loader;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import website.automate.jwebrobot.AbstractTest;
import website.automate.jwebrobot.ConfigurationProperties;
import website.automate.jwebrobot.exceptions.NonReadableFileException;
import java.util.List;
import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class PatternScenarioLoaderIT extends AbstractTest {
@Autowired
private ScenarioLoader scenarioLoader;
@Test
public void loadScenariosFromTheBaseDirectoryRecursively(){
List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader"),
ConfigurationProperties.DEFAULT_REPORT_PATH);
assertThat(scenarioFiles.size(), is(2));
}
@Test
public void loadSingleScenarioFromPath(){
List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader/multi.yaml"),
ConfigurationProperties.DEFAULT_REPORT_PATH);
assertThat(scenarioFiles.size(), is(1));
}
@Test(expected=NonReadableFileException.class)
public void failLoadingNonExistingFile(){
scenarioLoader.load(asList("./src/test/resources/loader/non-existent.yaml"),
ConfigurationProperties.DEFAULT_REPORT_PATH);
}
}
| package website.automate.jwebrobot.loader;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import website.automate.jwebrobot.AbstractTest;
import website.automate.jwebrobot.ConfigurationProperties;
import website.automate.jwebrobot.exceptions.NonReadableFileException;
import java.util.List;
import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class PatternScenarioLoaderIT extends AbstractTest {
@Autowired
private ScenarioLoader scenarioLoader;
@Test
public void loadScenariosFromTheBaseDirectoryRecursively(){
List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader"),
ConfigurationProperties.DEFAULT_REPORT_PATH);
assertThat(scenarioFiles.size(), is(3));
}
@Test
public void loadSingleScenarioFromPath(){
List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader/multi.yaml"),
ConfigurationProperties.DEFAULT_REPORT_PATH);
assertThat(scenarioFiles.size(), is(1));
}
@Test(expected=NonReadableFileException.class)
public void failLoadingNonExistingFile(){
scenarioLoader.load(asList("./src/test/resources/loader/non-existent.yaml"),
ConfigurationProperties.DEFAULT_REPORT_PATH);
}
}
|
fix(grid): Remove whitespace between polygon elements | import React, {PropTypes, Component} from 'react';
import Color from '~/src/tools/Color';
export default class Polygon extends Component {
static propTypes = {
points: PropTypes.array.isRequired,
fillColor: PropTypes.instanceOf(Color).isRequired
}
constructor(props){
super(props);
this.state = {
points: this.props.points,
fillColor: this.props.fillColor
};
}
setFillColor(color){
this.setState({fillColor: color});
}
setPoints(points){
this.setPoints({points: points});
}
componentWillReceiveProps(nextProps){
let nextState = {};
if (nextProps.points){
nextState.points = nextProps.points;
}
if (nextProps.fillColor){
nextState.fillColor = nextProps.fillColor;
}
this.props = nextProps;
this.setState(nextState);
}
render() {
const {points, fillColor} = this.state;
let pointsMapped = points.map((e) => e[0] + ',' + e[1]).join(' ');
return (<polygon
points={pointsMapped}
style={{
fill: fillColor.toHTML(),
stroke: fillColor.toHTML()
}}/>);
}
}
| import React, {PropTypes, Component} from 'react';
import Color from '~/src/tools/Color';
export default class Polygon extends Component {
static propTypes = {
points: PropTypes.array.isRequired,
fillColor: PropTypes.instanceOf(Color).isRequired
}
constructor(props){
super(props);
this.state = {
points: this.props.points,
fillColor: this.props.fillColor
};
}
setFillColor(color){
this.setState({fillColor: color});
}
setPoints(points){
this.setPoints({points: points});
}
componentWillReceiveProps(nextProps){
let nextState = {};
if (nextProps.points){
nextState.points = nextProps.points;
}
if (nextProps.fillColor){
nextState.fillColor = nextProps.fillColor;
}
this.props = nextProps;
this.setState(nextState);
}
render() {
const {points, fillColor} = this.state;
let pointsMapped = points.map((e) => e[0] + ',' + e[1]).join(' ');
return (<polygon
points={pointsMapped}
style={{
fill: fillColor.toHTML()
}}/>);
}
}
|
Add random GT to a given vcf | import pysam
from numpy.random import choice
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype")
new_header.samples.add(sample_name)
default_probs = [1 - default_af * (1 + default_af), default_af, default_af * default_af]
with open(outname, 'w') as out_vcf:
out_vcf.write(str(new_header))
for rec in vcf_pointer.fetch():
rec_copy = rec.copy()
if "GT" not in rec_copy.format.keys():
if "AF" not in rec_copy.info.keys():
gt_probs = default_probs
else:
af = rec_copy.info["AF"]
gt_probs = [1 - af * (1 + af), af, af * af]
c = choice(["0/0", "0/1", "1/1"], p=gt_probs)
out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n")
vcf_pointer.close()
| import pysam
from numpy.random import choice
import math
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype")
new_header.samples.add(sample_name)
default_probs = [1 - default_af - math.pow(default_af, 2), default_af, math.pow(default_af, 2)]
with open(outname, 'w') as out_vcf:
out_vcf.write(str(new_header))
for rec in vcf_pointer.fetch():
rec_copy = rec.copy()
if "GT" not in rec_copy.format.keys():
if "AF" not in rec_copy.info.keys():
gt_probs = default_probs
else:
af = rec_copy.info["AF"]
gt_probs = [1 - af - math.pow(af, 2), af, math.pow(af, 2)]
c = choice(["0/0", "0/1", "1/1"], p=gt_probs)
out_vcf.write("\t".join([str(rec_copy)[:-1], "GT", c]) + "\n")
vcf_pointer.close()
|
Use pysolr instead of haystack in indexing job | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **options):
from parliament.search.models import IndexingTask
delete_tasks = list(
IndexingTask.objects.filter(action='delete')
)
update_tasks = list(
IndexingTask.objects.filter(action='update').prefetch_related('content_object')
)
solr = pysolr.Solr(settings.HAYSTACK_SOLR_URL)
if update_tasks:
update_objs = [t.content_object for t in update_tasks if t.content_object]
update_objs.sort(key=lambda o: o.__class__.__name__)
for cls, objs in itertools.groupby(update_objs, lambda o: o.__class__):
print "Indexing %s" % cls
index = site.get_index(cls)
prepared_objs = [index.prepare(o) for o in objs]
solr.add(prepared_objs)
IndexingTask.objects.filter(id__in=[t.id for t in update_tasks]).delete()
if delete_tasks:
for dt in delete_tasks:
print "Deleting %s" % dt.identifier
solr.delete(id=dt.identifier, commit=False)
solr.commit()
IndexingTask.objects.filter(id__in=[t.id for t in delete_tasks]).delete()
| import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **options):
from parliament.search.models import IndexingTask
delete_tasks = list(
IndexingTask.objects.filter(action='delete')
)
update_tasks = list(
IndexingTask.objects.filter(action='update').prefetch_related('content_object')
)
if update_tasks:
update_objs = [t.content_object for t in update_tasks if t.content_object]
update_objs.sort(key=lambda o: o.__class__.__name__)
for cls, objs in itertools.groupby(update_objs, lambda o: o.__class__):
print "Indexing %s" % cls
index = site.get_index(cls)
index.backend.update(index, list(objs))
IndexingTask.objects.filter(id__in=[t.id for t in update_tasks]).delete()
if delete_tasks:
solr = pysolr.Solr(settings.HAYSTACK_SOLR_URL)
for dt in delete_tasks:
print "Deleting %s" % dt.identifier
solr.delete(id=dt.identifier, commit=False)
solr.commit()
IndexingTask.objects.filter(id__in=[t.id for t in delete_tasks]).delete()
|
Fix initialization of proof of worker index | angular.module('GLBrowserCrypto', [])
.factory('glbcProofOfWork', ['$q', function($q) {
// proofOfWork return the answer to the proof of work
// { [challenge string] -> [ answer index] }
var str2Uint8Array = function(str) {
var result = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
result[i] = str.charCodeAt(i);
}
return result;
};
var getWebCrypto = function() {
if (typeof window !== 'undefined') {
if (window.crypto) {
return window.crypto.subtle || window.crypto.webkitSubtle;
}
if (window.msCrypto) {
return window.msCrypto.subtle;
}
}
};
return {
proofOfWork: function(str) {
var deferred = $q.defer();
var i = 0;
var xxx = function (hash) {
hash = new Uint8Array(hash);
if (hash[31] === 0) {
deferred.resolve(i);
} else {
i += 1;
work();
}
}
var work = function() {
var hashme = str2Uint8Array(str + i);
var damnIE = getWebCrypto().digest({name: "SHA-256"}, hashme);
if (damnIE.then !== undefined) {
damnIE.then(xxx);
} else {
damnIE.oncomplete = function(r) { xxx(r.target.result); };
}
}
work();
return deferred.promise;
}
};
}]);
| angular.module('GLBrowserCrypto', [])
.factory('glbcProofOfWork', ['$q', function($q) {
// proofOfWork return the answer to the proof of work
// { [challenge string] -> [ answer index] }
var str2Uint8Array = function(str) {
var result = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
result[i] = str.charCodeAt(i);
}
return result;
};
var getWebCrypto = function() {
if (typeof window !== 'undefined') {
if (window.crypto) {
return window.crypto.subtle || window.crypto.webkitSubtle;
}
if (window.msCrypto) {
return window.msCrypto.subtle;
}
}
};
return {
proofOfWork: function(str) {
var deferred = $q.defer();
var i;
var xxx = function (hash) {
hash = new Uint8Array(hash);
if (hash[31] === 0) {
deferred.resolve(i);
} else {
i += 1;
work();
}
}
var work = function() {
var hashme = str2Uint8Array(str + i);
var damnIE = getWebCrypto().digest({name: "SHA-256"}, hashme);
if (damnIE.then !== undefined) {
damnIE.then(xxx);
} else {
damnIE.oncomplete = function(r) { xxx(r.target.result); };
}
}
work();
return deferred.promise;
}
};
}]);
|
Add `is_acquired` property to FileLock | # -*- encoding: utf-8 -*-
import os
import fcntl
from tagcache.utils import open_file
class FileLock(object):
def __init__(self, path):
self.path = path
self.fd = None
@property
def is_acquired(self):
return self.fd is not None
def acquire(self, ex=False, nb=False):
"""
Acquire a lock on a path.
:param ex (optional): default False, acquire a exclusive lock if True
:param nb (optional): default False, non blocking if True
:return: True on success
:raise: raise RuntimeError if a lock has been acquired
"""
if self.fd is not None:
raise RuntimeError("A lock has been held")
try:
# open or create the lock file
self.fd = open_file(self.path, os.O_RDWR|os.O_CREAT)
lock_flags = fcntl.LOCK_EX if ex else fcntl.LOCK_SH
if nb:
lock_flags |= fcntl.LOCK_NB
fcntl.flock(self.fd, lock_flags)
return True
except Exception, e:
if self.fd is not None:
os.close(self.fd)
self.fd = None
return False
def release(self):
"""
Release the lock.
"""
if self.fd is None:
return
fcntl.flock(self.fd, fcntl.LOCK_UN)
self.fd = None
| # -*- encoding: utf-8 -*-
import os
import fcntl
from tagcache.utils import open_file
class FileLock(object):
def __init__(self, path):
self.path = path
self.fd = None
def acquire(self, ex=False, nb=False):
"""
Acquire a lock on a path.
:param ex (optional): default False, acquire a exclusive lock if True
:param nb (optional): default False, non blocking if True
:return: True on success
:raise: raise RuntimeError if a lock has been acquired
"""
if self.fd is not None:
raise RuntimeError("A lock has been held")
try:
# open or create the lock file
self.fd = open_file(self.path, os.O_RDWR|os.O_CREAT)
lock_flags = fcntl.LOCK_EX if ex else fcntl.LOCK_SH
if nb:
lock_flags |= fcntl.LOCK_NB
fcntl.flock(self.fd, lock_flags)
return True
except Exception, e:
if self.fd is not None:
os.close(self.fd)
self.fd = None
return False
def release(self):
"""
Release the lock.
"""
if self.fd is None:
return
fcntl.flock(self.fd, fcntl.LOCK_UN)
self.fd = None
|
Support for true as config value (Default config is used if true is passed) | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace abexto\ydc\base\common;
/**
* Abstract Base Class for yDoctrine Components
*
* Component class which implements hierarchical components and is usually used to implement
* configuration wrappers for Doctrine Classes
*
* @author Andreas Prucha, Abexto - Helicon Software Development
*/
abstract class AbstractDoctrineComponent extends \yii\base\Component
{
/**
* @var AbstractDoctrineComponent Parent object. Do not set this value in configuration.
*/
public $parent = null;
public function __construct($config = array())
{
parent::__construct($config === true ? [] : $config);
}
public static function create(AbstractDoctrineComponent $parentObject, $properties = [], $className = null)
{
if (!array_key_exists('class', $properties)) {
if (!$className) {
$className = static::className();
}
} else {
$className = $properties['class'];
unset($properties['class']);
}
$properties['parent'] = $parentObject;
return new $className($properties);
}
/**
* Returns the Root Component
*
* @return \abexto\ydc\base\common\AbstractDoctrineComponent
*/
public function getRootComponent()
{
if (!$this->parent instanceof AbstractDoctrineComponent) {
return $this; // I am the root component ==> RETURN
} else {
return ($this->parent->getRootComponent()); // Ask the Parent and ==> RETURN
}
return NULL;
}
}
| <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace abexto\ydc\base\common;
/**
* Abstract Base Class for yDoctrine Components
*
* Component class which implements hierarchical components and is usually used to implement
* configuration wrappers for Doctrine Classes
*
* @author Andreas Prucha, Abexto - Helicon Software Development
*/
abstract class AbstractDoctrineComponent extends \yii\base\Component
{
/**
* @var AbstractDoctrineComponent Parent object. Do not set this value in configuration.
*/
public $parent = null;
public static function create(AbstractDoctrineComponent $parentObject, $properties = [], $className = null)
{
if (!array_key_exists('class', $properties)) {
if (!$className) {
$className = static::className();
}
} else {
$className = $properties['class'];
unset($properties['class']);
}
$properties['parent'] = $parentObject;
return new $className($properties);
}
/**
* Returns the Root Component
*
* @return \abexto\ydc\base\common\AbstractDoctrineComponent
*/
public function getRootComponent()
{
if (!$this->parent instanceof AbstractDoctrineComponent) {
return $this; // I am the root component ==> RETURN
} else {
return ($this->parent->getRootComponent()); // Ask the Parent and ==> RETURN
}
return NULL;
}
}
|
Return XML path in case of errors | /*
*
* A simple script to create (or print) a JSON file from an XML file
*
*/
var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var output = './';
module.exports = (function () {
this.publishJSON = function (file, outputDir) {
parser.parseString(file, function (err, result) {
if (err) throw err;
var outputFilename = outputDir + file.split(".xml")[0] + '.json';
fs.writeFile(outputFilename, JSON.stringify(result, null, 4), function (err) {
if (err) throw err
console.log("JSON saved to " + outputFilename);
});
});
}
this.convertToJSON = function (file, callBack) {
fs.readFile(file, 'utf-8', function (err, xml) {
if (err) console.log(err)
parser.parseString(xml, function (err, result) {
if (err) callBack({"file": file});
else callBack({"result": result, "file": file});
});
});
}
this.convertToJSONSync = function (file) {
fs.readFile(file, 'utf-8', function (err, xml) {
if (err) console.log(err)
parser.parseString(xml, function (err, result) {
if (err);
else return {"result": result, "file": file};
});
});
}
return this;
})();
| /*
*
* A simple script to create (or print) a JSON file from an XML file
*
*/
var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var output = './';
module.exports = (function () {
this.publishJSON = function (file, outputDir) {
parser.parseString(file, function (err, result) {
if (err) throw err;
var outputFilename = outputDir + file.split(".xml")[0] + '.json';
fs.writeFile(outputFilename, JSON.stringify(result, null, 4), function (err) {
if (err) throw err
console.log("JSON saved to " + outputFilename);
});
});
}
this.convertToJSON = function (file, callBack) {
fs.readFile(file, 'utf-8', function (err, xml) {
if (err) console.log(err)
parser.parseString(xml, function (err, result) {
if (err) callBack("Error!");
else callBack({"result": result, "file": file});
});
});
}
this.convertToJSONSync = function (file) {
fs.readFile(file, 'utf-8', function (err, xml) {
if (err) console.log(err)
parser.parseString(xml, function (err, result) {
if (err);
else return {"result": result, "file": file};
});
});
}
return this;
})();
|
Fix run tests with Celery | #!/usr/bin/env python
import sys
from optparse import OptionParser
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
},
INSTALLED_APPS=[
'django.contrib.contenttypes',
'celery_rpc',
'celery_rpc.tests',
],
ROOT_URLCONF='',
DEBUG=True,
CELERY_RPC_CONFIG = {
'CELERY_ALWAYS_EAGER': True
},
)
from django_nose import NoseTestSuiteRunner
def runtests(*test_args, **kwargs):
if 'south' in settings.INSTALLED_APPS:
from south.management.commands import patch_for_test_db_setup
patch_for_test_db_setup()
if not test_args:
test_args = ['celery_rpc']
test_runner = NoseTestSuiteRunner(**kwargs)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('--verbosity', dest='verbosity', action='store',
default=1, type=int)
parser.add_options(NoseTestSuiteRunner.options)
(options, args) = parser.parse_args()
runtests(*args, **options.__dict__)
| #!/usr/bin/env python
import sys
from optparse import OptionParser
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_celery_rpc',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
},
INSTALLED_APPS=[
'django.contrib.contenttypes',
'celery_rpc',
'celery_rpc.tests',
],
ROOT_URLCONF='',
DEBUG=False,
)
from django_nose import NoseTestSuiteRunner
def runtests(*test_args, **kwargs):
if 'south' in settings.INSTALLED_APPS:
from south.management.commands import patch_for_test_db_setup
patch_for_test_db_setup()
if not test_args:
test_args = ['celery_rpc']
test_runner = NoseTestSuiteRunner(**kwargs)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('--verbosity', dest='verbosity', action='store',
default=1, type=int)
parser.add_options(NoseTestSuiteRunner.options)
(options, args) = parser.parse_args()
runtests(*args, **options.__dict__)
|
Use standard sms: format rather than MozActivity for SMS brick. | module.exports = {
className: 'sms',
template: require('./index.html'),
data: {
name: 'SMS',
icon: '/images/blocks_sms.png',
attributes: {
value: {
label: 'Phone #',
type: 'string',
value: '+18005555555'
},
messageBody: {
label: 'Message',
type: 'string',
value: '',
},
innerHTML: {
label: 'Label',
type: 'string',
value: 'Send SMS'
}
}
},
ready: function () {
var self = this;
self.$el.addEventListener('click', function (e) {
if (self.$parent.$parent.$data.params.mode !== 'play') return;
e.preventDefault();
var number = self.$data.attributes.value.value;
var body = self.$data.attributes.messageBody.value
window.location = 'sms:' + number + '?body=' + body;
});
}
};
| module.exports = {
className: 'sms',
template: require('./index.html'),
data: {
name: 'SMS',
icon: '/images/blocks_sms.png',
attributes: {
value: {
label: 'Phone #',
type: 'string',
value: '+18005555555'
},
messageBody: {
label: 'Message',
type: 'string',
value: '',
},
innerHTML: {
label: 'Label',
type: 'string',
value: 'Send SMS'
}
}
},
ready: function () {
var self = this;
self.$el.addEventListener('click', function (e) {
if (!window.MozActivity) return;
if (self.$parent.$parent.$data.params.mode !== 'play') return;
e.preventDefault();
new MozActivity({
name: 'new',
data: {
type: 'websms/sms',
number: self.$data.attributes.value.value,
body: self.$data.attributes.messageBody.value,
}
});
});
}
};
|
Correct implementation of the while loop | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.GenericInterface()
self.master = pymw.PyMW_Master(mwinterface, delete_files=not debug)
def mine(self, artist):
self.mine_internal(Node(artist, NodeTypes.ARTIST))
(finished_task, new_relationships) = self.master.get_result()
while new_relationships:
for n in new_relationships:
self.relationships.append(n)
if n.get_predicate() not in self.nodes:
self.mine_internal(n.get_predicate())
(finished_task, new_relationships) = self.master.get_result()
def mine_internal(self, current_node, level=0, parent=None, relationship=None):
self.nodes.append(current_node)
infoboxplugin = artgraph.plugins.infobox.InfoboxPlugin(current_node)
self.task_queue.append(self.master.submit_task(infoboxplugin.get_nodes, input_data=(infoboxplugin,), modules=("artgraph",), data_files=("my.cnf",)))
| import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.GenericInterface()
self.master = pymw.PyMW_Master(mwinterface, delete_files=not debug)
def mine(self, artist):
self.mine_internal(Node(artist, NodeTypes.ARTIST))
(finished_task, new_relationships) = self.master.get_result()
while new_relationships:
for n in new_relationships:
self.relationships.append(n)
if n.get_predicate() not in self.nodes:
self.mine_internal(n.get_predicate())
def mine_internal(self, current_node, level=0, parent=None, relationship=None):
self.nodes.append(current_node)
infoboxplugin = artgraph.plugins.infobox.InfoboxPlugin(current_node)
self.task_queue.append(self.master.submit_task(infoboxplugin.get_nodes, input_data=(infoboxplugin,), modules=("artgraph",), data_files=("my.cnf",)))
|
Disable min_priority filter for now | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
mn = state.get_move_number()
if mn == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
tried_count = 0
for pos in p_i:
# create an AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
tried_count += 1
if depth > 3 and tried_count >= 2:
return
def terminal_test(self, state):
return state.terminal()
| #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
mn = state.get_move_number()
if mn == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
if depth > 4:
min_priority = 3
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
tried_count = 0
for pos in p_i:
# create an AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
tried_count += 1
if depth > 3 and tried_count >= 2:
return
def terminal_test(self, state):
return state.terminal()
|
Fix rasterio to version 0.36.0 now that 1.0 is out
There are some incompatibilities between the two. Until I can go to NHM
to upgrade their setup, I'll pin it to the old version. | from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio==0.36.0',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
| from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
|
Remove unicode string markers which are removed in python3 | """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'repositories',
sa.Column('owner_type', sa.Enum('organization', 'user', native_enum=False),
nullable=False)
)
op.add_column(
'repositories',
sa.Column('owner_name', sa.String(), nullable=False)
)
op.add_column(
'repositories',
sa.Column('owner_id', sa.Integer(), nullable=False)
)
op.drop_column('repositories', 'user')
op.create_unique_constraint(
"uq_owner_type_owner_name",
"repositories",
["owner_type", "owner_name"],
)
def downgrade():
op.add_column(
'repositories',
sa.Column('user', sa.String(), nullable=False)
)
op.drop_constraint('uq_owner_type_owner_name', 'repositories', 'unique')
op.drop_column('repositories', 'owner_id')
op.drop_column('repositories', 'owner_name')
op.drop_column('repositories', 'owner_type')
| """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'repositories',
sa.Column('owner_type', sa.Enum('organization', 'user', native_enum=False),
nullable=False)
)
op.add_column(
'repositories',
sa.Column('owner_name', sa.String(), nullable=False)
)
op.add_column(
'repositories',
sa.Column('owner_id', sa.Integer(), nullable=False)
)
op.drop_column('repositories', u'user')
op.create_unique_constraint(
"uq_owner_type_owner_name",
"repositories",
["owner_type", "owner_name"],
)
def downgrade():
op.add_column(
'repositories',
sa.Column(u'user', sa.String(), nullable=False)
)
op.drop_constraint('uq_owner_type_owner_name', 'repositories', 'unique')
op.drop_column('repositories', 'owner_id')
op.drop_column('repositories', 'owner_name')
op.drop_column('repositories', 'owner_type')
|
Fix wrong path to flood data to push. | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for demo purpose only.
"""
help = 'Script to load flood test data for demo purpose only.'
def handle(self, *args, **options):
# Copy file to hazard drop directory
REALTIME_HAZARD_DROP = os.environ.get(
'REALTIME_HAZARD_DROP',
'/home/realtime/hazard-drop/')
hazard_drop_path = mkdtemp(dir=REALTIME_HAZARD_DROP)
hazard_drop_path = os.path.join(
hazard_drop_path, os.path.basename(flood_layer_uri))
print 'Copy flood data to %s' % hazard_drop_path
shutil.copy(flood_layer_uri, hazard_drop_path)
flood_id = '2018022511-6-rw'
print 'Send flood data to InaSAFE Django with flood id = %s' % flood_id
process_flood.delay(
flood_id=flood_id,
data_source='hazard_file',
data_source_args={
'filename': hazard_drop_path
}
)
| # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for demo purpose only.
"""
help = 'Script to load flood test data for demo purpose only.'
def handle(self, *args, **options):
# Copy file to hazard drop directory
REALTIME_HAZARD_DROP = os.environ.get(
'REALTIME_HAZARD_DROP',
'/home/realtime/hazard-drop/')
hazard_drop_path = mkdtemp(dir=REALTIME_HAZARD_DROP)
hazard_drop_path = os.path.join(
hazard_drop_path, os.path.basename(flood_layer_uri))
print 'Copy flood data to %s' % hazard_drop_path
shutil.copy(flood_layer_uri, hazard_drop_path)
flood_id = '2018022511-6-rw'
print 'Send flood data to InaSAFE Django with flood id = %s' % flood_id
process_flood.delay(
flood_id=flood_id,
data_source='hazard_file',
data_source_args={
'filename': flood_layer_uri
}
)
|
Remove modal padding around rebuild change list | import React from "react";
import { map, sortBy } from "lodash-es";
import { Row, Col, ListGroup, ListGroupItem, Panel } from "react-bootstrap";
import { LoadingPlaceholder } from "../../base";
export default function RebuildHistory ({ unbuilt, error }) {
const extraChanges = unbuilt.page_count > 1
? (
<ListGroupItem key="last-item">
<div style={{textAlign: "right"}}>
+ {unbuilt.total_count - unbuilt.per_page} more changes
</div>
</ListGroupItem>
) : null;
let content;
if (unbuilt === null) {
content = <LoadingPlaceholder margin="22px" />;
} else {
const historyComponents = map(sortBy(unbuilt.documents, "otu.name"), change =>
<ListGroupItem key={change.id}>
<Row>
<Col md={5}>
<strong>{change.otu.name}</strong>
</Col>
<Col md={7}>
{change.description || "No Description"}
</Col>
</Row>
</ListGroupItem>
);
content = (
<ListGroup style={{overflowY: "auto", maxHeight: "700px"}}>
{historyComponents}
{extraChanges}
</ListGroup>
);
}
const panelStyle = error ? "panel-danger" : "panel-default";
return (
<Panel className={panelStyle}>
<Panel.Heading>Changes</Panel.Heading>
{content}
</Panel>
);
}
| import React from "react";
import { map, sortBy } from "lodash-es";
import { Row, Col, ListGroup, ListGroupItem, Panel } from "react-bootstrap";
import { LoadingPlaceholder } from "../../base";
export default function RebuildHistory ({ unbuilt, error }) {
const extraChanges = unbuilt.page_count > 1
? (
<ListGroupItem key="last-item">
<div style={{textAlign: "right"}}>
+ {unbuilt.total_count - unbuilt.per_page} more changes
</div>
</ListGroupItem>
) : null;
let content;
if (unbuilt === null) {
content = <LoadingPlaceholder margin="22px" />;
} else {
const historyComponents = map(sortBy(unbuilt.documents, "otu.name"), change =>
<ListGroupItem key={change.id}>
<Row>
<Col md={5}>
<strong>{change.otu.name}</strong>
</Col>
<Col md={7}>
{change.description || "No Description"}
</Col>
</Row>
</ListGroupItem>
);
content = (
<ListGroup style={{overflowY: "auto", maxHeight: "700px"}}>
{historyComponents}
{extraChanges}
</ListGroup>
);
}
const panelStyle = error ? "panel-danger" : "panel-default";
return (
<Panel className={panelStyle}>
<Panel.Heading>Changes</Panel.Heading>
<Panel.Body>
{content}
</Panel.Body>
</Panel>
);
}
|
Fix to ensure the unsubscribe on next operator used for database queries can be reused | package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu ([email protected])
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public void onCompleted() {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onCompleted();
}
}
}
@Override
public void onError(Throwable e) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onError(e);
}
}
}
@Override
public void onNext(T t) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
try {
subscriber.onNext(t);
subscriber.onCompleted();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
subscriber.onError(e);
}
}
}
}
};
}
}
| package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu ([email protected])
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
private final AtomicBoolean completed = new AtomicBoolean();
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
@Override
public void onCompleted() {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onCompleted();
}
}
}
@Override
public void onError(Throwable e) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
subscriber.onError(e);
}
}
}
@Override
public void onNext(T t) {
this.unsubscribe();
if (!subscriber.isUnsubscribed()) {
if (completed.compareAndSet(false, true)) {
try {
subscriber.onNext(t);
subscriber.onCompleted();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
subscriber.onError(e);
}
}
}
}
};
}
}
|
Make the irrelevant object a constant | IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __enter__(self):
self.before = self.__apply()
if not self.expected_before is IRRELEVANT:
check = self.before == self.expected_before
assert check, self.__precondition_failure_msg_for('before')
def __exit__(self, type, value, traceback):
self.after = self.__apply()
if not self.expected_after is IRRELEVANT:
check = self.after == self.expected_after
assert check, self.__precondition_failure_msg_for('after')
assert self.before != self.after, self.__equality_failure_message
def __apply(self):
return self.thing(*self.args, **self.kwargs)
@property
def __equality_failure_message(self):
return 'Expected before %s != %s after' % (self.before, self.after)
def __precondition_failure_msg_for(self, condition):
return '%s value did not change (%s)' % (
condition,
getattr(self, condition)
)
class AssertsMixin(object):
assertChanges = ChangeWatcher
| irrelevant = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', irrelevant)
self.expected_after = kwargs.pop('after', irrelevant)
def __enter__(self):
self.before = self.__apply()
if not self.expected_before is irrelevant:
check = self.before == self.expected_before
assert check, self.__precondition_failure_msg_for('before')
def __exit__(self, type, value, traceback):
self.after = self.__apply()
if not self.expected_after is irrelevant:
check = self.after == self.expected_after
assert check, self.__precondition_failure_msg_for('after')
assert self.before != self.after, self.__equality_failure_message
def __apply(self):
return self.thing(*self.args, **self.kwargs)
@property
def __equality_failure_message(self):
return 'Expected before %s != %s after' % (self.before, self.after)
def __precondition_failure_msg_for(self, condition):
return '%s value did not change (%s)' % (
condition,
getattr(self, condition)
)
class AssertsMixin(object):
assertChanges = ChangeWatcher
|
Make commit_on_http_success commit for status codes from 200 to 399 and not only with 200
Signed-off-by: Álvaro Arranz García <[email protected]> | from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success response. This way, if the
view function return a success reponse, a commit is made; if the viewfunc
produces an exception or return an error response, a rollback is made.
"""
if using is None:
using = DEFAULT_DB_ALIAS
def wrapped_func(*args, **kwargs):
enter_transaction_management(using=using)
managed(True, using=using)
try:
res = func(*args, **kwargs)
except:
if is_dirty(using=using):
rollback(using=using)
raise
else:
if is_dirty(using=using):
if not isinstance(res, HttpResponse) or res.status_code < 200 or res.status_code >= 400:
rollback(using=using)
else:
try:
commit(using=using)
except:
rollback(using=using)
raise
leave_transaction_management(using=using)
return res
return wrapped_func
| from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success response. This way, if the
view function return a success reponse, a commit is made; if the viewfunc
produces an exception or return an error response, a rollback is made.
"""
if using is None:
using = DEFAULT_DB_ALIAS
def wrapped_func(*args, **kwargs):
enter_transaction_management(using=using)
managed(True, using=using)
try:
res = func(*args, **kwargs)
except:
if is_dirty(using=using):
rollback(using=using)
raise
else:
if is_dirty(using=using):
if not isinstance(res, HttpResponse) or res.status_code > 200 or res.status_code < 200:
rollback(using=using)
else:
try:
commit(using=using)
except:
rollback(using=using)
raise
leave_transaction_management(using=using)
return res
return wrapped_func
|
Remove trailing slash in GitLab url
Signed-off-by: kfei <[email protected]> | app
.factory("gitlab",
["$http", "$q", "Config",
function($http, $q, Config) {
function gitlab() {}
gitlab.prototype.imageUrl = function(path) {
return Config.gitlabUrl.replace(/\/*$/, "") + path;
};
gitlab.prototype.callapi = function(method, path) {
var deferred = $q.defer();
var url = Config.gitlabUrl.replace(/\/*$/, "") + '/api/v3' + path;
$http({
url: url,
method: method,
headers: {
'SUDO': 'root',
'PRIVATE-TOKEN': Config.gitlabToken
}
})
.success(function(data, status, headers, config) {
deferred.resolve({
data: data,
status: status,
headers: headers,
config: config
});
})
.error(function(data, status, headers, config) {
deferred.reject({
data: data,
status: status,
headers: headers,
config: config
});
});
return deferred.promise;
};
return new gitlab();
}])
;
| app
.factory("gitlab",
["$http", "$q", "Config",
function($http, $q, Config) {
function gitlab() {}
gitlab.prototype.imageUrl = function(path) {
return Config.gitlabUrl + path;
};
gitlab.prototype.callapi = function(method, path) {
var deferred = $q.defer();
var url = Config.gitlabUrl.replace(/\/*$/, "") + '/api/v3' + path;
$http({
url: url,
method: method,
headers: {
'SUDO': 'root',
'PRIVATE-TOKEN': Config.gitlabToken
}
})
.success(function(data, status, headers, config) {
deferred.resolve({
data: data,
status: status,
headers: headers,
config: config
});
})
.error(function(data, status, headers, config) {
deferred.reject({
data: data,
status: status,
headers: headers,
config: config
});
});
return deferred.promise;
};
return new gitlab();
}])
;
|
Fix Installation Issues -> missing Boto3 | import setuptools
import codecs
import os.path
# Used to read the file
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
# Used to extract out the __version__
def get_version(rel_path):
for line in read(rel_path).splitlines():
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
else:
raise RuntimeError("Unable to find version string.")
# Used to read the readme file
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="NearBeach",
version=get_version('NearBeach/__init__.py'),
author="Luke Christopher Clarke",
author_email="[email protected]",
description="NearBeach - an open source project management tool",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/robotichead/NearBeach",
packages=setuptools.find_packages(),
install_requires=[
'django',
'simplejson',
'pillow',
'urllib3',
'boto3',
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
include_package_data=True,
)
| import setuptools
import codecs
import os.path
# Used to read the file
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
# Used to extract out the __version__
def get_version(rel_path):
for line in read(rel_path).splitlines():
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
else:
raise RuntimeError("Unable to find version string.")
# Used to read the readme file
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="NearBeach",
version=get_version('NearBeach/__init__.py'),
author="Luke Christopher Clarke",
author_email="[email protected]",
description="NearBeach - an open source project management tool",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/robotichead/NearBeach",
packages=setuptools.find_packages(),
install_requires=[
'django',
'simplejson',
'pillow',
'urllib3',
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
include_package_data=True,
)
|
Add tests for admin client models | /* global ic */
var ajax = function () {
return ic.ajax.request.apply(null, arguments);
};
// Used in API request fail handlers to parse a standard api error
// response json for the message to display
function getRequestErrorMessage(request, performConcat) {
var message,
msgDetail;
// Can't really continue without a request
if (!request) {
return null;
}
// Seems like a sensible default
message = request.statusText;
// If a non 200 response
if (request.status !== 200) {
try {
// Try to parse out the error, or default to 'Unknown'
if (request.responseJSON.errors && Ember.isArray(request.responseJSON.errors)) {
message = request.responseJSON.errors.map(function (errorItem) {
return errorItem.message;
});
} else {
message = request.responseJSON.error || 'Unknown Error';
}
} catch (e) {
msgDetail = request.status ? request.status + ' - ' + request.statusText : 'Server was not available';
message = 'The server returned an error (' + msgDetail + ').';
}
}
if (performConcat && Ember.isArray(message)) {
message = message.join('<br />');
}
// return an array of errors by default
if (!performConcat && typeof message === 'string') {
message = [message];
}
return message;
}
export {getRequestErrorMessage, ajax};
export default ajax;
| /* global ic */
var ajax = window.ajax = function () {
return ic.ajax.request.apply(null, arguments);
};
// Used in API request fail handlers to parse a standard api error
// response json for the message to display
function getRequestErrorMessage(request, performConcat) {
var message,
msgDetail;
// Can't really continue without a request
if (!request) {
return null;
}
// Seems like a sensible default
message = request.statusText;
// If a non 200 response
if (request.status !== 200) {
try {
// Try to parse out the error, or default to 'Unknown'
if (request.responseJSON.errors && Ember.isArray(request.responseJSON.errors)) {
message = request.responseJSON.errors.map(function (errorItem) {
return errorItem.message;
});
} else {
message = request.responseJSON.error || 'Unknown Error';
}
} catch (e) {
msgDetail = request.status ? request.status + ' - ' + request.statusText : 'Server was not available';
message = 'The server returned an error (' + msgDetail + ').';
}
}
if (performConcat && Ember.isArray(message)) {
message = message.join('<br />');
}
// return an array of errors by default
if (!performConcat && typeof message === 'string') {
message = [message];
}
return message;
}
export {getRequestErrorMessage, ajax};
export default ajax;
|
Add send() method to chat object. | <?php
namespace MinePlus\WebSocketBundle;
use Symfony\Component\Console\Output\OutputInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
protected $output;
public function __construct(OutputInterface $output)
{
$this->clients = new \SplObjectStorage;
$this->output = $output;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
$this->output->writeln('New Connection: '.$conn->resourceId);
}
public function onMessage(ConnectionInterface $from, $msg)
{
$this->output->writeln($from->resourceId.': '.$msg);
$this->broadcast($msg);
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
$this->output->writeln('Lost Connection: '.$conn->resourceId);
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
$conn->close();
}
private function broadcast($msg, $exception = null)
{
foreach ($this->clients as $client)
{
if ($exception != $client) $client->send($msg);
}
}
private function send($client, $msg)
{
if (is_object($client)) {
$client->send($msg);
} else if (is_int($client)) {
foreach ($this->clients as $c) {
if ($c->resourceId == $client) {
$c->send($msg);
}
}
}
}
}
?>
| <?php
namespace MinePlus\WebSocketBundle;
use Symfony\Component\Console\Output\OutputInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
protected $output;
public function __construct(OutputInterface $output)
{
$this->clients = new \SplObjectStorage;
$this->output = $output;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
$this->output->writeln('New Connection: '.$conn->resourceId);
}
public function onMessage(ConnectionInterface $from, $msg)
{
$this->output->writeln($from->resourceId.': '.$msg);
$this->broadcast($msg);
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
$this->output->writeln('Lost Connection: '.$conn->resourceId);
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
$conn->close();
}
private function broadcast($msg, $exception = null)
{
foreach ($this->clients as $client)
{
if ($exception != $client) $client->send($msg);
}
}
}
?>
|
Add CSS for moving cards down a little | 'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
e.style.display = 'table-cell';
} else {
e.style.display = 'none';
}
});
}
window.addEventListener ('load', myMain, false);
function myMain (evt) {
var jsInitChecktimer = setInterval (checkForDomReady, 111);
function checkForDomReady () {
var selector = jQuery('#ghx-column-headers > li.ghx-column');
if (selector) {
selector.append(function() {
return jQuery('<a href="#" class="column-header-hider"><i class="aui-icon aui-icon-small aui-iconfont-remove-label ghx-iconfont"></i></a>')
.click(function() {
var col = jQuery(this).parent().data('id');
toggle_visibility('[data-id="'+col+'"]');
toggle_visibility('[data-column-id="'+col+'"]');
});
});
clearInterval(jsInitChecktimer);
}
var somePadding = jQuery('.ghx-wrap-issue');
if(somePadding){
somePadding.css('padding-top','20px');
}
}
}
| 'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
e.style.display = 'table-cell';
} else {
e.style.display = 'none';
}
});
}
window.addEventListener ('load', myMain, false);
function myMain (evt) {
var jsInitChecktimer = setInterval (checkForDomReady, 111);
function checkForDomReady () {
var selector = jQuery('#ghx-column-headers > li.ghx-column');
if (selector) {
selector.append(function() {
return jQuery('<a href="#" class="column-header-hider"><i class="aui-icon aui-icon-small aui-iconfont-remove-label ghx-iconfont"></i></a>')
.click(function() {
var col = jQuery(this).parent().data('id');
toggle_visibility('[data-id="'+col+'"]');
toggle_visibility('[data-column-id="'+col+'"]');
});
});
clearInterval(jsInitChecktimer);
}
}
}
|
Check whether a layer existing on the map before trying to add it | const addPaintOptions = (options, layer) => {
if (layer.isPoint) {
options['type'] = 'circle'
options['paint'] = {
'circle-radius': [
'interpolate',
['exponential', 1],
['zoom'],
0, 1.5,
6, 4
],
'circle-color': layer.color,
'circle-opacity': 0.7
}
} else {
options['type'] = 'fill'
options['paint'] = {
'fill-color': layer.color,
'fill-opacity': 0.8,
}
}
}
export default {
methods: {
addRasterTileLayer (layer) {
if(!this.hasExistingMapLayer(layer.id)) {
this.map.addLayer({
id: layer.id,
type: 'raster',
minzoom: 0,
maxzoom: 22,
source: {
type: 'raster',
tiles: [layer.url],
tileSize: 256,
},
layout: {
visibility: 'visible'
}
}, this.firstForegroundLayerId)
}
},
addRasterDataLayer(layer) {
if(!this.hasExistingMapLayer(layer.id)) {
const options = {
id: layer.id,
source: {
type: 'geojson',
data: layer.url
},
layout: {
visibility: 'visible'
}
}
addPaintOptions(options, layer)
this.map.addLayer(options, this.firstForegroundLayerId)
}
},
hasExistingMapLayer (id) {
const existingMapLayer = this.map.getLayer(id)
return typeof existingMapLayer !== 'undefined'
}
},
}
| const addPaintOptions = (options, layer) => {
if (layer.isPoint) {
options['type'] = 'circle'
options['paint'] = {
'circle-radius': [
'interpolate',
['exponential', 1],
['zoom'],
0, 1.5,
6, 4
],
'circle-color': layer.color,
'circle-opacity': 0.7
}
} else {
options['type'] = 'fill'
options['paint'] = {
'fill-color': layer.color,
'fill-opacity': 0.8,
}
}
}
export default {
methods: {
addRasterTileLayer (layer) {
this.map.addLayer({
id: layer.id,
type: 'raster',
minzoom: 0,
maxzoom: 22,
source: {
type: 'raster',
tiles: [layer.url],
tileSize: 256,
},
layout: {
visibility: 'visible'
}
}, this.firstForegroundLayerId)
},
addRasterDataLayer(layer) {
const options = {
id: layer.id,
source: {
type: 'geojson',
data: layer.url
},
layout: {
visibility: 'visible'
}
}
addPaintOptions(options, layer)
console.log('Adding data layer:', layer, options, this.firstForegroundLayerId)
this.map.addLayer(options, this.firstForegroundLayerId)
},
},
}
|
Change download url for release 0.3.6 | from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.6',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = '[email protected]',
url = 'https://github.com/hspandher/django-test-utils',
download_url = 'https://github.com/hspandher/django-test-utils/tarball/0.3.6',
keywords = ['testing', 'django', 'mongo', 'redis', 'neo4j', 'TDD', 'python', 'memcache', 'django rest framework'],
license = 'MIT',
install_requires = [
'django>1.6'
],
extras_require = {
'mongo_testing': ['mongoengine>=0.8.7'],
'redis_testing': ['django-redis>=3.8.2'],
'neo4j_testing': ['py2neo>=2.0.6'],
'rest_framework_testing': ['djangorestframework>=3.0.5'],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
'Topic :: Database',
],
)
| from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.5',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = '[email protected]',
url = 'https://github.com/hspandher/django-test-utils',
download_url = 'https://github.com/hspandher/django-test-utils/tarball/0.1',
keywords = ['testing', 'django', 'mongo', 'redis', 'neo4j', 'TDD', 'python', 'memcache', 'django rest framework'],
license = 'MIT',
install_requires = [
'django>1.6'
],
extras_require = {
'mongo_testing': ['mongoengine>=0.8.7'],
'redis_testing': ['django-redis>=3.8.2'],
'neo4j_testing': ['py2neo>=2.0.6'],
'rest_framework_testing': ['djangorestframework>=3.0.5'],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
'Topic :: Database',
],
)
|
Add support for lenient reading where reading too much is full of zeros. | package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
public class ReadLenientTest {
@Test
public void testLenient() {
doTest(Bytes.allocateDirect(64));
doTest(Bytes.elasticHeapByteBuffer(64));
doTest(Bytes.from(""));
}
private void doTest(Bytes bytes) {
bytes.lenient(true);
ByteBuffer bb = ByteBuffer.allocateDirect(32);
bytes.read(bb);
assertEquals(0, bb.position());
assertEquals(BigDecimal.ZERO, bytes.readBigDecimal());
assertEquals(BigInteger.ZERO, bytes.readBigInteger());
assertEquals(false, bytes.readBoolean());
assertEquals(null, bytes.read8bit());
assertEquals(null, bytes.readUtf8());
assertEquals(0, bytes.readByte());
assertEquals(-1, bytes.readUnsignedByte()); // note this behaviour is need to find the end of a stream.
assertEquals(0, bytes.readShort());
assertEquals(0, bytes.readUnsignedShort());
assertEquals(0, bytes.readInt());
assertEquals(0, bytes.readUnsignedInt());
assertEquals(0.0, bytes.readFloat(), 0.0);
assertEquals(0.0, bytes.readDouble(), 0.0);
bytes.release();
}
}
| package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
public class ReadLenientTest {
@Test
public void testLenient() {
doTest(Bytes.allocateDirect(64));
doTest(Bytes.elasticHeapByteBuffer(64));
doTest(Bytes.from(""));
}
private void doTest(Bytes bytes) {
bytes.lenient(true);
ByteBuffer bb = ByteBuffer.allocateDirect(32);
bytes.read(bb);
assertEquals(0, bb.position());
assertEquals(BigDecimal.ZERO, bytes.readBigDecimal());
assertEquals(BigInteger.ZERO, bytes.readBigInteger());
assertEquals(false, bytes.readBoolean());
assertEquals(null, bytes.read8bit());
assertEquals(null, bytes.readUtf8());
assertEquals(0, bytes.readByte());
assertEquals(-1, bytes.readUnsignedByte()); // note this behaviour is need to find the end of a stream.
assertEquals(0, bytes.readShort());
assertEquals(0, bytes.readUnsignedShort());
assertEquals(0, bytes.readInt());
assertEquals(0, bytes.readUnsignedInt());
assertEquals(0.0, bytes.readFloat(), 0.0);
assertEquals(0.0, bytes.readDouble(), 0.0);
}
}
|
Add the flatten option for bar chart with numbers
Module appears to work in exactly the same way after doing this | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || 'uniqueEvents:sum';
var options = {
valueAttr: valueAttr,
axisPeriod: this.model.get('axis-period') || 'week'
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options['dataSource'] = _.extend({}, this.model.get('data-source'), {'query-params': _.extend({'flatten': true}, this.model.get('data-source')['query-params'])});
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
valueAttr: 'uniqueEvents',
formatOptions: this.model.get('format'),
maxBars: 6
};
}
};
});
| define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || 'uniqueEvents:sum';
var options = {
valueAttr: valueAttr,
axisPeriod: this.model.get('axis-period') || 'week'
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
valueAttr: 'uniqueEvents',
formatOptions: this.model.get('format'),
maxBars: 6
};
}
};
});
|
Raise version and change keywords for upcoming release | from setuptools import setup, find_packages
import os
version = '0.5'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description="Admin Controller add-on for basic TG identity model.",
long_description=README + "\n" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin',
author='Christopher Perkins',
author_email='[email protected]',
url='tgtools.googlecode.com',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'tgext.crud>=0.4',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
import os
version = '0.4'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description="Admin Controller add-on for basic TG identity model.",
long_description=README + "\n" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='TG2, TG, sprox, Rest, internet, adminn',
author='Christopher Perkins',
author_email='[email protected]',
url='tgtools.googlecode.com',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'tgext.crud>=0.4',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Fix error typo and changed post request to use expected request body | import { EventEmitter } from 'events'
import axios from 'axios'
export default class RoomService extends EventEmitter {
constructor() {
super()
}
addRoom(timeslots) {
this.createRoom(room, this.hasBeenAdded.bind(this), this.getThem.bind(this))
}
getThem(userid) {
this.getRooms(userid, this.gotthem.bind(this))
}
createRoom(interviewer, roomid, callback) {
axios.post('/api/Meeting', {
owner_id: interviewer,
job_position: 'janitor'
})
.then(function (response) {
console.log(response)
callback()
})
.catch(function (error) {
console.log(error);
});
}
getRooms(userid, callback) {
axios.get('/api/Meeting', {
params: {
owner_id: userid
}
})
.then(function (response) {
response.data.forEach(function(slot) {
slot.start = new Date(slot.start)
slot.end = new Date(slot.end)
})
callback(response)
//this.gotthem(reponse).bind(this)
console.log('got slots', response);
console.log('got slots', response.data);
})
.catch(function (error) {
console.log(error);
});
}
hasBeenAdded(slots) {
this.emit('rooms_added', slots)
}
gotthem(slots) {
this.emit('got_rooms', slots)
}
}
| import { EventEmitter } from 'events'
import axios from 'axios'
export default class RoomService extends EventEmitter {
constructor() {
super()
}
addRoom(timeslots) {
this.createRoom(room, this.hasBeenAdded.bind(this), this.getThem.bind(this))
}
getThem(userid) {
this.getRooms(userid, this.gotthem.bind(this))
}
createRoom(interviewer, roomid, callback) {
axios.post('/api/Meeting', {
owner_id: interviewer,
room_url:,
time:
})
.then(function (response) {
console.log(response)
callback()
})
.catch(function (error) {
console.log(error);
});
}
getRooms(userid, callback) {
axios.get('/api/Meeting', {
params: {
owner_id: userid
}
})
.then(function (response) {
response.data.forEach(function(slot) {
slot.start = new Date(slot.start)
slot.end = new Date(slot.end)
})
callback(response)
//this.gotthem(reponse).bind(this)
console.log('got slots', response);
console.log('got slots', response.data);
})
.catch(function (error) {
console.log(error);
});
}
hasBeenAdded(slots) {
this.emit('rooms_added', slots)
}
gotthem(slots) {
this.emit('got_rooms', slots)
}
}
|
Fix bug with composed variants without parent context | import React from 'react';
import PropTypes from 'prop-types';
import { CONTEXT_KEY, contextType } from './connectVariants';
import _ from 'lodash';
export default class VariantProvider extends React.Component {
static propTypes = {
variants: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]),
compose: PropTypes.bool,
};
static defaultProps = {
compose: false,
};
static childContextTypes = {
[CONTEXT_KEY]: contextType,
};
getChildContext() {
if (this.props.compose) {
const parentVariants = this.context[CONTEXT_KEY]
? this.context[CONTEXT_KEY].variants
: {};
return {
[CONTEXT_KEY]: {
variants: [...parentVariants, ...this.getVariantArray()],
},
};
}
return {
[CONTEXT_KEY]: {
variants: this.getVariantArray(),
},
};
}
getVariantArray = () => {
if (_.isArray(this.props.variants)) {
return this.props.variants;
}
return [this.props.variants];
};
render() {
return React.Children.only(this.props.children);
}
}
export const asVariant = (
variants = ['default'],
compose = false,
) => WrappedComponent => props => (
<VariantProvider variants={variants} compose={compose}>
<WrappedComponent {...props} />
</VariantProvider>
);
| import React from 'react';
import PropTypes from 'prop-types';
import { CONTEXT_KEY, contextType } from './connectVariants';
import _ from 'lodash';
export default class VariantProvider extends React.Component {
static propTypes = {
variants: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]),
compose: PropTypes.bool,
};
static defaultProps = {
compose: false,
};
static childContextTypes = {
[CONTEXT_KEY]: contextType,
};
getChildContext() {
if (this.props.compose) {
return {
[CONTEXT_KEY]: {
variants: [
...this.context[CONTEXT_KEY].variants,
...this.getVariantArray(),
],
},
};
}
return {
[CONTEXT_KEY]: {
variants: this.getVariantArray(),
},
};
}
getVariantArray = () => {
if (_.isArray(this.props.variants)) {
return this.props.variants;
}
return [this.props.variants];
};
render() {
return React.Children.only(this.props.children);
}
}
export const asVariant = (
variants = ['default'],
compose = false,
) => WrappedComponent => props => (
<VariantProvider variants={variants} compose={compose}>
<WrappedComponent {...props} />
</VariantProvider>
);
|
Clone object before processing JSON |
/**
*
*
* @param {object} object The output from Alpaca
* @return {object} A corrected version of the output. This should be a
* valid Swagger spec.
*/
module.exports = function processJSON (objectFuncParam) {
const object = JSON.parse(JSON.stringify(objectFuncParam));
if (object.paths) {
/*
* Take all elements in the methods array and put them in the parent path
* element with `methodName` as the key and the method object as the value.
*/
Object.keys(object.paths).forEach((key) => {
const path = object.paths[key];
path.methods.forEach((method) => {
const methodName = method.methodName;
// Ignore if method is not set or if path already has the same method.
if (methodName === undefined || {}.hasOwnProperty.call(path, methodName)) {
return;
}
// Delete the key from the method object.
const methodObj = method;
delete methodObj.methodName;
// Set the method object as a child of the path object.
path[methodName] = method;
});
// Delete the old list as it isn't actually a part of the Swagger spec
delete path.methods;
});
} else {
object.paths = {};
}
if (object.security) {
/*
* Put the `value` field of each security object as the actual value of the
* object.
*/
Object.keys(object.security).forEach((key) => {
object.security[key] = object.security[key].value;
});
}
return object;
};
|
/**
*
*
* @param {object} object The output from Alpaca
* @return {object} A corrected version of the output. This should be a
* valid Swagger spec.
*/
module.exports = function processJSON (objectFuncParam) {
const object = objectFuncParam;
if (object.paths) {
/*
* Take all elements in the methods array and put them in the parent path
* element with `methodName` as the key and the method object as the value.
*/
Object.keys(object.paths).forEach((key) => {
const path = object.paths[key];
path.methods.forEach((method) => {
const methodName = method.methodName;
// Ignore if method is not set or if path already has the same method.
if (methodName === undefined || {}.hasOwnProperty.call(path, methodName)) {
return;
}
// Delete the key from the method object.
const methodObj = method;
delete methodObj.methodName;
// Set the method object as a child of the path object.
path[methodName] = method;
});
// Delete the old list as it isn't actually a part of the Swagger spec
delete path.methods;
});
} else {
object.paths = {};
}
if (object.security) {
/*
* Put the `value` field of each security object as the actual value of the
* object.
*/
Object.keys(object.security).forEach((key) => {
object.security[key] = object.security[key].value;
});
}
return object;
};
|
Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage | from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return self.file.file.storage.exists(self.file.path)
def get_file_name(self):
if self.file.name in ('', None):
name = u"%s" % (self.file.original_filename,)
else:
name = u"%s" % (self.file.name,)
return name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
| from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return exists(self.file.path)
def get_file_name(self):
return self.file.name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
|
Use different TED talk - don't load insecure images. | <div id="mainWrapper" class="dark-bg">
<div id="header" >
<div class="row center-text">
<div class="small-12 columns">
<h1>You have reached Kyle's website.</h1>
</div>
</div>
</div>
<div id="content">
<div class="row center-text">
<div class="small-12 columns">
<h3>Enjoy one of my favorite TED talks</h3>
<hr>
</div>
</div>
<div class="row center-text">
<div class="small-12 columns">
<div class="flex-video widescreen">
<iframe width="853" height="480" src="https://www.youtube-nocookie.com/embed/qp0HIF3SfI4?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div id="footer">
<?php include_once "$docRoot/include/footer.php"; ?>
</div>
</div>
| <div id="mainWrapper" class="dark-bg">
<div id="header" >
<div class="row center-text">
<div class="small-12 columns">
<h1>You have reached Kyle's website.</h1>
</div>
</div>
</div>
<div id="content">
<div class="row center-text">
<div class="small-12 columns">
<h3>Enjoy one of my favorite TED talks</h3>
<hr>
</div>
</div>
<div class="row center-text">
<div class="small-12 columns">
<div class="flex-video widescreen vimeo">
<iframe src="https://embed-ssl.ted.com/talks/benjamin_zander_on_music_and_passion.html" width="854" height="480" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</div>
</div>
</div>
</div>
<div id="footer">
<?php include_once "$docRoot/include/footer.php"; ?>
</div>
</div>
|
Fix class name in annotation | <?php
namespace HostBox\Components;
use Nette;
/**
* Class ComponentFactory
* @package HostBox\Components
*/
abstract class ComponentFactory extends Nette\Object {
/** @var mixed */
protected $config;
/** @var array */
protected $plugins;
public function __call($name, $args) {
if (substr($name, 0, 6) == 'create' && strlen($name) > 6) {
if ($this->config === NULL)
throw new Nette\MemberAccessException('Config is not set');
$name = substr($name, -(strlen($name) - 6));
/** @var Nette\Reflection\ClassType $calledClass */
$calledClass = get_called_class();
$reflection = $calledClass::getReflection();
$namespace = $reflection->getNamespaceName();
$componentName = $namespace . '\\' . $name;
/** @var ISocialPluginComponent $component */
$component = new $componentName($this->config);
if (!empty($args) && is_array($settings = $args[0])) {
$component->assign($settings);
}
return $component;
} else {
throw new Nette\MemberAccessException(sprintf('%s is not create method', $name));
}
}
}
| <?php
namespace HostBox\Components;
use Nette;
/**
* Class SocialPluginComponent
* @package HostBox\Components
*/
abstract class ComponentFactory extends Nette\Object {
/** @var mixed */
protected $config;
/** @var array */
protected $plugins;
public function __call($name, $args) {
if (substr($name, 0, 6) == 'create' && strlen($name) > 6) {
if ($this->config === NULL)
throw new Nette\MemberAccessException('Config is not set');
$name = substr($name, -(strlen($name) - 6));
/** @var Nette\Reflection\ClassType $calledClass */
$calledClass = get_called_class();
$reflection = $calledClass::getReflection();
$namespace = $reflection->getNamespaceName();
$componentName = $namespace . '\\' . $name;
/** @var ISocialPluginComponent $component */
$component = new $componentName($this->config);
if (!empty($args) && is_array($settings = $args[0])) {
$component->assign($settings);
}
return $component;
} else {
throw new Nette\MemberAccessException(sprintf('%s is not create method', $name));
}
}
}
|
Use util.inherits instead of simple prototype assignment. | var RedisStore = require('connect-redis');
var url = require('url');
var util = require('util');
var envVariables = ['REDIS_SESSION_URI', 'REDIS_URI', 'REDIS_SESSION_URL', 'REDIS_URL', 'REDISTOGO_URL', 'OPENREDIS_URL'];
var fallback = 'redis://localhost:6379'
module.exports = function(connect){
var store = RedisStore(connect);
function AutoconfigRedisStore (options) {
if(!options) {
options = {};
} else if(typeof options === 'string') {
options = { url: options };
}
if(!options.host) {
var redisUrl = options.url;
if(!redisUrl) {
for(var i = 0; i < envVariables.length; i++) {
if(redisUrl = process.env[envVariables[i]]) {
break;
}
}
}
var config = url.parse(redisUrl || fallback);
options.host = config.hostname;
if(config.port) {
options.port = config.port;
}
if(config.path && config.path !== '/') {
options.db = config.path.replace(/^\//, '');
}
if(config.auth) {
options.pass = config.auth.split(":")[1];
}
}
store.call(this, options);
}
util.inherits(AutoconfigRedisStore, store);
return AutoconfigRedisStore;
};
| var RedisStore = require('connect-redis');
var url = require('url');
var envVariables = ['REDIS_SESSION_URI', 'REDIS_URI', 'REDIS_SESSION_URL', 'REDIS_URL', 'REDISTOGO_URL', 'OPENREDIS_URL'];
var fallback = 'redis://localhost:6379'
module.exports = function(connect){
var store = RedisStore(connect);
function KrakenRedisStore (options) {
if(!options) {
options = {};
} else if(typeof options === 'string') {
options = { url: options };
}
if(!options.host) {
var redisUrl = options.url;
if(!redisUrl) {
for(var i = 0; i < envVariables.length; i++) {
if(redisUrl = process.env[envVariables[i]]) {
break;
}
}
}
var config = url.parse(redisUrl || fallback);
options.host = config.hostname;
if(config.port) {
options.port = config.port;
}
if(config.path && config.path !== '/') {
options.db = config.path.replace(/^\//, '');
}
if(config.auth) {
options.pass = config.auth.split(":")[1];
}
}
store.call(this, options);
}
KrakenRedisStore.prototype = store.prototype;
return KrakenRedisStore;
};
|
Prepend log entries to try to stay above the fold | (function() {
var opQueue = new OperationQueue(),
counter = 0;
function demoLog(msg) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(msg));
$("#logger").prepend(li);
}
$("#success").click(function() {
demoLog("Calling success handler");
(opQueue.getSuccessHandler())(counter++);
});
$("#failure").click(function() {
demoLog("Calling failure handler");
(opQueue.getFailureHandler())(counter++);
});
$("#reset").click(function() {
demoLog("Calling reset");
opQueue.reset();
});
$("#onSuccess").click(function() {
opQueue.queue(function(result) {
demoLog("Success " + result);
});
});
$("#onFailure").click(function() {
opQueue.queue({
onFailure: function(result) {
demoLog("Failure " + result);
}
});
});
$("#onBoth").click(function() {
opQueue.queue({
onSuccess: function(result) {
demoLog("Both Success " + result);
},
onFailure: function(result) {
demoLog("Both Failure " + result);
}
});
});
})();
| (function() {
var opQueue = new OperationQueue(),
counter = 0;
function demoLog(msg) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(msg));
$("#logger").append(li);
}
$("#success").click(function() {
demoLog("Calling success handler");
(opQueue.getSuccessHandler())(counter++);
});
$("#failure").click(function() {
demoLog("Calling failure handler");
(opQueue.getFailureHandler())(counter++);
});
$("#reset").click(function() {
demoLog("Calling reset");
opQueue.reset();
});
$("#onSuccess").click(function() {
opQueue.queue(function(result) {
demoLog("Success " + result);
});
});
$("#onFailure").click(function() {
opQueue.queue({
onFailure: function(result) {
demoLog("Failure " + result);
}
});
});
$("#onBoth").click(function() {
opQueue.queue({
onSuccess: function(result) {
demoLog("Both Success " + result);
},
onFailure: function(result) {
demoLog("Both Failure " + result);
}
});
});
})();
|
Move those methods to own class [ci skip] | # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
|
Add revid to Notification object
Since most edit-related notifications include revid attributes,
we should include the revids in the Notification objects as we're
building them (if they exist).
Change-Id: Ifdb98e7c79729a1c2f7a5c4c4366e28071a48239 | # -*- coding: utf-8 -*-
"""Classes and functions for working with the Echo extension."""
from __future__ import absolute_import, unicode_literals
import pywikibot
class Notification(object):
"""A notification issued by the Echo extension."""
def __init__(self, site):
"""Construct an empty Notification object."""
self.site = site
@classmethod
def fromJSON(cls, site, data):
"""
Construct a Notification object from JSON data returned by the API.
@rtype: Notification
"""
notif = cls(site)
notif.id = data['id'] # TODO: use numeric id ?
notif.type = data['type']
notif.category = data['category']
notif.timestamp = pywikibot.Timestamp.fromtimestampformat(data['timestamp']['mw'])
if 'title' in data and 'full' in data['title']:
notif.page = pywikibot.Page(site, data['title']['full'])
else:
notif.page = None
if 'agent' in data and 'name' in data['agent']:
notif.agent = pywikibot.User(site, data['agent']['name'])
else:
notif.agent = None
if 'read' in data:
notif.read = pywikibot.Timestamp.fromtimestampformat(data['read'])
else:
notif.read = False
notif.content = data.get('*', None)
notif.revid = data.get('revid', None)
return notif
def mark_as_read(self):
"""Mark the notification as read."""
return self.site.notifications_mark_read(list=self.id)
| # -*- coding: utf-8 -*-
"""Classes and functions for working with the Echo extension."""
from __future__ import absolute_import, unicode_literals
import pywikibot
class Notification(object):
"""A notification issued by the Echo extension."""
def __init__(self, site):
"""Construct an empty Notification object."""
self.site = site
@classmethod
def fromJSON(cls, site, data):
"""
Construct a Notification object from JSON data returned by the API.
@rtype: Notification
"""
notif = cls(site)
notif.id = data['id'] # TODO: use numeric id ?
notif.type = data['type']
notif.category = data['category']
notif.timestamp = pywikibot.Timestamp.fromtimestampformat(data['timestamp']['mw'])
if 'title' in data and 'full' in data['title']:
notif.page = pywikibot.Page(site, data['title']['full'])
else:
notif.page = None
if 'agent' in data and 'name' in data['agent']:
notif.agent = pywikibot.User(site, data['agent']['name'])
else:
notif.agent = None
if 'read' in data:
notif.read = pywikibot.Timestamp.fromtimestampformat(data['read'])
else:
notif.read = False
notif.content = data.get('*', None)
return notif
def mark_as_read(self):
"""Mark the notification as read."""
return self.site.notifications_mark_read(list=self.id)
|
Replace custom status codes with http module | module.exports = function (app, nus) {
var opts = app.get('opts')
, http = require('http')
, router = require('express').Router();
router.route('/shorten')
.post(function (req, res) {
nus.shorten(req.body['long_url'], function (err, reply) {
if (err) {
jsonResponse(res, err);
} else if (reply) {
reply.short_url = opts.url.replace(/\/$/, '') + '/' + reply.hash;
jsonResponse(res, 200, reply);
} else {
jsonResponse(res, 500);
}
});
});
router.route('/expand')
.post(function (req, res) {
nus.expand(req.body['short_url'], function (err, reply) {
if (err) {
jsonResponse(res, err);
} else if (reply) {
jsonResponse(res, 200, reply);
} else {
jsonResponse(res, 500);
}
});
});
function jsonResponse (res, code, data) {
data = data || {};
data.status_code = (http.STATUS_CODES[code]) ? code : 503,
data.status_txt = http.STATUS_CODES[code] || http.STATUS_CODES[503]
res.status(data.status_code).json(data)
}
return router;
};
| module.exports = function (app, nus) {
var opts = app.get('opts')
, router = require('express').Router();
router.route('/shorten')
.post(function (req, res) {
nus.shorten(req.body['long_url'], function (err, reply) {
if (err) {
jsonResponse(res, err);
} else if (reply) {
reply.short_url = opts.url.replace(/\/$/, '') + '/' + reply.hash;
jsonResponse(res, 200, reply);
} else {
jsonResponse(res, 500);
}
});
});
router.route('/expand')
.post(function (req, res) {
nus.expand(req.body['short_url'], function (err, reply) {
if (err) {
jsonResponse(res, err);
} else if (reply) {
jsonResponse(res, 200, reply);
} else {
jsonResponse(res, 500);
}
});
});
function jsonResponse (res, code, data) {
var status_codes = {
200: 'OK',
300: 'Incorrect Link',
400: 'Bad Request',
404: 'Not Found',
500: 'Internal Server Error',
503: 'Unknown Server Error'
};
res.type('application/json');
data = data || {};
data.status_code = (status_codes[code]) ? code : 503,
data.status_txt = status_codes[code] || status_codes[503]
res.status(data.status_code).json(data)
}
return router;
};
|
Use lines list as stdout | package com.github.blindpirate.gogradle.task.go;
import java.io.File;
import java.util.List;
public class PackageTestContext {
private String packagePath;
private List<File> testFiles;
private List<String> stdout;
public String getPackagePath() {
return packagePath;
}
public List<File> getTestFiles() {
return testFiles;
}
public List<String> getStdout() {
return stdout;
}
public static PackageTestContextBuilder builder() {
return new PackageTestContextBuilder();
}
public static final class PackageTestContextBuilder {
private String packagePath;
private List<File> testFiles;
private List<String> stdout;
private PackageTestContextBuilder() {
}
public PackageTestContextBuilder withPackagePath(String packagePath) {
this.packagePath = packagePath;
return this;
}
public PackageTestContextBuilder withTestFiles(List<File> testFiles) {
this.testFiles = testFiles;
return this;
}
public PackageTestContextBuilder withStdout(List<String> stdout) {
this.stdout = stdout;
return this;
}
public PackageTestContext build() {
PackageTestContext packageTestContext = new PackageTestContext();
packageTestContext.stdout = this.stdout;
packageTestContext.testFiles = this.testFiles;
packageTestContext.packagePath = this.packagePath;
return packageTestContext;
}
}
}
| package com.github.blindpirate.gogradle.task.go;
import java.io.File;
import java.util.List;
public class PackageTestContext {
private String packagePath;
private List<File> testFiles;
private String stdout;
public String getPackagePath() {
return packagePath;
}
public List<File> getTestFiles() {
return testFiles;
}
public String getStdout() {
return stdout;
}
public static PackageTestContextBuilder builder() {
return new PackageTestContextBuilder();
}
public static final class PackageTestContextBuilder {
private String packagePath;
private List<File> testFiles;
private String stdout;
private PackageTestContextBuilder() {
}
public PackageTestContextBuilder withPackagePath(String packagePath) {
this.packagePath = packagePath;
return this;
}
public PackageTestContextBuilder withTestFiles(List<File> testFiles) {
this.testFiles = testFiles;
return this;
}
public PackageTestContextBuilder withStdout(String stdout) {
this.stdout = stdout;
return this;
}
public PackageTestContext build() {
PackageTestContext packageTestContext = new PackageTestContext();
packageTestContext.stdout = this.stdout;
packageTestContext.testFiles = this.testFiles;
packageTestContext.packagePath = this.packagePath;
return packageTestContext;
}
}
}
|
Add wordpress-muplugin is allowable package type | <?php
namespace BeanstalkSatisGen\File;
class Composer extends Json
{
/**
* Returns whether or not this composer file is a satis package based on the
* contents.
*
* @return boolean
*/
public function isComposerPackage()
{
return
! empty($this->content) &&
$this->hasName() &&
(
$this->hasPackageType() ||
$this->isSatisPackage()
);
}
/**
* Whether or not this composer file has a name
*/
protected function hasName()
{
return ! empty($this->content->name);
}
/**
* Whether or not this composer.json has a type that is a package
*
* @return bool
*/
protected function hasPackageType()
{
$allowableTypes = array(
'library',
'wordpress-plugin',
'wordpress-muplugin',
'symfony-bundle',
'drupal-module'
);
return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
}
/**
* Whether or not this composer is a satis package
*
* @return bool
*/
protected function isSatisPackage()
{
return
isset($this->content->extra) &&
isset($this->content->extra->{'satis-package'}) &&
true === $this->content->extra->{'satis-package'};
}
}
| <?php
namespace BeanstalkSatisGen\File;
class Composer extends Json
{
/**
* Returns whether or not this composer file is a satis package based on the
* contents.
*
* @return boolean
*/
public function isComposerPackage()
{
return
! empty($this->content) &&
$this->hasName() &&
(
$this->hasPackageType() ||
$this->isSatisPackage()
);
}
/**
* Whether or not this composer file has a name
*/
protected function hasName()
{
return ! empty($this->content->name);
}
/**
* Whether or not this composer.json has a type that is a package
*
* @return bool
*/
protected function hasPackageType()
{
$allowableTypes = array(
'library',
'wordpress-plugin',
'symfony-bundle',
'drupal-module'
);
return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
}
/**
* Whether or not this composer is a satis package
*
* @return bool
*/
protected function isSatisPackage()
{
return
isset($this->content->extra) &&
isset($this->content->extra->{'satis-package'}) &&
true === $this->content->extra->{'satis-package'};
}
}
|
Create function to return all jobs by state
I moved this for security reasons (so we can use Auth). | <?php
namespace App\Http\Controllers;
use App\Job;
use App\Http\Controllers\Controller;
class JobController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show matches page.
*
* @return \Illuminate\Http\Response
*/
public function matchIndex()
{
return view('matches');
}
/**
* Show job page.
*
* @return \Illuminate\Http\Response
*/
public function jobIndex()
{
$id = $request['id'];
$job = Job::findOfFail($id);
$title = $job->title;
$description = $job->description;
$hours = $job->hous;
$salary = $job->salary;
$availablefrom = $job->availablefrom;
$location = $job->location;
$startdate = $job->startdate;
return view("job",["title"=>$title, "description"=>$description, "hours"=>$hours, "salary"=>$salary, "availablefrom"=>$availablefrom, "location"=>$location, "startdate"=>$startdate]);
}
/**
* Delete job.
*
* @return void
*/
public function delete()
{
$job = $request['id'];
Job::destroy($job);
return redirect()->route('home');
}
public function getJobs($state){
$jobs = Job::where('state', $state)->get();
return $jobs;
}
}
| <?php
namespace App\Http\Controllers;
use App\Job;
use App\Http\Controllers\Controller;
class JobController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show post page.
*
* @return \Illuminate\Http\Response
*/
public function matchIndex()
{
return view('matches');
}
/**
* Show job page.
*
* @return \Illuminate\Http\Response
*/
public function jobIndex()
{
$id = $request['id'];
$job = Job::findOfFail($id);
$title = $job->title;
$description = $job->description;
$hours = $job->hous;
$salary = $job->salary;
$availablefrom = $job->availablefrom;
$location = $job->location;
$startdate = $job->startdate;
return view("job",["title"=>$title, "description"=>$description, "hours"=>$hours, "salary"=>$salary, "availablefrom"=>$availablefrom, "location"=>$location, "startdate"=>$startdate]);
}
/**
* Delete job.
*
* @return void
*/
public function delete()
{
$job = $request['id'];
Job::destroy($job);
return redirect()->route('home');
}
public function getJobs($state){
return "hello";
}
}
|
Watch unit tests and rerun on change | module.exports = function(grunt) {
grunt.initConfig({
concat: {
options: {
separator: ''
},
app: {
dest: 'deploy/app.js',
src: [
'src/intro.js.frag',
'src/*.js',
'src/outro.js.frag'
]
}
},
watch: {
scripts: {
files: ['src/*.js*', 'unittests/*.spec.js'],
tasks: ['unittests']
},
css: {
files: ['*.css'],
tasks: ['csslint']
},
},
csslint: {
src: ['*.css']
},
jshint: {
all: {
files: {
src: ['deploy/app.js']
}
}
},
jasmine: {
all: {
src: ['deploy/app.js'],
options: {
specs: 'unittests/*.spec.js',
outfile: 'test-results.html',
keepRunner: true,
helpers: [
'lib/angular.js',
'lib/angular-mocks.js'
]
}
}
},
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.registerTask('unittests', ['concat', 'jshint', 'jasmine:all']);
grunt.registerTask('default', ['csslint', 'unittests']);
grunt.registerTask('dev', ['default', 'watch']);
};
| module.exports = function(grunt) {
grunt.initConfig({
concat: {
options: {
separator: ''
},
app: {
dest: 'deploy/app.js',
src: [
'src/intro.js.frag',
'src/*.js',
'src/outro.js.frag'
]
}
},
watch: {
scripts: {
files: ['src/*.js*'],
tasks: ['unittests']
},
css: {
files: ['*.css'],
tasks: ['csslint']
},
},
csslint: {
src: ['*.css']
},
jshint: {
all: {
files: {
src: ['deploy/app.js']
}
}
},
jasmine: {
all: {
src: ['deploy/app.js'],
options: {
specs: 'unittests/*.spec.js',
outfile: 'test-results.html',
keepRunner: true,
helpers: [
'lib/angular.js',
'lib/angular-mocks.js'
]
}
}
},
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.registerTask('unittests', ['concat', 'jshint', 'jasmine:all']);
grunt.registerTask('default', ['csslint', 'unittests']);
grunt.registerTask('dev', ['default', 'watch']);
};
|
refactor: Rename all streams tab key to 'allStreams'.
Reason behind this change is to avoid confusion as there is already tab with key 'streams' in home tabs. | /* @flow */
import React from 'react';
import { StyleSheet, Text } from 'react-native';
import { TabNavigator, TabBarTop } from 'react-navigation';
import { FormattedMessage } from 'react-intl';
import tabsOptions from '../styles/tabs';
import SubscriptionsContainer from '../streams/SubscriptionsContainer';
import StreamListContainer from '../subscriptions/StreamListContainer';
const styles = StyleSheet.create({
tab: {
padding: 10,
fontSize: 16,
},
});
export default TabNavigator(
{
subscribed: {
screen: props => <SubscriptionsContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: props => (
<Text style={[styles.tab, { color: props.tintColor }]}>
<FormattedMessage id="Subscribed" defaultMessage="Subscribed" />
</Text>
),
},
},
allStreams: {
screen: props => <StreamListContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: props => (
<Text style={[styles.tab, { color: props.tintColor }]}>
<FormattedMessage id="All streams" defaultMessage="All streams" />
</Text>
),
},
},
},
tabsOptions({
tabBarComponent: TabBarTop,
tabBarPosition: 'top',
showLabel: true,
showIcon: false,
tabWidth: 100,
}),
);
| /* @flow */
import React from 'react';
import { StyleSheet, Text } from 'react-native';
import { TabNavigator, TabBarTop } from 'react-navigation';
import { FormattedMessage } from 'react-intl';
import tabsOptions from '../styles/tabs';
import SubscriptionsContainer from '../streams/SubscriptionsContainer';
import StreamListContainer from '../subscriptions/StreamListContainer';
const styles = StyleSheet.create({
tab: {
padding: 10,
fontSize: 16,
},
});
export default TabNavigator(
{
subscribed: {
screen: props => <SubscriptionsContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: props => (
<Text style={[styles.tab, { color: props.tintColor }]}>
<FormattedMessage id="Subscribed" defaultMessage="Subscribed" />
</Text>
),
},
},
streams: {
screen: props => <StreamListContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: props => (
<Text style={[styles.tab, { color: props.tintColor }]}>
<FormattedMessage id="All streams" defaultMessage="All streams" />
</Text>
),
},
},
},
tabsOptions({
tabBarComponent: TabBarTop,
tabBarPosition: 'top',
showLabel: true,
showIcon: false,
tabWidth: 100,
}),
);
|
Remove the creation of a function in map render | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BaseChart } from 'react-jsx-highcharts';
class HighchartsMapChart extends Component {
static propTypes = {
getHighcharts: PropTypes.func.isRequired // Provided by HighchartsProvider
};
static defaultProps = {
callback: () => {}
};
getGeoJSON = map => {
if (!map) return;
return (typeof map === 'string') ? this.props.getHighcharts().maps[map] : map;
}
callback = chart => {
const geojson = this.geojson;
if (geojson) {
const format = this.props.getHighcharts().format;
const { mapText, mapTextFull } = chart.options.credits;
chart.mapCredits = format(mapText, { geojson });
chart.mapCreditsFull = format(mapTextFull, { geojson });
}
this.props.callback(chart)
}
render () {
const { map, chart, ...rest } = this.props;
this.geojson = this.getGeoJSON(map);
return (
<BaseChart
chart={{ ...chart, map: this.geojson }}
mapNavigation={{ enabled: false }}
xAxis={{ id: 'xAxis' }}
yAxis={{ id: 'yAxis' }}
{...rest}
callback={this.callback}
chartCreationFunc={this.props.getHighcharts().mapChart}
chartType="mapChart" />
);
}
}
export default HighchartsMapChart;
| import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BaseChart } from 'react-jsx-highcharts';
class HighchartsMapChart extends Component {
static propTypes = {
getHighcharts: PropTypes.func.isRequired // Provided by HighchartsProvider
};
static defaultProps = {
callback: () => {}
};
getGeoJSON = map => {
if (!map) return;
return (typeof map === 'string') ? this.props.getHighcharts().maps[map] : map;
}
callback = geojson => chart => {
if (geojson) {
const format = this.props.getHighcharts().format;
const { mapText, mapTextFull } = chart.options.credits;
chart.mapCredits = format(mapText, { geojson });
chart.mapCreditsFull = format(mapTextFull, { geojson });
}
this.props.callback(chart)
}
render () {
const { map, chart, ...rest } = this.props;
const geojson = this.getGeoJSON(map);
return (
<BaseChart
chart={{ ...chart, map: geojson }}
mapNavigation={{ enabled: false }}
xAxis={{ id: 'xAxis' }}
yAxis={{ id: 'yAxis' }}
{...rest}
callback={this.callback(geojson)}
chartCreationFunc={this.props.getHighcharts().mapChart}
chartType="mapChart" />
);
}
}
export default HighchartsMapChart;
|
Use PackageName-x.x.x for consistency with CLI install usage. | <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>
<a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name; ?>"><?php echo $context->name; ?></a>-<?php echo $context->version['release']; ?>
</h2>
<ul class="package-info">
<li><strong>Version:</strong>
<span><?php echo $context->version['release']; ?></span>
</li>
<li><strong>Stability:</strong>
<span><?php echo $context->stability['release']; ?></span>
</li>
<li><strong>Released on:</strong>
<span><abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?></abbr></span>
</li>
<li><strong>License:</strong>
<span><?php echo $context->license['name']; ?></span>
</li>
</ul>
<?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>
</div>
<div class="grid_4 right releases">
<h3>Release Notes</h3>
<?php echo nl2br($context->notes); ?>
</div>
</div>
| <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>
<a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name; ?>"><?php echo $context->name; ?></a> ::
<?php echo $context->version['release']; ?>
</h2>
<ul class="package-info">
<li><strong>Version:</strong>
<span><?php echo $context->version['release']; ?></span>
</li>
<li><strong>Stability:</strong>
<span><?php echo $context->stability['release']; ?></span>
</li>
<li><strong>Released on:</strong>
<span><abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?></abbr></span>
</li>
<li><strong>License:</strong>
<span><?php echo $context->license['name']; ?></span>
</li>
</ul>
<?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>
</div>
<div class="grid_4 right releases">
<h3>Release Notes</h3>
<?php echo nl2br($context->notes); ?>
</div>
</div>
|
Use props instead of state | import { h } from 'preact'
import Nav from '../components/Nav'
import Loading from '../components/Loading'
import displayDate from '../helpers/display-date'
const Wrapper = (props) => {
let textClass = ''
if (!props.showInfo)
textClass = 'hidden'
if (props.isLoading) {
return (
<Loading />
)
} else {
if (props.isFailure) {
return (
<div class="loading">
<h1 class="title">
Request failed {props.tries + 1} times. <br/>
Try again later.
</h1>
</div>
)
} else {
return (
<div>
<Nav
date={props.date}
onPreviousClick={props.onPreviousClick}
onNextClick={props.onNextClick}
onToggleClick={props.onToggleClick}
onRandomClick={props.onRandomClick} />
<div class="wrapper" style={{backgroundImage: `url(${props.image_hd})`}}>
<div class={`container ${textClass}`}>
<div class="text">
<h1>{props.title}</h1>
<p>
{props.explanation}
</p>
<p>
{displayDate(props.date)}
</p>
</div>
</div>
</div>
</div>
)
}
}
}
export default Wrapper
| import { h } from 'preact'
import Nav from '../components/Nav'
import Loading from '../components/Loading'
import displayDate from '../helpers/display-date'
const Wrapper = (props) => {
let textClass = ''
if (!props.showInfo)
textClass = 'hidden'
if (props.isLoading) {
return (
<Loading />
)
} else {
if (props.isFailure) {
return (
<h1>Request failed {this.state.tries + 1} times. Try again later. </h1>
)
} else {
return (
<div>
<Nav
date={props.date}
onPreviousClick={props.onPreviousClick}
onNextClick={props.onNextClick}
onToggleClick={props.onToggleClick}
onRandomClick={props.onRandomClick} />
<div class="wrapper" style={{backgroundImage: `url(${props.image_hd})`}}>
<div class={`container ${textClass}`}>
<div class="text">
<h1>{props.title}</h1>
<p>
{props.explanation}
</p>
<p>
{displayDate(props.date)}
</p>
</div>
</div>
</div>
</div>
)
}
}
}
export default Wrapper
|
[hide_input_all] Fix loading for either before or after notebook loads. | // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace',
'base/js/events'
], function(
$,
Jupyter,
events
) {
"use strict";
function set_input_visible(show) {
Jupyter.notebook.metadata.hide_input = !show;
if (show) $('div.input').show('slow');
else $('div.input').hide('slow');
var btn = $('#toggle_codecells');
btn.toggleClass('active', !show);
var icon = btn.find('i');
icon.toggleClass('fa-eye', show);
icon.toggleClass('fa-eye-slash', !show);
$('#toggle_codecells').attr(
'title', (show ? 'Hide' : 'Show') + ' codecell inputs');
}
function toggle() {
set_input_visible($('#toggle_codecells').hasClass('active'));
}
function initialize () {
set_input_visible(Jupyter.notebook.metadata.hide_input !== true);
}
var load_ipython_extension = function() {
Jupyter.toolbar.add_buttons_group([{
id : 'toggle_codecells',
label : 'Hide codecell inputs',
icon : 'fa-eye',
callback : function() {
toggle();
setTimeout(function() { $('#toggle_codecells').blur(); }, 500);
}
}]);
if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) {
// notebook_loaded.Notebook event has already happened
initialize();
}
events.on('notebook_loaded.Notebook', initialize);
};
return {
load_ipython_extension : load_ipython_extension
};
});
| // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace'
], function(
$,
IPython
) {
"use strict";
function set_input_visible(show) {
IPython.notebook.metadata.hide_input = !show;
if (show) $('div.input').show('slow');
else $('div.input').hide('slow');
var btn = $('#toggle_codecells');
btn.toggleClass('active', !show);
var icon = btn.find('i');
icon.toggleClass('fa-eye', show);
icon.toggleClass('fa-eye-slash', !show);
$('#toggle_codecells').attr(
'title', (show ? 'Hide' : 'Show') + ' codecell inputs');
}
function toggle() {
set_input_visible($('#toggle_codecells').hasClass('active'));
}
var load_ipython_extension = function() {
IPython.toolbar.add_buttons_group([{
id : 'toggle_codecells',
label : 'Hide codecell inputs',
icon : 'fa-eye',
callback : function() {
toggle();
setTimeout(function() { $('#toggle_codecells').blur(); }, 500);
}
}]);
set_input_visible(IPython.notebook.metadata.hide_input !== true);
};
return {
load_ipython_extension : load_ipython_extension
};
});
|
Bump version number (so readthedocs picks it up). | """
"""
__version__ = '0.2'
__release__ = '0.2a1'
def inject_app_defaults():
"""
Automatically inject the default settings for this app.
If settings has already been configured, then we need to add
our defaults to that (if not overridden), and in all cases we
also want to inject our settings into the global_settings object,
so we can use diffsettings.
Based on:
http://passingcuriosity.com/2010/default-settings-for-django-applications/
but with improvements for importing/assignation failures.
"""
try:
import settings as app_settings
from django.conf import settings, global_settings
from django.core.exceptions import ImproperlyConfigured
except ImportError:
return
for key in dir(app_settings):
if key.isupper():
value = getattr(app_settings, key)
setattr(global_settings, key, value)
if not hasattr(settings, key):
# We can just ignore failures, as this means we are
# not set up, so global_settings will suffice.
try:
setattr(settings, key, value)
except (ImproperlyConfigured, ImportError):
pass
inject_app_defaults()
default_app_config = 'boardinghouse.apps.BoardingHouseConfig' | """
"""
__version__ = '0.1'
__release__ = '0.1a3'
def inject_app_defaults():
"""
Automatically inject the default settings for this app.
If settings has already been configured, then we need to add
our defaults to that (if not overridden), and in all cases we
also want to inject our settings into the global_settings object,
so we can use diffsettings.
Based on:
http://passingcuriosity.com/2010/default-settings-for-django-applications/
but with improvements for importing/assignation failures.
"""
try:
import settings as app_settings
from django.conf import settings, global_settings
from django.core.exceptions import ImproperlyConfigured
except ImportError:
return
for key in dir(app_settings):
if key.isupper():
value = getattr(app_settings, key)
setattr(global_settings, key, value)
if not hasattr(settings, key):
# We can just ignore failures, as this means we are
# not set up, so global_settings will suffice.
try:
setattr(settings, key, value)
except (ImproperlyConfigured, ImportError):
pass
inject_app_defaults()
default_app_config = 'boardinghouse.apps.BoardingHouseConfig' |
Remove param check for backup type on v2.1 API
The backup type is only used by glance, so nova check it make
no sense; currently we have daily and weekly as only valid param
but someone may add 'monthly' as param. nova should allow it
and delegate the error. This patch removes check on v2.1 API.
Change-Id: I59bbc0f589c8c280eb8cd87aa279898fffaeab7a
Closes-Bug: #1361490 | # Copyright 2014 NEC Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.api.validation import parameter_types
create_backup = {
'type': 'object',
'properties': {
'create_backup': {
'type': 'object',
'properties': {
'name': parameter_types.name,
'backup_type': {
'type': 'string',
},
'rotation': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 0,
},
'metadata': {
'type': 'object',
}
},
'required': ['name', 'backup_type', 'rotation'],
'additionalProperties': False,
},
},
'required': ['create_backup'],
'additionalProperties': False,
}
| # Copyright 2014 NEC Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.api.validation import parameter_types
create_backup = {
'type': 'object',
'properties': {
'create_backup': {
'type': 'object',
'properties': {
'name': parameter_types.name,
'backup_type': {
'type': 'string',
'enum': ['daily', 'weekly'],
},
'rotation': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 0,
},
'metadata': {
'type': 'object',
}
},
'required': ['name', 'backup_type', 'rotation'],
'additionalProperties': False,
},
},
'required': ['create_backup'],
'additionalProperties': False,
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.