text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Make sure we actually run JSCS..... @jwilsson
|
module.exports = function( grunt ) {
'use strict';
var srcFiles = [
'bot.js',
'*.botplug.js',
'Gruntfile.js'
];
grunt.initConfig({
pkg: grunt.file.readJSON( 'package.json' ),
jshint: {
all: srcFiles,
options: {
jshintrc: '.jshintrc'
}
},
jscs: {
src: srcFiles
}
});
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-jscs' );
grunt.registerTask( 'test', [ 'jshint', 'jscs' ] );
grunt.registerTask( 'default', [ 'test' ] );
};
|
module.exports = function( grunt ) {
'use strict';
var srcFiles = [
'bot.js',
'*.botplug.js',
'Gruntfile.js'
];
grunt.initConfig({
pkg: grunt.file.readJSON( 'package.json' ),
jshint: {
all: srcFiles,
options: {
jshintrc: '.jshintrc'
}
},
jscs: {
src: srcFiles
}
});
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-jscs' );
grunt.registerTask( 'test', [ 'jshint' ] );
grunt.registerTask( 'default', [ 'test' ] );
};
|
Switch to headless chrome from chrome
|
const webpack = require('./webpack.config')
process.env.CHROME_BIN = require('puppeteer').executablePath()
module.exports = config => {
config.set({
frameworks: ['mocha', 'chai'],
files: ['test/components/index.js', 'test/components/*.js'],
preprocessors: {
'test/components/*.js': ['webpack']
},
webpack,
webpackMiddleware: {
stats: 'errors-only',
noInfo: true
},
browsers: ['ChromeHeadless'],
reporters: ['mocha'],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
})
if (process.env.TRAVIS) {
config.browsers = ['Chrome_travis_ci']
}
}
|
const webpack = require('./webpack.config')
module.exports = config => {
config.set({
frameworks: ['mocha', 'chai'],
files: [
{ pattern: 'test/components/*.js', watched: false }
],
preprocessors: {
'test/components/*.js': ['webpack']
},
webpack,
webpackMiddleware: {
stats: 'errors-only',
noInfo: true
},
browsers: ['Chrome'],
reporters: ['mocha'],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
})
if (process.env.TRAVIS) {
config.browsers = ['Chrome_travis_ci']
}
}
|
Allow version parsing code to use non-annotated tags
|
# -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_distribution('hydrachain')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'hydrachain')):
# not installed, but there is another version that *is*
raise DistributionNotFound
__version__ = _dist.version
except DistributionNotFound:
pass
if not __version__:
try:
rev = subprocess.check_output(['git', 'describe', '--tags', '--dirty'])
match = GIT_DESCRIBE_RE.match(rev)
if match:
__version__ = "{}+git-{}".format(match.group("version"), match.group("git"))
except:
pass
if not __version__:
__version__ = 'undefined'
# ########### endversion ##################
|
# -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_distribution('hydrachain')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'hydrachain')):
# not installed, but there is another version that *is*
raise DistributionNotFound
__version__ = _dist.version
except DistributionNotFound:
pass
if not __version__:
try:
rev = subprocess.check_output(['git', 'describe', '--dirty'])
match = GIT_DESCRIBE_RE.match(rev)
if match:
__version__ = "{}+git-{}".format(match.group("version"), match.group("git"))
except:
pass
if not __version__:
__version__ = 'undefined'
# ########### endversion ##################
|
Fix element(data) always returns 0
|
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import 'semantic-ui-css/components/api';
import $ from 'jquery';
$.fn.extend({
taxonMoveUp() {
const element = this;
element.api({
method: 'PUT',
on: 'click',
beforeSend(settings) {
/* eslint-disable-next-line no-param-reassign */
settings.data = {
position: jquery(this).data('position') - 1,
};
return settings;
},
onSuccess() {
window.location.reload();
},
});
},
taxonMoveDown() {
const element = this;
element.api({
method: 'PUT',
on: 'click',
beforeSend(settings) {
/* eslint-disable-next-line no-param-reassign */
settings.data = {
position: jquery(this).data('position') + 1,
};
return settings;
},
onSuccess() {
window.location.reload();
},
});
},
});
|
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import 'semantic-ui-css/components/api';
import $ from 'jquery';
$.fn.extend({
taxonMoveUp() {
const element = this;
element.api({
method: 'PUT',
on: 'click',
beforeSend(settings) {
/* eslint-disable-next-line no-param-reassign */
settings.data = {
position: element.data('position') - 1,
};
return settings;
},
onSuccess() {
window.location.reload();
},
});
},
taxonMoveDown() {
const element = this;
element.api({
method: 'PUT',
on: 'click',
beforeSend(settings) {
/* eslint-disable-next-line no-param-reassign */
settings.data = {
position: element.data('position') + 1,
};
return settings;
},
onSuccess() {
window.location.reload();
},
});
},
});
|
Fix missing class on friends listing page
|
{{--
Copyright 2015-2017 ppy Pty. Ltd.
This file is part of osu!web. osu!web is distributed with the hope of
attracting more community contributions to the core ecosystem of osu!.
osu!web is free software: you can redistribute it and/or modify
it under the terms of the Affero GNU General Public License version 3
as published by the Free Software Foundation.
osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with osu!web. If not, see <http://www.gnu.org/licenses/>.
--}}
@extends('master')
@section('content')
@include('home._user_header_default', [
'title' => trans('home.user.header.welcome', ['username' => Auth::user()->username])
])
<div class="osu-page osu-page--generic osu-page--small osu-page--dark-bg">
<div class="user-friends">
<h2 class="user-friends__title">{{trans('friends.title')}}</h2>
@include('objects._userlist', ['userlist' => $userlist])
</div>
</div>
@endsection
|
{{--
Copyright 2015-2017 ppy Pty. Ltd.
This file is part of osu!web. osu!web is distributed with the hope of
attracting more community contributions to the core ecosystem of osu!.
osu!web is free software: you can redistribute it and/or modify
it under the terms of the Affero GNU General Public License version 3
as published by the Free Software Foundation.
osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with osu!web. If not, see <http://www.gnu.org/licenses/>.
--}}
@extends('master')
@section('content')
@include('home._user_header_default', [
'title' => trans('home.user.header.welcome', ['username' => Auth::user()->username])
])
<div class="osu-page osu-page--generic osu-page--dark-bg">
<div class="user-friends">
<h2 class="user-friends__title">{{trans('friends.title')}}</h2>
@include('objects._userlist', ['userlist' => $userlist])
</div>
</div>
@endsection
|
Enable cubemap texture lod in Plask
|
var glu = require('pex-glu');
var color = require('pex-color');
var sys = require('pex-sys');
var Context = glu.Context;
var Material = glu.Material;
var Program = glu.Program;
var Color = color.Color;
var merge = require('merge');
var fs = require('fs');
var Platform = sys.Platform;
var TexturedCubeMapGLSL = fs.readFileSync(__dirname + '/TexturedCubeMap.glsl', 'utf8');
function TexturedCubeMap(uniforms) {
this.gl = Context.currentContext;
if (Platform.isBrowser) {
this.lodExt = this.gl.getExtension('EXT_shader_texture_lod');
if (this.lodExt) {
TexturedCubeMapGLSL = '#define LOD_ENABLED 1\n' + TexturedCubeMapGLSL;
TexturedCubeMapGLSL = '#define WEBGL 1\n' + TexturedCubeMapGLSL;
TexturedCubeMapGLSL = '#define textureCubeLod textureCubeLodEXT\n' + TexturedCubeMapGLSL;
}
}
else {
TexturedCubeMapGLSL = '#define LOD_ENABLED 1\n' + TexturedCubeMapGLSL;
}
var program = new Program(TexturedCubeMapGLSL);
var defaults = {
lod: -1
};
uniforms = merge(defaults, uniforms);
Material.call(this, program, uniforms);
}
TexturedCubeMap.prototype = Object.create(Material.prototype);
module.exports = TexturedCubeMap;
|
var glu = require('pex-glu');
var color = require('pex-color');
var sys = require('pex-sys');
var Context = glu.Context;
var Material = glu.Material;
var Program = glu.Program;
var Color = color.Color;
var merge = require('merge');
var fs = require('fs');
var Platform = sys.Platform;
var TexturedCubeMapGLSL = fs.readFileSync(__dirname + '/TexturedCubeMap.glsl', 'utf8');
function TexturedCubeMap(uniforms) {
this.gl = Context.currentContext;
if (Platform.isBrowser) {
this.lodExt = this.gl.getExtension('EXT_shader_texture_lod');
if (this.lodExt) {
TexturedCubeMapGLSL = '#define LOD_ENABLED 1\n' + TexturedCubeMapGLSL;
TexturedCubeMapGLSL = '#define WEBGL 1\n' + TexturedCubeMapGLSL;
TexturedCubeMapGLSL = '#define textureCubeLod textureCubeLodEXT\n' + TexturedCubeMapGLSL;
}
}
var program = new Program(TexturedCubeMapGLSL);
var defaults = {
lod: -1
};
uniforms = merge(defaults, uniforms);
Material.call(this, program, uniforms);
}
TexturedCubeMap.prototype = Object.create(Material.prototype);
module.exports = TexturedCubeMap;
|
[Java] Add comment for pre-order iteration.
|
package collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
import binarytrees.TreeNode;
/**
* An iterator that iterates through a binary tree in pre-order.
*/
public class PreorderIterator<T> implements Iterator<T> {
private T nextItem;
private final Stack<TreeNode<T>> stack;
public PreorderIterator(TreeNode<T> rootNode) {
this.nextItem = null;
this.stack = new Stack<TreeNode<T>>();
stack.push(rootNode);
}
@Override
public boolean hasNext() {
if (nextItem != null) {
return true;
}
if (stack.empty()) {
return false;
}
TreeNode<T> node = stack.peek();
nextItem = node.getValue();
if (node.hasLeft()) {
stack.push(node.getLeft());
} else {
while (!stack.empty()) {
TreeNode<T> current = stack.pop();
if (current.hasRight()) {
stack.push(current.getRight());
break;
}
}
}
return true;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T toReturn = nextItem;
nextItem = null;
return toReturn;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
package collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
import binarytrees.TreeNode;
public class PreorderIterator<T> implements Iterator<T> {
private T nextItem;
private final Stack<TreeNode<T>> stack;
public PreorderIterator(TreeNode<T> rootNode) {
this.nextItem = null;
this.stack = new Stack<TreeNode<T>>();
stack.push(rootNode);
}
@Override
public boolean hasNext() {
if (nextItem != null) {
return true;
}
if (stack.empty()) {
return false;
}
TreeNode<T> node = stack.peek();
nextItem = node.getValue();
if (node.hasLeft()) {
stack.push(node.getLeft());
} else {
while (!stack.empty()) {
TreeNode<T> current = stack.pop();
if (current.hasRight()) {
stack.push(current.getRight());
break;
}
}
}
return true;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T toReturn = nextItem;
nextItem = null;
return toReturn;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
Reduce amount of calculations in broadphase.
|
/*globals define*/
define([
'physics/intersection'
], function( Intersection ) {
'use strict';
// Filter all physics entities that may be colliding.
function broadphase( entities ) {
var potentials = [];
var aabbs = entities.map(function( entity ) {
return entity.aabb();
});
var length = entities.length;
var i, j;
var aabb0, aabb1;
for ( i = 0; i < length; i++ ) {
aabb0 = aabbs[i];
for ( j = i + 1; j < length; j++ ) {
aabb1 = aabbs[j];
if ( Intersection.aabb( aabb0, aabb1 ) ) {
potentials.push( [ entities[i], entities[j] ] );
}
}
}
return potentials;
}
function sort2d( a, b ) {
if ( a.x === b.x ) {
return a.y - b.y;
}
return a.x - b.x;
}
return {
broadphase: broadphase,
sort2d: sort2d
};
});
|
/*globals define*/
define([
'physics/intersection'
], function( Intersection ) {
'use strict';
// Filter all physics entities that may be colliding.
function broadphase( entities ) {
var potentials = [];
var aabb0,
aabb1;
entities.forEach(function( a ) {
aabb0 = a.aabb();
entities.forEach(function( b ) {
if ( a === b ) {
return;
}
aabb1 = b.aabb();
if ( Intersection.aabb( aabb0, aabb1 ) ) {
potentials.push( [ a, b ] );
}
});
});
return potentials;
}
function sort2d( a, b ) {
if ( a.x === b.x ) {
return a.y - b.y;
}
return a.x - b.x;
}
/**
* Determine all unique pairs of entities.
*/
function unique( pairsArray ) {
pairsArray.forEach(function() {
pairsArray.forEach(function() {
});
});
}
return {
broadphase: broadphase,
sort2d: sort2d
};
});
|
Set a mode instead of prining it
|
package se.soy.gpg;
import java.util.List;
import java.util.ArrayList;
public class GPG {
// FIXME Remove when done
static<T> void println(T arg) { System.out.println(arg); }
public static void main(String[] args) {
println("main");
GPG.encrypt().armor().recipient("0xrecipient").output();
/*
GPG.encrypt().armor().recipient("0xrecipient").output();
GPG.decrypt().armor().local-user("0xlocaluser").output("/tmp/a-file");
GPG.sign().armor().();
*/
}
private String mode;
private boolean armor = false;
private List<String> recipients = new ArrayList<String>();
public void output() {
println("OPTIONS:");
println(String.format("mode: %s", mode));
println(String.format("armor?: %s", (armor) ? "true" : "false"));
println(String.format("recipients?: %s", recipients));
}
public static GPG encrypt() {
GPG gpg = new GPG();
gpg.mode = "encrypt";
return gpg;
}
public GPG armor() {
this.armor = true;
return this;
}
public GPG recipient(String recipient) {
this.recipients.add(recipient);
return this;
}
}
|
package se.soy.gpg;
import java.util.List;
import java.util.ArrayList;
public class GPG {
// FIXME Remove when done
static<T> void println(T arg) { System.out.println(arg); }
public static void main(String[] args) {
println("main");
GPG.encrypt().armor().recipient("0xrecipient").output();
/*
GPG.encrypt().armor().recipient("0xrecipient").output();
GPG.decrypt().armor().local-user("0xlocaluser").output("/tmp/a-file");
GPG.sign().armor().();
*/
}
private boolean armor = false;
private List<String> recipients = new ArrayList<String>();
public void output() {
println("OPTIONS:");
println(String.format("armor?: %s", (armor) ? "true" : "false"));
println(String.format("recipients?: %s", recipients));
}
public static GPG encrypt() {
GPG gpg = new GPG();
println("encrypt()");
return gpg;
}
public GPG armor() {
this.armor = true;
return this;
}
public GPG recipient(String recipient) {
this.recipients.add(recipient);
return this;
}
}
|
Set production as default environment
|
<?php
namespace MyTravel\Core\Config;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
final class ApplicationConfiguration implements ConfigurationInterface {
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();
// Build the tree
$node = $treeBuilder
->root('application')
->children();
$node
->enumNode('environment')->defaultValue('prod')
->values(array('dev', 'staging', 'prod'))
->info('Which environment the application currently runs (dev|staging|prod).')
->end()
->scalarNode('appname')->defaultValue('MyTravel')->end()
->scalarNode('view')->defaultValue('default')->end()
->integerNode('pagecachetime')
->defaultValue(60*60*24)
->info('Cache expiration time in seconds.')
->end()
->end();
return $treeBuilder;
}
}
|
<?php
namespace MyTravel\Core\Config;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
final class ApplicationConfiguration implements ConfigurationInterface {
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();
// Build the tree
$node = $treeBuilder
->root('application')
->children();
$node
->enumNode('environment')->defaultValue('dev')
->values(array('dev', 'staging', 'prod'))
->info('Which environment the application currently runs (dev|staging|prod).')
->end()
->scalarNode('appname')->defaultValue('MyTravel')->end()
->scalarNode('view')->defaultValue('default')->end()
->integerNode('pagecachetime')
->defaultValue(60*60*24)
->info('Cache expiration time in seconds.')
->end()
->end();
return $treeBuilder;
}
}
|
Update test specs according to code modification
|
define(function(require) {
var test = require('../../test')
var assert = test.assert
//assert(seajs.log('seajs.log test', 'group') === undefined, 'group')
assert(seajs.log('a') === undefined, 'log')
assert(seajs.log('a ' + 1) === undefined, 'log')
assert(seajs.log('a', 'warn') === undefined, 'warn')
assert(seajs.log('a', 'info') === undefined, 'info')
assert(seajs.log('a', 'error') === undefined, 'error')
//assert(seajs.log('a', 'time') === undefined, 'time')
//assert(seajs.log('a', 'timeEnd') === undefined, 'timeEnd')
assert(seajs.log('a', 'dir') === undefined, 'dir')
assert(seajs.log({ name: 'a' }, 'dir') === undefined, 'dir')
//assert(seajs.log('seajs.log test', 'groupEnd') === undefined, 'groupEnd')
test.next()
});
|
define(function(require) {
var test = require('../../test')
var assert = test.assert
assert(seajs.log('seajs.log test', 'group') === undefined, 'group')
assert(seajs.log('a') === undefined, 'log')
assert(seajs.log('a ' + 1) === undefined, 'log')
assert(seajs.log('a', 'warn') === undefined, 'warn')
assert(seajs.log('a', 'info') === undefined, 'info')
assert(seajs.log('a', 'error') === undefined, 'error')
assert(seajs.log('a', 'time') === undefined, 'time')
assert(seajs.log('a', 'timeEnd') === undefined, 'timeEnd')
assert(seajs.log('a', 'dir') === undefined, 'dir')
assert(seajs.log({ name: 'a' }, 'dir') === undefined, 'dir')
assert(seajs.log('seajs.log test', 'groupEnd') === undefined, 'groupEnd')
test.next()
});
|
Change name to texture name
|
package info.u_team.u_team_core.item.armor;
import net.minecraft.entity.Entity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.*;
public class UArmorItem extends ArmorItem {
protected final String textureName;
public UArmorItem(String textureName, Properties properties, IArmorMaterial material, EquipmentSlotType slot) {
this(textureName, null, properties, material, slot);
}
public UArmorItem(String textureName, ItemGroup group, Properties properties, IArmorMaterial material, EquipmentSlotType slot) {
super(material, slot, group == null ? properties : properties.group(group));
this.textureName = textureName;
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlotType slot, String type) {
if (!material.getName().equals("invalid")) {
return null;
}
return String.format("%s:textures/models/armor/%s_layer_%d%s.png", getRegistryName().getNamespace(), textureName, (slot == EquipmentSlotType.LEGS ? 2 : 1), type == null ? "" : String.format("_%s", type));
}
protected String getTypeString(EquipmentSlotType slot) {
switch (slot) {
case HEAD:
return "helmet";
case CHEST:
return "chestplate";
case LEGS:
return "leggings";
case FEET:
return "boots";
default:
return "invalid";
}
}
}
|
package info.u_team.u_team_core.item.armor;
import net.minecraft.entity.Entity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.*;
public class UArmorItem extends ArmorItem {
protected final String name;
public UArmorItem(String name, Properties properties, IArmorMaterial material, EquipmentSlotType slot) {
this(name, null, properties, material, slot);
}
public UArmorItem(String name, ItemGroup group, Properties properties, IArmorMaterial material, EquipmentSlotType slot) {
super(material, slot, group == null ? properties : properties.group(group));
this.name = name;
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlotType slot, String type) {
if (!material.getName().equals("invalid")) {
return null;
}
return String.format("%s:textures/models/armor/%s_layer_%d%s.png", getRegistryName().getNamespace(), name, (slot == EquipmentSlotType.LEGS ? 2 : 1), type == null ? "" : String.format("_%s", type));
}
protected String getTypeString(EquipmentSlotType slot) {
switch (slot) {
case HEAD:
return "helmet";
case CHEST:
return "chestplate";
case LEGS:
return "leggings";
case FEET:
return "boots";
default:
return "invalid";
}
}
}
|
Update message passing method visibility
|
package io.elssa.net;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class MessageRouterBase {
private List<MessageListener> listeners
= Collections.synchronizedList(new ArrayList<>());
/**
* Adds a message listener (consumer) to this MessageRouter. Listeners
* receive messages that are published by this MessageRouter.
*
* @param listener {@link MessageListener} that will consume messages
* published by this MessageRouter.
*/
public void addListener(MessageListener listener) {
listeners.add(listener);
}
public void removeListener(MessageListener listener) {
listeners.remove(listener);
}
protected void onConnnect(NetworkEndpoint endpoint) {
for (MessageListener listener : listeners) {
listener.onConnect(endpoint);
}
}
protected void onDisconnect(NetworkEndpoint endpoint) {
for (MessageListener listener : listeners) {
listener.onDisconnect(endpoint);
}
}
protected void onMessage(ElssaMessage msg) {
for (MessageListener listener : listeners) {
listener.onMessage(msg);
}
}
}
|
package io.elssa.net;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class MessageRouterBase {
private List<MessageListener> listeners
= Collections.synchronizedList(new ArrayList<>());
/**
* Adds a message listener (consumer) to this MessageRouter. Listeners
* receive messages that are published by this MessageRouter.
*
* @param listener {@link MessageListener} that will consume messages
* published by this MessageRouter.
*/
public void addListener(MessageListener listener) {
listeners.add(listener);
}
public void removeListener(MessageListener listener) {
listeners.remove(listener);
}
public void onConnnect(NetworkEndpoint endpoint) {
for (MessageListener listener : listeners) {
listener.onConnect(endpoint);
}
}
public void onDisconnect(NetworkEndpoint endpoint) {
for (MessageListener listener : listeners) {
listener.onDisconnect(endpoint);
}
}
public void onMessage(ElssaMessage msg) {
for (MessageListener listener : listeners) {
listener.onMessage(msg);
}
}
}
|
Allow subsystems to not map a sqlachemy entity
|
import flask
from infosystem.common.subsystem.controller import *
from infosystem.common.subsystem.driver import *
from infosystem.common.subsystem.manager import *
from infosystem.common.subsystem.router import *
class Subsystem(flask.Blueprint):
def __init__(self, resource=None, router=None, controller=None, manager=None,
driver=None, individual_name=None, collection_name=None, operations=[]):
individual_name = individual_name or resource.individual()
collection_name = collection_name or resource.collection()
super().__init__(collection_name, collection_name)
driver = driver(resource) if driver else Driver(resource) if resource else None
manager = manager(driver) if manager else Manager(driver)
controller = controller(manager, individual_name, collection_name) if controller else Controller(manager, individual_name, collection_name)
router = router(controller, collection_name, routes=operations) if router else Router(controller, collection_name, routes=operations)
self.name = collection_name
self.router = router
self.manager = manager
self.register_routes()
def register_routes(self):
for route in self.router.routes:
self.add_url_rule(
route['url'], view_func=route['callback'], methods=[route['method']])
|
import flask
from infosystem.common.subsystem.controller import *
from infosystem.common.subsystem.driver import *
from infosystem.common.subsystem.manager import *
from infosystem.common.subsystem.router import *
class Subsystem(flask.Blueprint):
def __init__(self, resource, router=None, controller=None, manager=None,
driver=None, operations=[]):
super().__init__(resource.collection(), resource.collection())
driver = driver(resource) if driver else Driver(resource)
manager = manager(driver) if manager else Manager(driver)
controller = controller(manager, resource.individual(), resource.collection()) if controller else Controller(manager, resource.individual(), resource.collection())
router = router(controller, resource.collection(), routes=operations) if router else Router(controller, resource.collection(), routes=operations)
self.name = resource.collection()
self.router = router
self.manager = manager
self.register_routes()
def register_routes(self):
for route in self.router.routes:
self.add_url_rule(
route['url'], view_func=route['callback'], methods=[route['method']])
|
Set auth token on page reloads
|
(function (angular) {
"use strict";
angular.module("mflAdminAppConfig", [
"sil.common.logging",
"sil.api.wrapper",
"sil.grid",
"mfl.auth.oauth2"
])
.constant("SERVER_URL", window.MFL_SETTINGS.SERVER_URL)
.constant("CREDZ", window.MFL_SETTINGS.CREDZ)
.config(["loggingConfigProvider", function(loggingConfig){
loggingConfig.LOG_TO_SERVER = false;
loggingConfig.LOG_SERVER_URL = undefined;
loggingConfig.LOG_TO_CONSOLE = true;
}])
.config(["silGridConfigProvider", function(silGridConfig){
silGridConfig.apiMaps = {
};
silGridConfig.appConfig = "mflAdminAppConfig";
}])
.run(["api.auth", function (auth) {
var token = auth.getToken();
if (! _.isNull(token)) {
auth.setXHRToken(token);
}
}]);
})(angular);
|
(function (angular) {
"use strict";
angular.module("mflAdminAppConfig", [
"sil.common.logging",
"sil.api.wrapper",
"sil.grid"
])
.constant("SERVER_URL", window.MFL_SETTINGS.SERVER_URL)
.constant("CREDZ", window.MFL_SETTINGS.CREDZ)
.config(["loggingConfigProvider", function(loggingConfig){
loggingConfig.LOG_TO_SERVER = false;
loggingConfig.LOG_SERVER_URL = undefined;
loggingConfig.LOG_TO_CONSOLE = true;
}])
.config(["silGridConfigProvider", function(silGridConfig){
silGridConfig.apiMaps = {
};
silGridConfig.appConfig = "mflAdminAppConfig";
}]);
})(angular);
|
Use Linkr-unique session cookie name
|
# flake8: noqa: E501
import config.options
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABASE_HOST,
database_name=config.options.DATABASE_NAME,
)
SQLALCHEMY_TEST_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABASE_HOST,
database_name=config.options.DATABASE_NAME + '_test',
)
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Flask session cookie name
SESSION_COOKIE_NAME = 'linkr-session'
# Flask session secret key
SECRET_KEY = '\xec5\xea\xc9\x9f,o\xd7v\xac\x06\xe2\xeeK2\xb9\x1d\x8a\xdel\xb27\x8a\xa8>\x07\n\xd4Z\xfeO\xa1'
|
# flake8: noqa: E501
import config.options
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABASE_HOST,
database_name=config.options.DATABASE_NAME,
)
SQLALCHEMY_TEST_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABASE_HOST,
database_name=config.options.DATABASE_NAME + '_test',
)
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Flask session secret key
SECRET_KEY = '\xec5\xea\xc9\x9f,o\xd7v\xac\x06\xe2\xeeK2\xb9\x1d\x8a\xdel\xb27\x8a\xa8>\x07\n\xd4Z\xfeO\xa1'
|
qa: Remove race between connecting and shutdown on separate connections
|
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy, wait_until
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
# Force connection establishment by executing a dummy command.
node.getblockcount()
Thread(target=test_long_call, args=(node,)).start()
# Wait until the server is executing the above `waitfornewblock`.
wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2)
# Wait 1 second after requesting shutdown but not before the `stop` call
# finishes. This is to ensure event loop waits for current connections
# to close.
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
|
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
Thread(target=test_long_call, args=(node,)).start()
# wait 1 second to ensure event loop waits for current connections to close
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
|
openid: Fix notice about unititialized variable.
|
<?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}
$error = NULL;
try {
if (!empty($_GET['openid_url'])) {
$authSource->doAuth($state, (string)$_GET['openid_url']);
}
} catch (Exception $e) {
$error = $e->getMessage();
}
$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();
|
<?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}
try {
if (!empty($_GET['openid_url'])) {
$authSource->doAuth($state, (string)$_GET['openid_url']);
}
} catch (Exception $e) {
$error = $e->getMessage();
}
$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();
|
Fix retrieving model values for empty strings
|
<?php namespace Laraplus\Form\DataStores;
trait RetrievesModelValues
{
/**
* @var ArrayAccess|array
*/
protected $model = null;
/**
* @param ArrayAccess|array $model
*/
public function bind($model)
{
$this->model = $model;
}
/**
* @param string $name
* @param null|ArrayAccess|array $offset
* @return null|string
*/
public function getModelValue($name, $offset = null)
{
$model = isset($offset) ? $offset : $this->model;
if(($from = strpos($name, '[')) && ($to = strpos($name, ']'))) {
$newName = substr($name, $from+1, $to-$from-1) . substr($name, $to+1);
$offset = substr($name, 0, $from);
if(!isset($model[$offset])) return null;
return $this->getModelValue($newName, $model[$offset]);
}
if (is_array($model) && isset($model[$name])) {
return $model[$name];
}
if(is_object($model) && strlen($model->$name)) {
return $model->$name;
}
return null;
}
}
|
<?php namespace Laraplus\Form\DataStores;
trait RetrievesModelValues
{
/**
* @var ArrayAccess|array
*/
protected $model = null;
/**
* @param ArrayAccess|array $model
*/
public function bind($model)
{
$this->model = $model;
}
/**
* @param string $name
* @param null|ArrayAccess|array $offset
* @return null|string
*/
public function getModelValue($name, $offset = null)
{
$model = isset($offset) ? $offset : $this->model;
if(($from = strpos($name, '[')) && ($to = strpos($name, ']'))) {
$newName = substr($name, $from+1, $to-$from-1) . substr($name, $to+1);
$offset = substr($name, 0, $from);
if(!isset($model[$offset])) return null;
return $this->getModelValue($newName, $model[$offset]);
}
if (is_array($model) && isset($model[$name])) {
return $model[$name];
}
if(is_object($model) && $model->$name) {
return $model->$name;
}
return null;
}
}
|
Add classifier indicating only Python2.7 support
|
import uuid
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm",
version="1.00.0",
packages=find_packages(),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm",
include_package_data=True,
install_requires=reqs,
entry_points={
'console_scripts': [
'cl_napalm_configure=napalm.clitools.cl_napalm_configure:main',
],
}
)
|
import uuid
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm",
version="1.00.0",
packages=find_packages(),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm",
include_package_data=True,
install_requires=reqs,
entry_points={
'console_scripts': [
'cl_napalm_configure=napalm.clitools.cl_napalm_configure:main',
],
}
)
|
Use a list comprehension and set() to make the active_users query simpler and faster.
|
from datetime import timedelta, datetime
from django.db import models
from django.contrib.auth.models import User
class RequestManager(models.Manager):
def active_users(self, **options):
"""
Returns a list of active users.
Any arguments passed to this method will be
given to timedelta for time filtering.
Example:
>>> Request.object.active_users(minutes=15)
[<User: kylef>, <User: krisje8>]
"""
qs = self.filter(user__isnull=False)
if options:
time = datetime.now() - timedelta(**options)
qs = qs.filter(time__gte=time)
requests = qs.select_related('user').only('user')
return set([request.user for request in requests])
|
from datetime import timedelta, datetime
from django.db import models
from django.contrib.auth.models import User
class RequestManager(models.Manager):
def active_users(self, **options):
"""
Returns a list of active users.
Any arguments passed to this method will be
given to timedelta for time filtering.
Example:
>>> Request.object.active_users(minutes=15)
[<User: kylef>, <User: krisje8>]
"""
qs = self.filter(user__isnull=False)
if options:
time = datetime.now() - timedelta(**options)
qs = qs.filter(time__gte=time)
requests = qs.select_related('user').only('user')
users = []
done = []
for request in requests:
if not (request.user.pk in done):
done.append(request.user.pk)
users.append(request.user)
return users
|
Allow configuration to override app name
|
var express = require('express');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
function appCtor(cfg, pool) {
var app = express();
// app-wide default page title
app.locals.title = cfg.env.APP_NAME || 'DingRoll';
app.set('trust proxy', true);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(serveStatic(__dirname + '/static'));
app.use(serveStatic(__dirname + '/icons'));
app.use(serveStatic(__dirname + '/manifests'));
app.use(session({
store: new RedisStore({
host: cfg.redis.hostname,
port: cfg.redis.port}),
secret: cfg.env.SECRET_KEY_BASE,
resave: false,
saveUninitialized: false
}));
app.use(function (req, res, next) {
if (!req.session) {
return next(new Error("couldn't find sessions"));
}
else return next();
});
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req, res) {
return res.render('index');
});
app.get('/m', function(req, res) {
return res.render('messaging');
});
return app;
}
module.exports = appCtor;
|
var express = require('express');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
function appCtor(cfg, pool) {
var app = express();
// app-wide default page title
app.locals.title = 'DingRoll';
app.set('trust proxy', true);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(serveStatic(__dirname + '/static'));
app.use(serveStatic(__dirname + '/icons'));
app.use(serveStatic(__dirname + '/manifests'));
app.use(session({
store: new RedisStore({
host: cfg.redis.hostname,
port: cfg.redis.port}),
secret: cfg.env.SECRET_KEY_BASE,
resave: false,
saveUninitialized: false
}));
app.use(function (req, res, next) {
if (!req.session) {
return next(new Error("couldn't find sessions"));
}
else return next();
});
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req, res) {
return res.render('index');
});
app.get('/m', function(req, res) {
return res.render('messaging');
});
return app;
}
module.exports = appCtor;
|
Add skos_registry to the request.
Add the skos_registry to the request through the add_request_method
directive.
|
# -*- coding: utf8 -*-
from zope.interface import Interface
from skosprovider.registry import Registry
class ISkosRegistry(Interface):
pass
def _build_skos_registry(registry):
skos_registry = registry.queryUtility(ISkosRegistry)
if skos_registry is not None:
return skos_registry
skos_registry = Registry()
registry.registerUtility(skos_registry, ISkosRegistry)
return registry.queryUtility(ISkosRegistry)
def get_skos_registry(registry):
#Argument might be a config or request
regis = getattr(registry, 'registry', None)
if regis is None:
regis = registry
return regis.queryUtility(ISkosRegistry)
def includeme(config):
_build_skos_registry(config.registry)
config.add_directive('get_skos_registry', get_skos_registry)
config.add_request_method(get_skos_registry, 'skos_registry', reify=True)
config.add_route('skosprovider.conceptschemes', '/conceptschemes')
config.add_route('skosprovider.conceptscheme', '/conceptschemes/{scheme_id}')
config.add_route('skosprovider.conceptscheme.concepts', '/conceptschemes/{scheme_id}/concepts')
config.add_route('skosprovider.concept', '/conceptschemes/{scheme_id}/concepts/{concept_id}')
config.scan()
|
# -*- coding: utf8 -*-
from zope.interface import Interface
from skosprovider.registry import Registry
class ISkosRegistry(Interface):
pass
def _build_skos_registry(registry):
skos_registry = registry.queryUtility(ISkosRegistry)
if skos_registry is not None:
return skos_registry
skos_registry = Registry()
registry.registerUtility(skos_registry, ISkosRegistry)
return registry.queryUtility(ISkosRegistry)
def get_skos_registry(registry):
#Argument might be a config or request
regis = getattr(registry, 'registry', None)
if regis is None:
regis = registry
return regis.queryUtility(ISkosRegistry)
def includeme(config):
_build_skos_registry(config.registry)
config.add_directive('get_skos_registry', get_skos_registry)
config.add_route('skosprovider.conceptschemes', '/conceptschemes')
config.add_route('skosprovider.conceptscheme', '/conceptschemes/{scheme_id}')
config.add_route('skosprovider.conceptscheme.concepts', '/conceptschemes/{scheme_id}/concepts')
config.add_route('skosprovider.concept', '/conceptschemes/{scheme_id}/concepts/{concept_id}')
config.scan()
|
Rename proc object config key from proc_entry to simply object.
|
import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
text = open('/proc/%s' % self.conf['object']).read()
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start']
|
import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
text = open('/proc/%s' % self.conf['proc_entry'])
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start']
|
Add passive supervizer module support
|
/**
* Otagai.js
* Based on https://github.com/olafurnielsen/form5-node-express-mongoose-coffeescript
*/
var express = require('express'),
http = require('http'),
fs = require('fs'),
passport = require('passport'),
mongoose = require('mongoose'),
coffee = require('coffee-script')
var env = process.env.NODE_ENV || 'development',
config = require('./config/environment')[env],
auth = require('./config/middlewares/authorization')
// Bootstrap database
console.log('Connecting to database at ' + config.db)
mongoose.connect(config.db)
// Bootstrap models
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
require(models_path+'/'+file)
});
// bootstrap passport config
require('./config/passport')(passport, config)
var app = express()
// express settings
require('./config/express')(app, config, passport)
// Bootstrap routes
require('./config/routes')(app, config, passport, auth)
// Helper funtions
require('./app/helpers/general')(app)
// Start the app by listening on <port>
var host = process.argv[2] || '0.0.0.0';
var port = process.argv[3] || process.env.PORT || 3000
http.createServer(app).listen(port, host, function(){
console.log("\u001b[36mApp running on port " + port + "\u001b[0m")
});
|
/**
* Otagai.js
* Based on https://github.com/olafurnielsen/form5-node-express-mongoose-coffeescript
*/
var express = require('express'),
http = require('http'),
fs = require('fs'),
passport = require('passport'),
mongoose = require('mongoose'),
coffee = require('coffee-script')
var env = process.env.NODE_ENV || 'development',
config = require('./config/environment')[env],
auth = require('./config/middlewares/authorization')
// Bootstrap database
console.log('Connecting to database at ' + config.db)
mongoose.connect(config.db)
// Bootstrap models
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
require(models_path+'/'+file)
});
// bootstrap passport config
require('./config/passport')(passport, config)
var app = express()
// express settings
require('./config/express')(app, config, passport)
// Bootstrap routes
require('./config/routes')(app, config, passport, auth)
// Helper funtions
require('./app/helpers/general')(app)
// Start the app by listening on <port>
var port = process.env.PORT || 3000
http.createServer(app).listen(port, function(){
console.log("\u001b[36mApp running on port " + port + "\u001b[0m")
});
|
Add ability to specify defaults through hash
|
$.fn.filterByData = function(prop, val) {
return this.filter(
function() { return $(this).data(prop)==val; }
);
};
$(document).ready(function() {
var radios = $('.table-view.radio');
var saveBtn = $('#save');
var options = {};
var hash = window.location.hash.substring(1);
if (hash) {
try {
var parsed = JSON.parse(hash);
options = parsed;
} catch (e) {
console.error('Error parsing options: ', hash);
}
}
radios.each(function (index) {
var radio = $(this);
var buttons = radio.find('li.table-view-cell > a');
if (options[radio.data('name')]) {
var button = buttons.filterByData('value', options[radio.data('name')]);
button.addClass('active');
}
buttons.click(function() {
buttons.removeClass('active');
$(this).addClass('active');
});
});
saveBtn.click(function() {
var object = {};
radios.each(function (index) {
var radio = $(this);
var key = radio.data('name');
var value = radio.find('.active').first().data('value');
if (value) {
object[key] = value;
}
});
window.location.href = "pebblejs://close#" + encodeURIComponent(JSON.stringify(object));
});
});
|
$(document).ready(function() {
var radios = $('.table-view.radio');
var saveBtn = $('#save');
radios.each(function (index) {
var radio = $(this);
var buttons = radio.find('li.table-view-cell > a');
buttons.click(function() {
buttons.removeClass('active');
$(this).addClass('active');
});
});
saveBtn.click(function() {
var object = {};
radios.each(function (index) {
var radio = $(this);
var key = radio.data('name');
var value = radio.find('.active').first().data('value');
if (value) {
object[key] = value;
}
});
window.location.href = "pebblejs://close#" + encodeURIComponent(JSON.stringify(object));
});
});
|
Send pageview on app load and THEN listen
|
import React, { Component } from 'react';
import { Route, Router } from 'react-router';
import ReactGA from 'react-ga';
import createHistory from 'history/createBrowserHistory';
import ScrollToTop from 'shared/components/scrollToTop/scrollToTop';
import Home from './scenes/home/home';
const history = createHistory();
ReactGA.initialize('UA-75642413-1');
class App extends Component {
componentDidMount() {
// History listening doesn't catch first page load
ReactGA.set({ page: history.location.pathname });
ReactGA.pageview(history.location.pathname);
if (process.env.NODE_ENV === 'production') {
history.listen((location) => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
}
}
render() {
return (
<Router history={history}>
<ScrollToTop>
<Route path="/" component={Home} />
</ScrollToTop>
</Router>
);
}
}
export default App;
|
import React, { Component } from 'react';
import { Route, Router } from 'react-router';
import ReactGA from 'react-ga';
import createHistory from 'history/createBrowserHistory';
import ScrollToTop from 'shared/components/scrollToTop/scrollToTop';
import Home from './scenes/home/home';
const history = createHistory();
ReactGA.initialize('UA-75642413-1');
class App extends Component {
componentDidMount() {
if (process.env.NODE_ENV === 'production') {
history.listen((location) => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
}
}
render() {
return (
<Router history={history}>
<ScrollToTop>
<Route path="/" component={Home} />
</ScrollToTop>
</Router>
);
}
}
export default App;
|
Fix Ajax user form fields with pre-set values
`values[i].objectId` is only set for users added manually via the UI. For pre-existing usernames, only `values[i].value` exists.
|
/**
* Data handler for a user form builder field in an Ajax form.
*
* @author Matthias Schmidt
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/Form/Builder/Field/User
* @since 5.2
*/
define(['Core', './Field', 'WoltLabSuite/Core/Ui/ItemList'], function(Core, FormBuilderField, UiItemList) {
"use strict";
/**
* @constructor
*/
function FormBuilderFieldUser(fieldId) {
this.init(fieldId);
};
Core.inherit(FormBuilderFieldUser, FormBuilderField, {
/**
* @see WoltLabSuite/Core/Form/Builder/Field/Field#_getData
*/
_getData: function() {
var values = UiItemList.getValues(this._fieldId);
var usernames = [];
for (var i = 0, length = values.length; i < length; i++) {
usernames.push(values[i].value);
}
var data = {};
data[this._fieldId] = usernames.join(',');
return data;
}
});
return FormBuilderFieldUser;
});
|
/**
* Data handler for a user form builder field in an Ajax form.
*
* @author Matthias Schmidt
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/Form/Builder/Field/User
* @since 5.2
*/
define(['Core', './Field', 'WoltLabSuite/Core/Ui/ItemList'], function(Core, FormBuilderField, UiItemList) {
"use strict";
/**
* @constructor
*/
function FormBuilderFieldUser(fieldId) {
this.init(fieldId);
};
Core.inherit(FormBuilderFieldUser, FormBuilderField, {
/**
* @see WoltLabSuite/Core/Form/Builder/Field/Field#_getData
*/
_getData: function() {
var values = UiItemList.getValues(this._fieldId);
var usernames = [];
for (var i = 0, length = values.length; i < length; i++) {
if (values[i].objectId) {
usernames.push(values[i].value);
}
}
var data = {};
data[this._fieldId] = usernames.join(',');
return data;
}
});
return FormBuilderFieldUser;
});
|
Change ready button to be a gradient to stand out
|
import { Button } from './Widgets';
export default class Ready extends React.Component {
ready(r) {
ws.send({cmd: r ? 'ready' : 'not_ready'});
}
render() {
const r = this.ready;
const btn =
!this.props.ready ?
<Button onClick={r.bind(this, true)}
style={{background: "radial-gradient(circle, orange 40%, red)"}}>
{this.props.readyText ? this.props.readyText : 'Ready'}
</Button>
: this.props.state === 'Waiting' ?
<Button bg="red" onClick={r.bind(this, false)}>Not Ready</Button>
: <Button bg="green">Waiting...</Button>;
return btn;
}
}
|
import { Button } from './Widgets';
export default class Ready extends React.Component {
ready(r) {
ws.send({cmd: r ? 'ready' : 'not_ready'});
}
render() {
const r = this.ready;
const btn =
!this.props.ready ?
<Button bg="green" onClick={r.bind(this, true)}>
{this.props.readyText ? this.props.readyText : 'Ready'}
</Button>
: this.props.state === 'Waiting' ?
<Button bg="red" onClick={r.bind(this, false)}>Not Ready</Button>
: <Button bg="green">Waiting...</Button>;
return btn;
}
}
|
Set default workers to 10
|
#!/usr/bin/env node
var prerender = require('./lib');
process.env.PORT = process.env.PORT || 4000
var server = prerender({
workers: process.env.PHANTOM_CLUSTER_NUM_WORKERS || 10,
iterations: process.env.PHANTOM_WORKER_ITERATIONS || 10,
phantomBasePort: process.env.PHANTOM_CLUSTER_BASE_PORT || 12300,
messageTimeout: process.env.PHANTOM_CLUSTER_MESSAGE_TIMEOUT
});
// server.use(prerender.basicAuth());
// server.use(prerender.whitelist());
server.use(prerender.blacklist());
// server.use(prerender.logger());
server.use(prerender.removeScriptTags());
server.use(prerender.httpHeaders());
// server.use(prerender.inMemoryHtmlCache());
// server.use(prerender.s3HtmlCache());
server.use(prerender.redisHtmlCache());
server.start();
|
#!/usr/bin/env node
var prerender = require('./lib');
process.env.PORT = process.env.PORT || 4000
var server = prerender({
workers: process.env.PHANTOM_CLUSTER_NUM_WORKERS,
iterations: process.env.PHANTOM_WORKER_ITERATIONS || 10,
phantomBasePort: process.env.PHANTOM_CLUSTER_BASE_PORT || 12300,
messageTimeout: process.env.PHANTOM_CLUSTER_MESSAGE_TIMEOUT
});
// server.use(prerender.basicAuth());
// server.use(prerender.whitelist());
server.use(prerender.blacklist());
// server.use(prerender.logger());
server.use(prerender.removeScriptTags());
server.use(prerender.httpHeaders());
// server.use(prerender.inMemoryHtmlCache());
// server.use(prerender.s3HtmlCache());
server.use(prerender.redisHtmlCache());
server.start();
|
Change naming for method receiver
|
package testclient
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/parnurzeal/gorequest"
)
// TODO consider drop *testing.T parameter
func New(t *testing.T, handler http.Handler) *gorequest.SuperAgent {
mockTransport := mockTransport{
handler: handler,
}
// Don't replace httpClient's Transport with SuperAgent's Transport
gorequest.DisableTransportSwap = true
httpAgent := gorequest.New()
httpAgent.Client = &http.Client{Transport: mockTransport}
return httpAgent
}
type mockTransport struct {
handler http.Handler
}
func (mt mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
rr := httptest.NewRecorder()
//rr.Body = &bytes.Buffer{}
mt.handler.ServeHTTP(rr, req)
return &http.Response{
StatusCode: rr.Code,
Status: http.StatusText(rr.Code),
Header: rr.HeaderMap,
Body: ioutil.NopCloser(rr.Body),
ContentLength: int64(rr.Body.Len()),
Request: req,
}, nil
}
|
package testclient
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/parnurzeal/gorequest"
)
// TODO consider drop *testing.T parameter
func New(t *testing.T, handler http.Handler) *gorequest.SuperAgent {
mockTransport := mockTransport{
handler: handler,
}
// Don't replace httpClient's Transport with SuperAgent's Transport
gorequest.DisableTransportSwap = true
httpAgent := gorequest.New()
httpAgent.Client = &http.Client{Transport: mockTransport}
return httpAgent
}
type mockTransport struct {
handler http.Handler
}
func (t mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
rr := httptest.NewRecorder()
//rr.Body = &bytes.Buffer{}
t.handler.ServeHTTP(rr, req)
return &http.Response{
StatusCode: rr.Code,
Status: http.StatusText(rr.Code),
Header: rr.HeaderMap,
Body: ioutil.NopCloser(rr.Body),
ContentLength: int64(rr.Body.Len()),
Request: req,
}, nil
}
|
Change permission to correct codename of change_subject
|
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.views.generic import ListView, UpdateView
from admin.subjects.forms import SubjectForm
from osf.models.subject import Subject
from osf.models.preprint_provider import PreprintProvider
class SubjectListView(PermissionRequiredMixin, ListView):
model = Subject
permission_required = 'osf.view_subject'
paginate_by = 100
raise_exception = True
def get_queryset(self):
req_obj = self.request.GET
qs = super(SubjectListView, self).get_queryset().order_by('text')
if PreprintProvider.objects.filter(_id=req_obj.get('provider_id')).exists():
qs = qs.filter(provider___id=req_obj.get('provider_id'))
return qs
def get_context_data(self, **kwargs):
context = super(SubjectListView, self).get_context_data(**kwargs)
context['filterable_provider_ids'] = dict({'': '---'}, **dict(PreprintProvider.objects.values_list('_id', 'name')))
return context
class SubjectUpdateView(PermissionRequiredMixin, UpdateView):
form_class = SubjectForm
model = SubjectForm.Meta.model
permission_required = 'osf.change_subject'
raise_exception = True
def get_success_url(self, *args, **kwargs):
return reverse_lazy('subjects:list')
|
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.views.generic import ListView, UpdateView
from admin.subjects.forms import SubjectForm
from osf.models.subject import Subject
from osf.models.preprint_provider import PreprintProvider
class SubjectListView(PermissionRequiredMixin, ListView):
model = Subject
permission_required = 'osf.view_subject'
paginate_by = 100
raise_exception = True
def get_queryset(self):
req_obj = self.request.GET
qs = super(SubjectListView, self).get_queryset().order_by('text')
if PreprintProvider.objects.filter(_id=req_obj.get('provider_id')).exists():
qs = qs.filter(provider___id=req_obj.get('provider_id'))
return qs
def get_context_data(self, **kwargs):
context = super(SubjectListView, self).get_context_data(**kwargs)
context['filterable_provider_ids'] = dict({'': '---'}, **dict(PreprintProvider.objects.values_list('_id', 'name')))
return context
class SubjectUpdateView(PermissionRequiredMixin, UpdateView):
form_class = SubjectForm
model = SubjectForm.Meta.model
permission_required = 'osf.edit_subject'
raise_exception = True
def get_success_url(self, *args, **kwargs):
return reverse_lazy('subjects:list')
|
Remove non-standard homebrew install path
|
const { delimiter } = require("path");
const Color = require("color");
const which = require("which");
const shell = getShell();
module.exports.onWindow = (browserWindow) =>
browserWindow.setVibrancy("ultra-dark");
module.exports.decorateConfig = (config) =>
Object.assign({}, config, {
backgroundColor: Color(config.backgroundColor).alpha(0.85).rgb().string(),
fontFamily:
'"Fira Code", Menlo, "DejaVu Sans Mono", "Lucida Console", monospace',
termCSS: `
x-screen x-row {
font-variant-ligatures: initial;
}
`,
shell,
});
function getShell() {
const path = ["/usr/local/bin", process.env.PATH].join(delimiter);
try {
return which.sync("fish", {
path,
});
} catch (error) {
console.warn(
`Fish shell not found in path ${path}. Falling back to bash shell.`
);
}
return which.sync("bash");
}
|
const { delimiter } = require("path");
const Color = require("color");
const which = require("which");
const shell = getShell();
module.exports.onWindow = (browserWindow) =>
browserWindow.setVibrancy("ultra-dark");
module.exports.decorateConfig = (config) =>
Object.assign({}, config, {
backgroundColor: Color(config.backgroundColor).alpha(0.85).rgb().string(),
fontFamily:
'"Fira Code", Menlo, "DejaVu Sans Mono", "Lucida Console", monospace',
termCSS: `
x-screen x-row {
font-variant-ligatures: initial;
}
`,
shell,
});
function getShell() {
const path = [
`${process.env.HOME}/brew/bin`,
"/usr/local/bin",
process.env.PATH,
].join(delimiter);
try {
return which.sync("fish", {
path,
});
} catch (error) {
console.warn(
`Fish shell not found in path ${path}. Falling back to bash shell.`
);
}
return which.sync("bash");
}
|
OEE-620: Create REST API resource to get dictionary/enum items. Fix CS
|
<?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\ORM\QueryBuilder;
interface DictionaryValueListProviderInterface
{
/**
* Checks whether the provider supports a given entity
*
* @param string $className The FQCN of an entity
*
* @return bool TRUE if this provider supports the given entity; otherwise, FALSE
*/
public function supports($className);
/**
* Gets a query builder for getting dictionary item values for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return QueryBuilder
*/
public function getValueListQueryBuilder($className);
/**
* Gets the configuration of the entity serializer for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return array
*/
public function getSerializationConfig($className);
/**
* Gets a list of entity classes supported by this provider
*
* @return string[]
*/
public function getSupportedEntityClasses();
}
|
<?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\ORM\QueryBuilder;
interface DictionaryValueListProviderInterface
{
/**
* Checks whether the provider supports a given entity
*
* @param string $className The FQCN of an entity
*
* @return bool TRUE if this provider supports the given entity; otherwise, FALSE
*/
public function supports($className);
/**
* Gets a query builder for getting dictionary item values for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return QueryBuilder
*/
public function getValueListQueryBuilder($className);
/**
* Gets the configuration of the entity serializer for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return array
*/
public function getSerializationConfig($className);
/**
* Gets a list of entity classes supported by this provider
*
* @return string[]
*/
public function getSupportedEntityClasses();
}
|
Fix missing MR widget status icons
Fix https://gitlab.com/gitlab-org/gitlab-ce/issues/40283
Regressed in
https://gitlab.com/gitlab-org/gitlab-ce/commit/d01d509bd8612f9879fa762de8ea3763bcff81cf
|
import ciIcon from '../../vue_shared/components/ci_icon.vue';
import loadingIcon from '../../vue_shared/components/loading_icon.vue';
export default {
props: {
status: { type: String, required: true },
showDisabledButton: { type: Boolean, required: false },
},
components: {
ciIcon,
loadingIcon,
},
computed: {
statusObj() {
return {
group: this.status,
icon: `status_${this.status}`,
};
},
},
template: `
<div class="space-children flex-container-block append-right-10">
<div v-if="status === 'loading'" class="mr-widget-icon">
<loading-icon />
</div>
<ci-icon v-else :status="statusObj" />
<button
v-if="showDisabledButton"
type="button"
class="js-disabled-merge-button btn btn-success btn-sm"
disabled="true">
Merge
</button>
</div>
`,
};
|
import ciIcon from '../../vue_shared/components/ci_icon.vue';
import loadingIcon from '../../vue_shared/components/loading_icon.vue';
export default {
props: {
status: { type: String, required: true },
showDisabledButton: { type: Boolean, required: false },
},
components: {
ciIcon,
loadingIcon,
},
computed: {
statusObj() {
return {
group: this.status,
icon: `icon_status_${this.status}`,
};
},
},
template: `
<div class="space-children flex-container-block append-right-10">
<div v-if="status === 'loading'" class="mr-widget-icon">
<loading-icon />
</div>
<ci-icon v-else :status="statusObj" />
<button
v-if="showDisabledButton"
type="button"
class="js-disabled-merge-button btn btn-success btn-sm"
disabled="true">
Merge
</button>
</div>
`,
};
|
Add in the init the newly introduced function
|
# expose the most frequently used functions in the top level.
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images,
check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
|
# expose the most frequently used functions in the top level.
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
|
Update download servlet to pull from cloud storage.
|
package com.google.sps.servlets;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/workspace/downloadWorkspace")
public class DownloadWorkspace extends HttpServlet {
WorkspaceFactory workspaceFactory;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
workspaceFactory = WorkspaceFactory.getInstance();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String downloadID = req.getParameter("downloadID");
resp.setContentType("application/x-gzip");
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
BlobKey blobKey =
blobstoreService.createGsBlobKey(
"/gs/fulfillment-deco-step-2020.appspot.com/" + downloadID);
blobstoreService.serve(blobKey, resp);
}
}
|
package com.google.sps.servlets;
import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/workspace/downloadWorkspace")
public class DownloadWorkspace extends HttpServlet {
WorkspaceFactory workspaceFactory;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
workspaceFactory = WorkspaceFactory.getInstance();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Workspace w = workspaceFactory.fromWorkspaceID(req.getParameter("workspaceID"));
resp.setContentType("application/x-gzip");
try {
w.getArchive().archive(resp.getOutputStream());
} catch (InterruptedException | ExecutionException e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
|
Fix for whitespace.py so that Windows will save Unix EOLs.
|
"""Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(filepath, 'rb')
stripped = ''
flag = False
for line in handle.readlines():
stripped_line = line.rstrip() + '\n'
if line != stripped_line:
flag = True
stripped += stripped_line
handle.close()
if flag:
print('FAIL: %s' % filepath)
overwritefile(filepath, stripped)
else:
print('OK: %s' % filepath)
def overwritefile(filepath, contents):
handle = open(filepath, 'wb')
handle.write(contents)
handle.close()
if __name__ == '__main__':
scanpath('.')
|
"""Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(filepath, 'r')
stripped = ''
flag = False
for line in handle.readlines():
stripped_line = line.rstrip() + '\n'
if line != stripped_line:
flag = True
stripped += stripped_line
handle.close()
if flag:
overwritefile(filepath, stripped)
def overwritefile(filepath, contents):
handle = open(filepath, 'w')
handle.write(contents)
handle.close()
if __name__ == '__main__':
scanpath('.')
|
Add test case for binary search tree program
|
// Program that creates a binary search tree: each node has up to two children, and all left descendants of a node is less than or equal to the node and all right descendants are greater than the node
// create node class
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
// create constructor for binary search tree
function BinarySearchTree() {
this.root = null;
}
// function for inserting value into appropriate location in tree
BinarySearchTree.prototype.push = function(val){
var rootNode = this.root;
// if there is no root node
if(!rootNode){
this.root = new Node(val);
return;
}
var currentNode = rootNode;
var newNode = new Node(val);
while(currentNode){
if(val < currentNode.value){
if(!currentNode.left){
currentNode.left = newNode;
break;
} else {
currentNode = currentNode.left;
}
} else {
if(!currentNode.right) {
currentNode.right = newNode;
break;
} else {
currentNode = currentNode.right;
}
}
}
}
// test case
var testTree = new BinarySearchTree();
testTree.push(4);
testTree.push(9);
testTree.push(2);
testTree.push(7);
testTree.push(3);
// expect 4 to be root node, 2 to be left child and 9 to be right child of 4, 7 to be left child of 9, and 3 to be right child of 2
console.log(testTree);
|
// Program that creates a binary search tree: each node has up to two children, and all left descendants of a node is less than or equal to the node and all right descendants are greater than the node
// create node class
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
// create constructor for binary search tree
function BinarySearchTree() {
this.root = null;
}
BinarySearchTree.prototype.push = function(val){
var rootNode = this.root;
if(!rootNode){
this.root = new Node(val);
return;
}
var currentNode = rootNode;
var newNode = new Node(val);
while(currentNode){
if(val < currentNode.value){
if(!currentNode.left){
currentNode.left = newNode;
break;
} else {
currentNode = currentNode.left;
}
} else {
if(!currentNode.right) {
currentNode.right = newNode;
break;
} else {
currentNode = currentNode.right;
}
}
}
}
|
Fix issue with Windows paths
|
package org.rabix.executor.pathmapper.local;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Map;
import org.rabix.bindings.mapper.FileMappingException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.executor.config.StorageConfiguration;
import com.google.inject.Inject;
public class LocalPathMapper implements FilePathMapper {
private final StorageConfiguration storageConfig;
@Inject
public LocalPathMapper(final StorageConfiguration storageConfig) {
this.storageConfig = storageConfig;
}
@Override
public String map(String path, Map<String, Object> config) throws FileMappingException {
if (!Paths.get(path).isAbsolute()) {
try {
return new File(storageConfig.getPhysicalExecutionBaseDir(), path).getCanonicalPath();
} catch (IOException e) {
throw new FileMappingException(e);
}
}
return path;
}
}
|
package org.rabix.executor.pathmapper.local;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.rabix.bindings.mapper.FileMappingException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.executor.config.StorageConfiguration;
import com.google.inject.Inject;
public class LocalPathMapper implements FilePathMapper {
private final StorageConfiguration storageConfig;
@Inject
public LocalPathMapper(final StorageConfiguration storageConfig) {
this.storageConfig = storageConfig;
}
@Override
public String map(String path, Map<String, Object> config) throws FileMappingException {
if (!path.startsWith(File.separator)) {
try {
return new File(storageConfig.getPhysicalExecutionBaseDir(), path).getCanonicalPath();
} catch (IOException e) {
throw new FileMappingException(e);
}
}
return path;
}
}
|
Remove `objects' group as useless
|
from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.items(), key=lambda x: x[1])[0]
def score(self):
return self._score
class NamedObject:
def __init__(self):
self._entities = []
def __bool__(self):
return bool(self._entities)
def add(self, object_type, score, normal_form):
self._entities.append((object_type, score, normal_form))
def calc_entities(self):
forms = defaultdict(EntityForm)
for object_type, score, normal_form in self._entities:
forms[object_type].add_form(score, normal_form)
return forms
|
from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.items(), key=lambda x: x[1])[0]
def score(self):
return self._score
class NamedObject:
def __init__(self):
self._entities = []
def __bool__(self):
return bool(self._entities)
def add(self, object_type, score, normal_form):
self._entities.append((object_type, score, normal_form))
def calc_entities(self):
forms = defaultdict(EntityForm)
forms['object'] = self._make_global_entity()
for object_type, score, normal_form in self._entities:
forms[object_type].add_form(score, normal_form)
return forms
def _make_global_entity(self):
global_form = EntityForm()
for _, score, form in self._entities:
global_form.add_form(score, form)
return global_form
|
Use `let` instead of `var` for aliases
|
'use strict';
// Dependencies
const cssnext = require('cssnext')
const path = require('path')
// Aliases
let basedir = __dirname
module.exports = {
paths: {
destination: path.join(basedir, 'dist'),
source: path.join(basedir, 'src'),
templates: path.join(basedir, 'templates')
},
processors: {
defaults: {
'*.md': {
kind: 'page',
template: 'page'
},
'posts/**/*.md': {
kind: 'post',
permalink: false,
template: 'post'
}
},
extractPathData: {
'posts/**/*.md': 'posts/{category}/{date}--{slug}.md'
},
postcss: [
cssnext()
]
},
globals: {
site: {
title: 'Steffen Bruchmann’s Website'
}
}
}
|
'use strict';
// Dependencies
const cssnext = require('cssnext')
const path = require('path')
// Aliases
var basedir = __dirname
module.exports = {
paths: {
destination: path.join(basedir, 'dist'),
source: path.join(basedir, 'src'),
templates: path.join(basedir, 'templates')
},
processors: {
defaults: {
'*.md': {
kind: 'page',
template: 'page'
},
'posts/**/*.md': {
kind: 'post',
permalink: false,
template: 'post'
}
},
extractPathData: {
'posts/**/*.md': 'posts/{category}/{date}--{slug}.md'
},
postcss: [
cssnext()
]
},
globals: {
site: {
title: 'Steffen Bruchmann’s Website'
}
}
}
|
refactor(components): Rename prop name => iconName
|
import React from 'react'
import PropTypes from 'prop-types'
import {SimpleMenu, MenuAnchor, Icon} from '..'
class IconMenu extends React.PureComponent {
static displayName = 'IconMenu'
static propTypes = {
children: PropTypes.node,
iconName: PropTypes.string,
open: PropTypes.bool,
}
static defaultProps = {
open: false,
}
handleClick = this._handleClick.bind(this)
handleClose = this._handleClose.bind(this)
constructor(props) {
super(props)
this.state = {
open: props.open,
}
}
_handleClick() {
this.setState(state => ({
open: !state.open,
}))
}
_handleClose() {
this.setState({open: false})
}
render() {
return (
<MenuAnchor>
<Icon
href="javascript:void(0);"
name={this.props.iconName}
onClick={this.handleClick}
tagName="a"
/>
<SimpleMenu
onCancel={this.handleClose}
open={this.state.open}
>
{this.props.children}
</SimpleMenu>
</MenuAnchor>
)
}
}
export default IconMenu
|
import React from 'react'
import PropTypes from 'prop-types'
import {SimpleMenu, MenuAnchor, Icon} from '..'
class IconMenu extends React.PureComponent {
static displayName = 'IconMenu'
static propTypes = {
children: PropTypes.node,
name: PropTypes.string,
open: PropTypes.bool,
}
static defaultProps = {
open: false,
}
handleClick = this._handleClick.bind(this)
handleClose = this._handleClose.bind(this)
constructor(props) {
super(props)
this.state = {
open: props.open,
}
}
_handleClick() {
this.setState(state => ({
open: !state.open,
}))
}
_handleClose() {
this.setState({open: false})
}
render() {
return (
<MenuAnchor>
<Icon
href="javascript:void(0);"
name={this.props.name}
onClick={this.handleClick}
tagName="a"
/>
<SimpleMenu
onCancel={this.handleClose}
open={this.state.open}
>
{this.props.children}
</SimpleMenu>
</MenuAnchor>
)
}
}
export default IconMenu
|
fix(travis): Use a cleaner way of excluding release tags
|
/* @flow */
import type { Template } from 'create-npm/lib/template'
export default function({
encryptedNpmToken,
encryptedGitHubToken
}: {
encryptedNpmToken: string,
encryptedGitHubToken: string
}): Template {
return {
path: '.travis.yml',
content: `
dist: xenial
language: node_js
node_js: node
cache: yarn
env:
global:
- secure: ${encryptedGitHubToken}
- secure: ${encryptedNpmToken}
if: tag IS blank
deploy:
provider: script
skip_cleanup: true
script:
- yarn release
`
}
}
|
/* @flow */
import type { Template } from 'create-npm/lib/template'
export default function({
encryptedNpmToken,
encryptedGitHubToken
}: {
encryptedNpmToken: string,
encryptedGitHubToken: string
}): Template {
return {
path: '.travis.yml',
content: `
dist: xenial
language: node_js
node_js: node
cache: yarn
env:
global:
- secure: ${encryptedGitHubToken}
- secure: ${encryptedNpmToken}
branches:
only:
- master
deploy:
provider: script
skip_cleanup: true
script:
- yarn release
`
}
}
|
Once: Remove assert on event.name (handled somewhere else)
|
'use strict';
/**
* Once middleware will block an event if there is already a scheduled event
* @param {Event} event the event to check
* @param {DBWrkr} wrkr wrkr instance to work with
* @param {function} done callback
*/
function once(event, wrkr, done) {
const findSpec = {
name: event.name
};
if (event.tid) findSpec.tid = event.tid;
wrkr.find(findSpec, (err, events) => {
if (err) return done(err);
// Mark event as Blocked, DBWrkr.publish will not store it
if (events.length) {
event.__blocked = true;
}
event.when = event.once;
if (typeof event.when === 'number') { // ms
event.when = new Date(Date.now()+event.when);
}
delete event.once;
return done();
});
}
// Exports
module.exports = {
once: once
};
|
const assert = require('assert');
'use strict';
/**
* Once middleware will block an event if there is already a scheduled event
* @param {Event} event the event to check
* @param {DBWrkr} wrkr wrkr instance to work with
* @param {function} done callback
*/
function once(event, wrkr, done) {
assert(typeof event.name === 'string', 'event must be a valid event');
const findSpec = {
name: event.name
};
if (event.tid) findSpec.tid = event.tid;
wrkr.find(findSpec, (err, events) => {
if (err) return done(err);
// Mark event as Blocked, DBWrkr.publish will not store it
if (events.length) {
event.__blocked = true;
}
event.when = event.once;
if (typeof event.when === 'number') { // ms
event.when = new Date(Date.now()+event.when);
}
delete event.once;
return done();
});
}
// Exports
module.exports = {
once: once
};
|
Update access token for Instagram feed
|
const Instafeed = require('instafeed.js');
const $ = require('jquery');
var feed = new Instafeed({
get: 'user',
userId: '3120245646',
clientId: ' 5d325f2ba927465d9c3933be01ee870c',
accessToken: '3120245646.1677ed0.442f6331662045c0a14c9802e799ccf6',
resolution: 'standard_resolution',
template: '<div class="instaimage" style="background-image: url(\'\{{image}}\');"><a href="https://www.instagram.com/breakout_ev/"><span class="instaCaption">\{{caption}}</span><span class="instHover"></span></div></a>',
limit: 20
});
feed.run();
// Register listeners for video section play button and link
$(function () {
$('.trigger-play').click(function () {
$('#landingpage-video-before').hide();
$('#video-bg').hide();
$('#landingpage-video').show();
$('iframe#landingpage-video-iframe').attr('src', $('iframe#landingpage-video-iframe').attr('src').replace('autoplay=0', 'autoplay=1'));
});
});
|
const Instafeed = require('instafeed.js');
const $ = require('jquery');
var feed = new Instafeed({
get: 'user',
userId: '3120245646',
clientId: '5d325f2ba927465d9c3933be01ee870c',
accessToken: '3120245646.5d325f2.0d425d18ec6e4e459683a3493c01c9cd',
resolution: 'standard_resolution',
template: '<div class="instaimage" style="background-image: url(\'\{{image}}\');"><a href="https://www.instagram.com/breakout_ev/"><span class="instaCaption">\{{caption}}</span><span class="instHover"></span></div></a>',
limit: 20
});
feed.run();
// Register listeners for video section play button and link
$(function () {
$('.trigger-play').click(function () {
$('#landingpage-video-before').hide();
$('#video-bg').hide();
$('#landingpage-video').show();
$('iframe#landingpage-video-iframe').attr('src', $('iframe#landingpage-video-iframe').attr('src').replace('autoplay=0', 'autoplay=1'));
});
});
|
Add ability to exclude trunks by passing % before it
For example, ./run_nose -v %FilmTitles %BookTitles
|
import functools
import sys
import nose
from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk
__author__ = 'moskupols'
_multiprocess_shared_ = True
_all_trunks = set(trunks_registered())
_trunk_filter = _all_trunks
def trunk_parametrized(trunks=set(trunks_registered())):
def decorate(tester):
@functools.wraps(tester)
def generate_tests(*args):
for t in _trunk_filter & trunks:
yield (tester, t) + args
return generate_tests
return decorate
@functools.lru_cache()
def asset_cache(trunk):
return tuple(applied_modifiers(resource_by_trunk(trunk)()))
def main(args=None):
global _trunk_filter
if args is None:
args = sys.argv
include = _all_trunks & set(args)
exclude_percented = set('%' + t for t in _all_trunks) & set(args)
exclude = set(e[1:] for e in exclude_percented)
if len(include) == 0:
include = _all_trunks
_trunk_filter = include - exclude
args = [arg for arg in args if arg not in include | exclude_percented]
nose.main(argv=args)
|
import functools
import sys
import nose
from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk
__author__ = 'moskupols'
_multiprocess_shared_ = True
_all_trunks = set(trunks_registered())
_trunk_filter = _all_trunks
def trunk_parametrized(trunks=set(trunks_registered())):
def decorate(tester):
@functools.wraps(tester)
def generate_tests(*args):
for t in _trunk_filter & trunks:
yield (tester, t) + args
return generate_tests
return decorate
@functools.lru_cache()
def asset_cache(trunk):
return tuple(applied_modifiers(resource_by_trunk(trunk)()))
def main(args=None):
global _trunk_filter
if args is None:
args = sys.argv
_trunk_filter = _all_trunks & set(args)
if len(_trunk_filter) == 0:
_trunk_filter = _all_trunks
args = [arg for arg in args if arg not in _trunk_filter]
nose.main(argv=args)
|
Add missing file to commit - Refactor app structure
|
import { combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'
import { routerReducer } from 'react-router-redux'
import organization from '../app/home/Home/modules/organization'
import starredBoard from '../app/home/Home/modules/starredBoard'
import notification from '../app/home/Home/modules/notification'
import popOver from '../app/home/Home/modules/popOver'
import modals from '../app/home/Home/modules/modals'
import board from '../app/home/Home/modules/board'
import user from '../app/home/Home/modules/user'
import login from '../app/login/Login/modules/login'
import signUp from '../app/signup/SignUp/modules/signUp'
const rootReducer = combineReducers({
organization,
starredBoard,
notification,
popOver,
modals,
board,
user,
login,
signUp,
form: formReducer,
routing: routerReducer
})
export default rootReducer;
|
import { combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'
import { routerReducer } from 'react-router-redux'
import organization from '../pages/home/Home/modules/organization'
import starredBoard from '../pages/home/Home/modules/starredBoard'
import notification from '../pages/home/Home/modules/notification'
import popOver from '../pages/home/Home/modules/popOver'
import modals from '../pages/home/Home/modules/modals'
import board from '../pages/home/Home/modules/board'
import user from '../pages/home/Home/modules/user'
import login from '../pages/login/Login/modules/login'
import signUp from '../pages/signup/SignUp/modules/signUp'
const rootReducer = combineReducers({
organization,
starredBoard,
notification,
popOver,
modals,
board,
user,
login,
signUp,
form: formReducer,
routing: routerReducer
})
export default rootReducer;
|
Add install_requires and remove ctypes from requirements.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The Screen class lets you to do positioned writes to the dos terminal.
The Screen class also allows you to specify the colors for foreground and
background, to the extent the dos terminal allows.
"""
classifiers = """\
Development Status :: 3 - Alpha
Environment :: Win32 (MS Windows)
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Operating System :: Microsoft :: MS-DOS
Programming Language :: Python
Topic :: Software Development :: Libraries
Topic :: System :: Shells
Topic :: Terminals
"""
from distutils.core import setup
doclines = __doc__.split('\n')
setup(
name='dosbox-screen',
version='0.0.3',
requires=['colorama'],
install_requires=['colorama'],
description=doclines[0],
classifiers=[line for line in classifiers.split('\n') if line],
long_description=' '.join(doclines),
license="BSD",
#platform='win32',
author='Bjorn Pettersen',
author_email='bjorn@tkbe.org',
url='https://github.com/thebjorn/doscmd-screen',
download_url='https://github.com/thebjorn/doscmd-screen',
py_modules=['screen']
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The Screen class lets you to do positioned writes to the dos terminal.
The Screen class also allows you to specify the colors for foreground and
background, to the extent the dos terminal allows.
"""
classifiers = """\
Development Status :: 3 - Alpha
Environment :: Win32 (MS Windows)
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Operating System :: Microsoft :: MS-DOS
Programming Language :: Python
Topic :: Software Development :: Libraries
Topic :: System :: Shells
Topic :: Terminals
"""
from distutils.core import setup
doclines = __doc__.split('\n')
setup(
name='dosbox-screen',
version='0.0.1',
requires=['ctypes', 'colorama'],
description=doclines[0],
classifiers=[line for line in classifiers.split('\n') if line],
long_description=' '.join(doclines),
license="BSD",
#platform='win32',
author='Bjorn Pettersen',
author_email='bjorn@tkbe.org',
url='https://github.com/thebjorn/doscmd-screen',
download_url='https://github.com/thebjorn/doscmd-screen',
py_modules=['screen']
)
|
Add 'string_types' as found in six.
|
"""
Compatibility support for Python 2.7. Remove when Python 2.7 support is
no longer required.
"""
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
input = raw_input
except NameError:
input = input
try:
text_type = unicode
except NameError:
text_type = str
string_types = tuple(set(str, text_type))
try:
import cPickle as pickle
except ImportError:
import pickle
try:
from itertools import ifilter as filter
except ImportError:
filter = filter
# Taken from six.py
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_vars.get('__slots__', ()):
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
try:
import builtins
except ImportError:
import __builtin__ as builtins
|
"""
Compatibility support for Python 2.7. Remove when Python 2.7 support is
no longer required.
"""
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
input = raw_input
except NameError:
input = input
try:
text_type = unicode
except NameError:
text_type = str
try:
import cPickle as pickle
except ImportError:
import pickle
try:
from itertools import ifilter as filter
except ImportError:
filter = filter
# Taken from six.py
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_vars.get('__slots__', ()):
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
try:
import builtins
except ImportError:
import __builtin__ as builtins
|
Include width and height in brand image
|
/* Tooling
/* ========================================================================== */
import { $assign as $, $dispatch, $replaceAll } from 'esri-global-shared';
/* Brand
/* ========================================================================== */
const prefix = 'esri-header-brand';
export default () => {
/* Brand: Image
/* ====================================================================== */
const $targetImage = $(
document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
{ class: `${prefix}-image` }
);
/* Brand
/* ====================================================================== */
const $target = $('a', { class: prefix, id: prefix },
$targetImage
);
// On Click
$target.addEventListener('click', (event) => {
$dispatch($target, 'header:click:brand', { event });
});
/* Brand: On Update
/* ====================================================================== */
$target.addEventListener('header:update:brand', ({ detail }) => {
$($target, { href: detail.href, aria: { label: detail.label } });
$($targetImage, { viewBox: `0 0 ${detail.width} ${detail.height}`, width: `${detail.width}`, height: `${detail.height}` });
$replaceAll($targetImage,
...detail.image.map(
(d) => $(
document.createElementNS('http://www.w3.org/2000/svg', 'path'),
{ d }
)
)
);
});
return $target;
}
|
/* Tooling
/* ========================================================================== */
import { $assign as $, $dispatch, $replaceAll } from 'esri-global-shared';
/* Brand
/* ========================================================================== */
const prefix = 'esri-header-brand';
export default () => {
/* Brand: Image
/* ====================================================================== */
const $targetImage = $(
document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
{ class: `${prefix}-image` }
);
/* Brand
/* ====================================================================== */
const $target = $('a', { class: prefix, id: prefix },
$targetImage
);
// On Click
$target.addEventListener('click', (event) => {
$dispatch($target, 'header:click:brand', { event });
});
/* Brand: On Update
/* ====================================================================== */
$target.addEventListener('header:update:brand', ({ detail }) => {
$($target, { href: detail.href, aria: { label: detail.label } });
$($targetImage, { viewBox: `0 0 ${detail.width} ${detail.height}` });
$replaceAll($targetImage,
...detail.image.map(
(d) => $(
document.createElementNS('http://www.w3.org/2000/svg', 'path'),
{ d }
)
)
);
});
return $target;
}
|
Fix returned promise upon errors
Fixes #5.
|
'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');
module.exports = () => {
if (process.platform !== 'linux') {
return Promise.reject(new Error('Only Linux systems are supported'));
}
return execa('lsb_release', ['-a', '--short']).then(res => {
const stdout = res.stdout.split('\n');
return {
os: stdout[0],
name: stdout[1],
release: stdout[2],
code: stdout[3]
};
}).catch(() => {
return pify(getos).then(res => {
return {
os: res.dist,
name: `${res.dist} ${res.release}`,
release: res.release,
code: res.codename
};
});
});
};
|
'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');
module.exports = () => {
if (process.platform !== 'linux') {
return Promise.reject(new Error('Only Linux systems are supported'));
}
return execa('lsb_release', ['-a', '--short']).then(res => {
const stdout = res.stdout.split('\n');
return {
os: stdout[0],
name: stdout[1],
release: stdout[2],
code: stdout[3]
};
}).catch(() => {
return pify(getos)(res => {
return {
os: res.dist,
name: `${res.dist} ${res.release}`,
release: res.release,
code: res.codename
};
});
});
};
|
Add a skip_publish flag to the deploy task.
|
"""Django project fabfile."""
import os
from fabric.api import puts, task
from fabric.utils import indent
from deploy import deploy_to_heroku, prepare_to_deploy, tag_project
from publish import update_staticfiles, upload_staticfiles
from settings import PROJECT_ENVIRONMENT, PROJECT_ROOT, SITE_NAME, STATIC_ROOT
@task(default=True)
def info():
"""Display information about the project configuration."""
puts("Django project for site '%s' located at '%s':" % (SITE_NAME, PROJECT_ROOT))
puts(indent('PROJECT_ENVIRONMENT = %s' % PROJECT_ENVIRONMENT, 4))
puts(indent('DJANGO_SETTINGS_MODULE = %s'
% os.environ.get('DJANGO_SETTINGS_MODULE', ''), 4))
puts(indent('STATIC_ROOT = %s' % STATIC_ROOT, 4))
@task
def publish():
"""Publish assets to Amazon S3."""
update_staticfiles()
upload_staticfiles()
@task
def deploy(skip_publish=False):
"""Publish and deploy the site."""
prepare_to_deploy()
if not skip_publish:
publish()
# TODO: Add support for other environments.
tag_project('production')
deploy_to_heroku()
|
"""Django project fabfile."""
import os
from fabric.api import puts, task
from fabric.utils import indent
from deploy import deploy_to_heroku, prepare_to_deploy, tag_project
from publish import update_staticfiles, upload_staticfiles
from settings import PROJECT_ENVIRONMENT, PROJECT_ROOT, SITE_NAME, STATIC_ROOT
@task(default=True)
def info():
"""Display information about the project configuration."""
puts("Django project for site '%s' located at '%s':" % (SITE_NAME, PROJECT_ROOT))
puts(indent('PROJECT_ENVIRONMENT = %s' % PROJECT_ENVIRONMENT, 4))
puts(indent('DJANGO_SETTINGS_MODULE = %s'
% os.environ.get('DJANGO_SETTINGS_MODULE', ''), 4))
puts(indent('STATIC_ROOT = %s' % STATIC_ROOT, 4))
@task
def publish():
"""Publish assets to Amazon S3."""
update_staticfiles()
upload_staticfiles()
@task
def deploy():
"""Publish and deploy the site."""
prepare_to_deploy()
publish()
# TODO: Add support for other environments.
tag_project('production')
deploy_to_heroku()
|
Rename remaining 'shortName' refs to 'versionDisplayName'
|
package org.springframework.site.domain.projects;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class ProjectVersionTests {
@Test
public void getDisplayNameForCurrentVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.RELEASE", ProjectRelease.ReleaseStatus.CURRENT, "", "", "", "");
assertThat(version.getVersionDisplayName(), equalTo("1.2.3"));
}
@Test
public void getDisplayNameForPreReleaseVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.M1", ProjectRelease.ReleaseStatus.PRERELEASE, "", "", "", "");
assertThat(version.getVersionDisplayName(), equalTo("1.2.3.M1"));
}
@Test
public void getDisplayNameForOtherVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.RC1", ProjectRelease.ReleaseStatus.PRERELEASE,"", "", "", "");
assertThat(version.getVersionDisplayName(), equalTo("1.2.3.RC1"));
}
}
|
package org.springframework.site.domain.projects;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class ProjectVersionTests {
@Test
public void getShortNameForCurrentVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.RELEASE", ProjectRelease.ReleaseStatus.CURRENT, "", "", "", "");
assertThat(version.getVersionDisplayName(), equalTo("1.2.3"));
}
@Test
public void getShortNameForPreReleaseVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.M1", ProjectRelease.ReleaseStatus.PRERELEASE, "", "", "", "");
assertThat(version.getVersionDisplayName(), equalTo("1.2.3.M1"));
}
@Test
public void getShortNameForOtherVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.RC1", ProjectRelease.ReleaseStatus.PRERELEASE,"", "", "", "");
assertThat(version.getVersionDisplayName(), equalTo("1.2.3.RC1"));
}
}
|
Adjust blog test to use the base class
|
from test_base import MyHomeTest
from .models import BlogPost
class BlogTestCase(MyHomeTest):
def setUp(self):
BlogPost.objects.create(
datetime='2014-01-01T12:00:00Z',
title='livetitle',
content='livecontent',
live=True)
BlogPost.objects.create(
datetime='2014-01-01T12:00:00Z',
title='hiddentitle',
content='hiddencontent',
live=False)
def _test_404(self, url):
g = self.client.get(url)
self.assertEqual(g.status_code, 404)
def test_view(self):
self._test_get('/blog/', ins=['livetitle'], notins=['No Items', 'hiddentitle'])
def test_view_one(self):
self._test_get('/blog/post/1/', ins=['livetitle', 'livecontent'])
def test_view_one_nonlive(self):
self._test_404('/blog/post/2/')
def test_view_miss(self):
self._test_404('/blog/post/100/')
|
from django.test import SimpleTestCase, Client
from .models import BlogPost
class BlogTestCase(SimpleTestCase):
def setUp(self):
BlogPost.objects.create(
datetime='2014-01-01 12:00:00',
title='title',
content='content',
live=True)
def _test_get(self, url, *, ins=[], not_ins=[]):
g = self.client.get(url)
for in_ in ins:
self.assertContains(g, in_)
for nin_ in not_ins:
self.assertNotContains(g, nin_)
def _test_404(self, url):
g = self.client.get(url)
self.assertEqual(g.status_code, 404)
def test_view(self):
self._test_get('/blog/', ins=['title', 'content'], not_ins=['No Items'])
def test_view_one(self):
self._test_get('/blog/post/1/', ins=['title', 'content'])
def test_view_miss(self):
self._test_404('/blog/post/100/')
|
Add null to return type for getRecentMedia
|
<?php
namespace Frontend\Modules\Instagram\Ajax;
use Frontend\Core\Engine\Base\AjaxAction as FrontendBaseAJAXAction;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel;
use Symfony\Component\HttpFoundation\Response;
/**
* Fetches the recent user media and passes it back to javascript
*/
class LoadRecentMedia extends FrontendBaseAJAXAction
{
public function execute(): void
{
parent::execute();
$this->output(Response::HTTP_OK, $this->getRecentMedia());
}
private function getRecentMedia(): ?array
{
return FrontendInstagramModel::getRecentMedia(
$this->getRequest()->request->get('userId'),
FrontendModel::get('fork.settings')->get('Instagram', 'num_recent_items', 10)
);
}
}
|
<?php
namespace Frontend\Modules\Instagram\Ajax;
use Frontend\Core\Engine\Base\AjaxAction as FrontendBaseAJAXAction;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel;
use Symfony\Component\HttpFoundation\Response;
/**
* Fetches the recent user media and passes it back to javascript
*/
class LoadRecentMedia extends FrontendBaseAJAXAction
{
public function execute(): void
{
parent::execute();
$this->output(Response::HTTP_OK, $this->getRecentMedia());
}
private function getRecentMedia(): array
{
return FrontendInstagramModel::getRecentMedia(
$this->getRequest()->request->get('userId'),
FrontendModel::get('fork.settings')->get('Instagram', 'num_recent_items', 10)
);
}
}
|
Add more NTC unit tests
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(object):
def test_ntc_resistance(self):
# Values arbitrarily from Murata NCP15WB473D03RC
assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
assert_approx_equal(ntc_resistance("47k", "4050K", "-18°C"), 463773.791)
assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(object):
def test_ntc_resistance(self):
# Values arbitrarily from Murata NCP15WB473D03RC
assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)
|
Return only tasks without start time for surprise
|
package jfdi.logic.commands;
import jfdi.logic.events.NoSurpriseEvent;
import jfdi.logic.events.SurpriseEvent;
import jfdi.logic.interfaces.Command;
import jfdi.storage.apis.TaskAttributes;
import jfdi.storage.apis.TaskDb;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**
* @author Xinan
*/
public class WildcardCommand extends Command {
private WildcardCommand(Builder builder) {}
public static class Builder {
public WildcardCommand build() {
return new WildcardCommand(this);
}
}
@Override
public void execute() {
ArrayList<TaskAttributes> incompleteTasks = TaskDb.getInstance().getAll().stream()
.filter(task -> !task.isCompleted() && task.getStartDateTime() == null)
.collect(Collectors.toCollection(ArrayList::new));
SecureRandom random = new SecureRandom();
if (!incompleteTasks.isEmpty()) {
TaskAttributes lucky = incompleteTasks.get(random.nextInt(incompleteTasks.size()));
eventBus.post(new SurpriseEvent(lucky));
} else {
eventBus.post(new NoSurpriseEvent(NoSurpriseEvent.Error.NO_TASKS));
}
}
@Override
public void undo() {
throw new UnsupportedOperationException();
}
}
|
package jfdi.logic.commands;
import jfdi.logic.events.NoSurpriseEvent;
import jfdi.logic.events.SurpriseEvent;
import jfdi.logic.interfaces.Command;
import jfdi.storage.apis.TaskAttributes;
import jfdi.storage.apis.TaskDb;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**
* @author Xinan
*/
public class WildcardCommand extends Command {
private WildcardCommand(Builder builder) {}
public static class Builder {
public WildcardCommand build() {
return new WildcardCommand(this);
}
}
@Override
public void execute() {
ArrayList<TaskAttributes> incompleteTasks = TaskDb.getInstance().getAll().stream()
.filter(task -> !task.isCompleted()).collect(Collectors.toCollection(ArrayList::new));
SecureRandom random = new SecureRandom();
if (!incompleteTasks.isEmpty()) {
TaskAttributes lucky = incompleteTasks.get(random.nextInt(incompleteTasks.size()));
eventBus.post(new SurpriseEvent(lucky));
} else {
eventBus.post(new NoSurpriseEvent(NoSurpriseEvent.Error.NO_TASKS));
}
}
@Override
public void undo() {
throw new UnsupportedOperationException();
}
}
|
Split data processing / checks to separate module
|
var NO_DATA = 'no data';
module.exports = {
prepareModuleForRender: function (dashboardConfig, module) {
var data = {
departmentCode: dashboardConfig.department.abbr.toLowerCase(),
dashboardSlug: dashboardConfig.slug,
dashboardTitle: dashboardConfig.title,
moduleType: module['module-type'],
title: module.title,
latest: module.data[0] || null,
secondLatest: module.data[1] || null
};
data.displaySlide = this.displaySlide(data);
if (data.displaySlide) {
data = this.checkForMissingData(data);
}
return data;
},
displaySlide: function (data) {
var returnVal = true;
if ((!data.latest && !data.secondLatest) ||
((data.latest.formatted_value === NO_DATA) &&
(data.secondLatest.formatted_value === NO_DATA))) {
returnVal = false;
}
return returnVal;
},
checkForMissingData: function (data) {
if (data.latest.formatted_value !== NO_DATA) {
data.latestAvailable = true;
}
if (data.secondLatest && (data.secondLatest.formatted_value !== NO_DATA)) {
data.secondLatestAvailable = true;
}
data.showChange = data.latestAvailable && data.secondLatestAvailable;
data.showSecondLatest = !data.latestAvailable && data.secondLatestAvailable;
return data;
}
};
|
var NO_DATA = 'no data';
module.exports = {
prepareModuleForRender: function (dashboardConfig, module) {
var data = {
departmentCode: dashboardConfig.department.abbr.toLowerCase(),
dashboardSlug: dashboardConfig.slug,
dashboardTitle: dashboardConfig.title,
moduleType: module['module-type'],
title: module.title,
latest: module.data[0] || null,
secondLatest: module.data[1] || null
};
data.displaySlide = this.displaySlide(data);
if (data.displaySlide) {
data = this.checkForMissingData(data);
}
return data;
},
displaySlide: function (data) {
var returnVal = true;
if ((!data.latest && !data.secondLatest) ||
((data.latest.formatted_value === NO_DATA) &&
(data.secondLatest.formatted_value === NO_DATA))) {
returnVal = false;
}
return returnVal;
},
checkForMissingData: function (data) {
if (data.latest.formatted_value !== NO_DATA) {
data.latestAvailable = true;
}
if (data.secondLatest && (data.secondLatest.formatted_value !== NO_DATA)) {
data.secondLatestAvailable = true;
}
data.showChange = data.latestAvailable && data.secondLatestAvailable;
data.showSecondLatest = !data.latestAvailable && data.secondLatestAvailable;
return data;
}
};
|
Backport: Fix special keys opening menu when key is unbound
(backport of daec4de7bf091f84a789c90d3956f5aa91486203 to affected branches)
|
package squeek.speedometer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import squeek.speedometer.gui.screen.ScreenSpeedometerSettings;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent;
public class SpeedometerKeyHandler
{
private static final KeyBinding SETTINGS_KEY = new KeyBinding("squeedometer.key.settings", Keyboard.KEY_P, ModInfo.MODID);
static
{
ClientRegistry.registerKeyBinding(SETTINGS_KEY);
}
@SubscribeEvent
public void onKeyEvent(KeyInputEvent event)
{
if (SETTINGS_KEY.isPressed())
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.currentScreen != null)
return;
mc.displayGuiScreen(new ScreenSpeedometerSettings());
}
}
}
|
package squeek.speedometer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import squeek.speedometer.gui.screen.ScreenSpeedometerSettings;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent;
public class SpeedometerKeyHandler
{
private static final KeyBinding SETTINGS_KEY = new KeyBinding("squeedometer.key.settings", Keyboard.KEY_P, ModInfo.MODID);
static
{
ClientRegistry.registerKeyBinding(SETTINGS_KEY);
}
@SubscribeEvent
public void onKeyEvent(KeyInputEvent event)
{
if (Keyboard.getEventKeyState() && Keyboard.getEventKey() == SETTINGS_KEY.getKeyCode())
{
Minecraft mc = Minecraft.getMinecraft();
if (mc.currentScreen != null)
return;
mc.displayGuiScreen(new ScreenSpeedometerSettings());
}
}
}
|
Add explanation about default log level.
|
"""Configuration file for harness.py
Author: Ian Huston
"""
import logging
# Directory structure
# Change the names of various directories
#Change to using the base run directory with bin, pyflation, scripts immediately below.
CODEDIRNAME = "."
RUNDIRNAME = "runs"
RESULTSDIRNAME = "results"
LOGDIRNAME = "applogs"
QSUBSCRIPTSDIRNAME = "qsubscripts"
QSUBLOGSDIRNAME = "qsublogs"
#Name of provenance file which records the code revisions and results files added
provenancefilename = "provenance.log"
# Compression type to be used with PyTables:
# PyTables stores results in HDF5 files. The compression it uses can be
# selected here. For maximum compatibility with other HDF5 utilities use "zlib".
# For maximum efficiency in both storage space and recall time use "blosc".
hdf5complib = "blosc"
hdf5complevel = 2
#This is the default log level which can be overridden in run_config.
# The logging level changes how much is saved to logging files.
# Choose from logging.DEBUG, .INFO, .WARN, .ERROR, .CRITICAL in decreasing order of verbosity
LOGLEVEL = logging.INFO
##################################################
# debug logging control
# 0 for off, 1 for on
##################################################
_debug = 1
#Program name
PROGRAM_NAME = "Pyflation"
VERSION = "0.1.0"
|
"""Configuration file for harness.py
Author: Ian Huston
"""
import logging
# Directory structure
# Change the names of various directories
#Change to using the base run directory with bin, pyflation, scripts immediately below.
CODEDIRNAME = "."
RUNDIRNAME = "runs"
RESULTSDIRNAME = "results"
LOGDIRNAME = "applogs"
QSUBSCRIPTSDIRNAME = "qsubscripts"
QSUBLOGSDIRNAME = "qsublogs"
#Name of provenance file which records the code revisions and results files added
provenancefilename = "provenance.log"
# Compression type to be used with PyTables:
# PyTables stores results in HDF5 files. The compression it uses can be
# selected here. For maximum compatibility with other HDF5 utilities use "zlib".
# For maximum efficiency in both storage space and recall time use "blosc".
hdf5complib = "blosc"
hdf5complevel = 2
# The logging level changes how much is saved to logging files.
# Choose from logging.DEBUG, .INFO, .WARN, .ERROR, .CRITICAL in decreasing order of verbosity
LOGLEVEL = logging.INFO
##################################################
# debug logging control
# 0 for off, 1 for on
##################################################
_debug = 1
#Program name
PROGRAM_NAME = "Pyflation"
VERSION = "0.1.0"
|
Use fixed alpha for low pass filter
Previous calculation was wrong. t is the low pass' filter
time constant (!) and dT is the event delivery rate in nano
seconds.
Chose to use a constant for now (and to ignore delta time).
|
package de.markusfisch.android.shadereditor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
public class AccelerometerListener
implements SensorEventListener
{
private ShaderRenderer renderer;
private long last = 0;
public AccelerometerListener( ShaderRenderer r )
{
renderer = r;
}
public void reset()
{
last = 0;
}
@Override
public final void onAccuracyChanged( Sensor sensor, int accuracy )
{
}
@Override
public final void onSensorChanged( SensorEvent event )
{
if( last > 0 )
{
final float a = .8f;
final float b = 1f-a;
renderer.gravity[0] =
a*renderer.gravity[0]+
b*event.values[0];
renderer.gravity[1] =
a*renderer.gravity[1]+
b*event.values[1];
renderer.gravity[2] =
a*renderer.gravity[2]+
b*event.values[2];
renderer.linear[0] =
event.values[0]-
renderer.gravity[0];
renderer.linear[1] =
event.values[1]-
renderer.gravity[1];
renderer.linear[2] =
event.values[2]-
renderer.gravity[2];
}
last = event.timestamp;
}
}
|
package de.markusfisch.android.shadereditor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
public class AccelerometerListener
implements SensorEventListener
{
private ShaderRenderer renderer;
private long last = 0;
public AccelerometerListener( ShaderRenderer r )
{
renderer = r;
}
public void reset()
{
last = 0;
}
@Override
public final void onAccuracyChanged( Sensor sensor, int accuracy )
{
}
@Override
public final void onSensorChanged( SensorEvent event )
{
if( last > 0 )
{
final float t = event.timestamp;
final float a = t/(t+(t-last));
final float b = 1f-a;
renderer.gravity[0] =
a*renderer.gravity[0]+
b*event.values[0];
renderer.gravity[1] =
a*renderer.gravity[1]+
b*event.values[1];
renderer.gravity[2] =
a*renderer.gravity[2]+
b*event.values[2];
renderer.linear[0] =
event.values[0]-
renderer.gravity[0];
renderer.linear[1] =
event.values[1]-
renderer.gravity[1];
renderer.linear[2] =
event.values[2]-
renderer.gravity[2];
}
last = event.timestamp;
}
}
|
Add link to Font Fabric website
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react/addons';
import styles from './Footer.less';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
export default class Footer {
render() {
var currentYear = new Date().getFullYear();
return (
<footer className="Footer container">
<div className="Footer-container">
<p>
© 2011—{currentYear} Toni Karttunen. All rights reserved.
<a href="https://github.com/tonikarttunen/tonikarttunen-com/">Source code</a>.
Bebas Neue font © <a href='http://www.fontfabric.com'>Font Fabric</a>.
</p>
</div>
</footer>
);
}
}
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react/addons';
import styles from './Footer.less';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
export default class Footer {
render() {
var currentYear = new Date().getFullYear();
return (
<footer className="Footer container">
<div className="Footer-container">
<p>
© 2011—{currentYear} Toni Karttunen. All rights reserved.
<a href="https://github.com/tonikarttunen/tonikarttunen-com/">Source code</a>.
</p>
</div>
</footer>
);
}
}
|
Set properties of AdminApi after ajax response
|
Discourse.AdminApi = Discourse.Model.extend({
VALID_KEY_LENGTH: 64,
keyExists: function(){
var key = this.get('key') || '';
return key && key.length === this.VALID_KEY_LENGTH;
}.property('key'),
generateKey: function(){
var adminApi = this;
Discourse.ajax('/admin/api/generate_key', {type: 'POST'}).then(function (result) {
adminApi.set('key', result.key);
});
},
regenerateKey: function(){
alert(Em.String.i18n('not_implemented'));
}
});
Discourse.AdminApi.reopenClass({
find: function() {
var model = Discourse.AdminApi.create();
Discourse.ajax("/admin/api").then(function(data) {
model.setProperties(data);
});
return model;
}
});
|
Discourse.AdminApi = Discourse.Model.extend({
VALID_KEY_LENGTH: 64,
keyExists: function(){
var key = this.get('key') || '';
return key && key.length === this.VALID_KEY_LENGTH;
}.property('key'),
generateKey: function(){
var adminApi = this;
Discourse.ajax('/admin/api/generate_key', {type: 'POST'}).then(function (result) {
adminApi.set('key', result.key);
});
},
regenerateKey: function(){
alert(Em.String.i18n('not_implemented'));
}
});
Discourse.AdminApi.reopenClass({
find: function() {
return Discourse.ajax("/admin/api").then(function(data) {
return Discourse.AdminApi.create(data);
});
}
});
|
Fix missing create=True attribute in docker tests
|
from __future__ import absolute_import
from __future__ import unicode_literals
import mock
from pre_commit.languages import docker
from pre_commit.util import CalledProcessError
def test_docker_is_running_process_error():
with mock.patch(
'pre_commit.languages.docker.cmd_output',
side_effect=CalledProcessError(*(None,) * 4),
):
assert docker.docker_is_running() is False
def test_docker_fallback_uid():
def invalid_attribute():
raise AttributeError
with mock.patch('os.getuid', invalid_attribute, create=True):
assert docker.getuid() == docker.FALLBACK_UID
def test_docker_fallback_gid():
def invalid_attribute():
raise AttributeError
with mock.patch('os.getgid', invalid_attribute, create=True):
assert docker.getgid() == docker.FALLBACK_GID
|
from __future__ import absolute_import
from __future__ import unicode_literals
import mock
from pre_commit.languages import docker
from pre_commit.util import CalledProcessError
def test_docker_is_running_process_error():
with mock.patch(
'pre_commit.languages.docker.cmd_output',
side_effect=CalledProcessError(*(None,) * 4),
):
assert docker.docker_is_running() is False
def test_docker_fallback_uid():
def invalid_attribute():
raise AttributeError
with mock.patch('os.getuid', invalid_attribute):
assert docker.getuid() == docker.FALLBACK_UID
def test_docker_fallback_gid():
def invalid_attribute():
raise AttributeError
with mock.patch('os.getgid', invalid_attribute):
assert docker.getgid() == docker.FALLBACK_GID
|
Align with changes in OverviewTable.
|
/*jslint browser: true, single: true, maxlen: 120, eval: true, white: true */
/*global define */
/*global set_based_abc_inline_js*/
//----------------------------------------------------------------------------------------------------------------------
define(
'SetBased/Abc/Core/Page/CorePage',
['jquery',
'SetBased/Abc/Page/Page',
'SetBased/Abc/Core/InputTable',
'SetBased/Abc/Table/OverviewTablePackage',
'SetBased/Abc/Form/FormPackage'],
function ($, Page, InputTable, OverviewTable, Form) {
'use strict';
//------------------------------------------------------------------------------------------------------------------
$('form').submit(InputTable.setCsrfValue);
Form.registerForm('form');
InputTable.registerTable('form');
Page.enableDatePicker();
OverviewTable.registerTable('.overview-table');
$('.icon_action').click(Page.showConfirmMessage);
if (window.hasOwnProperty('set_based_abc_inline_js')) {
eval(set_based_abc_inline_js);
}
//------------------------------------------------------------------------------------------------------------------
}
);
//----------------------------------------------------------------------------------------------------------------------
|
/*jslint browser: true, single: true, maxlen: 120, eval: true, white: true */
/*global define */
/*global set_based_abc_inline_js*/
//----------------------------------------------------------------------------------------------------------------------
define(
'SetBased/Abc/Core/Page/CorePage',
['jquery',
'SetBased/Abc/Page/Page',
'SetBased/Abc/Core/InputTable',
'SetBased/Abc/Table/OverviewTablePackage',
'SetBased/Abc/Form/FormPackage'],
function ($, Page, InputTable, OverviewTable, Form) {
'use strict';
//------------------------------------------------------------------------------------------------------------------
$('form').submit(InputTable.setCsrfValue);
Form.registerForm('form');
InputTable.registerTable('form');
Page.enableDatePicker();
OverviewTable.registerTable('.overview_table');
$('.icon_action').click(Page.showConfirmMessage);
if (window.hasOwnProperty('set_based_abc_inline_js')) {
eval(set_based_abc_inline_js);
}
//------------------------------------------------------------------------------------------------------------------
}
);
//----------------------------------------------------------------------------------------------------------------------
|
Use DIRECTORY_SEPARATOR instead of '/'
|
<?php
namespace CarlBennett\MVC\Libraries;
use \CarlBennett\MVC\Libraries\Exceptions\TemplateNotFoundException;
use \CarlBennett\MVC\Libraries\Logger;
use \SplObjectStorage;
final class Template {
protected $context;
protected $template;
public function __construct(&$context, $template) {
$this->additional_css = [];
$this->opengraph = new SplObjectStorage();
$this->setContext($context);
$this->setTemplate($template);
}
public function getContext() {
return $this->context;
}
public function getTemplate() {
return $this->template;
}
public function render() {
$cwd = getcwd();
try {
chdir($cwd . DIRECTORY_SEPARATOR . "templates");
if (!file_exists($this->template)) {
throw new TemplateNotFoundException($this);
}
require($this->template);
} finally {
chdir($cwd);
}
}
public function setContext(&$context) {
$this->context = $context;
}
public function setTemplate($template) {
$this->template = "." . DIRECTORY_SEPARATOR
. str_replace("/", DIRECTORY_SEPARATOR, $template) . ".phtml";
Logger::logMetric("template", $template);
}
}
|
<?php
namespace CarlBennett\MVC\Libraries;
use \CarlBennett\MVC\Libraries\Exceptions\TemplateNotFoundException;
use \CarlBennett\MVC\Libraries\Logger;
use \SplObjectStorage;
final class Template {
protected $context;
protected $template;
public function __construct(&$context, $template) {
$this->additional_css = [];
$this->opengraph = new SplObjectStorage();
$this->setContext($context);
$this->setTemplate($template);
}
public function getContext() {
return $this->context;
}
public function getTemplate() {
return $this->template;
}
public function render() {
$cwd = getcwd();
try {
chdir($cwd . "/templates");
if (!file_exists($this->template)) {
throw new TemplateNotFoundException($this);
}
require($this->template);
} finally {
chdir($cwd);
}
}
public function setContext(&$context) {
$this->context = $context;
}
public function setTemplate($template) {
$this->template = "./" . $template . ".phtml";
Logger::logMetric("template", $template);
}
}
|
Add package transip.service or else this is not installed
|
from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read(),
url = 'http://github.com/goabout/transip-backup',
download_url = 'http://github.com/goabout/transip-backup/archives/master',
packages = ['transip', 'transip.service'],
include_package_data = True,
zip_safe = False,
platforms = ['all'],
test_suite = 'tests',
entry_points = {
'console_scripts': [
'transip-api = transip.transip_cli:main',
],
},
install_requires = [
'requests',
],
)
|
from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read(),
url = 'http://github.com/goabout/transip-backup',
download_url = 'http://github.com/goabout/transip-backup/archives/master',
packages = ['transip'],
include_package_data = True,
zip_safe = False,
platforms = ['all'],
test_suite = 'tests',
entry_points = {
'console_scripts': [
'transip-api = transip.transip_cli:main',
],
},
install_requires = [
'requests',
],
)
|
Read the conf file using absolute paths
|
# Yith Library Server is a password storage server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Yith Library Server is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>.
import os
import os.path
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
from pyramid.paster import setup_logging
from raven.middleware import Sentry
from waitress import serve
basedir= os.path.dirname(os.path.realpath(__file__))
conf_file = os.path.join(
basedir,
'yithlibraryserver', 'config-templates', 'production.ini'
)
application = loadapp('config:%s' % conf_file)
application = agent.WSGIApplicationWrapper(Sentry(application))
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
scheme = os.environ.get("SCHEME", "https")
setup_logging(conf_file)
serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
|
# Yith Library Server is a password storage server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Yith Library Server is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>.
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
from raven.middleware import Sentry
application = loadapp('config:production.ini',
relative_to='yithlibraryserver/config-templates')
application = agent.WSGIApplicationWrapper(Sentry(application))
|
mscgen: Change package name to sphinxcontrib-mscgen
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension mscgen',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension mscgen',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
|
Remove override on createJSModules. Required for RN 0.57.0
|
package ca.bigdata.voice.dtmf;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class BigDataDTMFPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new BigDataDTMFModule(reactContext));
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
package ca.bigdata.voice.dtmf;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class BigDataDTMFPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new BigDataDTMFModule(reactContext));
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
CC-5781: Upgrade script for new storage quota implementation
Include propel library
|
<?php
require_once 'propel/runtime/lib/Propel.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
<?php
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
Replace shaded import with non-shaded one
|
package uk.ac.ebi.atlas.commons.writers.impl;
import au.com.bytecode.opencsv.CSVWriter;
import com.google.common.base.Throwables;
import uk.ac.ebi.atlas.commons.writers.TsvWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class TsvWriterImpl implements TsvWriter {
private Writer writer;
public TsvWriterImpl(Writer writer){
this.writer=writer;
}
@Override
public void write(List<String[]> lines) {
try(CSVWriter csvWriter = new CSVWriter(writer, '\t')){
csvWriter.writeAll(lines);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
}
|
package uk.ac.ebi.atlas.commons.writers.impl;
import au.com.bytecode.opencsv.CSVWriter;
import autovalue.shaded.com.google.common.common.base.Throwables;
import uk.ac.ebi.atlas.commons.writers.TsvWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class TsvWriterImpl implements TsvWriter {
private Writer writer;
public TsvWriterImpl(Writer writer){
this.writer=writer;
}
@Override
public void write(List<String[]> lines) {
try(CSVWriter csvWriter = new CSVWriter(writer, '\t')){
csvWriter.writeAll(lines);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
}
|
Use instanstanceof Array when checking for array
|
import { MicroState } from 'ember-microstates';
export default MicroState.extend({
initialValueFor([array]) {
if (array === undefined) {
return [];
} else if (array instanceof Array) {
return array;
} else {
return [ array ];
}
},
prototypeFor(value = []) {
let wrapped = value.slice();
Object.defineProperty(wrapped, 'valueOf', {
value() {
return value;
}
});
return wrapped;
},
actions: {
add(list, item) {
return list.concat(item);
},
remove(list, item) {
return list.filter(i => i !== item);
},
push(list, item) {
return list.concat(item);
},
pop(list) {
return list.slice(0, list.length - 1);
},
shift(list) {
return list.slice(1);
},
unshift(list, item) {
return [item].concat(list);
}
}
});
|
import { MicroState } from 'ember-microstates';
export default MicroState.extend({
initialValueFor([array]) {
if (array === undefined) {
return [];
} else if (array && array.length != null && array.forEach) {
return array;
} else {
return [ array ];
}
},
prototypeFor(value = []) {
let wrapped = value.slice();
Object.defineProperty(wrapped, 'valueOf', {
value() {
return value;
}
});
return wrapped;
},
actions: {
add(list, item) {
return list.concat(item);
},
remove(list, item) {
return list.filter(i => i !== item);
},
push(list, item) {
return list.concat(item);
},
pop(list) {
return list.slice(0, list.length - 1);
},
shift(list) {
return list.slice(1);
},
unshift(list, item) {
return [item].concat(list);
}
}
});
|
Make legend a bit better
|
requirejs.config({
paths: {
'jquery': './lib/components/jquery/dist/jquery.min'
}
});
require( [ 'src/graph' ] , function( Graph ) {
var functions = [
function( domGraph ) {
var graph = new Graph( domGraph );
graph.newSerie("serieTest")
.setLabel( "My serie" )
.autoAxis()
.setData( [ [1, 2], [2, 5], [3, 10] ] )
.showMarkers( true )
.setMarkerType( 1 );
graph.newSerie("serieTest")
.setLabel( "My serie 2" )
.autoAxis()
.setData( [ [2, 4], [3, 1], [5, 20] ] )
.setLineColor('red');
graph.makeLegend({
frame: true,
frameWidth: 1,
frameColor: "black",
backgroundColor: "rgba(100, 100, 100, 0.5)"
});
graph.redraw( );
graph.drawSeries();
}
]
for( var i = 0, l = functions.length ; i < l ; i ++ ) {
functions[ i ]("example-1-graph");
$("#example-1-source").html( functions[ i ].toString() );
}
} );
|
requirejs.config({
paths: {
'jquery': './lib/components/jquery/dist/jquery.min'
}
});
require( [ 'src/graph' ] , function( Graph ) {
var functions = [
function( domGraph ) {
var graph = new Graph( domGraph );
graph.newSerie("serieTest")
.setLabel( "My serie" )
.autoAxis()
.setData( [ [1, 2], [2, 5], [3, 10] ] )
.showMarkers( true )
.setMarkerType( 1 );
graph.newSerie("serieTest")
.setLabel( "My serie 2" )
.autoAxis()
.setData( [ [2, 4], [3, 1], [5, 20] ] )
.setLineColor('red');
graph.makeLegend({
frame: true,
frameWidth: 1,
frameColor: "green",
backgroundColor: "blue"
});
graph.redraw( );
graph.drawSeries();
}
]
for( var i = 0, l = functions.length ; i < l ; i ++ ) {
functions[ i ]("example-1-graph");
$("#example-1-source").html( functions[ i ].toString() );
}
} );
|
Fix the request.POST, usage of formset and redirect at the end
|
from django.contrib.auth.decorators import permission_required
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ReportForm, CopyFormSet
from .models import Report
@permission_required('reports.add_report', login_url='members:login')
def add_report(request):
data = request.POST if request.POST else None
report_form = ReportForm(data)
formset = CopyFormSet(data, instance=request.session.get('report_in_creation', Report()))
if report_form.is_valid():
report = report_form.save()
request.session['report_in_creation'] = formset.instance = report
if formset.is_valid():
formset.save()
del request.session['report_in_creation']
return redirect('/members/profile/')
return render(request, 'reports/add.html', locals())
def listing(request, page):
reports_list = Report.objects.all()
paginator = Paginator(reports_list, 30)
reports = paginator.page(page)
return render(request, 'reports/listing.html', {"reports": reports})
def show(request, id):
report = get_object_or_404(Report, id=id)
return render(request, 'reports/show.html', locals())
|
from django.contrib.auth.decorators import permission_required
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404
from .forms import ReportForm, CopyFormSet
from .models import Report
@permission_required('reports.add_report', login_url='members:login')
def add_report(request):
data = request.POST if request else None
report_form = ReportForm(data)
if report_form.is_valid():
formset = CopyFormSet(data, instance=request.session.get('report_in_creation', Report()))
report = report_form.save()
request.session['report_in_creation'] = formset.instance = report
if formset.is_valid():
formset.save()
del request.session['report_in_creation']
return render(request, 'reports/add.html', locals())
def listing(request, page):
reports_list = Report.objects.all()
paginator = Paginator(reports_list, 30)
reports = paginator.page(page)
return render(request, 'reports/listing.html', {"reports": reports})
def show(request, id):
report = get_object_or_404(Report, id=id)
return render(request, 'reports/show.html', locals())
|
Implement the methods for the asserts
|
/**
* Created with IntelliJ IDEA.
* User: jhasmanyquiroz
* Date: 11/10/15
* Time: 11:00 AM
* To change this template use File | Settings | File Templates.
*/
package steps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import ui.PageTransporter;
import ui.pages.HomePage;
import ui.pages.LoginPage;
import ui.pages.MainPage;
import static org.testng.Assert.assertTrue;
public class LoginSteps {
private static PageTransporter page = PageTransporter.getInstance();
private HomePage homePage;
private LoginPage loginPage;
private MainPage mainPage;
@Given("^I navigate to Login page$")
public void navigateLoginPage(){
mainPage = page.navigateToMainPage();
loginPage = mainPage.clickLogInButton();
//loginPage = page.navigateToLoginPage();
}
@When("^I login as \"(.*?)\" with password \"(.*?)\"$")
public void loginAs(String userName, String userPassword){
homePage = loginPage.loginSuccessful(userName, userPassword);
}
@Then("^I should login successfully.$")
public void shouldLoginSuccessfully(){
assertTrue(homePage.isPartnersDisplayed(), "User Name displayed");
}
}
|
/**
* Created with IntelliJ IDEA.
* User: jhasmanyquiroz
* Date: 11/10/15
* Time: 11:00 AM
* To change this template use File | Settings | File Templates.
*/
package steps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import ui.PageTransporter;
public class LoginSteps {
public PageTransporter page = PageTransporter.getInstance();
@Given("^I navigate to Login page$")
public void navigateLoginPage(){
page.navigateToMainPage();
}
@When("^I login as \"(.*?)\" with password \"(.*?)\"$")
public void loginAs(String userName, String userPassword){
page.navigateToLoginPage();
}
@Then("^I should login successfully$")
public void should_login_successfully(){
}
}
|
Add a function for easily getting the top level domain of a URL
|
var Class = require('./Class')
var URL = Class(function() {
this._extractionRegex = new RegExp([
'^', // start at the beginning of the string
'((\\w+:)?//)?', // match a possible protocol, like http://, ftp://, or // for a relative url
'(\\w[\\w\\.]+)?', // match a possible domain
'(\\/[^\\?#]+)?', // match a possible path
'(\\?[^#]+)?', // match possible GET parameters
'(#.*)?' // match the rest of the URL as the hash
].join(''), 'i')
this.init = function(url) {
var match = (url || '').toString().match(this._extractionRegex) || []
this.protocol = match[2] || ''
this.host = match[3] || ''
this.pathname = match[4] || ''
this.search = (match[5]||'').substr(1)
this.hash = (match[6]||'').substr(1)
}
this.toString = function() {
return [
this.protocol,
this.host ? '//' + this.host : '',
this.pathname,
this.search ? '?' + this.search : '',
this.hash ? '#' + this.hash : ''
].join('')
}
this.getTopLevelDomain = function() {
if (!this.host) { return '' }
var parts = this.host.split('.')
return parts.slice(parts.length - 2).join('.')
}
})
module.exports = function url(url) { return new URL(url) }
|
var Class = require('./Class')
var URL = Class(function() {
this._extractionRegex = new RegExp([
'^', // start at the beginning of the string
'((\\w+:)?//)?', // match a possible protocol, like http://, ftp://, or // for a relative url
'(\\w[\\w\\.]+)?', // match a possible domain
'(\\/[^\\?#]+)?', // match a possible path
'(\\?[^#]+)?', // match possible GET parameters
'(#.*)?' // match the rest of the URL as the hash
].join(''), 'i')
this.init = function(url) {
var match = (url || '').toString().match(this._extractionRegex) || []
this.protocol = match[2] || ''
this.host = match[3] || ''
this.pathname = match[4] || ''
this.search = (match[5]||'').substr(1)
this.hash = (match[6]||'').substr(1)
}
this.toString = function() {
return [
this.protocol,
this.host ? '//' + this.host : '',
this.pathname,
this.search ? '?' + this.search : '',
this.hash ? '#' + this.hash : ''
].join('')
}
})
module.exports = function url(url) { return new URL(url) }
|
Add mesh points to plot
|
"""
===============================
Piecewise Affine Transformation
===============================
This example shows how to use the Piecewise Affine Transformation.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import PiecewiseAffineTransform, warp
from skimage import data
image = data.lena()
rows, cols = image.shape[0], image.shape[1]
src_cols = np.linspace(0, cols, 20)
src_rows = np.linspace(0, rows, 10)
src_rows, src_cols = np.meshgrid(src_rows, src_cols)
src = np.dstack([src_cols.flat, src_rows.flat])[0]
# add sinusoidal oscillation to row coordinates
dst_rows = src[:, 1] - np.sin(np.linspace(0, 3 * np.pi, src.shape[0])) * 50
dst_cols = src[:, 0]
dst_rows *= 1.5
dst_rows -= 1.5 * 50
dst = np.vstack([dst_cols, dst_rows]).T
tform = PiecewiseAffineTransform()
tform.estimate(src, dst)
out_rows = image.shape[0] - 1.5 * 50
out_cols = cols
out = warp(image, tform, output_shape=(out_rows, out_cols))
plt.imshow(out)
plt.plot(tform.inverse(src)[:, 0], tform.inverse(src)[:, 1], '.b')
plt.axis((0, out_cols, out_rows, 0))
plt.show()
|
"""
===============================
Piecewise Affine Transformation
===============================
This example shows how to use the Piecewise Affine Transformation.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import PiecewiseAffineTransform, warp
from skimage import data
image = data.lena()
rows, cols = image.shape[0], image.shape[1]
src_cols = np.linspace(0, cols, 20)
src_rows = np.linspace(0, rows, 20)
src_rows, src_cols = np.meshgrid(src_rows, src_cols)
src = np.dstack([src_cols.flat, src_rows.flat])[0]
# add sinusoidal oscillation to row coordinates
dst_rows = src[:, 1] - np.sin(np.linspace(0, 3 * np.pi, src.shape[0])) * 50
dst_cols = src[:, 0]
dst_rows *= 1.5
dst_rows -= 1.5 * 50
dst = np.vstack([dst_cols, dst_rows]).T
tform = PiecewiseAffineTransform()
tform.estimate(src, dst)
output_shape = (image.shape[0] - 1.5 * 50, image.shape[1])
out = warp(image, tform, output_shape=output_shape)
plt.imshow(out)
plt.show()
|
Fix lib import for linux platforms
|
const { copyFileSync, existsSync } = require('fs')
const { join } = require('path')
const IS_LINUX = !['win32', 'darwin'].includes(process.platform)
if (!IS_LINUX) {
const baseDir = ({
'darwin': '/usr/local/lib',
'win32': 'C:\\Windows\\system32'
}[process.platform])
const libFilename = ({
'darwin': 'libmpv.1.dylib',
'win32': 'mpv-1.dll'
}[process.platform])
const libPath = join(baseDir, libFilename)
if (!existsSync(libPath)) {
console.warn('KawAnime [PostInstall] -- Could not find libmpv library file. Please install it and put it in `public/mpv`')
} else {
console.log(`KawAnime [PostInstall] -- Found libmpv at ${libPath}`)
copyFileSync(
libPath,
join(__dirname, '..', '..', '..', 'public', 'mpv', libFilename)
)
}
}
|
const { copyFileSync, existsSync } = require('fs')
const { join } = require('path')
const IS_LINUX = !['win32', 'darwin'].includes(process.platform)
const baseDir = ({
'darwin': '/usr/local/lib',
'win32': 'C:\\Windows\\system32'
}[process.platform])
const libFilename = ({
'darwin': 'libmpv.1.dylib',
'win32': 'mpv-1.dll'
}[process.platform])
const libPath = join(baseDir, libFilename)
if (IS_LINUX) {
console.log('KawANime [PostInstall] -- Linux platform detected, no need to move any library')
} else if (!existsSync(libPath)) {
console.warn('KawAnime [PostInstall] -- Could not find libmpv library file. Please install it and put it in `public/mpv`')
} else {
console.log(`KawAnime [PostInstall] -- Found libmpv at ${libPath}`)
copyFileSync(
libPath,
join(__dirname, '..', '..', '..', 'public', 'mpv', libFilename)
)
}
|
Use relative url for logfile
fixes #263
|
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var angular = require('angular');
var module = angular.module('sba-applications-logfile', ['sba-applications']);
global.sbaModules.push(module.name);
module.run(function ($sce, $http, ApplicationViews) {
ApplicationViews.register({
order: 1,
title: $sce.trustAsHtml('<i class="fa fa-file-text-o fa-fw"></i>Log'),
href: 'api/applications/{id}/logfile',
target: '_blank',
show: function (application) {
if (!application.managementUrl || !application.statusInfo.status || application.statusInfo.status === 'OFFLINE') {
return false;
}
return $http.head('api/applications/' + application.id + '/logfile').then(function () {
return true;
}).catch(function () {
return false;
});
}
});
});
|
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var angular = require('angular');
var module = angular.module('sba-applications-logfile', ['sba-applications']);
global.sbaModules.push(module.name);
module.run(function ($sce, $http, ApplicationViews) {
ApplicationViews.register({
order: 1,
title: $sce.trustAsHtml('<i class="fa fa-file-text-o fa-fw"></i>Log'),
href: '/api/applications/{id}/logfile',
target: '_blank',
show: function (application) {
if (!application.managementUrl || !application.statusInfo.status || application.statusInfo.status === 'OFFLINE') {
return false;
}
return $http.head('api/applications/' + application.id + '/logfile').then(function () {
return true;
}).catch(function () {
return false;
});
}
});
});
|
Fix prematurely firing reviewLinker directive
|
"use strict";
angular.module('arethusa.review').directive('reviewLinker', [
'review',
'translator',
function(review, translator) {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
scope.review = review;
scope.translations = {};
translator('review.link', scope.translations, 'link');
translator('review.unlink', scope.translations, 'unlink');
function setTitle(prop) {
element.attr('title', scope.translations[scope.icon]);
}
scope.$watch('translations', function(newVal, oldVal) {
if (newVal !== oldVal) setTitle();
});
scope.$watch('review.link', function(newVal, oldVal) {
if (newVal) {
scope.icon = 'unlink';
if (newVal !== oldVal) {
review.goToCurrentChunk();
}
} else {
scope.icon = 'link';
}
setTitle();
});
},
templateUrl: 'templates/arethusa.review/review_linker.html'
};
}
]);
|
"use strict";
angular.module('arethusa.review').directive('reviewLinker', [
'review',
'translator',
function(review, translator) {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
scope.review = review;
scope.translations = {};
translator('review.link', scope.translations, 'link');
translator('review.unlink', scope.translations, 'unlink');
function setTitle(prop) {
element.attr('title', scope.translations[scope.icon]);
}
scope.$watch('translations', function(newVal, oldVal) {
if (newVal !== oldVal) setTitle();
});
scope.$watch('review.link', function(newVal, oldVal) {
if (newVal) {
scope.icon = 'unlink';
review.goToCurrentChunk();
} else {
scope.icon = 'link';
}
setTitle();
});
},
templateUrl: 'templates/arethusa.review/review_linker.html'
};
}
]);
|
Remove unused Closure compiler configuration
Files are compiled using Uglifier, which has its own config.
|
({
appDir: "./app",
baseUrl: "scripts",
mainConfigFile: "./app/scripts/main.js",
dir: "./build",
pragmasOnSave: {
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: "uglify",
fileExclusionRegExp: /^\.|spec|tests/,
optimizeCss: "standard.keepLines",
generateSourceMaps: false,
preserveLicenseComments: false,
modules: [
{
name: "main",
include: [
"jquery",
"styles"
],
excludeShallow: [
'spec_runner'
]
},
{
name: "styles"
}
]
})
|
({
appDir: "./app",
baseUrl: "scripts",
mainConfigFile: "./app/scripts/main.js",
dir: "./build",
pragmasOnSave: {
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: "uglify",
closure: {
CompilerOptions: {
},
charset: 'UTF-8',
CompilationLevel: 'SIMPLE_OPTIMIZATIONS',
loggingLevel: 'SEVERE'
},
fileExclusionRegExp: /^\.|spec|tests/,
optimizeCss: "standard.keepLines",
generateSourceMaps: false,
preserveLicenseComments: false,
modules: [
{
name: "main",
include: [
"jquery",
"styles"
],
excludeShallow: [
'spec_runner'
]
},
{
name: "styles"
}
]
})
|
Allow submits from LostPasswordForm through
|
<?php
/**
* Description of MemberLoginFilter
*
* @author marcus
*/
class MemberLoginFilter implements RequestFilter
{
public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
{
}
/**
* Check if we're in a login request. If so, we're going to explicitly disable
* restrictedobjects permission checks. This is poor, but dictated by the core
* member login code performing writes prior to having a user context.
*
* @param \SS_HTTPRequest $request
* @param \Session $session
* @param \DataModel $model
*/
public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model)
{
if (strtolower($request->httpMethod()) === 'post' && (
$request->getURL() === 'Security/LoginForm' ||
$request->getURL() === 'Security/LostPasswordForm'
)) {
Restrictable::set_enabled(false);
}
}
}
|
<?php
/**
* Description of MemberLoginFilter
*
* @author marcus
*/
class MemberLoginFilter implements RequestFilter
{
public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
{
}
/**
* Check if we're in a login request. If so, we're going to explicitly disable
* restrictedobjects permission checks. This is poor, but dictated by the core
* member login code performing writes prior to having a user context.
*
* @param \SS_HTTPRequest $request
* @param \Session $session
* @param \DataModel $model
*/
public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model)
{
if (strtolower($request->httpMethod()) === 'post' && $request->getURL() === 'Security/LoginForm') {
Restrictable::set_enabled(false);
}
}
}
|
Make flag parsing example a bit more idiomatic
|
// Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.
//This is not a legal Go program, rather it provides a skeletal
//filter to serve as a minimal base for developing filters.
package <packagename>
import (
"afp"
"afp/flags"
"os"
)
type SkeletonFilter struct {
ctx *afp.Context
}
func (self *SkeletonFilter) Init(ctx *afp.Context, args []string) os.Error {
self.ctx = ctx
parser := flags.FlagParser(args)
a := parser.Int("a", DEFAULT_VALUE, "Argument Description")
parser.Parse()
return nil
}
func (self *SkeletonFilter) Stop() os.Error {
return nil
}
func (self *SkeletonFilter) GetType() int {
return afp.PIPE_< SOURCE | LINK | SINK >
}
func (self *SkeletonFilter) Start() {
//The first thing Start should do is store
//and pass on the header info.
header := <-self.ctx.HeaderSource
self.ctx.HeaderSink <- header
//Then process the content til there's no more to be had
for frame := range self.ctx.Source {
//Process frame
}
}
func NewSkeleton() afp.Filter {
return &SkeletonFilter{}
}
|
// Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.
//This is not a legal Go program, rather it provides a skeletal
//filter to serve as a minimal base for developing filters.
package <packagename>
import (
"afp"
"os"
)
type SkeletonFilter struct {
ctx *afp.Context
}
func (self *SkeletonFilter) Init(ctx *afp.Context, args []string) os.Error {
self.ctx = ctx
parser := flags.FlagParser(args)
var a *int = parser.Int("a", DEFAULT_VALUE, "Argument Description")
parser.Parse()
return nil
}
func (self *SkeletonFilter) Stop() os.Error {
return nil
}
func (self *SkeletonFilter) GetType() int {
return afp.PIPE_< SOURCE | LINK | SINK >
}
func (self *SkeletonFilter) Start() {
//The first thing Start should do is store
//and pass on the header info.
header := <-self.ctx.HeaderSource
self.ctx.HeaderSink <- header
for frame := range self.ctx.Source {
//Process frame
}
}
func NewSkeleton() afp.Filter {
return &SkeletonFilter{}
}
|
Add test for attribute instance assertion
|
import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_name_should_not_be_instance(self):
with self.assertRaises(AssertionError):
Attribute(name='instance')
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
|
import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
|
Designer: Add missing index command in revision
|
"""Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
op.create_index(None, 'designer_templates', ['backside_template_id'], schema='indico')
def downgrade():
op.drop_index('ix_designer_templates_backside_template_id', table_name='designer_templates', schema='indico')
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
|
"""Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
def downgrade():
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
|
Resolve spacing inconsistency (no space before function parameters)
|
;(function(global, factory) {
// Use UMD pattern to expose exported functions
if (typeof exports === 'object') {
// Expose to Node.js
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// Expose to RequireJS
define([], factory);
}
// Expose to global object (likely browser window)
var exports = factory();
for (var prop in exports) {
global[prop] = exports[prop];
}
}(this, function() {
var numIntervals = 0,
intervals = {};
var setCorrectingInterval = function(func, delay) {
var id = numIntervals++,
planned = Date.now() + delay;
function tick() {
func();
if (intervals[id]) {
planned += delay;
intervals[id] = setTimeout(tick, planned - Date.now());
}
}
intervals[id] = setTimeout(tick, delay);
return id;
};
var clearCorrectingInterval = function(id) {
clearTimeout(intervals[id]);
delete intervals[id];
};
return {
setCorrectingInterval: setCorrectingInterval,
clearCorrectingInterval: clearCorrectingInterval
};
}));
|
;(function(global, factory) {
// Use UMD pattern to expose exported functions
if (typeof exports === 'object') {
// Expose to Node.js
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// Expose to RequireJS
define([], factory);
}
// Expose to global object (likely browser window)
var exports = factory();
for (var prop in exports) {
global[prop] = exports[prop];
}
}(this, function() {
var numIntervals = 0,
intervals = {};
var setCorrectingInterval = function (func, delay) {
var id = numIntervals++,
planned = Date.now() + delay;
function tick () {
func();
if (intervals[id]) {
planned += delay;
intervals[id] = setTimeout(tick, planned - Date.now());
}
}
intervals[id] = setTimeout(tick, delay);
return id;
};
var clearCorrectingInterval = function (id) {
clearTimeout(intervals[id]);
delete intervals[id];
};
return {
setCorrectingInterval: setCorrectingInterval,
clearCorrectingInterval: clearCorrectingInterval
};
}));
|
Allow value to be set externally.
Currently the medium editor's value is only set on init. That makes
it impossible to reset a form on submit, for example. This commit
adds an observer that ensures the value is updated if the editor's
value differs from the component's value.
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
attributeBindings: ['contenteditable'],
editable: true,
isUserTyping: false,
plaintext: false,
classNames: ['editable'],
contenteditable: (function() {
var editable = this.get('editable');
return editable ? 'true' : undefined;
}).property('editable'),
didInsertElement: function() {
new MediumEditor(this.$(), (this.get('options') ? JSON.parse(this.get('options')) : {}));
return this.setContent();
},
focusOut: function() {
return this.set('isUserTyping', false);
},
keyDown: function(event) {
if (!event.metaKey) {
return this.set('isUserTyping', true);
}
},
input: function() {
if (this.get('plaintext')) {
return this.set('value', this.$().text());
} else {
return this.set('value', this.$().html());
}
},
render: function(buffer) {
buffer.push((this.get('value') || null));
},
valueDidChange: function() {
if (this.$() && this.get('value') !== this.$().html()) {
this.setContent();
}
}.observes('value'),
setContent: function() {
if (this.$()) {
return this.$().html(this.get('value'));
}
}
});
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
attributeBindings: ['contenteditable'],
editable: true,
isUserTyping: false,
plaintext: false,
classNames: ['editable'],
contenteditable: (function() {
var editable = this.get('editable');
return editable ? 'true' : undefined;
}).property('editable'),
didInsertElement: function() {
new MediumEditor(this.$(), (this.get('options') ? JSON.parse(this.get('options')) : {}));
return this.setContent();
},
focusOut: function() {
return this.set('isUserTyping', false);
},
keyDown: function(event) {
if (!event.metaKey) {
return this.set('isUserTyping', true);
}
},
input: function() {
if (this.get('plaintext')) {
return this.set('value', this.$().text());
} else {
return this.set('value', this.$().html());
}
},
render: function(buffer) {
buffer.push((this.get('value') || null));
},
setContent: function() {
var this_m = this;
if (this_m.$()) {
return this_m.$().html(this_m.get('value'));
}
}
});
|
Remove scrollLink attr from scholarship linkButton
|
import React, { Component } from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import PropTypes from 'prop-types';
import styles from './preview.css';
class Preview extends Component {
render() {
const { scholarship } = this.props;
return (
<div className={styles.preview}>
<h6 className={styles.previewHeader6}>{scholarship.name}</h6>
<div className={styles.buttonContainer}><LinkButton link={`scholarships/${scholarship.id}/apply`} text="Read More" theme="blue" /></div>
</div>
);
}
}
Preview.propTypes = {
scholarship: PropTypes.shape({
name: PropTypes.string,
description: PropTypes.string,
location: PropTypes.string,
open_time: PropTypes.string,
close_time: PropTypes.string,
id: PropTypes.number,
created_at: PropTypes.string,
updated_at: PropTypes.string
})
};
Preview.defaultProps = {
scholarship: false
};
export default Preview;
|
import React, { Component } from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import PropTypes from 'prop-types';
import styles from './preview.css';
class Preview extends Component {
render() {
const { scholarship } = this.props;
return (
<div className={styles.preview}>
<h6 className={styles.previewHeader6}>{scholarship.name}</h6>
<div className={styles.buttonContainer}><LinkButton link={`scholarships/${scholarship.id}/apply`} text="Read More" theme="blue" scrollLink /></div>
</div>
);
}
}
Preview.propTypes = {
scholarship: PropTypes.shape({
name: PropTypes.string,
description: PropTypes.string,
location: PropTypes.string,
open_time: PropTypes.string,
close_time: PropTypes.string,
id: PropTypes.number,
created_at: PropTypes.string,
updated_at: PropTypes.string
})
};
Preview.defaultProps = {
scholarship: false
};
export default Preview;
|
Use public key as id.
|
import json
import socket
from crypto import retrieve_key
from orderbook import create_confirm
def send_msg(ip, port, message):
'''Sends a raw string to the given ip and port. Closes the socket and returns the response.'''
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(message)
response = sock.recv(1024)
finally:
sock.close()
return response
def send_offer(ip, port, offer):
'''Sends an offer in JSON form to the given ip and port. offer parameter should be a dictionary.'''
message = json.dumps(offer)
return send_msg(ip, port, message)
def handle_response(response):
try:
response = json.loads(response)
if response and isinstance(response, basestring):
return None
if response and response['type'] == 'trade':
return handle_trade(response)
except ValueError:
return None
def handle_trade(trade):
# id is not yet properly implemented so we use this ugly hack for now
# Cancel messages are not yet implemented. See issue #7.
return create_confirm(
trade_id=trade['trade-id']
)
|
import json
import socket
from orderbook import create_confirm
def send_msg(ip, port, message):
'''Sends a raw string to the given ip and port. Closes the socket and returns the response.'''
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(message)
response = sock.recv(1024)
finally:
sock.close()
return response
def send_offer(ip, port, offer):
'''Sends an offer in JSON form to the given ip and port. offer parameter should be a dictionary.'''
message = json.dumps(offer)
return send_msg(ip, port, message)
def handle_response(response):
try:
response = json.loads(response)
if response and isinstance(response, basestring):
return None
if response and response['type'] == 'trade':
return handle_trade(response)
except ValueError:
return None
def handle_trade(trade):
# id is not yet properly implemented so we use this ugly hack for now
id = trade['trade-id'].split(';')[0]
# Cancel messages are not yet implemented. See issue #7.
return create_confirm(
id=id,
trade_id=trade['trade-id']
)
|
Check if you are using python 3.3+
|
# -*- coding: utf-8 -*-
"""
A text interface to Taiga.
"""
from __future__ import print_function
import sys
if sys.version_info[0] < 3 or sys.version_info[1] < 3:
print("Sorry, taiga-ncurses needs python >= 3.3", file=sys.stderr)
sys.exit(-1)
from taiga_ncurses import __name__, __description__, __version__
from setuptools import setup, find_packages
REQUIREMENTS = [
"requests==2.5.0",
"urwid>=1.3.0",
"x256==0.0.3"
]
NAME = __name__
DESCRIPTION = __description__
VERSION = "{0}.{1}".format(*__version__)
setup(name=NAME,
version=VERSION,
description=DESCRIPTION,
packages=find_packages(),
entry_points={
"console_scripts": ["taiga-ncurses = taiga_ncurses.cli:main"]
},
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: End Users/Desktop",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS",
"Programming Language :: Python :: 3.3",
],
install_requires=REQUIREMENTS,)
|
# -*- coding: utf-8 -*-
"""
A text interface to Taiga.
"""
from taiga_ncurses import __name__, __description__, __version__
from setuptools import setup, find_packages
REQUIREMENTS = [
"requests==2.5.0",
"urwid>=1.3.0",
"x256==0.0.3"
]
NAME = __name__
DESCRIPTION = __description__
VERSION = "{0}.{1}".format(*__version__)
setup(name=NAME,
version=VERSION,
description=DESCRIPTION,
packages=find_packages(),
entry_points={
"console_scripts": ["taiga-ncurses = taiga_ncurses.cli:main"]
},
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console :: Curses",
"Intended Audience :: End Users/Desktop",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS",
"Programming Language :: Python :: 3.3",
],
install_requires=REQUIREMENTS,)
|
Add a feed_storage and feed_cache to our Globals object.
|
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
#from myfedora.streams import DataStreamer
#self.datastreamer = DataStreamer()
FEED_CACHE = "/tmp/moksha-feeds"
from shove import Shove
from feedcache.cache import Cache
# is this not multi-process safe? or even thread safe?
self.feed_storage = Shove('file://' + FEED_CACHE)
self.feed_cache = Cache(self.feed_storage)
|
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
from myfedora.streams import DataStreamer
self.datastreamer = DataStreamer()
|
Fix branches being mixed in Tree structure
|
package net.acomputerdog.core.tree;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Branch<T> {
private final Branch<T> parent;
private final List<Branch<T>> branches = new LinkedList<Branch<T>>();
private final List<Leaf<T>> leaves = new LinkedList<Leaf<T>>();
private final Tree<T> tree;
public Branch(Tree<T> tree, Branch<T> parent) {
this.parent = parent;
this.tree = tree;
}
public boolean isRoot() {
return parent == null;
}
public Branch getParent() {
return parent;
}
public List<Branch<T>> getBranches() {
return Collections.unmodifiableList(branches);
}
public List<Leaf<T>> getLeaves() {
return Collections.unmodifiableList(leaves);
}
public int getNumBranches() {
return branches.size();
}
public int getNumLeaves() {
return leaves.size();
}
public void addBranch(Branch<T> branch) {
branches.add(branch);
}
public void addLeaf(Leaf<T> leaf) {
leaves.add(leaf);
}
public Tree<T> getTree() {
return tree;
}
}
|
package net.acomputerdog.core.tree;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Branch<T> {
private final Branch<T> parent;
private final Set<Branch<T>> branches = new HashSet<Branch<T>>();
private final Set<Leaf<T>> leaves = new HashSet<Leaf<T>>();
private final Tree<T> tree;
public Branch(Tree<T> tree, Branch<T> parent) {
this.parent = parent;
this.tree = tree;
}
public boolean isRoot() {
return parent == null;
}
public Branch getParent() {
return parent;
}
public Set<Branch<T>> getBranches() {
return Collections.unmodifiableSet(branches);
}
public Set<Leaf<T>> getLeaves() {
return Collections.unmodifiableSet(leaves);
}
public int getNumBranches() {
return branches.size();
}
public int getNumLeaves() {
return leaves.size();
}
public void addBranch(Branch<T> branch) {
branches.add(branch);
}
public void addLeaf(Leaf<T> leaf) {
leaves.add(leaf);
}
public Tree<T> getTree() {
return tree;
}
}
|
Add values to new field one at a time to avoid adding an ArrayList object.
|
package org.myrobotlab.document.transformer;
import org.myrobotlab.document.transformer.StageConfiguration;
import java.util.List;
import org.myrobotlab.document.Document;
/**
* This stage will rename the field on a document.
* @author kwatters
*
*/
public class RenameField extends AbstractStage {
private String oldName = "fielda";
private String newName = "fieldb";
@Override
public void startStage(StageConfiguration config) {
// TODO Auto-generated method stub
if (config != null) {
oldName = config.getProperty("oldName");
newName = config.getProperty("newName");
}
}
@Override
public List<Document> processDocument(Document doc) {
if (!doc.hasField(oldName)) {
return null;
}
for (Object o : doc.getField(oldName)) {
doc.addToField(newName, o);
}
doc.removeField(oldName);
return null;
}
@Override
public void stopStage() {
// TODO Auto-generated method stub
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
}
|
package org.myrobotlab.document.transformer;
import org.myrobotlab.document.transformer.StageConfiguration;
import java.util.List;
import org.myrobotlab.document.Document;
/**
* This stage will rename the field on a document.
* @author kwatters
*
*/
public class RenameField extends AbstractStage {
private String oldName = "fielda";
private String newName = "fieldb";
@Override
public void startStage(StageConfiguration config) {
// TODO Auto-generated method stub
if (config != null) {
oldName = config.getProperty("oldName");
newName = config.getProperty("newName");
}
}
@Override
public List<Document> processDocument(Document doc) {
if (!doc.hasField(oldName)) {
return null;
}
doc.addToField(newName, doc.getField(oldName));
doc.removeField(oldName);
return null;
}
@Override
public void stopStage() {
// TODO Auto-generated method stub
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
}
|
Fix an actual schema validation error in one of the tests
|
import pytest
import python_jsonschema_objects as pjo
@pytest.fixture
def test_class():
schema = {
'title': 'Example',
'properties': {
"claimed_by": {
"id": "claimed",
"type": ["string", "integer", "null"],
"description": "Robots Only. The human agent that has claimed this robot.",
},
}
}
builder = pjo.ObjectBuilder(schema)
ns = builder.build_classes()
return ns
@pytest.mark.parametrize('value', [
"Hi", 4, None])
def test_properties_can_have_multiple_types(test_class, value):
test_class.Example(claimed_by=value)
@pytest.mark.parametrize('value', [2.4])
def test_multiply_typed_properties_still_validate(test_class, value):
with pytest.raises(pjo.ValidationError):
test_class.Example(claimed_by=value)
|
import pytest
import python_jsonschema_objects as pjo
@pytest.fixture
def test_class():
schema = {
'title': 'Example',
'properties': {
"claimed_by": {
"id": "claimed",
"type": ["string", "integer", "null"],
"description": "Robots Only. The human agent that has claimed this robot.",
"required": False
},
}
}
builder = pjo.ObjectBuilder(schema)
ns = builder.build_classes()
return ns
@pytest.mark.parametrize('value', [
"Hi", 4, None])
def test_properties_can_have_multiple_types(test_class, value):
test_class.Example(claimed_by=value)
@pytest.mark.parametrize('value', [2.4])
def test_multiply_typed_properties_still_validate(test_class, value):
with pytest.raises(pjo.ValidationError):
test_class.Example(claimed_by=value)
|
Fix default object and validation
|
'use strict';
var assert = require('assert')
var dataServiceFactory = require('./dataService')
function createDataServices(config) {
var dataServices = {}
config.forEach((dsConfig) => {
dataServices[dsConfig.name] = dataServiceFactory(dsConfig)
})
return dataServices
}
/**
* DataService controller.
* Provides a getDataServiceForLayer method to take a layer config and
* return a predefined DataService
*/
class DataServiceController {
/**
* @constructor
* @param {object} config
*/
constructor(config) {
this.config = config || []
this.dataServices = createDataServices(this.config)
}
/**
* Convenience method to retrieve a dataSource for the given layerConfig definition
* Also verifies that the layer references a known dataSource
*/
getDataServiceForLayer(layerConfig) {
assert.ok(!!this.dataServices[layerConfig.dataSource], 'Layer `' + layerConfig.name + '` specifies a dataSource that doesn\'t exist')
return this.dataServices[layerConfig.dataSource]
}
}
/**
* Module entry point. Validates config object input using asserts
* @param {object} config
* @return {DataServiceController}
*/
module.exports = (config) => {
return new DataServiceController(config)
}
|
'use strict';
var assert = require('assert')
var dataServiceFactory = require('./dataService')
function createDataServices(config) {
var dataServices = {}
config.forEach((dsConfig) => {
dataServices[dsConfig.name] = dataServiceFactory(dsConfig)
})
return dataServices
}
/**
* DataService controller.
* Provides a getDataServiceForLayer method to take a layer config and
* return a predefined DataService
*/
class DataServiceController {
/**
* @constructor
* @param {object} config
*/
constructor(config) {
this.config = config
this.dataServices = createDataServices(config)
}
/**
* Convenience method to retrieve a dataSource for the given layerConfig definition
* Also verifies that the layer references a known dataSource
*/
getDataServiceForLayer(layerConfig) {
assert.ok(!!this.dataServices[layerConfig.dataSource], 'Layer ' + layerConfig.name + ' specifies a dataSource that doesn\'t exist')
return this.dataServices[layerConfig.dataSource]
}
}
/**
* Module entry point. Validates config object input using asserts
* @param {object} config
* @return {DataServiceController}
*/
module.exports = (config) => {
return new DataServiceController(config)
}
|
Comment addition and interface change from Vector to AbstractList
|
import java.util.AbstractList;
/**
*
*/
/**
* An interface for password store objects.
*
* @author Miltiadis Allamanis
*
*/
public interface IPasswordStore {
/**
* Return a list of all the stored passwords.
*
* @return a vector containing the ids of stored passwords
*/
public AbstractList<String> getAllStoredPasswordIds();
/**
* Remove password from store.
*
* @param aId
* the id of the password
* @return true if the password has been sucessfuly removed
*/
public boolean removePassword(final String aId);
/**
* Retrieve a unique password with the specified id.
*
* @param aId
* the unique password id to look for
* @return a Password object or null if no password with an id is found
*/
public Password retrivePassword(final String aId);
/**
* Store a password object to the store.
*
* @param aPassword
* the password to store
* @return true if the password has been stored sucessfully
*/
public boolean storePassword(final Password aPassword);
}
|
import java.util.Vector;
/**
*
*/
/**
* An interface for password store objects.
*
* @author Miltiadis Allamanis
*
*/
public interface IPasswordStore {
/**
* Return a list of all the stored passwords.
*
* @return a vector containing the ids of stored passwords
*/
public Vector<String> getAllStoredPasswordIds();
public boolean removePassword(final String aId);
/**
* Retrieve a unique password with the specified id.
*
* @param aId
* the unique password id to look for
* @return a Password object or null if no password with an id is found
*/
public Password retrivePassword(final String aId);
/**
* Store a password object to the store.
*
* @param aPassword
* the password to store
* @return true if the password has been stored sucessfully
*/
public boolean storePassword(final Password aPassword);
}
|
Use dot notation to calm jshint.
|
define(function(require, exports, module) {
"use strict";
var Backbone = require("backbone");
var candidatesTemplate = require("text!templates/candidates.html");
var CandidatesView = Backbone.View.extend({
tpl: _.template(candidatesTemplate),
render: function() {
this.$el.html(this.tpl({pairs: this._pairCandidates()}));
return this;
},
_pairCandidates: function() {
// Each object in pairs is another object with two keys: "capres" and "cawapres".
// The top keys will be caleg id.
var pairs = {};
_.each(this.collection.models, function(model) {
var id = model.get("id");
var id_mate = model.get("id_running_mate");
var role = model.get("role");
if (role === "capres" && _.isUndefined(pairs[id])) pairs[id] = {};
if (role === "cawapres" && _.isUndefined(pairs[id_mate])) pairs[id_mate] = {};
if (role === "capres") {
pairs[id].capres = model.toJSON();
} else if (role === "cawapres") {
pairs[id_mate].cawapres = model.toJSON();
}
});
return pairs;
}
});
module.exports = CandidatesView;
});
|
define(function(require, exports, module) {
"use strict";
var Backbone = require("backbone");
var candidatesTemplate = require("text!templates/candidates.html");
var CandidatesView = Backbone.View.extend({
tpl: _.template(candidatesTemplate),
render: function() {
this.$el.html(this.tpl({pairs: this._pairCandidates()}));
return this;
},
_pairCandidates: function() {
// Each object in pairs is another object with two keys: "capres" and "cawapres".
// The top keys will be caleg id.
var pairs = {};
_.each(this.collection.models, function(model) {
var id = model.get("id");
var id_mate = model.get("id_running_mate");
var role = model.get("role");
if (role === "capres" && _.isUndefined(pairs[id])) pairs[id] = {};
if (role === "cawapres" && _.isUndefined(pairs[id_mate])) pairs[id_mate] = {};
if (role === "capres") {
pairs[id]["capres"] = model.toJSON();
} else if (role === "cawapres") {
pairs[id_mate]["cawapres"] = model.toJSON();
}
});
return pairs;
}
});
module.exports = CandidatesView;
});
|
Add tests to the package
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup, Extension
from sysctl import get_version
modules = [
Extension(
'sysctl/_sysctl',
sources=['sysctl/_sysctl.c'],
extra_compile_args=["-Wall"],
)
]
setup(
name='sysctl',
version=get_version(),
url='https://github.com/williambr/py-sysctl',
license='BSD',
author='William Grzybowski',
author_email='wg@FreeBSD.org',
description='Wrapper for the sysctl* system functions',
long_description=open(
os.path.join(
os.path.dirname(__file__),
'README.rst'
)
).read(),
keywords='sysctl',
packages=('sysctl', 'sysctl/tests'),
platforms='any',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: BSD :: FreeBSD',
'Programming Language :: Python',
],
#cmdclass={'build_py': build_py},
ext_modules=modules,
test_suite='nose.collector',
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup, Extension
from sysctl import get_version
modules = [
Extension(
'sysctl/_sysctl',
sources=['sysctl/_sysctl.c'],
extra_compile_args=["-Wall"],
)
]
setup(
name='sysctl',
version=get_version(),
url='https://github.com/williambr/py-sysctl',
license='BSD',
author='William Grzybowski',
author_email='wg@FreeBSD.org',
description='Wrapper for the sysctl* system functions',
long_description=open(
os.path.join(
os.path.dirname(__file__),
'README.rst'
)
).read(),
keywords='sysctl',
packages=('sysctl', ),
platforms='any',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: BSD :: FreeBSD',
'Programming Language :: Python',
],
#cmdclass={'build_py': build_py},
ext_modules=modules,
test_suite='nose.collector',
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.