text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Use sed inline (unsure why mv was used originally). | # pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return int(mode)
except (TypeError, ValueError):
pass
# Return as-is (ie +x which we don't need to normalise, it always gets run)
return mode
def sed_replace(state, filename, line, replace, flags=None):
flags = ''.join(flags) if flags else ''
line = line.replace('/', '\/')
replace = replace.replace('/', '\/')
return 'sed -i "s/{0}/{1}/{2}" {3}'.format(
line, replace, flags, filename
)
def chmod(target, mode, recursive=False):
return 'chmod {0}{1} {2}'.format(('-R ' if recursive else ''), mode, target)
def chown(target, user, group=None, recursive=False):
command = 'chown'
user_group = None
if user and group:
user_group = '{0}:{1}'.format(user, group)
elif user:
user_group = user
elif group:
command = 'chgrp'
user_group = group
return '{0}{1} {2} {3}'.format(
command,
' -R' if recursive else '',
user_group,
target
)
| # pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return int(mode)
except (TypeError, ValueError):
pass
# Return as-is (ie +x which we don't need to normalise, it always gets run)
return mode
def sed_replace(state, filename, line, replace, flags=None):
flags = ''.join(flags) if flags else ''
line = line.replace('/', '\/')
replace = replace.replace('/', '\/')
temp_filename = state.get_temp_filename()
return 'sed "s/{0}/{1}/{2}" {3} > {4} && mv {4} {3}'.format(
line, replace, flags, filename, temp_filename
)
def chmod(target, mode, recursive=False):
return 'chmod {0}{1} {2}'.format(('-R ' if recursive else ''), mode, target)
def chown(target, user, group=None, recursive=False):
command = 'chown'
user_group = None
if user and group:
user_group = '{0}:{1}'.format(user, group)
elif user:
user_group = user
elif group:
command = 'chgrp'
user_group = group
return '{0}{1} {2} {3}'.format(
command,
' -R' if recursive else '',
user_group,
target
)
|
Disable raise php limits from \CSSmin
Unit tests can not be achieved due to max_execution_time set by default to 60 seconds from class \CSSmin. | <?php
namespace AssetsBundle\AssetFile\AssetFileFilter;
class CssAssetFileFilter extends \AssetsBundle\AssetFile\AssetFileFilter\AbstractAssetFileFilter {
/**
* @var string
*/
protected $assetFileFilterName = \AssetsBundle\AssetFile\AssetFile::ASSET_CSS;
/**
* @var \CSSmin
*/
protected $cssMin;
/**
* @param \AssetsBundle\AssetFile\AssetFile $oAssetFile
* @throws \LogicException
* @throws \InvalidArgumentException
* @return string
*/
public function filterAssetFile(\AssetsBundle\AssetFile\AssetFile $oAssetFile) {
//Try to retrieve cached filter rendering
if ($sCachedFilterRendering = $this->getCachedFilteredContent($oAssetFile)) {
return $sCachedFilterRendering;
}
$sFilteredContent = $this->getCSSmin()->run($oAssetFile->getAssetFileContents());
$this->cacheFilteredAssetFileContent($oAssetFile, $sFilteredContent);
return $sFilteredContent;
}
/**
* @return \CSSmin
* @throws \LogicException
*/
protected function getCSSmin() {
if ($this->cssMin instanceof \CSSmin) {
return $this->cssMin;
}
if (!class_exists('CSSmin')) {
throw new \LogicException('"CSSmin" class does not exist');
}
return $this->cssMin = new \CSSmin(false);
}
}
| <?php
namespace AssetsBundle\AssetFile\AssetFileFilter;
class CssAssetFileFilter extends \AssetsBundle\AssetFile\AssetFileFilter\AbstractAssetFileFilter {
/**
* @var string
*/
protected $assetFileFilterName = \AssetsBundle\AssetFile\AssetFile::ASSET_CSS;
/**
* @var \CSSmin
*/
protected $cssMin;
/**
* @param \AssetsBundle\AssetFile\AssetFile $oAssetFile
* @throws \LogicException
* @throws \InvalidArgumentException
* @return string
*/
public function filterAssetFile(\AssetsBundle\AssetFile\AssetFile $oAssetFile) {
//Try to retrieve cached filter rendering
if ($sCachedFilterRendering = $this->getCachedFilteredContent($oAssetFile)) {
return $sCachedFilterRendering;
}
$sFilteredContent = $this->getCSSmin()->run($oAssetFile->getAssetFileContents());
$this->cacheFilteredAssetFileContent($oAssetFile, $sFilteredContent);
return $sFilteredContent;
}
/**
* @return \CSSmin
* @throws \LogicException
*/
protected function getCSSmin() {
if ($this->cssMin instanceof \CSSmin) {
return $this->cssMin;
}
if (!class_exists('CSSmin')) {
throw new \LogicException('"CSSmin" class does not exist');
}
return $this->cssMin = new \CSSmin();
}
}
|
Create model name dynamically in Local authenticator | 'use strict';
/**
* Module dependencies.
*/
import { UNAUTHORIZED } from 'http-codes';
import capitalize from 'capitalize';
import models from './models';
module.exports = function({ CorePOSTAuthenticator }) {
return class LocalAuthenticator extends CorePOSTAuthenticator {
hubToAuthenticator() {
const debug = this.debug;
const dependencies = this.dependencies;
const name = this.name;
return async (req, res, next) => {
try {
const { username, password } = req.body;
debug(`authenticating username ${username} and password ${password}`);
const User =
dependencies.database.models[
`Authentication$${capitalize(name)}$User`
]; // TODO this is bad, models should come from the CorePOSTAuthenticator in an elegant format
const user = await User.findOne({
attributes: ['id', 'password'],
raw: true,
where: { username },
});
if (user) {
const { id, password: actualPassword } = user;
// Mock authentication code
// TODO replace with bcrypt
if (password === actualPassword) {
// success
res.send({ id });
} else {
// bad password
res.sendStatus(UNAUTHORIZED);
}
} else {
// user not found
res.sendStatus(UNAUTHORIZED);
}
} catch (error) {
debug('error within local authenticator', error.message);
throw error;
}
};
}
static models() {
return models;
}
};
};
| 'use strict';
/**
* Module dependencies.
*/
import { UNAUTHORIZED } from 'http-codes';
import models from './models';
module.exports = function({ CorePOSTAuthenticator }) {
return class LocalAuthenticator extends CorePOSTAuthenticator {
hubToAuthenticator() {
const debug = this.debug;
const dependencies = this.dependencies;
return async (req, res, next) => {
try {
const { username, password } = req.body;
debug(`authenticating username ${username} and password ${password}`);
const { Authentication$Local$User } = dependencies.database.models;
const user = await Authentication$Local$User.findOne({
attributes: ['id', 'password'],
raw: true,
where: { username },
});
if (user) {
const { id, password: actualPassword } = user;
// Mock authentication code
// TODO replace with bcrypt
if (password === actualPassword) {
// success
res.send({ id });
} else {
// bad password
res.sendStatus(UNAUTHORIZED);
}
} else {
// user not found
res.sendStatus(UNAUTHORIZED);
}
} catch (error) {
debug('error within local authenticator', error.message);
throw error;
}
};
}
static models() {
return models;
}
};
};
|
Update unittest to be complient with a newer version of pytest | import os
import sys
import tempfile
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
SCRIPTS_DIR = os.path.join(CURRENT_DIR, '..', 'scripts')
sys.path.append(SCRIPTS_DIR)
SAMPLE_DIR = os.path.join(CURRENT_DIR, 'sample')
from compute_abundance import abundance_calculation
import pytest
@pytest.mark.parametrize('blast,expected_abundance',
[ # Basic test
['scaffolds.blast',
{'scaff1': 1.75,
'scaff2': 3.75,
'scaff3': 1.25,
'scaff4': 1.25
}
],
# Test the case where a read can be found several times on the same scaffolds.
# this behavior is tolerated but is not intented to occur often
['scaffolds_multiple_reads.blast',
{ '159': 0.5,
'161': 1,
'175': 0.5,
'240': 3
},
]
]
)
def test_abundance_calculation(blast, expected_abundance):
blast_file = os.path.join(SAMPLE_DIR, blast)
abundance = abundance_calculation(blast_file)
assert set(abundance.keys()) == set(expected_abundance.keys())
assert sorted(abundance.values()) == pytest.approx(sorted(expected_abundance.values()))
| import os
import sys
import tempfile
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
SCRIPTS_DIR = os.path.join(CURRENT_DIR, '..', 'scripts')
sys.path.append(SCRIPTS_DIR)
SAMPLE_DIR = os.path.join(CURRENT_DIR, 'sample')
from compute_abundance import abundance_calculation
import pytest
@pytest.mark.parametrize('blast,expected_abundance',
[ # Basic test
['scaffolds.blast',
{'scaff1': 1.75,
'scaff2': 3.75,
'scaff3': 1.25,
'scaff4': 1.25
}
],
# Test the case where a read can be found several times on the same scaffolds.
# this behavior is tolerated but is not intented to occur often
['scaffolds_multiple_reads.blast',
{ '159': 0.5,
'161': 1,
'175': 0.5,
'240': 3
},
]
]
)
def test_abundance_calculation(blast, expected_abundance):
blast_file = os.path.join(SAMPLE_DIR, blast)
abundance = abundance_calculation(blast_file)
assert set(abundance.keys()) == set(expected_abundance.keys())
assert set(abundance.values()) == pytest.approx(set(expected_abundance.values()))
|
Add process_id into the $state.go statements. Have chooseExistingProcess make a REST call to get the list of processes. | (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.createSample = createSample;
ctrl.useTemplate = useTemplate;
ctrl.templates = templates;
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
});
}
function useTemplate(templateName) {
$state.go('projects.project.processes.create', {process: templateName, process_id: ''});
}
function createSample() {
$state.go('projects.project.processes.create', {process: 'As Received', process_id: ''});
}
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM';
$state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id});
});
});
}
}
}(angular.module('materialscommons')));
| (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state"];
function ProjectHomeController(project, mcmodal, templates, $state) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.createSample = createSample;
ctrl.useTemplate = useTemplate;
ctrl.templates = templates;
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName});
});
}
function useTemplate(templateName) {
$state.go('projects.project.processes.create', {process: templateName});
}
function createSample() {
$state.go('projects.project.processes.create', {process: 'As Received'});
}
function chooseExistingProcess() {
mcmodal.chooseExistingProcess(ctrl.project).then(function (existingProcess) {
$state.go('projects.project.processes.create', {process: existingProcess.process_name, process_id: existingProcess.id});
});
}
}
}(angular.module('materialscommons')));
|
Fix can't build entry point by incorrect build setting | const webpack = require("webpack");
const path = require("path");
const sourceDir = path.join(__dirname, "src");
const distDir = path.join(__dirname, "dist");
module.exports = {
target: "electron",
context: sourceDir,
entry: {
index: "./index.ts",
},
output: {
filename: "[name].js",
path: distDir,
libraryTarget: "commonjs-module"
},
resolve: {
extensions: [".js", ".ts"],
modules: ["node_modules"],
},
externals: [
(context, request, callback) => {
// Resolve `delir-core` module from Delir runtime version
if (/^delir-core/.test(request)) {
callback(null, `require("${request}")`);
return;
}
callback();
}
],
module: {
rules: [
{
test: /\.ts$/,
loader: "awesome-typescript-loader",
options: {
// If you want to type checking, please set 'false' to this option.
// But delir-core typings is very broken. TypeScript warns to delir-core's broken typing...
transpileOnly: true
}
}
]
}
};
| const webpack = require("webpack");
const path = require("path");
const sourceDir = path.join(__dirname, "src");
const distDir = path.join(__dirname, "dist");
module.exports = {
target: "electron",
context: sourceDir,
entry: "./index.ts",
output: {
filename: "[name].js",
path: distDir,
libraryTarget: "commonjs-module"
},
resolve: {
extensions: [".js", ".ts"],
modules: ["node_modules"],
},
externals: [
(context, request, callback) => {
// Resolve `delir-core` module from Delir runtime version
if (/^delir-core/.test(request)) {
callback(null, `require("${request}")`);
return;
}
callback();
}
],
module: {
rules: [
{
test: /\.ts$/,
loader: "awesome-typescript-loader",
options: {
// If you want to type checking, please set 'false' to this option.
// But delir-core typings is very broken. TypeScript warns to delir-core's broken typing...
transpileOnly: true
}
}
]
}
}; |
Debug should be for socket.io instead of primus | 'use strict';
var socketio = require('socket.io');
var Proto = require('uberproto');
var debug = require('debug')('feathers:socket.io');
var commons = require('feathers-commons').socket;
module.exports = function (config) {
return function () {
var app = this;
app.enable('feathers socketio');
// Monkey patch app.setup(server)
Proto.mixin({
service: commons.service,
setup: function (server) {
if (this.disabled('feathers socketio')) {
return this._super.apply(this, arguments);
}
var io = this.io = socketio.listen(server);
if (typeof config === 'function') {
debug('Calling SocketIO configuration function');
config.call(this, io);
}
var result = this._super.apply(this, arguments);
debug('Setting up SocketIO');
commons.setup.call(this, {
method: 'emit',
connection: function() {
return io.sockets;
},
clients: function() {
return io.sockets.sockets;
},
params: function(socket) {
return socket.feathers;
}
});
return result;
}
}, app);
};
};
| 'use strict';
var socketio = require('socket.io');
var Proto = require('uberproto');
var debug = require('debug')('feathers:primus');
var commons = require('feathers-commons').socket;
module.exports = function (config) {
return function () {
var app = this;
app.enable('feathers socketio');
// Monkey patch app.setup(server)
Proto.mixin({
service: commons.service,
setup: function (server) {
if (this.disabled('feathers socketio')) {
return this._super.apply(this, arguments);
}
var io = this.io = socketio.listen(server);
if (typeof config === 'function') {
debug('Calling SocketIO configuration function');
config.call(this, io);
}
var result = this._super.apply(this, arguments);
debug('Setting up SocketIO');
commons.setup.call(this, {
method: 'emit',
connection: function() {
return io.sockets;
},
clients: function() {
return io.sockets.sockets;
},
params: function(socket) {
return socket.feathers;
}
});
return result;
}
}, app);
};
};
|
Add news footer to media tile | (function(env) {
"use strict";
env.ddg_spice_dogo_news = function(api_result) {
if (!api_result || !api_result.results || !api_result.results.length) {
return Spice.failed('dogo_news');
}
// Get original query.
var script = $('[src*="/js/spice/dogo_news/"]')[0],
source = $(script).attr("src"),
query = decodeURIComponent(source.match(/dogo_news\/([^\/]+)/)[1]);
DDG.require('moment.js', function(){
Spice.add({
id: 'dogo_news',
name: 'Kids News',
data: api_result.results,
meta: {
sourceName: 'DOGOnews',
sourceUrl: 'http://www.dogonews.com/search?query=' + encodeURIComponent(query),
itemType: 'kids news articles'
},
normalize: function(item) {
var thumb = item.hi_res_thumb || item.thumb;
return {
title: item.name,
source: item.author,
url: item.url,
excerpt: item.summary,
description: item.summary,
image: thumb,
relative_time: moment(item.published_at).fromNow()
};
},
templates:{
group: 'media',
options: {
footer: Spice.dogo_news.footer
}
}
});
});
};
}(this)); | (function(env) {
"use strict";
env.ddg_spice_dogo_news = function(api_result) {
if (!api_result || !api_result.results || !api_result.results.length) {
return Spice.failed('dogo_news');
}
// Get original query.
var script = $('[src*="/js/spice/dogo_news/"]')[0],
source = $(script).attr("src"),
query = decodeURIComponent(source.match(/dogo_news\/([^\/]+)/)[1]);
DDG.require('moment.js', function(){
Spice.add({
id: 'dogo_news',
name: 'Kids News',
data: api_result.results,
meta: {
sourceName: 'DOGOnews',
sourceUrl: 'http://www.dogonews.com/search?query=' + encodeURIComponent(query),
itemType: 'kids news articles'
},
normalize: function(item) {
var thumb = item.hi_res_thumb || item.thumb;
return {
title: item.name,
source: item.author,
url: item.url,
excerpt: item.summary,
description: item.summary,
image: thumb,
relative_time: moment(item.published_at).fromNow()
};
},
templates:{
group: 'media'
}
});
});
};
}(this)); |
Test of index action working | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Song;
class SongController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$songs=Song::all();
var_dump($songs[0]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SongController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
|
Fix array addressing in nowplaying API again. :P | <?php
use \Entity\Station;
use \Entity\Song;
use \Entity\Schedule;
class Api_NowplayingController extends \PVL\Controller\Action\Api
{
public function indexAction()
{
$file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json';
$np_raw = file_get_contents($file_path_api);
// Sanity check for now playing data.
if (empty($np_raw))
{
$this->returnError('Now Playing data has not loaded into the cache. Wait for file reload.');
return;
}
if ($this->hasParam('id') || $this->hasParam('station'))
{
$np_arr = @json_decode($np_raw, TRUE);
$np = $np_arr['result'];
if ($this->hasParam('id'))
{
$id = (int)$this->getParam('id');
foreach($np as $key => $np_row)
{
if ($np_row['station']['id'] == $id)
{
$sc = $key;
break;
}
}
if (empty($sc))
return $this->returnError('Station not found!');
}
elseif ($this->hasParam('station'))
{
$sc = $this->getParam('station');
}
if (isset($np[$sc]))
$this->returnSuccess($np[$sc]);
else
return $this->returnError('Station not found!');
}
else
{
$this->returnRaw($np_raw, 'json');
}
}
} | <?php
use \Entity\Station;
use \Entity\Song;
use \Entity\Schedule;
class Api_NowplayingController extends \PVL\Controller\Action\Api
{
public function indexAction()
{
$file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json';
$np_raw = file_get_contents($file_path_api);
// Sanity check for now playing data.
if (empty($np_raw))
{
$this->returnError('Now Playing data has not loaded into the cache. Wait for file reload.');
return;
}
if ($this->hasParam('id') || $this->hasParam('station'))
{
$np_arr = @json_decode($np_raw, TRUE);
$np = $np_arr['result'];
if ($this->hasParam('id'))
{
$id = (int)$this->getParam('id');
foreach($np as $key => $station) {
if($station->id === $id) {
$sc = $key;
break;
}
}
if (!$sc)
return $this->returnError('Station not found!');
}
elseif ($this->hasParam('station'))
{
$sc = $this->getParam('station');
}
if (isset($np[$sc]))
$this->returnSuccess($np[$sc]);
else
return $this->returnError('Station not found!');
}
else
{
$this->returnRaw($np_raw, 'json');
}
}
} |
Remove buffer block on web | const path = require("path");
const { DefinePlugin } = require("webpack");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const SOURCE = path.resolve(__dirname, "./source");
const WEB_ENTRY = path.join(SOURCE, "web/index.js");
const DIST = path.resolve(__dirname, "./dist");
const plugins = [
new DefinePlugin({
BUTTERCUP_WEB: true
})
];
if (process.env.ANALYSE === "bundle") {
plugins.push(new BundleAnalyzerPlugin());
}
const baseConfig = {
devtool: false,
entry: WEB_ENTRY,
mode: "development",
module: {
rules: [
{
test: /(iconv-loader|bluebird)/,
use: "null-loader"
},
{
test: /\.js$/,
include: [
SOURCE
],
use: "babel-loader"
}
]
},
node: {
crypto: "empty",
fs: "empty",
net: "empty"
},
output: {
path: DIST,
filename: "buttercup-web.js",
library: "Buttercup",
libraryTarget: "umd"
},
plugins
};
module.exports = [
baseConfig,
Object.assign({}, baseConfig, {
mode: "production",
output: Object.assign({}, baseConfig.output, {
filename: "buttercup-web.min.js"
})
})
];
| const path = require("path");
const { DefinePlugin } = require("webpack");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const SOURCE = path.resolve(__dirname, "./source");
const WEB_ENTRY = path.join(SOURCE, "web/index.js");
const DIST = path.resolve(__dirname, "./dist");
const plugins = [
new DefinePlugin({
BUTTERCUP_WEB: true
})
];
if (process.env.ANALYSE === "bundle") {
plugins.push(new BundleAnalyzerPlugin());
}
const baseConfig = {
devtool: false,
entry: WEB_ENTRY,
mode: "development",
module: {
rules: [
{
test: /(iconv-loader|bluebird)/,
use: "null-loader"
},
{
test: /\.js$/,
include: [
SOURCE
],
use: "babel-loader"
}
]
},
node: {
buffer: "empty",
crypto: "empty",
fs: "empty",
net: "empty"
},
output: {
path: DIST,
filename: "buttercup-web.js",
library: "Buttercup",
libraryTarget: "umd"
},
plugins
};
module.exports = [
baseConfig,
Object.assign({}, baseConfig, {
mode: "production",
output: Object.assign({}, baseConfig.output, {
filename: "buttercup-web.min.js"
})
})
];
|
Migrate extensions in upgrade script | <?php namespace Flarum\Console;
use Illuminate\Contracts\Container\Container;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
class UpgradeCommand extends Command
{
/**
* @var Container
*/
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
parent::__construct();
}
protected function configure()
{
$this
->setName('upgrade')
->setDescription("Run Flarum's upgrade script");
}
/**
* @inheritdoc
*/
protected function fire()
{
$this->info('Upgrading Flarum...');
$this->upgrade();
$this->info('DONE.');
}
protected function upgrade()
{
$this->container->bind('Illuminate\Database\Schema\Builder', function($container) {
return $container->make('Illuminate\Database\ConnectionInterface')->getSchemaBuilder();
});
$migrator = $this->container->make('Flarum\Migrations\Migrator');
$migrator->run(base_path('core/migrations'));
foreach ($migrator->getNotes() as $note) {
$this->info($note);
}
$extensions = $this->container->make('Flarum\Support\ExtensionManager');
$migrator = $extensions->getMigrator();
foreach ($extensions->getInfo() as $extension) {
$this->info('Upgrading extension: '.$extension->name);
$extensions->enable($extension->name);
foreach ($migrator->getNotes() as $note) {
$this->info($note);
}
}
}
}
| <?php namespace Flarum\Console;
use Illuminate\Contracts\Container\Container;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
class UpgradeCommand extends Command
{
/**
* @var Container
*/
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
parent::__construct();
}
protected function configure()
{
$this
->setName('upgrade')
->setDescription("Run Flarum's upgrade script");
}
/**
* @inheritdoc
*/
protected function fire()
{
$this->info('Upgrading Flarum...');
$this->upgrade();
$this->info('DONE.');
}
protected function upgrade()
{
$this->container->bind('Illuminate\Database\Schema\Builder', function($container) {
return $container->make('Illuminate\Database\ConnectionInterface')->getSchemaBuilder();
});
$migrator = $this->container->make('Flarum\Migrations\Migrator');
$migrator->run(base_path('core/migrations'));
foreach ($migrator->getNotes() as $note) {
$this->info($note);
}
}
}
|
Send button state for toggle buttons. | /*
* Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* 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.
*/
(function($) {
$(function() {
$.fn.toggleButtons = function () {
return this.each(function () {
var $this = $(this);
$this.click(function() {
$this.toggleClass('off');
var url = $this.attr('href');
if(url) {
$.ajax({
url: url,
type: 'POST',
traditional: true,
cache: false,
context: this,
data: {
state: $this.hasClass('off')?0:1
}
}).fail(function() {
$this.toggleClass('off');
});
}
return false;
});
});
};
});
})(jQuery);
| /*
* Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* 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.
*/
(function($) {
$(function() {
$.fn.toggleButtons = function () {
return this.each(function () {
var $this = $(this);
$this.click(function() {
$this.toggleClass('off');
var url = $this.attr('href');
if(url) {
$.ajax({
url: url,
type: 'POST',
traditional: true,
cache: false,
context: this
}).fail(function() {
$this.toggleClass('off');
});
}
return false;
});
});
};
});
})(jQuery);
|
Sort returned images by date, taking into account overrides | import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesift_plugin.html"
def date_digest(self, images):
"""
return a list of unique dates, for all the images passed
"""
dates = {}
for i in images:
dates.setdefault(i.overrideable_date().date(), None)
return sorted(dates.keys())
def render(self, context, instance, placeholder):
url = context['request'].get_full_path()
date = context['request'].GET.get('date')
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
# there's no way around listing, sorry.
qs = list(qs)
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
# sort before limit
qs.sort(key=lambda i: i.overrideable_date())
if limit:
qs = qs[:limit]
context.update({
'dates': [d.isoformat() for d in self.date_digest(qs)],
'filtered':filtered,
'images': qs,
'instance': instance,
'placeholder': placeholder,
'url':url,
})
return context
plugin_pool.register_plugin(ImagesiftPlugin) | import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesift_plugin.html"
def date_digest(self, images):
"""
return a list of unique dates, for all the images passed
"""
dates = {}
for i in images:
dates.setdefault(i.overrideable_date().date(), None)
return sorted(dates.keys())
def render(self, context, instance, placeholder):
url = context['request'].get_full_path()
date = context['request'].GET.get('date')
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
if limit:
qs = qs[:limit]
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
qs = list(qs)
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
context.update({
'dates': [d.isoformat() for d in self.date_digest(qs)],
'filtered':filtered,
'images': qs,
'instance': instance,
'placeholder': placeholder,
'url':url,
})
return context
plugin_pool.register_plugin(ImagesiftPlugin) |
Fix error on flat trace with cahe test | # -*- coding: utf-8 -*-
from openfisca_web_api.handlers import get_flat_trace
def test_flat_trace():
tree = {
'name': 'a',
'period': 2019,
'children': [
{
'name': 'b',
'period': 2019,
'children': [],
'parameters': [],
'value': None
}
],
'parameters': [],
'value': None
}
trace = get_flat_trace(tree)
assert len(trace) == 2
assert trace['a<2019>']['dependencies'] == ['b<2019>']
assert trace['b<2019>']['dependencies'] == []
def test_flat_trace_with_cache():
tree = {
'children': [
{
'children': [{
'children': [],
'name': 'c',
'parameters': [],
'period': 2019,
'value': None
}
],
'name': 'b',
'parameters': [],
'period': 2019,
'value': None
},
{
'children': [],
'name': 'b',
'parameters': [],
'period': 2019,
'value': None
}
],
'name': 'a',
'parameters': [],
'period': 2019,
'value': None
}
trace = get_flat_trace(tree)
assert trace['b<2019>']['dependencies'] == ['c<2019>']
| # -*- coding: utf-8 -*-
from openfisca_web_api.handlers import get_flat_trace
def test_flat_trace():
tree = {
'name': 'a',
'period': 2019,
'children': [
{
'name': 'b',
'period': 2019,
'children': [],
'parameters': [],
'value': None
}
],
'parameters': [],
'value': None
}
trace = get_flat_trace(tree)
assert len(trace) == 2
assert trace['a<2019>']['dependencies'] == ['b<2019>']
assert trace['b<2019>']['dependencies'] == []
def test_flat_trace_with_cache():
tree = [{
'children': [{
'children': [{
'children': [],
'name': 'c',
'parameters': [],
'period': 2019,
'value': None
}],
'name': 'b',
'parameters': [],
'period': 2019,
'value': None
}, {
'children': [],
'name': 'b',
'parameters': [],
'period': 2019,
'value': None
}],
'name': 'a',
'parameters': [],
'period': 2019,
'value': None
}]
trace = get_flat_trace(tree)
assert trace['b<2019>']['dependencies'] == ['c<2019>']
|
Update ORB to latest version | orb = {
init: function () {
let language = localStorage.getItem("orb-language");
if (language) {
this.translateTo(window[language]);
}
else {
let browser_language = navigator.language.replace('-', '_');
this.translateTo(window[browser_language.toLowerCase()]);
}
},
translateTo: function (language) {
for (let property in language) {
if (this._isAnExistingPropertyInDOM(property)) {
let orbSelectorAll = document.querySelectorAll('[orb="'+property+'"]');
if (this._hasAnObjectInProperty(language[property])) {
let object = language[property];
for (let field in object) {
orbSelectorAll.forEach(function(element, index) {
element.innerHTML = object[field];
});
}
}
else {
orbSelectorAll.forEach(function(element, index) {
element.innerHTML = language[property];
});
}
}
}
localStorage.setItem("orb-language", language._language);
},
_isAnExistingPropertyInDOM: function (property) {
return document.querySelector('[orb="'+property+'"]') ? true : false;
},
_hasAnObjectInProperty: function (property) {
return typeof(property) === 'object';
}
};
orb.init(); | orb = {
init: function () {
let language = localStorage.getItem("orb-language");
if (language) {
this.translateTo(window[language]);
}
else {
let browser_language = navigator.language.replace('-', '_');
this.translateTo(window[browser_language.toLowerCase()]);
}
},
translateTo: function (language) {
for (let property in language) {
if (this._isAnExistingPropertyInDOM(property)) {
let orbSelector = document.querySelector('[orb="'+property+'"]');
if (this._hasAnObjectInProperty(language[property])) {
let object = language[property];
for (let field in object) {
orbSelector[field] = object[field];
}
}
else {
orbSelector.innerHTML = language[property];
}
}
}
localStorage.setItem("orb-language", language._language);
},
_isAnExistingPropertyInDOM: function (property) {
return document.querySelector('[orb="'+property+'"]') ? true : false;
},
_hasAnObjectInProperty: function (property) {
return typeof(property) === 'object';
}
};
orb.init();
|
Use InaSAFE in the email subject line rather | # noinspection PyUnresolvedReferences
from .prod import * # noqa
import os
print os.environ
ALLOWED_HOSTS = ['*']
ADMINS = (
('Tim Sutton', '[email protected]'),
('Ismail Sunni', '[email protected]'),
('Christian Christellis', '[email protected]'),
('Akbar Gumbira', '[email protected]'),)
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': os.environ['DATABASE_NAME'],
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
MEDIA_ROOT = '/home/web/media'
STATIC_ROOT = '/home/web/static'
# See fig.yml file for postfix container definition
#
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Host for sending e-mail.
EMAIL_HOST = 'smtp'
# Port for sending e-mail.
EMAIL_PORT = 25
# SMTP authentication information for EMAIL_HOST.
# See fig.yml for where these are defined
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'docker'
EMAIL_USE_TLS = False
EMAIL_SUBJECT_PREFIX = '[InaSAFE]'
| # noinspection PyUnresolvedReferences
from .prod import * # noqa
import os
print os.environ
ALLOWED_HOSTS = ['*']
ADMINS = (
('Tim Sutton', '[email protected]'),
('Ismail Sunni', '[email protected]'),
('Christian Christellis', '[email protected]'),
('Akbar Gumbira', '[email protected]'),)
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': os.environ['DATABASE_NAME'],
'USER': os.environ['DATABASE_USERNAME'],
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': os.environ['DATABASE_HOST'],
'PORT': 5432,
'TEST_NAME': 'unittests',
}
}
MEDIA_ROOT = '/home/web/media'
STATIC_ROOT = '/home/web/static'
# See fig.yml file for postfix container definition
#
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Host for sending e-mail.
EMAIL_HOST = 'smtp'
# Port for sending e-mail.
EMAIL_PORT = 25
# SMTP authentication information for EMAIL_HOST.
# See fig.yml for where these are defined
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'docker'
EMAIL_USE_TLS = False
EMAIL_SUBJECT_PREFIX = '[jakarta-flood-maps]'
|
Fix the detection of HTML5 support in the testsuite
The detection relied on detecting the test method added when introducing
the feature in symfony/dom-crawler. But as of Symfony 4.4, tests are
stripped from the dist archives. An additional detection based on a new
method added in later Symfony version is now used to filter out the
false positives (not detecting 4.4 and newer as being <3.3). | <?php
namespace Behat\Mink\Tests\Driver;
use Behat\Mink\Driver\BrowserKitDriver;
use Behat\Mink\Tests\Driver\Util\FixturesKernel;
use Symfony\Component\HttpKernel\Client;
class BrowserKitConfig extends AbstractConfig
{
public static function getInstance()
{
return new self();
}
/**
* {@inheritdoc}
*/
public function createDriver()
{
$client = new Client(new FixturesKernel());
return new BrowserKitDriver($client);
}
/**
* {@inheritdoc}
*/
public function getWebFixturesUrl()
{
return 'http://localhost';
}
protected function supportsJs()
{
return false;
}
public function skipMessage($testCase, $test)
{
if (
'Behat\Mink\Tests\Driver\Form\Html5Test' === $testCase
&& in_array($test, array(
'testHtml5FormAction',
'testHtml5FormMethod',
))
&& !method_exists('Symfony\Component\DomCrawler\Tests\FormTest', 'testGetMethodWithOverride')
// Symfony 4.4 removed tests from dist archives, making the previous detection return a false-positive
&& !method_exists('Symfony\Component\DomCrawler\Form', 'getName')
) {
return 'Mink BrowserKit doesn\'t support HTML5 form attributes before Symfony 3.3';
}
return parent::skipMessage($testCase, $test);
}
}
| <?php
namespace Behat\Mink\Tests\Driver;
use Behat\Mink\Driver\BrowserKitDriver;
use Behat\Mink\Tests\Driver\Util\FixturesKernel;
use Symfony\Component\HttpKernel\Client;
class BrowserKitConfig extends AbstractConfig
{
public static function getInstance()
{
return new self();
}
/**
* {@inheritdoc}
*/
public function createDriver()
{
$client = new Client(new FixturesKernel());
return new BrowserKitDriver($client);
}
/**
* {@inheritdoc}
*/
public function getWebFixturesUrl()
{
return 'http://localhost';
}
protected function supportsJs()
{
return false;
}
public function skipMessage($testCase, $test)
{
if (
'Behat\Mink\Tests\Driver\Form\Html5Test' === $testCase
&& in_array($test, array(
'testHtml5FormAction',
'testHtml5FormMethod',
))
&& !method_exists('Symfony\Component\DomCrawler\Tests\FormTest', 'testGetMethodWithOverride')
) {
return 'Mink BrowserKit doesn\'t support HTML5 form attributes before Symfony 3.3';
}
return parent::skipMessage($testCase, $test);
}
}
|
Add 'Z' character for Firefox date parsing. | 'use strict';
UheerApp
.controller('ListenController',
['$scope', '$stateParams', 'ChannelResource', 'MusicPlayer', 'config',
function ($scope, $stateParams, channels, MusicPlayer, config) {
$scope.toogleMute = function () {
if (!$scope.channel.CurrentId) {
toastr.warning('Cannot mute a channel which is not playing anything.', 'Ops!');
return false;
}
MusicPlayer.mute($scope.mute = !$scope.mute);
}
$scope.resync = function () {
$scope.currentMusic = null;
$scope.currentMusicCurrentTime = 0;
channels
.get({ id: $stateParams.id })
.$promise.then(function (channel) {
$scope.channel = channel;
$scope.channel.CurrentStartTime = new Date(Date.parse($scope.channel.CurrentStartTime + 'Z'));
MusicPlayer
.take($scope)
.start();
});
}
$scope.resync();
}]);
| 'use strict';
UheerApp
.controller('ListenController',
['$scope', '$stateParams', 'ChannelResource', 'MusicPlayer', 'config',
function ($scope, $stateParams, channels, MusicPlayer, config) {
$scope.toogleMute = function () {
if (!$scope.channel.CurrentId) {
toastr.warning('Cannot mute a channel which is not playing anything.', 'Ops!');
return false;
}
MusicPlayer.mute($scope.mute = !$scope.mute);
}
$scope.resync = function () {
$scope.currentMusic = null;
$scope.currentMusicCurrentTime = 0;
channels
.get({ id: $stateParams.id })
.$promise.then(function (channel) {
$scope.channel = channel;
$scope.channel.CurrentStartTime = new Date(Date.parse($scope.channel.CurrentStartTime));
MusicPlayer
.take($scope)
.start();
});
}
$scope.resync();
}]);
|
Fix typo in edit form | <?php
namespace DlcCategory\Form;
use DlcCategory\Form\BaseForm;
use DlcCategory\Service\Category as CategoryService;
use Zend\Form\FormInterface;
class EditCategory extends BaseForm
{
public function init()
{
parent::init();
$this->setLabel('Edit category');
}
public function bind($category, $flags = FormInterface::VALUES_NORMALIZED)
{
parent::bind($category, $flags);
$node = $this->getServiceLocator()
->get('dlccategory_category_service')
->getNestedSetManager()
->wrapNode($category);
if ($node->isRoot()) {
$insertionAs = CategoryService::ROOT_NODE;
$insertionOf = '';
} elseif ($node->hasNextSibling()) {
$insertionAs = CategoryService::PREV_SIBILING_OF;
$insertionOf = $node->getNextSibling()->getNode()->getId();
} elseif ($node->hasPrevSibling()) {
$insertionAs = CategoryService::NEXT_SIBILING_OF;
$insertionOf = $node->getPrivSibiling()->getNode()->getId();
} elseif ($node->hasParent()) {
$insertionAs = CategoryService::FIRST_CHILD_OF;
$insertionOf = $node->getParent()->getNode()->getId();
} else {
$insertionAs = '';
$insertionOf = '';
}
$this->byName['category']->get('insertion-method')->setValue($insertionAs);
$this->byName['category']->get('insertion-point')->setValue($insertionOf);
}
}
| <?php
namespace DlcCategory\Form;
use DlcCategory\Form\BaseForm;
use DlcCategory\Service\Category as CategoryService;
use Zend\Form\FormInterface;
class EditCategory extends BaseForm
{
public function init()
{
parent::init();
$this->setLabel('Edit category');
}
public function bind($category, $flags = FormInterface::VALUES_NORMALIZED)
{
parent::bind($category, $flags);
$node = $this->getServiceLocator()
->get('dlccategory_category_service')
->getNestedSetManager()
->wrapNode($category);
if ($node->isRoot()) {
$insertionAs = CategoryService::ROOT_NODE;
$insertionOf = '';
} elseif ($node->hasNextSibling()) {
$insertionAs = CategoryService::PREV_SIBILING_OF;
$insertionOf = $node->getNextSibiling()->getNode()->getId();
} elseif ($node->hasPrevSibling()) {
$insertionAs = CategoryService::NEXT_SIBILING_OF;
$insertionOf = $node->getPrivSibiling()->getNode()->getId();
} elseif ($node->hasParent()) {
$insertionAs = CategoryService::FIRST_CHILD_OF;
$insertionOf = $node->getParent()->getNode()->getId();
} else {
$insertionAs = '';
$insertionOf = '';
}
$this->byName['category']->get('insertion-method')->setValue($insertionAs);
$this->byName['category']->get('insertion-point')->setValue($insertionOf);
}
} |
Exclude \ from company name
Change-Id: Ife5a34a09f476e196aae6178886109750bcbe934 | <?php
namespace Directorzone\Service;
use Netsensia\Service\NetsensiaService;
class CompanyService extends NetsensiaService
{
public function isCompanyNumberTaken($companyNumber)
{
$sql =
"SELECT companyid " .
"FROM company " .
"WHERE number = :number";
$query = $this->getConnection()->prepare($sql);
$query->execute(
array(
':number' => $companyNumber,
)
);
return ($query->rowCount() == 1);
}
public function count()
{
$sql =
"SELECT count(*) as c " .
"FROM company";
$query = $this->getConnection()->prepare($sql);
$query->execute();
if ($row = $query->fetch()) {
return $row['c'];
} else {
return null;
}
}
public function getMaxAlphabeticalCompanyName()
{
$sql =
"SELECT name " .
"FROM company " .
"WHERE name NOT LIKE 'THE %' " .
"AND name NOT LIKE 'THE-%' " .
"AND name NOT LIKE '\\%' " .
"ORDER BY name DESC " .
"LIMIT 1";
$query = $this->getConnection()->prepare($sql);
$query->execute();
if ($row = $query->fetch()) {
$name = preg_replace('/^THE[ -]/', '', $row['name']);
return $name;
} else {
return null;
}
}
}
| <?php
namespace Directorzone\Service;
use Netsensia\Service\NetsensiaService;
class CompanyService extends NetsensiaService
{
public function isCompanyNumberTaken($companyNumber)
{
$sql =
"SELECT companyid " .
"FROM company " .
"WHERE number = :number";
$query = $this->getConnection()->prepare($sql);
$query->execute(
array(
':number' => $companyNumber,
)
);
return ($query->rowCount() == 1);
}
public function count()
{
$sql =
"SELECT count(*) as c " .
"FROM company";
$query = $this->getConnection()->prepare($sql);
$query->execute();
if ($row = $query->fetch()) {
return $row['c'];
} else {
return null;
}
}
public function getMaxAlphabeticalCompanyName()
{
$sql =
"SELECT name " .
"FROM company " .
"WHERE name NOT LIKE 'THE %' " .
"AND name NOT LIKE 'THE-%' " .
"ORDER BY name DESC " .
"LIMIT 1";
$query = $this->getConnection()->prepare($sql);
$query->execute();
if ($row = $query->fetch()) {
$name = preg_replace('/^THE[ -]/', '', $row['name']);
return $name;
} else {
return null;
}
}
}
|
Speed up DOI extraction with new regexp
Previously: running the DOI extraction test suite would take just over 7
seconds; with this new optimisation, it takes under 50 milliseconds.
The key is to replace the PHP logic which would incrementally strip
trailing punctuation off any matched DOI until it had a valid ending
with a regular expression that has the same behaviour. This is possible
if we're much more explicit about valid DOI suffixes. | <?php
namespace Altmetric\Identifiers;
class Doi
{
const REGEXP = <<<'EOT'
{
10 # Directory indicator (always 10)
\.
(?:
# ISBN-A
97[89]\. # ISBN (GS1) Bookland prefix
\d{2,8} # ISBN registration group element and publisher prefix
/ # Prefix/suffix divider
\d{1,7} # ISBN title enumerator and check digit
|
# DOI
\d{4,9} # Registrant code
/ # Prefix/suffix divider
(?:
# DOI suffix
\S+2-\# # Early Wiley suffix
|
\S+\(\S+\) # Suffix ending in balanced parentheses
|
\S+(?!\s)\p{^P} # Suffix ending in non-punctuation
)
)
}xu
EOT;
public static function extract($str)
{
preg_match_all(self::REGEXP, mb_strtolower($str, 'UTF-8'), $matches);
return $matches[0];
}
}
| <?php
namespace Altmetric\Identifiers;
class Doi
{
const REGEXP = <<<'EOT'
{
10 # Directory indicator (always 10)
\.
(?:
# ISBN-A
97[89]\. # ISBN (GS1) Bookland prefix
\d{2,8} # ISBN registration group element and publisher prefix
/ # Prefix/suffix divider
\d{1,7} # ISBN title enumerator and check digit
|
# DOI
\d{4,9} # Registrant code
/ # Prefix/suffix divider
\S+ # DOI suffix
)
}xu
EOT;
const VALID_ENDING = <<<'EOT'
/
(?:
\p{^P} # Non-punctuation character
|
\(.+\) # Balanced parentheses
|
2-\# # Early Wiley DOI suffix
)
$
/xu
EOT;
public static function extract($str)
{
preg_match_all(self::REGEXP, mb_strtolower($str, 'UTF-8'), $matches);
return array_filter(array_map([__CLASS__, 'extractOne'], $matches[0]));
}
public static function extractOne($str)
{
while (preg_match(self::REGEXP, mb_strtolower($str, 'UTF-8'), $matches)) {
if (preg_match(self::VALID_ENDING, $matches[0])) {
return $matches[0];
}
$str = preg_replace('/\p{P}$/u', '', $matches[0]);
}
}
}
|
Bump vers for uppercase Beta Code conversion
Fixed with PR https://github.com/cltk/cltk/pull/778 by Eleftheria Chatziargyriou ( @Sedictious ). | """Config for PyPI."""
from setuptools import find_packages
from setuptools import setup
setup(
author='Kyle P. Johnson',
author_email='[email protected]',
classifiers=[
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: Chinese (Traditional)',
'Natural Language :: English',
'Natural Language :: Greek',
'Natural Language :: Latin',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Text Processing',
'Topic :: Text Processing :: General',
'Topic :: Text Processing :: Linguistic',
],
description='NLP for the ancient world',
install_requires=['gitpython',
'nltk',
'python-crfsuite',
'pyuca',
'pyyaml',
'regex',
'whoosh'],
keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan', 'arabic'],
license='MIT',
long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.', # pylint: disable=C0301,
name='cltk',
packages=find_packages(),
url='https://github.com/cltk/cltk',
version='0.1.86',
zip_safe=True,
test_suite='cltk.tests.test_cltk',
)
| """Config for PyPI."""
from setuptools import find_packages
from setuptools import setup
setup(
author='Kyle P. Johnson',
author_email='[email protected]',
classifiers=[
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: Chinese (Traditional)',
'Natural Language :: English',
'Natural Language :: Greek',
'Natural Language :: Latin',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Text Processing',
'Topic :: Text Processing :: General',
'Topic :: Text Processing :: Linguistic',
],
description='NLP for the ancient world',
install_requires=['gitpython',
'nltk',
'python-crfsuite',
'pyuca',
'pyyaml',
'regex',
'whoosh'],
keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan', 'arabic'],
license='MIT',
long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.', # pylint: disable=C0301,
name='cltk',
packages=find_packages(),
url='https://github.com/cltk/cltk',
version='0.1.85',
zip_safe=True,
test_suite='cltk.tests.test_cltk',
)
|
Fix bug on start date for schedule calendar planification | define([], function() {
'use strict';
/**
* Save one row
* @param {$resource} resource
* @returns {Promise}
*/
var saveRow = function($q, resource) {
var deferred = $q.defer();
if (resource._id) {
resource.$save(deferred.resolve, deferred.reject);
} else {
resource.$create(deferred.resolve, deferred.reject);
}
return deferred.promise;
};
/**
* Save all account collections
*
*/
return function($scope, $q, catchOutcome) {
if (!$scope.user.roles || !$scope.user.roles.account) {
// TODO remove the existing collections
return;
}
var promises = [];
$scope.accountScheduleCalendars.forEach(function(document) {
// remove time on dates before saving
if (document.from instanceof Date) {
document.from.setHours(0,0,0,0);
}
if (document.to instanceof Date) {
document.to.setHours(0,0,0,0);
}
if ($scope.user.roles && $scope.user.roles.account) {
document.account = $scope.user.roles.account._id;
} else {
document.user = $scope.user._id;
}
promises.push(catchOutcome(saveRow($q, document)));
});
var promise = $q.all(promises);
return promise;
};
});
| define([], function() {
'use strict';
/**
* Save one row
* @param {$resource} resource
* @returns {Promise}
*/
var saveRow = function($q, resource) {
var deferred = $q.defer();
if (resource._id) {
resource.$save(deferred.resolve, deferred.reject);
} else {
resource.$create(deferred.resolve, deferred.reject);
}
return deferred.promise;
};
/**
* Save all account collections
*
*/
return function($scope, $q, catchOutcome) {
if (!$scope.user.roles || !$scope.user.roles.account) {
// TODO remove the existing collections
return;
}
var promises = [];
$scope.accountScheduleCalendars.forEach(function(document) {
if ($scope.user.roles && $scope.user.roles.account) {
document.account = $scope.user.roles.account._id;
} else {
document.user = $scope.user._id;
}
promises.push(catchOutcome(saveRow($q, document)));
});
var promise = $q.all(promises);
return promise;
};
});
|
Handle up button in about screen toolbar | package net.squanchy.about;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import net.squanchy.R;
import net.squanchy.fonts.TypefaceStyleableActivity;
import net.squanchy.navigation.Navigator;
public class AboutActivity extends TypefaceStyleableActivity {
private static final String SQUANCHY_WEBSITE = "https://squanchy.net";
private static final String SQUANCHY_GITHUB = "https://github.com/rock3r/squanchy";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
setupToolbar();
Navigator navigator = AboutInjector.obtain(this)
.navigator();
findViewById(R.id.website_button).setOnClickListener(
view -> navigator.toExternalUrl(SQUANCHY_WEBSITE)
);
findViewById(R.id.github_button).setOnClickListener(
view -> navigator.toExternalUrl(SQUANCHY_GITHUB)
);
findViewById(R.id.foss_button).setOnClickListener(
view -> navigator.toFossLicenses()
);
}
private void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| package net.squanchy.about;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import net.squanchy.R;
import net.squanchy.fonts.TypefaceStyleableActivity;
import net.squanchy.navigation.Navigator;
public class AboutActivity extends TypefaceStyleableActivity {
private static final String SQUANCHY_WEBSITE = "https://squanchy.net";
private static final String SQUANCHY_GITHUB = "https://github.com/rock3r/squanchy";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
setupToolbar();
Navigator navigator = AboutInjector.obtain(this)
.navigator();
findViewById(R.id.website_button).setOnClickListener(
view -> navigator.toExternalUrl(SQUANCHY_WEBSITE)
);
findViewById(R.id.github_button).setOnClickListener(
view -> navigator.toExternalUrl(SQUANCHY_GITHUB)
);
findViewById(R.id.foss_button).setOnClickListener(
view -> navigator.toFossLicenses()
);
}
private void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
|
Add ability to get a single item from the store | import deepAssign from 'deep-assign'
import getFilter from 'feathers-query-filters'
import { sorter, matcher, select, _ } from 'feathers-commons'
export default function makeServiceGetters (service) {
const { vuexOptions } = service
const idField = vuexOptions.module.idField || vuexOptions.global.idField
return {
list (state) {
return state.ids.map(id => state.keyedById[id])
},
find: state => (params = {}) => {
const { query, filters } = getFilter(params.query || {})
let values = _.values(state.keyedById).filter(matcher(query))
const total = values.length
if (filters.$sort) {
values.sort(sorter(filters.$sort))
}
if (filters.$skip) {
values = values.slice(filters.$skip)
}
if (typeof filters.$limit !== 'undefined') {
values = values.slice(0, filters.$limit)
}
if (filters.$select) {
values = values.map(value => _.pick(value, ...filters.$select))
}
// TODO: Figure out a nice API for turning off pagination.
return {
total,
limit: filters.$limit,
skip: filters.$skip || 0,
data: values
}
},
get: ({ keyedById }) => (id, params = {}) => {
return keyedById[id] ? select(params, idField)(keyedById[id]) : undefined
},
current (state) {
return state.currentId ? state.keyedById[state.currentId] : null
},
copy (state) {
return state.currentId ? deepAssign(state.keyedById[state.currentId]) : null
}
}
}
| import deepAssign from 'deep-assign'
import getFilter from 'feathers-query-filters'
// import { sorter, matcher, select, _ } from 'feathers-commons'
import { sorter, matcher, _ } from 'feathers-commons'
export default function makeServiceGetters (service) {
return {
list (state) {
return state.ids.map(id => state.keyedById[id])
},
getList: (state, getters) => (params = {}) => {
const { query, filters } = getFilter(params.query || {})
let values = _.values(getters.list).filter(matcher(query))
const total = values.length
if (filters.$sort) {
values.sort(sorter(filters.$sort))
}
if (filters.$skip) {
values = values.slice(filters.$skip)
}
if (typeof filters.$limit !== 'undefined') {
values = values.slice(0, filters.$limit)
}
if (filters.$select) {
values = values.map(value => _.pick(value, ...filters.$select))
}
return {
total,
limit: filters.$limit,
skip: filters.$skip || 0,
data: values
}
},
current (state) {
return state.currentId ? state.keyedById[state.currentId] : null
},
copy (state) {
return state.currentId ? deepAssign(state.keyedById[state.currentId]) : null
}
}
}
|
Remove button to tag select. | module.exports = Backbone.View.extend({
tagName: 'select',
className: 'tag-select form-control',
initialize: function (options) {
this.$el.selectize({
plugins: ['remove_button'],
valueField: 'id',
labelField: 'name',
searchField: ['slug', 'name'],
create: false,
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/tag',
type: 'GET',
dataType: 'json',
data: {
search: query
},
error: function() {
callback();
},
success: function(res) {
callback(res.data);
}
});
},
render: {
option: function(item, escape) {
return '<div>' + escape(item.name) + '</div>';
},
},
});
}
});
| module.exports = Backbone.View.extend({
tagName: 'select',
className: 'tag-select form-control',
initialize: function (options) {
this.$el.selectize({
valueField: 'id',
labelField: 'name',
searchField: ['slug', 'name'],
create: false,
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/tag',
type: 'GET',
dataType: 'json',
data: {
search: query
},
error: function() {
callback();
},
success: function(res) {
callback(res.data);
}
});
},
render: {
option: function(item, escape) {
return '<div>' + escape(item.name) + '</div>';
},
},
});
}
});
|
Remove redundant postgres CloudFoundry fixture | import json
import os
import pytest
from app.cloudfoundry_config import (
extract_cloudfoundry_config,
set_config_env_vars,
)
@pytest.fixture
def cloudfoundry_config():
return {
'postgres': [{
'credentials': {
'uri': 'postgres uri'
}
}],
'user-provided': []
}
@pytest.fixture
def cloudfoundry_environ(os_environ, cloudfoundry_config):
os.environ['VCAP_SERVICES'] = json.dumps(cloudfoundry_config)
os.environ['VCAP_APPLICATION'] = '{"space_name": "🚀🌌"}'
def test_extract_cloudfoundry_config_populates_other_vars(cloudfoundry_environ):
extract_cloudfoundry_config()
assert os.environ['SQLALCHEMY_DATABASE_URI'] == 'postgresql uri'
assert os.environ['NOTIFY_ENVIRONMENT'] == '🚀🌌'
assert os.environ['NOTIFY_LOG_PATH'] == '/home/vcap/logs/app.log'
def test_set_config_env_vars_ignores_unknown_configs(cloudfoundry_config, cloudfoundry_environ):
cloudfoundry_config['foo'] = {'credentials': {'foo': 'foo'}}
cloudfoundry_config['user-provided'].append({
'name': 'bar', 'credentials': {'bar': 'bar'}
})
set_config_env_vars(cloudfoundry_config)
assert 'foo' not in os.environ
assert 'bar' not in os.environ
| import json
import os
import pytest
from app.cloudfoundry_config import (
extract_cloudfoundry_config,
set_config_env_vars,
)
@pytest.fixture
def postgres_config():
return [
{
'credentials': {
'uri': 'postgres uri'
}
}
]
@pytest.fixture
def cloudfoundry_config(postgres_config):
return {
'postgres': postgres_config,
'user-provided': []
}
@pytest.fixture
def cloudfoundry_environ(os_environ, cloudfoundry_config):
os.environ['VCAP_SERVICES'] = json.dumps(cloudfoundry_config)
os.environ['VCAP_APPLICATION'] = '{"space_name": "🚀🌌"}'
def test_extract_cloudfoundry_config_populates_other_vars(cloudfoundry_environ):
extract_cloudfoundry_config()
assert os.environ['SQLALCHEMY_DATABASE_URI'] == 'postgresql uri'
assert os.environ['NOTIFY_ENVIRONMENT'] == '🚀🌌'
assert os.environ['NOTIFY_LOG_PATH'] == '/home/vcap/logs/app.log'
def test_set_config_env_vars_ignores_unknown_configs(cloudfoundry_config, cloudfoundry_environ):
cloudfoundry_config['foo'] = {'credentials': {'foo': 'foo'}}
cloudfoundry_config['user-provided'].append({
'name': 'bar', 'credentials': {'bar': 'bar'}
})
set_config_env_vars(cloudfoundry_config)
assert 'foo' not in os.environ
assert 'bar' not in os.environ
|
Fix FoldersList not refreshing correctly | import React, { Component } from 'react';
import Icon from 'react-fontawesome';
import classnames from 'classnames';
import AppActions from '../../actions/AppActions';
/*
|--------------------------------------------------------------------------
| LibraryFolders
|--------------------------------------------------------------------------
*/
export default class LibraryFolders extends Component {
static propTypes = {
folders: React.PropTypes.array,
refreshingLibrary: React.PropTypes.bool
}
constructor(props) {
super(props);
}
render() {
const self = this;
const foldersListClasses = classnames('musicfolders-list', {
empty: this.props.folders.length === 0
});
// TODO (y.solovyov): move to separate method that returns items
const removeButtonClasses = classnames('delete-libray-folder', {
disabled: self.props.refreshingLibrary
});
return (
<ul className={ foldersListClasses }>
{ this.props.folders.map((folder, i) => {
return(
<li key={ i }>
<Icon name='close'
className={ removeButtonClasses }
onClick={ self.removeFolder.bind(self, i) }
/>
{ folder }
</li>
);
}) }
</ul>
);
}
removeFolder(index) {
if (!this.props.refreshingLibrary) {
AppActions.library.removeFolder(index);
}
}
}
| import React, { PureComponent } from 'react';
import Icon from 'react-fontawesome';
import classnames from 'classnames';
import AppActions from '../../actions/AppActions';
/*
|--------------------------------------------------------------------------
| LibraryFolders
|--------------------------------------------------------------------------
*/
export default class LibraryFolders extends PureComponent {
static propTypes = {
folders: React.PropTypes.array,
refreshingLibrary: React.PropTypes.bool
}
constructor(props) {
super(props);
}
render() {
const self = this;
const foldersListClasses = classnames('musicfolders-list', {
empty: this.props.folders.length === 0
});
// TODO (y.solovyov): move to separate method that returns items
const removeButtonClasses = classnames('delete-libray-folder', {
disabled: self.props.refreshingLibrary
});
return (
<ul className={ foldersListClasses }>
{ this.props.folders.map((folder, i) => {
return(
<li key={ i }>
<Icon name='close'
className={ removeButtonClasses }
onClick={ self.removeFolder.bind(self, i) }
/>
{ folder }
</li>
);
}) }
</ul>
);
}
removeFolder(index) {
if (!this.props.refreshingLibrary) {
AppActions.library.removeFolder(index);
}
}
}
|
Set release version to 0.3.4 | from __future__ import absolute_import
import celery
from tornado import ioloop
from .connection import ConnectionPool
from .producer import NonBlockingTaskProducer
from .result import AsyncResult
VERSION = (0, 3, 4)
__version__ = '.'.join(map(str, VERSION))
def setup_nonblocking_producer(celery_app=None, io_loop=None,
on_ready=None, result_cls=AsyncResult,
limit=1):
celery_app = celery_app or celery.current_app
io_loop = io_loop or ioloop.IOLoop.instance()
NonBlockingTaskProducer.app = celery_app
NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop)
NonBlockingTaskProducer.result_cls = result_cls
if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'):
celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer
def connect():
broker_url = celery_app.connection().as_uri(include_password=True)
options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {})
NonBlockingTaskProducer.conn_pool.connect(broker_url,
options=options,
callback=on_ready)
io_loop.add_callback(connect)
| from __future__ import absolute_import
import celery
from tornado import ioloop
from .connection import ConnectionPool
from .producer import NonBlockingTaskProducer
from .result import AsyncResult
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION)) + '-dev'
def setup_nonblocking_producer(celery_app=None, io_loop=None,
on_ready=None, result_cls=AsyncResult,
limit=1):
celery_app = celery_app or celery.current_app
io_loop = io_loop or ioloop.IOLoop.instance()
NonBlockingTaskProducer.app = celery_app
NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop)
NonBlockingTaskProducer.result_cls = result_cls
if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'):
celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer
def connect():
broker_url = celery_app.connection().as_uri(include_password=True)
options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {})
NonBlockingTaskProducer.conn_pool.connect(broker_url,
options=options,
callback=on_ready)
io_loop.add_callback(connect)
|
Remove job references from navigation | from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, **kwargs):
request = kwargs.get('request')
if request.user.is_authenticated() and request.user.is_staff:
urls = [
(_('scheduling'), 'admin/scheduling/'),
(_('waitlist'), 'admin/waitlist/'),
(_('drudges'), 'admin/drudges/'),
(_('assignments'), 'admin/assignments/'),
(_('expense reports'), 'admin/expense_reports/'),
(_('regional offices'), 'admin/regional_offices/'),
(_('scope statements'), 'admin/scope_statements/'),
(_('specifications'), 'admin/specifications/'),
]
else:
urls = [
(_('dashboard'), 'dashboard/'),
(_('profile'), 'profile/'),
]
return [PagePretender(
title=capfirst(title),
url='%s%s' % (page.get_navigation_url(), url),
level=page.level+1,
tree_id=page.tree_id,
) for title, url in urls]
| from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, **kwargs):
request = kwargs.get('request')
if request.user.is_authenticated() and request.user.is_staff:
urls = [
(_('scheduling'), 'admin/scheduling/'),
(_('waitlist'), 'admin/waitlist/'),
(_('drudges'), 'admin/drudges/'),
(_('assignments'), 'admin/assignments/'),
(_('job references'), 'admin/jobreferences/'),
(_('expense reports'), 'admin/expense_reports/'),
(_('regional offices'), 'admin/regional_offices/'),
(_('scope statements'), 'admin/scope_statements/'),
(_('specifications'), 'admin/specifications/'),
]
else:
urls = [
(_('dashboard'), 'dashboard/'),
(_('profile'), 'profile/'),
]
return [PagePretender(
title=capfirst(title),
url='%s%s' % (page.get_navigation_url(), url),
level=page.level+1,
tree_id=page.tree_id,
) for title, url in urls]
|
Change goals passage with service (from message) | #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.srv import ApplyGoals
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def get_waypoints():
sequence = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data.get('name', ""),
x = waypoint_data['x'], # required
y = waypoint_data['y'], # required
radius = waypoint_data['radius'], # required
importance = waypoint_data.get('importance', 0),
drag = waypoint_data.get('drag', 0))
sequence.waypoints.append(waypoint)
return sequence
if __name__ == '__main__':
rospy.init_node('yaml_reader', anonymous=True)
goal_sequence = get_waypoints()
rospy.wait_for_service('apply_goals')
try:
apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals)
resp = apply_goals(goal_sequence)
print resp.message
except rospy.ServiceException, e:
print e
| #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data.get('name', ""),
x = waypoint_data['x'], # required
y = waypoint_data['y'], # required
radius = waypoint_data['radius'], # required
importance = waypoint_data.get('importance', 0),
drag = waypoint_data.get('drag', 0))
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
|
Switch browser list when running in Travis | module.exports = function(config) {
const files = [
{
pattern: 'browser/everything.html',
included: false,
served: true,
},
{
pattern: 'browser/everything.js',
included: true,
served: true,
},
{
pattern: 'spec/fixtures/*.json',
included: false,
served: true,
},
{
pattern: 'browser/vendor/requirejs/*.js',
included: false,
served: true,
},
{
pattern: 'browser/vendor/react/*.js',
included: false,
served: true,
},
{
pattern: 'browser/manifest.appcache',
included: false,
served: true,
},
'spec/*.js',
];
const configuration = {
basePath: '',
frameworks: ['mocha', 'chai'],
files,
exclude: [],
preprocessors: {},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeHeadless'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox'],
},
},
singleRun: true,
concurrency: Infinity
};
if (process.env.TRAVIS) {
configuration.browsers = ['ChromeHeadlessNoSandbox'];
}
config.set(configuration);
}
| module.exports = function(config) {
const files = [
{
pattern: 'browser/everything.html',
included: false,
served: true,
},
{
pattern: 'browser/everything.js',
included: true,
served: true,
},
{
pattern: 'spec/fixtures/*.json',
included: false,
served: true,
},
{
pattern: 'browser/vendor/requirejs/*.js',
included: false,
served: true,
},
{
pattern: 'browser/vendor/react/*.js',
included: false,
served: true,
},
{
pattern: 'browser/manifest.appcache',
included: false,
served: true,
},
'spec/*.js',
];
const configuration = {
basePath: '',
frameworks: ['mocha', 'chai'],
files,
exclude: [],
preprocessors: {},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome', 'ChromeHeadless', 'ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox'],
},
},
singleRun: true,
concurrency: Infinity
};
config.set(configuration);
}
|
Handle error in get diff stats | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from operator import attrgetter
from django.core.management.base import BaseCommand
import six
from corehq.apps.domain_migration_flags.api import get_uncompleted_migrations
from ...progress import COUCH_TO_SQL_SLUG
from .migrate_multiple_domains_from_couch_to_sql import (
format_diff_stats,
get_diff_stats,
)
class Command(BaseCommand):
"""Show domains for which the migration has been strated and not completed"""
def handle(self, **options):
migrations = get_uncompleted_migrations(COUCH_TO_SQL_SLUG)
for status, items in sorted(six.iteritems(migrations)):
print(status)
print("=" * len(status))
print("")
for item in sorted(items, key=attrgetter("domain")):
started = item.started_on
print("{}{}".format(
item.domain,
started.strftime(" (%Y-%m-%d)") if started else "",
))
try:
stats = get_diff_stats(item.domain)
print(format_diff_stats(stats))
except Exception as err:
print("Cannot get diff stats: {}".format(err))
print("")
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from operator import attrgetter
from django.core.management.base import BaseCommand
import six
from corehq.apps.domain_migration_flags.api import get_uncompleted_migrations
from ...progress import COUCH_TO_SQL_SLUG
from .migrate_multiple_domains_from_couch_to_sql import (
format_diff_stats,
get_diff_stats,
)
class Command(BaseCommand):
"""Show domains for which the migration has been strated and not completed"""
def handle(self, **options):
migrations = get_uncompleted_migrations(COUCH_TO_SQL_SLUG)
for status, items in sorted(six.iteritems(migrations)):
print(status)
print("=" * len(status))
print("")
for item in sorted(items, key=attrgetter("domain")):
started = item.started_on
print("{}{}".format(
item.domain,
started.strftime(" (%Y-%m-%d)") if started else "",
))
stats = get_diff_stats(item.domain)
print(format_diff_stats(stats))
print("")
|
Update the commit_over_52 template tag to be more efficient.
Replaced several list comprehensions with in-database operations and map calls for significantly improved performance. | from datetime import timedelta
from datetime import datetime
from django import template
from github2.client import Github
from package.models import Package, Commit
register = template.Library()
github = Github()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
commits = Commit.objects.filter(package=package).values_list('commit_date', flat=True)
for week in range(52):
weeks.append(len([x for x in commits if x < current and x > (current - timedelta(7))]))
current -= timedelta(7)
weeks.reverse()
weeks = map(str, weeks)
return ','.join(weeks)
@register.inclusion_tag('package/templatetags/usage.html')
def usage(user, package):
using = package.usage.filter(username=user) or False
count = 0
if using:
count = package.usage.count() - 1
return {
"using": using,
"count": count,
"package_id": package.id,
"user_id": user.id,
"show_count": True
}
@register.inclusion_tag('package/templatetags/usage.html')
def usage_no_count(user, package):
using = package.usage.filter(username=user) or False
count = 0
return {
"using": using,
"count": count,
"package_id": package.id,
"user_id": user.id,
"show_count": False
} | from datetime import timedelta
from datetime import datetime
from django import template
from github2.client import Github
from package.models import Package, Commit
register = template.Library()
github = Github()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
commits = [x.commit_date for x in Commit.objects.filter(package=package)]
for week in range(52):
weeks.append(len([x for x in commits if x < current and x > (current - timedelta(7))]))
current -= timedelta(7)
weeks.reverse()
weeks = [str(x) for x in weeks]
return ','.join(weeks)
@register.inclusion_tag('package/templatetags/usage.html')
def usage(user, package):
using = package.usage.filter(username=user) or False
count = 0
if using:
count = package.usage.count() - 1
return {
"using": using,
"count": count,
"package_id": package.id,
"user_id": user.id,
"show_count": True
}
@register.inclusion_tag('package/templatetags/usage.html')
def usage_no_count(user, package):
using = package.usage.filter(username=user) or False
count = 0
return {
"using": using,
"count": count,
"package_id": package.id,
"user_id": user.id,
"show_count": False
} |
Add '%' in coverage badge | # -*- coding: utf8 -*-
import requests
from django.contrib.staticfiles import finders
from django.core.cache import cache
def get_badge(succeeded):
key = 'badge{}'.format(succeeded)
badge = cache.get(key)
if badge is None:
if succeeded:
path = finders.find('badges/build-success.svg')
else:
path = finders.find('badges/build-failure.svg')
with open(path) as f:
badge = f.read()
cache.set(key, badge, timeout=60 * 60 * 24 * 7)
return badge
def get_coverage_badge(coverage):
key = 'badgecoverage{}'.format(coverage)
badge = cache.get(key)
if badge is None:
if coverage is None:
url = 'https://img.shields.io/badge/coverage-unknown-lightgrey.svg'
else:
url = 'https://img.shields.io/badge/coverage-{}%-{}.svg?style=flat'.format(
coverage,
_coverage_color(coverage)
)
badge = requests.get(url).text
cache.set(key, badge)
return badge
def _coverage_color(coverage):
if coverage == 100:
return 'brightgreen'
if coverage >= 90:
return 'green'
if coverage >= 70:
return 'yellow'
if coverage >= 50:
return 'orange'
return 'red'
| # -*- coding: utf8 -*-
import requests
from django.contrib.staticfiles import finders
from django.core.cache import cache
def get_badge(succeeded):
key = 'badge{}'.format(succeeded)
badge = cache.get(key)
if badge is None:
if succeeded:
path = finders.find('badges/build-success.svg')
else:
path = finders.find('badges/build-failure.svg')
with open(path) as f:
badge = f.read()
cache.set(key, badge, timeout=60 * 60 * 24 * 7)
return badge
def get_coverage_badge(coverage):
key = 'badgecoverage{}'.format(coverage)
badge = cache.get(key)
if badge is None:
if coverage is None:
url = 'https://img.shields.io/badge/coverage-unknown-lightgrey.svg'
else:
url = 'https://img.shields.io/badge/coverage-{}-{}.svg?style=flat'.format(
coverage,
_coverage_color(coverage)
)
badge = requests.get(url).text
cache.set(key, badge)
return badge
def _coverage_color(coverage):
if coverage == 100:
return 'brightgreen'
if coverage >= 90:
return 'green'
if coverage >= 70:
return 'yellow'
if coverage >= 50:
return 'orange'
return 'red'
|
Split tests out into commit and acceptance tests | /* global module */
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'app.js', 'blanket.js', 'gruntfile.js', 'src/**/*.js',
'test/**/*.js'
],
options: {
bitwise: true,
camelcase: true,
curly: true,
freeze: true,
indent: 4,
latedef: true,
newcap: true,
noarg: true,
noempty: true,
nonew: true,
quotmark: 'single',
undef: true,
unused: true,
trailing: true,
maxlen: 80
}
},
mochaTest: {
acceptanceTests: {
options: {
reporter: 'spec',
require: 'blanket'
},
src: ['test/acceptance/**/*.js']
},
commitTests: {
options: {
reporter: 'spec',
require: 'blanket'
},
src: ['test/commit/**/*.js']
},
coverage: {
options: {
reporter: 'html-cov',
quiet: true,
captureFile: 'coverage.html'
}
}
},
pkg: grunt.file.readJSON('package.json')
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('default', ['jshint', 'mochaTest']);
};
| /* global module */
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: ['app.js', 'blanket.js', 'gruntfile.js', 'src/**/*.js'],
options: {
bitwise: true,
camelcase: true,
curly: true,
freeze: true,
indent: 4,
latedef: true,
newcap: true,
noarg: true,
noempty: true,
nonew: true,
quotmark: 'single',
undef: true,
unused: true,
trailing: true,
maxlen: 80
}
},
mochaTest: {
coverage: {
options: {
reporter: 'html-cov',
quiet: true,
captureFile: 'coverage.html'
}
},
test: {
options: {
reporter: 'spec',
require: 'blanket'
},
src: ['test/**/*.js']
}
},
pkg: grunt.file.readJSON('package.json')
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('default', ['jshint', 'mochaTest']);
};
|
fix(expressions): Whitelist `DayOfWeek` enum for expressions | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.pipeline.expressions.whitelisting;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
public interface InstantiationTypeRestrictor {
Set<Class<?>> allowedTypes =
Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList(
String.class,
Date.class,
Integer.class,
Long.class,
Double.class,
Byte.class,
SimpleDateFormat.class,
Math.class,
Random.class,
UUID.class,
Boolean.class,
LocalDate.class,
DayOfWeek.class,
Instant.class,
ChronoUnit.class)));
static boolean supports(Class<?> type) {
return allowedTypes.contains(type);
}
}
| /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.pipeline.expressions.whitelisting;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
public interface InstantiationTypeRestrictor {
Set<Class<?>> allowedTypes =
Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList(
String.class,
Date.class,
Integer.class,
Long.class,
Double.class,
Byte.class,
SimpleDateFormat.class,
Math.class,
Random.class,
UUID.class,
Boolean.class,
LocalDate.class,
Instant.class,
ChronoUnit.class)));
static boolean supports(Class<?> type) {
return allowedTypes.contains(type);
}
}
|
Delete request ids when we're done with them; refactor | import { _ERROR } from 'constants'
const pendingIds = {} // requestIDs to timeoutIDs
let nextRequestID = 0
export default function createSocketMiddleware (socket, prefix) {
return ({ dispatch }) => {
// dispatch incoming actions sent by the server
socket.on('action', dispatch)
return next => action => {
const { type, meta } = action
// only apply to socket.io requests
if (!type || type.indexOf(prefix) !== 0) {
return next(action)
}
const requestID = nextRequestID++
// fire request action
next(action)
// error action if socket.io callback timeout
if (!(meta && meta.requireAck === false)) {
pending[requestID] = setTimeout(() => {
next({
type: type + _ERROR,
meta: {
error: `Server didn't respond; check network [${type}]`,
}
})
delete pending[requestID]
}, 1000)
}
// emit along with our acknowledgement callback (3rd arg)
// that receives data when the server calls ctx.acknowledge(data)
// in our case the data should be a *_SUCCESS or *_ERROR action
socket.emit('action', action, responseAction => {
clearTimeout(pending[requestID])
delete pending[requestID]
next(responseAction)
})
}
}
}
| import { _ERROR } from 'constants'
const pendingIds = {} // requestIDs to timeoutIDs
let nextRequestID = 0
export default function createSocketMiddleware (socket, prefix) {
return ({ dispatch }) => {
// dispatch incoming actions sent by the server
socket.on('action', dispatch)
return next => action => {
const { type, meta } = action
// only apply to socket.io requests
if (!type || type.indexOf(prefix) !== 0) {
return next(action)
}
const requestID = nextRequestID++
// fire request action
next(action)
// error action if socket.io callback timeout
if (!(meta && meta.requireAck === false)) {
pendingIds[requestID] = setTimeout(() => {
next({
type: type + _ERROR,
meta: {
error: `No response from server; check network connection (on action ${type})`,
}
})
}, 2000)
}
// emit with callback method (3rd arg) that is
// called using ctx.acknowledge(action) on the server
socket.emit('action', action, responseAction => {
// cancel dead man's timer
clearTimeout(pendingIds[requestID])
// action should typically have type *_SUCCESS or *_ERROR
return next(responseAction)
})
}
}
}
|
Fix function propagation to child to avoid react bind warning in logs | /** @jsx React.DOM */
var PersonContacts = React.createClass({
getInitialState: function() {
return {
filterText:""
}
},
handleUserInput: function(text) {
this.replaceState({
filterText: text
});
},
render: function () {
var self = this;
console.log('Render PersonContacts')
console.log(this.props);
if (!this.props.personPG) return (
<div id="contacts" className="clearfix">
<ul className="clearfix span3">
</ul>
</div>
);
var foafs = _.chain(this.props.personPG.rel(FOAF("knows")))
.map(function (contactPG) {
var contactURL = contactPG.pointer.value;
var onContactClick = function() {
self.props.onContactSelected(this,contactURL);
}
return (<PersonContactOnProfile
onPersonContactClick={onContactClick}
personPG={contactPG}
filterText={self.state.filterText}/>)
}).value();
return (
<div id="contacts" className="clearfix">
<ul className="clearfix span3">
{ foafs }
</ul>
</div>
);
}
});
| /** @jsx React.DOM */
var PersonContacts = React.createClass({
getInitialState: function() {
return {
filterText:""
}
},
handleUserInput: function(text) {
this.replaceState({
filterText: text
});
},
render: function () {
var self = this;
console.log('Render PersonContacts')
console.log(this.props);
if (!this.props.personPG) return (
<div id="contacts" className="clearfix">
<ul className="clearfix span3">
</ul>
</div>
);
var foafs = _.chain(this.props.personPG.rel(FOAF("knows")))
.map(function (contactPG) {
var contactURL = contactPG.pointer.value;
var onContactClick = self.props.onContactSelected.bind(this,contactURL);
return (<PersonContactOnProfile
onPersonContactClick={onContactClick}
personPG={contactPG}
filterText={self.state.filterText}/>)
}).value();
return (
<div id="contacts" className="clearfix">
<ul className="clearfix span3">
{ foafs }
</ul>
</div>
);
}
});
|
Check for TrackJs already loaded and if yes, reinitialize it. Fixed version. | window._trackJs = {
onError: function(payload, error) {
function itemExistInList(item, list) {
for (var i = 0; i < list.length; i++) {
if (item.indexOf(list[i]) > -1) {
return true;
}
}
return false;
}
var ignorableErrors = [
// General script error, not actionable
"[object Event]",
// General script error, not actionable
"Script error.",
// error when user interrupts script loading, nothing to fix
"Error loading script",
// an error caused by DealPly (http://www.dealply.com/) chrome extension
"DealPly",
// this error is reported when a post request returns error, i.e. html body
// the details provided in this case are completely useless, thus discarded
"Unexpected token <"
];
if (itemExistInList(payload.message, ignorableErrors)) {
return false;
}
payload.network = payload.network.filter(function(item) {
// ignore random errors from Intercom
if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) {
return false;
}
return true;
});
return true;
}
};
// if Track:js is already loaded, we need to initialize it
if (typeof trackJs !== 'undefined') trackJs.configure(window._trackJs);
| window._trackJs = {
onError: function(payload, error) {
function itemExistInList(item, list) {
for (var i = 0; i < list.length; i++) {
if (item.indexOf(list[i]) > -1) {
return true;
}
}
return false;
}
var ignorableErrors = [
// General script error, not actionable
"[object Event]",
// General script error, not actionable
"Script error.",
// error when user interrupts script loading, nothing to fix
"Error loading script",
// an error caused by DealPly (http://www.dealply.com/) chrome extension
"DealPly",
// this error is reported when a post request returns error, i.e. html body
// the details provided in this case are completely useless, thus discarded
"Unexpected token <"
];
if (itemExistInList(payload.message, ignorableErrors)) {
return false;
}
payload.network = payload.network.filter(function(item) {
// ignore random errors from Intercom
if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) {
return false;
}
return true;
});
return true;
}
};
|
Fix paths in mail out email management command | from django.conf import settings
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from ...models import WaitingListEntry, Survey
class Command(BaseCommand):
help = "Email links to survey instances for those that never saw a survey"
def handle(self, *args, **options):
survey = Survey.objects.get(active=True)
entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True)
for entry in entries:
instance = survey.instances.create(entry=entry)
site = Site.objects.get_current()
protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
ctx = {
"instance": instance,
"site": site,
"protocol": protocol,
}
subject = render_to_string("pinax/waitinglist/survey_invite_subject.txt", ctx)
subject = subject.strip()
message = render_to_string("pinax/waitinglist/survey_invite_body.txt", ctx)
EmailMessage(
subject,
message,
to=[entry.email],
from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL
).send()
| from django.conf import settings
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from ...models import WaitingListEntry, Survey
class Command(BaseCommand):
help = "Email links to survey instances for those that never saw a survey"
def handle(self, *args, **options):
survey = Survey.objects.get(active=True)
entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True)
for entry in entries:
instance = survey.instances.create(entry=entry)
site = Site.objects.get_current()
protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
ctx = {
"instance": instance,
"site": site,
"protocol": protocol,
}
subject = render_to_string("waitinglist/survey_invite_subject.txt", ctx)
subject = subject.strip()
message = render_to_string("waitinglist/survey_invite_body.txt", ctx)
EmailMessage(
subject,
message,
to=[entry.email],
from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL
).send()
|
Use decl.source.input.from as asset from | import eachUrlDecl from './eachUrlDecl'
import Result from './result'
import mix from 'util-mix'
import getp from 'getp'
export default function (customTransforms) {
return function (root, result) {
let postcssOpts = result.opts
if (!postcssOpts.from) {
return result.warn(
'postcss-custom-url requires postcss "from" option.'
)
}
return eachUrlDecl(root, function (decl) {
let parts = decl.value.split(/\burl\((.*?)\)/)
return Promise.all(
parts.map(function (value, i) {
if (i % 2 === 0) {
return Promise.resolve(value)
}
let urlResult = new Result(value, mix({}, postcssOpts, { from: getp(decl, 'source', 'input', 'from') || postcssOpts.from }))
if (!urlResult.url) {
result.warn(
'postcss-custom-url empty `url()` in ' + postcssOpts.from
)
return Promise.resolve('url()')
}
return urlResult.transform(customTransforms)
.then(function () {
return 'url(' + urlResult.url + ')'
})
})
)
.then(function (transformedParts) {
decl.value = transformedParts.join('')
})
})
}
}
| import eachUrlDecl from './eachUrlDecl'
import Result from './result'
export default function (customTransforms) {
return function (root, result) {
let postcssOpts = result.opts
if (!postcssOpts.from) {
return result.warn(
'postcss-custom-url requires postcss "from" option.'
)
}
return eachUrlDecl(root, function (decl) {
let parts = decl.value.split(/\burl\((.*?)\)/)
return Promise.all(
parts.map(function (value, i) {
if (i % 2 === 0) {
return Promise.resolve(value)
}
let urlResult = new Result(value, postcssOpts)
if (!urlResult.url) {
result.warn(
'postcss-custom-url empty `url()` in ' + postcssOpts.from
)
return Promise.resolve('url()')
}
return urlResult.transform(customTransforms)
.then(function () {
return 'url(' + urlResult.url + ')'
})
})
)
.then(function (transformedParts) {
decl.value = transformedParts.join('')
})
})
}
}
|
Fix entry point for Mako. | import os
import sys
import re
from setuptools import setup, find_packages
v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(name='dogpile.cache',
version=VERSION,
description="A caching front-end based on the Dogpile lock.",
long_description=open(readme).read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
keywords='caching',
author='Mike Bayer',
author_email='[email protected]',
url='http://bitbucket.org/zzzeek/dogpile.cache',
license='BSD',
packages=find_packages('.', exclude=['ez_setup', 'tests*']),
namespace_packages=['dogpile'],
entry_points="""
[mako.cache]
dogpile.cache = dogpile.cache.plugins.mako_cache:MakoPlugin
""",
zip_safe=False,
install_requires=['dogpile.core>=0.4.1'],
test_suite='nose.collector',
tests_require=['nose', 'mock'],
)
| import os
import sys
import re
from setuptools import setup, find_packages
v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(name='dogpile.cache',
version=VERSION,
description="A caching front-end based on the Dogpile lock.",
long_description=open(readme).read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
keywords='caching',
author='Mike Bayer',
author_email='[email protected]',
url='http://bitbucket.org/zzzeek/dogpile.cache',
license='BSD',
packages=find_packages('.', exclude=['ez_setup', 'tests*']),
namespace_packages=['dogpile'],
entry_points="""
[mako.cache]
dogpile = dogpile.cache.plugins.mako:MakoPlugin
""",
zip_safe=False,
install_requires=['dogpile.core>=0.4.1'],
test_suite='nose.collector',
tests_require=['nose', 'mock'],
)
|
Add assertions for the Http client response | <?php
declare(strict_types=1);
namespace Tests;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Http;
use LaravelZero\Framework\Contracts\Providers\ComposerContract;
final class HttpComponentTest extends TestCase
{
/** @test */
public function it_installs_the_required_packages(): void
{
$composerMock = $this->createMock(ComposerContract::class);
$composerMock->expects($this->exactly(2))
->method('require')
->withConsecutive(
[$this->equalTo('guzzlehttp/guzzle "^6.3.1"')],
[$this->equalTo('illuminate/http "^7.0"')]
);
$this->app->instance(ComposerContract::class, $composerMock);
Artisan::call('app:install', ['component' => 'http']);
}
/** @test */
public function it_can_use_the_http_client(): void
{
Http::fake();
$response = Http::withHeaders([
'X-Faked' => 'enabled',
])->get('https://faked.test');
Http::assertSent(function ($request) {
return $request->hasHeader('X-Faked', 'enabled')
&& $request->url('https://faked.test');
});
$this->assertTrue($response->ok());
$this->assertEmpty($response->body());
}
}
| <?php
declare(strict_types=1);
namespace Tests;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Http;
use LaravelZero\Framework\Contracts\Providers\ComposerContract;
final class HttpComponentTest extends TestCase
{
/** @test */
public function it_installs_the_required_packages(): void
{
$composerMock = $this->createMock(ComposerContract::class);
$composerMock->expects($this->exactly(2))
->method('require')
->withConsecutive(
[$this->equalTo('guzzlehttp/guzzle "^6.3.1"')],
[$this->equalTo('illuminate/http "^7.0"')]
);
$this->app->instance(ComposerContract::class, $composerMock);
Artisan::call('app:install', ['component' => 'http']);
}
/** @test */
public function it_can_use_the_http_client(): void
{
Http::fake();
Http::withHeaders([
'X-Faked' => 'enabled',
])->get('https://faked.test');
Http::assertSent(function ($request) {
return $request->hasHeader('X-Faked', 'enabled')
&& $request->url('https://faked.test');
});
}
}
|
Fix Application providers container contract | <?php
namespace Articstudio\IcebergApp\Provider;
use Articstudio\IcebergApp\Contract\Container as ContainerContract;
use Articstudio\IcebergApp\Support\Collection;
use Articstudio\IcebergApp\Exception\Provider\NotFoundException;
use Exception;
use Throwable;
trait ManagerByProveidersTrait {
private $providers;
public function __construct(array $providers = []) {
$this->providers = new Collection($providers);
}
public function register(ContainerContract $container) {
foreach ($this->providers AS $provider) {
$this->registerProvider($container, $provider);
}
}
public function add($provider) {
$this->providers->push($provider);
}
private function registerProvider(ContainerContract $container, $provider_class_name) {
if (!is_string($provider_class_name) || !class_exists($provider_class_name)) {
throw new NotFoundException(sprintf('Provider error while retrieving "%s"', $provider_class_name));
}
try {
$provider = new $provider_class_name;
} catch (Exception $exception) {
throw new NotFoundException(sprintf('Provider error while retrieving "%s"', $provider_class_name), null, $exception);
} catch (Throwable $exception) {
throw new NotFoundException(sprintf('Provider error while retrieving "%s"', $provider_class_name), null, $exception);
}
call_user_func_array(array($provider, 'register'), array($container));
}
}
| <?php
namespace Articstudio\IcebergApp\Provider;
use Psr\Container\ContainerInterface as ContainerContract;
use Articstudio\IcebergApp\Support\Collection;
use Articstudio\IcebergApp\Exception\Provider\NotFoundException;
use Exception;
use Throwable;
trait ManagerByProveidersTrait {
private $providers;
public function __construct(array $providers = []) {
$this->providers = new Collection($providers);
}
public function register(ContainerContract $container) {
foreach ($this->providers AS $provider) {
$this->registerProvider($container, $provider);
}
}
public function add($provider) {
$this->providers->push($provider);
}
private function registerProvider(ContainerContract $container, $provider_class_name) {
if (!is_string($provider_class_name) || !class_exists($provider_class_name)) {
throw new NotFoundException(sprintf('Provider error while retrieving "%s"', $provider_class_name));
}
try {
$provider = new $provider_class_name;
} catch (Exception $exception) {
throw new NotFoundException(sprintf('Provider error while retrieving "%s"', $provider_class_name), null, $exception);
} catch (Throwable $exception) {
throw new NotFoundException(sprintf('Provider error while retrieving "%s"', $provider_class_name), null, $exception);
}
call_user_func_array(array($provider, 'register'), array($container));
}
}
|
Bump version for more usefulness. | from setuptools import setup, find_packages
version = '0.1.0'
setup(name='scoville',
version=version,
description="A tool for measureing tile latency.",
long_description=open('README.md').read(),
classifiers=[
# strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Utilities',
],
keywords='tile latency mvt',
author='Matt Amos, Mapzen',
author_email='[email protected]',
url='https://github.com/tilezen/scoville',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'PyYAML',
'contextlib2',
'Shapely',
'pycurl',
'mapbox_vector_tile',
'psycopg2',
'boto3'
],
entry_points=dict(
console_scripts=[
'scoville = scoville.command:scoville_main',
]
)
)
| from setuptools import setup, find_packages
version = '0.0.1'
setup(name='scoville',
version=version,
description="A tool for measureing tile latency.",
long_description=open('README.md').read(),
classifiers=[
# strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Utilities',
],
keywords='tile latency mvt',
author='Matt Amos, Mapzen',
author_email='[email protected]',
url='https://github.com/tilezen/scoville',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'PyYAML',
'contextlib2',
'Shapely',
'pycurl',
'mapbox_vector_tile',
'psycopg2',
'boto3'
],
entry_points=dict(
console_scripts=[
'scoville = scoville.command:scoville_main',
]
)
)
|
Copy the .htaccess to the release directory | module.exports = {
main: {
files: [
{
expand: true,
cwd: 'assets/',
src: ['**', '.htaccess'],
dest: 'out/'
}
]
},
require: {
src: 'vendor/requirejs/require.js',
dest: 'out/js/lib/require.js'
},
jQuery: {
src: 'vendor/jquery/dist/jquery.js',
dest: 'out/js/lib/jquery.js'
},
jQueryMin: {
src: 'vendor/jquery/dist/jquery.min.js',
dest: 'out/js/lib/jquery.min.js'
},
js: {
files: [
{
expand: true,
cwd: 'src/js/app',
src: ['**/*.js'],
dest: 'out/js/app'
}
]
},
libs: {
files: [
{
expand: true,
cwd: 'vendor',
src: ['**/*.js'],
dest: 'out/js/lib'
}
]
},
fonts: {
files: [
{
expand: true,
cwd: 'src/icons/generated/',
src: ['*.eot', '*.svg', '*.ttf', '*.woff'],
dest: 'out/fonts'
}
]
},
leaflet: {
files: [
{
expand: true,
cwd: 'vendor/leaflet-dist/images',
src: ['**'],
dest: 'out/leaflet/images'
}
]
}
}; | module.exports = {
main: {
files: [
{
expand: true,
cwd: 'assets/',
src: ['**'],
dest: 'out/'
}
]
},
require: {
src: 'vendor/requirejs/require.js',
dest: 'out/js/lib/require.js'
},
jQuery: {
src: 'vendor/jquery/dist/jquery.js',
dest: 'out/js/lib/jquery.js'
},
jQueryMin: {
src: 'vendor/jquery/dist/jquery.min.js',
dest: 'out/js/lib/jquery.min.js'
},
js: {
files: [
{
expand: true,
cwd: 'src/js/app',
src: ['**/*.js'],
dest: 'out/js/app'
}
]
},
libs: {
files: [
{
expand: true,
cwd: 'vendor',
src: ['**/*.js'],
dest: 'out/js/lib'
}
]
},
fonts: {
files: [
{
expand: true,
cwd: 'src/icons/generated/',
src: ['*.eot', '*.svg', '*.ttf', '*.woff'],
dest: 'out/fonts'
}
]
},
leaflet: {
files: [
{
expand: true,
cwd: 'vendor/leaflet-dist/images',
src: ['**'],
dest: 'out/leaflet/images'
}
]
}
}; |
Fix watched threads (new not all) | <?php
/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserActivityInjector.php');
/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserCountActivityInjector.php');
class SV_UserActivity_XenForo_ControllerPublic_Watched extends XFCP_SV_UserActivity_XenForo_ControllerPublic_Watched
{
protected function forumFetcher(
/** @noinspection PhpUnusedParameterInspection */
XenForo_ControllerResponse_View $response,
$action,
array $config)
{
if (empty($response->params['forumsWatched']))
{
return null;
}
return array_keys($response->params['forumsWatched']);
}
protected function threadFetcher(
/** @noinspection PhpUnusedParameterInspection */
XenForo_ControllerResponse_View $response,
$action,
array $config)
{
$key = ($action == 'threads') ? 'newThreads' : 'threads';
if (empty($response->params[$key]))
{
return null;
}
return array_keys($response->params[$key]);
}
protected $countActivityInjector = [
[
'activeKey' => 'watched-forums',
'type' => 'node',
'actions' => ['forums'],
'fetcher' => 'forumFetcher',
],
[
'activeKey' => 'watched-threads',
'type' => 'thread',
'actions' => ['threads', 'threadsall'],
'fetcher' => 'threadFetcher'
],
];
use UserCountActivityInjector;
}
| <?php
/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserActivityInjector.php');
/** @noinspection PhpIncludeInspection */
include_once('SV/UserActivity/UserCountActivityInjector.php');
class SV_UserActivity_XenForo_ControllerPublic_Watched extends XFCP_SV_UserActivity_XenForo_ControllerPublic_Watched
{
protected function forumFetcher(
/** @noinspection PhpUnusedParameterInspection */
XenForo_ControllerResponse_View $response,
$action,
array $config)
{
if (empty($response->params['forumsWatched']))
{
return null;
}
return array_keys($response->params['forumsWatched']);
}
protected function threadFetcher(
/** @noinspection PhpUnusedParameterInspection */
XenForo_ControllerResponse_View $response,
$action,
array $config)
{
if (empty($response->params['threads']))
{
return null;
}
return array_keys($response->params['threads']);
}
protected $countActivityInjector = [
[
'activeKey' => 'watched-forums',
'type' => 'node',
'actions' => ['forums'],
'fetcher' => 'forumFetcher',
],
[
'activeKey' => 'watched-threads',
'type' => 'thread',
'actions' => ['threads', 'threadsall'],
'fetcher' => 'threadFetcher'
],
];
use UserCountActivityInjector;
}
|
feature/oop-api-refactoring: Fix placeholders in template string | # -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{{ name }} = {{ value }}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
| # -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{name} = {value}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
|
Use new API in integration tests. | (function(){
var window = this;
// Utility object dom scripting normalization
var DOM = {
on: (function() {
if(window.addEventListener) {
return function(target, type, listener) {
target.addEventListener(type, listener, false);
};
}
return function(target, type, listener) {
target.attachEvent('on' + type, listener);
};
})(),
off: (function() {
if(window.removeEventListener) {
return function(target, type, listener) {
target.removeEventListener(type, listener, false);
};
}
return function(target, type, listener) {
target.detachEvent('on' + type, listener);
};
})(),
cancelEvent: function(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
};
var STORAGE_TRANSPORT_EVENT_TYPE = 'message';
// Storage transport
var eventHub = StorageMessenger.create();
// Send message using storage transport
var sendMessage = function(event) {
var messageInput = document.getElementById('message');
var message = messageInput.value;
DOM.cancelEvent(event);
messageInput.value = '';
eventHub.trigger(STORAGE_TRANSPORT_EVENT_TYPE, message);
};
// Handler for storage transport message events
var showReceivedMessage = function(params) {
var value = params || '';
document.getElementById('received-message').value = value;
};
eventHub.on(STORAGE_TRANSPORT_EVENT_TYPE, showReceivedMessage);
DOM.on(document.getElementById('message-form'), 'submit', sendMessage);
}).call(this);
| (function(){
var window = this;
// Utility object dom scripting normalization
var DOM = {
on: (function() {
if(window.addEventListener) {
return function(target, type, listener) {
target.addEventListener(type, listener, false);
};
}
return function(target, type, listener) {
target.attachEvent('on' + type, listener);
};
})(),
off: (function() {
if(window.removeEventListener) {
return function(target, type, listener) {
target.removeEventListener(type, listener, false);
};
}
return function(target, type, listener) {
target.detachEvent('on' + type, listener);
};
})(),
cancelEvent: function(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
};
var STORAGE_TRANSPORT_EVENT_TYPE = 'message';
// Storage transport
var eventHub = StorageMessenger.EventHub.create();
// Send message using storage transport
var sendMessage = function(event) {
var messageInput = document.getElementById('message');
var message = messageInput.value;
DOM.cancelEvent(event);
messageInput.value = '';
eventHub.trigger(STORAGE_TRANSPORT_EVENT_TYPE, message);
};
// Handler for storage transport message events
var showReceivedMessage = function(params) {
var value = params || '';
document.getElementById('received-message').value = value;
};
eventHub.on(STORAGE_TRANSPORT_EVENT_TYPE, showReceivedMessage);
DOM.on(document.getElementById('message-form'), 'submit', sendMessage);
}).call(this);
|
Fix para no permitir insertar jugadores sin nombre | var UI = (function () {
var ui, game, html;
var clock;
function UI(_game) {
game = _game;
ui = this;
this.init();
html = $('.principal-wrapper');
html.on('click', '#add_player_btn', this.addPlayer)
.on('keypress', '#player',this.enterOnPlayerInput )
.on('click', '#start_btn', this.startGame)
};
UI.prototype.init = function(){
clock = $('#countdown').remove();
}
UI.prototype.addPlayer = function () {
if ($("#player").length > 0 && $("#players_list ol").length > 0) {
var player = $("#player").val();
if(player != ''){
game.newPlayer(player);
$("#players_list ol").append('<li>' + player + '</li>');
$("#player").val("");
}
}
};
UI.prototype.enterOnPlayerInput = function (e) {
if (e.which == 13) {//Enter key pressed
$('#add_player_btn').click();//Trigger same click event
}
};
UI.prototype.startGame = function () {
if (game.getPlayersNumber() >= 2) {
game.startGame();
game.play();
} else {
//TODO
alert('Minimo dos jugadores');
}
};
UI.prototype.StartTurn = function(){
};
return UI;
})();
| var UI = (function () {
var ui, game, html;
function UI(_game) {
game = _game;
ui = this;
html = $('.principal-wrapper');
html
.on('click', '#add_player_btn', this.addPlayer)
.on('keypress', '#player',this.enterOnPlayerInput )
.on('click', '#start_btn', this.startGame)
};
UI.prototype.addPlayer = function () {
if ($("#player").length > 0 && $("#players_list ol").lengh > 0) {
var player = $("#player").val();
game.newPlayer(player);
$("#players_list ol").append('<li>' + player + '</li>');
$("#player").val("");
}
};
UI.prototype.enterOnPlayerInput = function (e) {
if (e.which == 13) {//Enter key pressed
$('#add_player_btn').click();//Trigger same click event
}
};
UI.prototype.startGame = function () {
if (game.getPlayersNumber() >= 2) {
game.startGame();
game.play();
} else {
//TODO
alert('Minimo dos jugadores');
}
};
return UI;
})();
|
Add Instagram link to footer | <?php
/**
* Created by PhpStorm.
* User: mgrloren
* Date: 7/31/15
* Time: 2:55 PM
*/
?>
<footer>
<div class="container">
<div class="row">
<div class="col-sm-6">
<ul class="list-inline">
{{--<li><i class="icon-facebook icon-2x"></i></li>--}}
<li><a href="https://twitter.com/lorenlang"><i class="icon-twitter icon-2x"></i></a></li>
{{--<li><i class="icon-google-plus icon-2x"></i></li>--}}
{{--<li><i class="icon-pinterest icon-2x"></i></li>--}}
<li><a href="https://instagram.com/lorenlang00"><i class="icon-instagram icon-2x"></i></a></li>
<li><a href="https://www.linkedin.com/in/lorenlang"><i class="icon-linkedin icon-2x"></i></a></li>
<li><a href="http://wheresmyhead.com/feed"><i class="icon-rss icon-2x"></i></a></li>
</ul>
</div>
<div class="col-sm-6">
{{--<p class="pull-right">Built with <i class="icon-heart-empty"></i> at <a href="http://www.bootply.com">Bootply</a></p> --}}
</div>
</div>
</div>
</footer>
| <?php
/**
* Created by PhpStorm.
* User: mgrloren
* Date: 7/31/15
* Time: 2:55 PM
*/
?>
<footer>
<div class="container">
<div class="row">
<div class="col-sm-6">
<ul class="list-inline">
{{--<li><i class="icon-facebook icon-2x"></i></li>--}}
<li><a href="https://twitter.com/lorenlang"><i class="icon-twitter icon-2x"></i></a></li>
{{--<li><i class="icon-google-plus icon-2x"></i></li>--}}
{{--<li><i class="icon-pinterest icon-2x"></i></li>--}}
<li><a href="https://www.linkedin.com/in/lorenlang"><i class="icon-linkedin icon-2x"></i></a></li>
<li><a href="http://wheresmyhead.com/feed"><i class="icon-rss icon-2x"></i></a></li>
</ul>
</div>
<div class="col-sm-6">
{{--<p class="pull-right">Built with <i class="icon-heart-empty"></i> at <a href="http://www.bootply.com">Bootply</a></p> --}}
</div>
</div>
</div>
</footer>
|
Allow devDependencies in demos and tests | module.exports = {
"env": {
"browser": true
},
"extends": [
"airbnb",
// These prettier configs are used to disable inherited rules that conflict
// with the way prettier will format code. Full info here:
// https://github.com/prettier/eslint-config-prettier
"prettier",
"prettier/flowtype",
"prettier/react"
],
"parser": "babel-eslint",
"plugins": [
"flowtype",
"import",
"react",
"prettier"
],
"rules": {
"flowtype/define-flow-type": "error",
"flowtype/require-valid-file-annotation": [
2,
"always"
],
"flowtype/type-id-match": [
"error",
"^([A-Z][a-z0-9]+)+$"
],
"flowtype/use-flow-type": "error",
"import/no-duplicates": "error",
"import/no-extraneous-dependencies": [
"error",
{ "devDependencies": ["**/test.jsx", "**/demo.jsx", "**/*.demo.jsx", "**/demo/*.jsx"] }
],
"no-duplicate-imports": "off",
"no-nested-ternary": "off",
"no-warning-comments": [
"error",
{
"terms": [
"fixme"
]
}
],
"react/no-unused-prop-types": "off",
"prettier/prettier": [
"error",
{
// Options to pass to prettier: https://github.com/prettier/prettier#api
"singleQuote": true,
"trailingComma": "all"
},
"@prettier"
]
}
};
| module.exports = {
"env": {
"browser": true
},
"extends": [
"airbnb",
// These prettier configs are used to disable inherited rules that conflict
// with the way prettier will format code. Full info here:
// https://github.com/prettier/eslint-config-prettier
"prettier",
"prettier/flowtype",
"prettier/react"
],
"parser": "babel-eslint",
"plugins": [
"flowtype",
"import",
"react",
"prettier"
],
"rules": {
"flowtype/define-flow-type": "error",
"flowtype/require-valid-file-annotation": [
2,
"always"
],
"flowtype/type-id-match": [
"error",
"^([A-Z][a-z0-9]+)+$"
],
"flowtype/use-flow-type": "error",
"import/no-duplicates": "error",
"no-duplicate-imports": "off",
"no-nested-ternary": "off",
"no-warning-comments": [
"error",
{
"terms": [
"fixme"
]
}
],
"react/no-unused-prop-types": "off",
"prettier/prettier": [
"error",
{
// Options to pass to prettier: https://github.com/prettier/prettier#api
"singleQuote": true,
"trailingComma": "all"
},
"@prettier"
]
}
};
|
Update author and trove details | from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_description=open('README.rst').read(),
keywords='django apps',
license='New BSD License',
author='Horst Gutmann, Curtis Maloney',
author_email='[email protected]',
url='http://github.com/funkybob/django-flatblocks/',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Plugins',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
packages=find_packages(exclude=['test_project']),
package_data={
'flatblocks': [
'templates/flatblocks/*.html',
'locale/*/*/*.mo',
'locale/*/*/*.po',
]
},
zip_safe=False,
requires = [
'Django (>=1.4)',
],
)
| from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_description=open('README.rst').read(),
keywords='django apps',
license='New BSD License',
author='Horst Gutmann',
author_email='[email protected]',
url='http://github.com/funkybob/django-flatblocks/',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Plugins',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
packages=find_packages(exclude=['test_project']),
package_data={
'flatblocks': [
'templates/flatblocks/*.html',
'locale/*/*/*.mo',
'locale/*/*/*.po',
]
},
zip_safe=False,
requires = [
'Django (>=1.4)',
],
)
|
Change logs for google music | from gmusicapi import Mobileclient
def create_playlist(playlist_name, artists, email, password, max_top_tracks=2):
api = Mobileclient()
logged_in = api.login(email, password, Mobileclient.FROM_MAC_ADDRESS)
if not logged_in:
raise Exception('Could not connect')
song_ids = []
for artist_name in artists:
search = api.search(artist_name)
if len(search["artist_hits"]) == 0:
print('{}: Does not exist in Google Music. Skipping'.format(artist_name))
else:
artist_id = search["artist_hits"][0]["artist"]["artistId"]
artist = api.get_artist_info(artist_id, include_albums=False,
max_top_tracks=max_top_tracks, max_rel_artist=0)
if 'topTracks' not in artist:
print('{}: Exists but no songs found on Google Music. Skipping'.format(artist_name))
else:
song_ids = song_ids + [track['nid'] for track in artist['topTracks']]
print('{}: Found {} song(s). Will add'.format(artist_name, len(artist['topTracks'])))
playlist_id = api.create_playlist(playlist_name)
print('\nCreated playlist "{}" ({})'.format(playlist_name, playlist_id))
api.add_songs_to_playlist(playlist_id, song_ids)
print('Added {} songs to the playlist'.format(len(song_ids)))
print('All done. Enjoy! 🤘')
| from gmusicapi import Mobileclient
def create_playlist(playlist_name, artists, email, password, max_top_tracks=2):
api = Mobileclient()
logged_in = api.login(email, password, Mobileclient.FROM_MAC_ADDRESS)
if not logged_in:
raise Exception('Could not connect')
song_ids = []
for artist_name in artists:
search = api.search(artist_name)
if len(search["artist_hits"]) == 0:
print('{}: Does not exist in Google Music. Skipping'.format(artist_name))
else:
artist_id = search["artist_hits"][0]["artist"]["artistId"]
artist = api.get_artist_info(artist_id, include_albums=False,
max_top_tracks=max_top_tracks, max_rel_artist=0)
if 'topTracks' not in artist:
print('{}: Exists but no songs found on Google Music. Skipping'.format(artist_name))
else:
song_ids = song_ids + [track['nid'] for track in artist['topTracks']]
print('{}: Found {} song(s). Will add'.format(artist_name, len(artist['topTracks'])))
playlist_id = api.create_playlist(playlist_name)
print('\nCreated playlist {} ({})'.format(playlist_name, playlist_id))
api.add_songs_to_playlist(playlist_id, song_ids)
print('Added {} songs to the playlist'.format(len(song_ids)))
print('All done, well done. Enjoy!')
|
Add new swing package to exports. | /**
* JFreeChart module.
*/
module org.jfree.chart {
requires java.desktop;
exports org.jfree.chart;
exports org.jfree.chart.annotations;
exports org.jfree.chart.axis;
exports org.jfree.chart.date;
exports org.jfree.chart.editor;
exports org.jfree.chart.entity;
exports org.jfree.chart.event;
exports org.jfree.chart.imagemap;
exports org.jfree.chart.labels;
exports org.jfree.chart.needle;
exports org.jfree.chart.panel;
exports org.jfree.chart.plot;
exports org.jfree.chart.plot.dial;
exports org.jfree.chart.renderer;
exports org.jfree.chart.renderer.category;
exports org.jfree.chart.renderer.xy;
exports org.jfree.chart.swing;
exports org.jfree.chart.text;
exports org.jfree.chart.title;
exports org.jfree.chart.ui;
exports org.jfree.chart.urls;
exports org.jfree.chart.util;
exports org.jfree.data;
exports org.jfree.data.category;
exports org.jfree.data.function;
exports org.jfree.data.gantt;
exports org.jfree.data.general;
exports org.jfree.data.io;
exports org.jfree.data.json;
exports org.jfree.data.statistics;
exports org.jfree.data.time;
exports org.jfree.data.time.ohlc;
exports org.jfree.data.xml;
exports org.jfree.data.xy;
} | /**
* JFreeChart module.
*/
module org.jfree.chart {
requires java.desktop;
exports org.jfree.chart;
exports org.jfree.chart.annotations;
exports org.jfree.chart.axis;
exports org.jfree.chart.date;
exports org.jfree.chart.editor;
exports org.jfree.chart.entity;
exports org.jfree.chart.event;
exports org.jfree.chart.imagemap;
exports org.jfree.chart.labels;
exports org.jfree.chart.needle;
exports org.jfree.chart.panel;
exports org.jfree.chart.plot;
exports org.jfree.chart.plot.dial;
exports org.jfree.chart.renderer;
exports org.jfree.chart.renderer.category;
exports org.jfree.chart.renderer.xy;
exports org.jfree.chart.text;
exports org.jfree.chart.title;
exports org.jfree.chart.ui;
exports org.jfree.chart.urls;
exports org.jfree.chart.util;
exports org.jfree.data;
exports org.jfree.data.category;
exports org.jfree.data.function;
exports org.jfree.data.gantt;
exports org.jfree.data.general;
exports org.jfree.data.io;
exports org.jfree.data.json;
exports org.jfree.data.statistics;
exports org.jfree.data.time;
exports org.jfree.data.time.ohlc;
exports org.jfree.data.xml;
exports org.jfree.data.xy;
} |
Simplify SEBlock by broadcast of binary op
instead of explicit broadcast_to. The main motivation of this
change is to simplify the exported ONNX, but this would also
improve performance. | import chainer
import chainer.functions as F
import chainer.links as L
class SEBlock(chainer.Chain):
"""A squeeze-and-excitation block.
This block is part of squeeze-and-excitation networks. Channel-wise
multiplication weights are inferred from and applied to input feature map.
Please refer to `the original paper
<https://arxiv.org/pdf/1709.01507.pdf>`_ for more details.
.. seealso::
:class:`chainercv.links.model.senet.SEResNet`
Args:
n_channel (int): The number of channels of the input and output array.
ratio (int): Reduction ratio of :obj:`n_channel` to the number of
hidden layer units.
"""
def __init__(self, n_channel, ratio=16):
super(SEBlock, self).__init__()
reduction_size = n_channel // ratio
with self.init_scope():
self.down = L.Linear(n_channel, reduction_size)
self.up = L.Linear(reduction_size, n_channel)
def forward(self, u):
B, C, H, W = u.shape
z = F.average(u, axis=(2, 3))
x = F.relu(self.down(z))
x = F.sigmoid(self.up(x))
x = F.reshape(x, x.shape[:2] + (1, 1))
# Spatial axes of `x` will be broadcasted.
return u * x
| import chainer
import chainer.functions as F
import chainer.links as L
class SEBlock(chainer.Chain):
"""A squeeze-and-excitation block.
This block is part of squeeze-and-excitation networks. Channel-wise
multiplication weights are inferred from and applied to input feature map.
Please refer to `the original paper
<https://arxiv.org/pdf/1709.01507.pdf>`_ for more details.
.. seealso::
:class:`chainercv.links.model.senet.SEResNet`
Args:
n_channel (int): The number of channels of the input and output array.
ratio (int): Reduction ratio of :obj:`n_channel` to the number of
hidden layer units.
"""
def __init__(self, n_channel, ratio=16):
super(SEBlock, self).__init__()
reduction_size = n_channel // ratio
with self.init_scope():
self.down = L.Linear(n_channel, reduction_size)
self.up = L.Linear(reduction_size, n_channel)
def forward(self, u):
B, C, H, W = u.shape
z = F.average(u, axis=(2, 3))
x = F.relu(self.down(z))
x = F.sigmoid(self.up(x))
x = F.broadcast_to(x, (H, W, B, C))
x = x.transpose((2, 3, 0, 1))
return u * x
|
Add error handling to guestfs initializer | from abc import ABCMeta, abstractmethod
import guestfs
from xii import util, error
class NeedGuestFS():
__metaclass__ = ABCMeta
@abstractmethod
def get_tmp_volume_path(self):
pass
def guest(self):
def _start_guestfs():
try:
path = self.get_tmp_volume_path()
guest = guestfs.GuestFS()
guest.add_drive(path)
guest.launch()
guest.mount("/dev/sda1", "/")
if guest.exists('/etc/sysconfig/selinux'):
guest.get_selinux = lambda: 1
except RuntimeError as e:
raise error.ExecError("guestfs error: {}".format(e))
return guest
def _close_guest(guest):
guest.sync()
guest.umount("/")
guest.close()
return self.share("guestfs", _start_guestfs, _close_guest)
def guest_get_users(self):
content = self.guest().cat('/etc/passwd').split("\n")
return util.parse_passwd(content)
def guest_user_home(self, name):
users = self.guest_get_users()
if name not in users:
return None
return users[name]["home"]
def guest_get_groups(self):
content = self.guest().cat('/etc/group').split("\n")
return util.parse_groups(content)
| from abc import ABCMeta, abstractmethod
import guestfs
from xii import util
class NeedGuestFS():
__metaclass__ = ABCMeta
@abstractmethod
def get_tmp_volume_path(self):
pass
def guest(self):
def _start_guestfs():
path = self.get_tmp_volume_path()
guest = guestfs.GuestFS()
guest.add_drive(path)
guest.launch()
guest.mount("/dev/sda1", "/")
if guest.exists('/etc/sysconfig/selinux'):
guest.get_selinux = lambda: 1
return guest
def _close_guest(guest):
guest.sync()
guest.umount("/")
guest.close()
return self.share("guestfs", _start_guestfs, _close_guest)
def guest_get_users(self):
content = self.guest().cat('/etc/passwd').split("\n")
return util.parse_passwd(content)
def guest_user_home(self, name):
users = self.guest_get_users()
if name not in users:
return None
return users[name]["home"]
def guest_get_groups(self):
content = self.guest().cat('/etc/group').split("\n")
return util.parse_groups(content)
|
Add param doc of SAEKVStorage | # -*- coding: utf-8 -*-
from . import SessionStorage
class SaeKVDBStorage(SessionStorage):
"""
SaeKVDBStorage 使用SAE 的 KVDB 来保存你的session ::
import werobot
from werobot.session.saekvstorage import SaeKVDBStorage
session_storage = SaeKVDBStorage()
robot = werobot.WeRoBot(token="token", enable_session=True,
session_storage=session_storage)
需要先在后台开启 KVDB 支持
:param prefix: KVDB 中 Session 数据 key 的 prefix 。默认为 ``ws_``
"""
def __init__(self, prefix='ws_'):
try:
import sae.kvdb
except ImportError:
raise RuntimeError("SaeKVDBStorage requires SAE environment")
self.kv = sae.kvdb.KVClient()
self.prefix = prefix
def key_name(self, s):
return '{prefix}{s}'.format(prefix=self.prefix, s=s)
def get(self, id):
return self.kv.get(self.key_name(id)) or {}
def set(self, id, value):
return self.kv.set(self.key_name(id), value)
def delete(self, id):
return self.kv.delete(self.key_name(id))
| # -*- coding: utf-8 -*-
from . import SessionStorage
class SaeKVDBStorage(SessionStorage):
"""
SaeKVDBStorage 使用SAE 的 KVDB 来保存你的session ::
import werobot
from werobot.session.saekvstorage import SaeKVDBStorage
session_storage = SaeKVDBStorage()
robot = werobot.WeRoBot(token="token", enable_session=True,
session_storage=session_storage)
需要先在后台开启 KVDB 支持
"""
def __init__(self, prefix='WeRoBotSession_'):
try:
import sae.kvdb
except ImportError:
raise RuntimeError("SaeKVDBStorage requires SAE environment")
self.kv = sae.kvdb.KVClient()
self.prefix = prefix
def key_name(self, s):
return '{prefix}{s}'.format(prefix=self.prefix, s=s)
def get(self, id):
return self.kv.get(self.key_name(id)) or {}
def set(self, id, value):
return self.kv.set(self.key_name(id), value)
def delete(self, id):
return self.kv.delete(self.key_name(id))
|
Use Eloquent::getMorphClass() instead of get_class() for Morph Map support. | <?php
namespace Trexology\Pointable\Models;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
/**
* @var string
*/
protected $table = 'point_transactions';
/**
* @var array
*/
protected $guarded = ['id', 'created_at', 'updated_at'];
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function pointable()
{
return $this->morphTo();
}
/**
* @param Model $pointable
*
* @return static
*/
public function getCurrentPoints(Model $pointable)
{
$currentPoint = Transaction::
where('pointable_id', $pointable->id)
->where('pointable_type', $pointable->getMorphClass())
->orderBy('created_at', 'desc')
->lists('current')->first();
if (!$currentPoint) {
$currentPoint = 0.0;
}
return $currentPoint;
}
/**
* @param Model $pointable
* @param $amount
* @param $message
* @param $data
*
* @return static
*/
public function addTransaction(Model $pointable, $amount, $message, $data = null)
{
$transaction = new static();
$transaction->amount = $amount;
$transaction->current = $this->getCurrentPoints($pointable) + $amount;
$transaction->message = $message;
if ($data) {
$transaction->fill($data);
}
// $transaction->save();
$pointable->transactions()->save($transaction);
return $transaction;
}
}
| <?php
namespace Trexology\Pointable\Models;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
/**
* @var string
*/
protected $table = 'point_transactions';
/**
* @var array
*/
protected $guarded = ['id', 'created_at', 'updated_at'];
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function pointable()
{
return $this->morphTo();
}
/**
* @param Model $pointable
*
* @return static
*/
public function getCurrentPoints(Model $pointable)
{
$currentPoint = Transaction::
where('pointable_id', $pointable->id)
->where('pointable_type', get_class($pointable))
->orderBy('created_at', 'desc')
->lists('current')->first();
if (!$currentPoint) {
$currentPoint = 0.0;
}
return $currentPoint;
}
/**
* @param Model $pointable
* @param $amount
* @param $message
* @param $data
*
* @return static
*/
public function addTransaction(Model $pointable, $amount, $message, $data = null)
{
$transaction = new static();
$transaction->amount = $amount;
$transaction->current = $this->getCurrentPoints($pointable) + $amount;
$transaction->message = $message;
if ($data) {
$transaction->fill($data);
}
// $transaction->save();
$pointable->transactions()->save($transaction);
return $transaction;
}
}
|
Test if <TextInputRow> passing unknown props to its inner <input> | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { mount } from 'enzyme';
import TextInputRow, { PureTextInputRow, BEM } from '../TextInputRow';
describe('formRow(TextInputRow)', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
const element = (
<TextInputRow
label="foo"
defaultValue="bar" />
);
ReactDOM.render(element, div);
});
});
describe('Pure <TextInputRow>', () => {
it('renders an <input> inside with all unknown props', () => {
const wrapper = mount(
<PureTextInputRow
label="foo"
defaultValue="bar" />
);
expect(wrapper.find('input').exists()).toBeTruthy();
wrapper.setProps({ id: 'foo', tabIndex: 3 });
expect(wrapper.find('input').prop('id')).toBe('foo');
expect(wrapper.find('input').prop('tabIndex')).toBe(3);
});
it('enters and leaves focused state on input events', () => {
const focusedModifier = BEM.root
.modifier('focused')
.toString({ stripBlock: true });
const wrapper = mount(
<PureTextInputRow
label="foo"
defaultValue="bar" />
);
expect(wrapper.state('focused')).toBeFalsy();
wrapper.find('input').simulate('focus');
expect(wrapper.state('focused')).toBeTruthy();
expect(wrapper.hasClass(focusedModifier)).toBeTruthy();
wrapper.find('input').simulate('blur');
expect(wrapper.state('focused')).toBeFalsy();
expect(wrapper.hasClass(focusedModifier)).toBeFalsy();
});
});
| import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { mount } from 'enzyme';
import TextInputRow, { PureTextInputRow, BEM } from '../TextInputRow';
describe('formRow(TextInputRow)', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
const element = (
<TextInputRow
label="foo"
defaultValue="bar" />
);
ReactDOM.render(element, div);
});
});
describe('Pure <TextInputRow>', () => {
it('renders an <input> inside', () => {
const wrapper = mount(
<PureTextInputRow
label="foo"
defaultValue="bar" />
);
expect(wrapper.find('input').exists()).toBeTruthy();
});
it('enters and leaves focused state on input events', () => {
const focusedModifier = BEM.root
.modifier('focused')
.toString({ stripBlock: true });
const wrapper = mount(
<PureTextInputRow
label="foo"
defaultValue="bar" />
);
expect(wrapper.state('focused')).toBeFalsy();
wrapper.find('input').simulate('focus');
expect(wrapper.state('focused')).toBeTruthy();
expect(wrapper.hasClass(focusedModifier)).toBeTruthy();
wrapper.find('input').simulate('blur');
expect(wrapper.state('focused')).toBeFalsy();
expect(wrapper.hasClass(focusedModifier)).toBeFalsy();
});
});
|
Add comments for timed shoot | try:
import wpilib
except ImportError:
from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state
class TimedShootAutonomous(StatefulAutonomous):
'''
Tunable autonomous mode that does dumb time-based shooting
decisions. Works consistently.
'''
DEFAULT = False
MODE_NAME = "Timed shoot"
def __init__(self, components):
super().__init__(components)
self.register_sd_var('drive_speed', 0.5)
def on_disable(self):
'''This function is called when autonomous mode is disabled'''
pass
def update(self, tm):
# always keep the arm down
self.intake.armDown()
if tm > 0.3:
self.catapult.pulldown()
super().update(tm)
@timed_state(duration=1.2, next_state='drive', first=True)
def drive_wait(self, tm, state_tm):
'''Wait some period before we start driving'''
pass
@timed_state(duration=1.4, next_state='launch')
def drive(self, tm, state_tm):
'''Start the launch sequence! Drive slowly forward for N seconds'''
self.drive.move(0, self.drive_speed, 0)
@timed_state(duration=1.0)
def launch(self, tm):
'''Finally, fire and keep firing for 1 seconds'''
self.catapult.launchNoSensor()
| try:
import wpilib
except ImportError:
from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state
class TimedShootAutonomous(StatefulAutonomous):
'''
Tunable autonomous mode that does dumb time-based shooting
decisions. Works consistently.
'''
DEFAULT = False
MODE_NAME = "Timed shoot"
def __init__(self, components):
super().__init__(components)
self.register_sd_var('drive_speed', 0.5)
def on_disable(self):
'''This function is called when autonomous mode is disabled'''
pass
def update(self, tm):
# always keep the arm down
self.intake.armDown()
if tm > 0.3:
self.catapult.pulldown()
super().update(tm)
@timed_state(duration=1.2, next_state='drive', first=True)
def drive_wait(self, tm, state_tm):
pass
@timed_state(duration=1.4, next_state='launch')
def drive(self, tm, state_tm):
self.drive.move(0, self.drive_speed, 0)
@timed_state(duration=1.0)
def launch(self, tm):
self.catapult.launchNoSensor()
|
Simplify the province list API
It only contains province data as a list without the separate ordering
information. The order of the province data in the list is the order of
provinces. | from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
return dict(pid=province.id,
name=province.name,
code=province.code)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True) \
.order_by('order')
provinces = list(map(_province_to_dict, provinces))
return dict(provinces=provinces)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
| from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
data = dict(pid=province.id,
name=province.name,
code=province.code)
return (province.id, data)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True)
ordering = [province.id for province in provinces]
provinces = dict(map(_province_to_dict, provinces))
last_update = Province.objects.filter(enabled=True) \
.order_by('-updated') \
.values_list('updated', flat=True)[0]
return dict(provinces=provinces,
ordering=ordering)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
|
Throw exception when bad rcon | <?php
/**
* Created by PhpStorm.
* User: Bram
* Date: 1-9-2017
* Time: 06:59
*/
namespace Stormyy\B3\Helper;
use q3tool;
use Stormyy\B3\Models\B3Server;
abstract class Cod4Server
{
public static function getRcon(B3Server $server){
}
public static function screenshotAll(B3Server $server){
$tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
$response = $tool->send_rcon('getss all');
return $response;
}
public static function screenshot(B3Server $server, $guid, $user=null){
try {
$filename = '';
if ($user != null) {
$filename = ' user-' . $user->id . '-';
}
$tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
$response = $tool->send_rcon('getss ' . $guid . $filename);
if(str_contains($response, 'Bad rcon')){
throw new \Exception('Bad rcon');
}
return $response;
} catch (\Exception $exception){
return response()->json([
'code' => 'InvalidRcon',
'message' => 'Invalid rcon try reloading the nehoscreenshotuploader plugin'
], 500);
}
}
} | <?php
/**
* Created by PhpStorm.
* User: Bram
* Date: 1-9-2017
* Time: 06:59
*/
namespace Stormyy\B3\Helper;
use q3tool;
use Stormyy\B3\Models\B3Server;
abstract class Cod4Server
{
public static function getRcon(B3Server $server){
}
public static function screenshotAll(B3Server $server){
$tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
$response = $tool->send_rcon('getss all');
return $response;
}
public static function screenshot(B3Server $server, $guid, $user=null){
try {
$filename = '';
if ($user != null) {
$filename = ' user-' . $user->id . '-';
}
$tool = new q3tool($server->host, $server->port, \Crypt::decrypt($server->rcon));
$response = $tool->send_rcon('getss ' . $guid . $filename);
return $response;
} catch (\Exception $exception){
return response()->json([
'code' => 'InvalidRcon',
'message' => 'Invalid rcon try reloading the nehoscreenshotuploader plugin'
], 500);
}
}
} |
Handle geojson feature without latlon | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import DropItem
from scrapy import signals
class GeoJsonWriterPipeline(object):
def __init__(self):
dispatcher.connect(self.spider_opened, signals.spider_opened)
dispatcher.connect(self.spider_closed, signals.spider_closed)
self.file = None
def spider_opened(self, spider):
self.file = open('{}.jl'.format(spider.name), 'wb')
def spider_closed(self, spider):
self.file.close()
def process_item(self, item, spider):
feature = {
"type": "Feature",
"properties": item['properties'],
}
if item.get('lon_lat'):
feature['geometry'] = {
"type": "Point",
"coordinates": item['lon_lat']
}
line = json.dumps(feature, separators=(',', ':'))
self.file.write(line)
self.file.write('\n')
return item
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
def process_item(self, item, spider):
if item['properties']['ref'] in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(item['properties']['ref'])
return item
| # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import DropItem
from scrapy import signals
class GeoJsonWriterPipeline(object):
def __init__(self):
dispatcher.connect(self.spider_opened, signals.spider_opened)
dispatcher.connect(self.spider_closed, signals.spider_closed)
self.file = None
def spider_opened(self, spider):
self.file = open('{}.jl'.format(spider.name), 'wb')
def spider_closed(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps({
"type": "Feature",
"properties": item['properties'],
"geometry": {
"type": "Point",
"coordinates": item['lon_lat']
}
}, separators=(',', ':'))
self.file.write(line)
self.file.write('\n')
return item
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
def process_item(self, item, spider):
if item['properties']['ref'] in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(item['properties']['ref'])
return item
|
Remove unused variable from `about` view | <?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\ContactForm;
class SiteController extends Controller
{
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
'view' => 'error.twig',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'mellon' : null,
],
];
}
public function actionIndex()
{
return $this->render('index.twig');
}
public function actionContact()
{
$model = new ContactForm();
if (
$model->load(Yii::$app->request->post()) &&
$model->contact(Yii::$app->params['adminEmail'])
) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact.twig', ['model' => $model]);
}
public function actionAbout()
{
return $this->render('about.twig');
}
}
| <?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\ContactForm;
class SiteController extends Controller
{
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
'view' => 'error.twig',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'mellon' : null,
],
];
}
public function actionIndex()
{
return $this->render('index.twig');
}
public function actionContact()
{
$model = new ContactForm();
if (
$model->load(Yii::$app->request->post()) &&
$model->contact(Yii::$app->params['adminEmail'])
) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact.twig', ['model' => $model]);
}
public function actionAbout()
{
return $this->render('about.twig', ['server' => $_SERVER]);
}
}
|
NXDRIVE-170: Remove long timeout to make file blacklisting bug appear, waiting for the fix | import os
from nxdrive.tests.common import IntegrationTestCase
from nxdrive.client import LocalClient
class TestIntegrationCopy(IntegrationTestCase):
def test_synchronize_remote_copy(self):
# Get local and remote clients
local = LocalClient(os.path.join(self.local_nxdrive_folder_1,
self.workspace_title))
remote = self.remote_document_client_1
# Bind the server and root workspace
self.bind_server(self.ndrive_1, self.user_1, self.nuxeo_url, self.local_nxdrive_folder_1, self.password_1)
#TODO: allow use of self.bind_root(self.ndrive_1, self.workspace, self.local_nxdrive_folder_1)
remote.register_as_root(self.workspace)
# Create a file and a folder in the remote root workspace
remote.make_file('/', 'test.odt', 'Some content.')
remote.make_folder('/', 'Test folder')
# Copy the file to the folder remotely
remote.copy('/test.odt', '/Test folder')
# Launch ndrive, expecting 4 synchronized items
self.ndrive(self.ndrive_1)
self.assertTrue(local.exists('/'))
self.assertTrue(local.exists('/Test folder'))
self.assertTrue(local.exists('/test.odt'))
self.assertTrue(local.exists('/Test folder/test.odt'))
self.assertEquals(local.get_content('/Test folder/test.odt'),
'Some content.')
| import os
from nxdrive.tests.common import IntegrationTestCase
from nxdrive.client import LocalClient
class TestIntegrationCopy(IntegrationTestCase):
def test_synchronize_remote_copy(self):
# Get local and remote clients
local = LocalClient(os.path.join(self.local_nxdrive_folder_1,
self.workspace_title))
remote = self.remote_document_client_1
# Bind the server and root workspace
self.bind_server(self.ndrive_1, self.user_1, self.nuxeo_url, self.local_nxdrive_folder_1, self.password_1)
#TODO: allow use of self.bind_root(self.ndrive_1, self.workspace, self.local_nxdrive_folder_1)
remote.register_as_root(self.workspace)
# Create a file and a folder in the remote root workspace
remote.make_file('/', 'test.odt', 'Some content.')
remote.make_folder('/', 'Test folder')
# Copy the file to the folder remotely
remote.copy('/test.odt', '/Test folder')
# Launch ndrive, expecting 4 synchronized items
self.ndrive(self.ndrive_1, quit_timeout=300)
self.assertTrue(local.exists('/'))
self.assertTrue(local.exists('/Test folder'))
self.assertTrue(local.exists('/test.odt'))
self.assertTrue(local.exists('/Test folder/test.odt'))
self.assertEquals(local.get_content('/Test folder/test.odt'),
'Some content.')
|
CRM-323: Make Address entity plain
- fixed dependencny on AbstractAddress | <?php
namespace Oro\Bundle\AddressBundle\Form\Handler;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Oro\Bundle\AddressBundle\Entity\AbstractAddress;
class AddressHandler
{
/**
* @var FormInterface
*/
protected $form;
/**
* @var Request
*/
protected $request;
/**
* @var ObjectManager
*/
protected $manager;
/**
*
* @param FormInterface $form
* @param Request $request
* @param ObjectManager $manager
*/
public function __construct(FormInterface $form, Request $request, ObjectManager $manager)
{
$this->form = $form;
$this->request = $request;
$this->manager = $manager;
}
/**
* Process form
*
* @param AbstractAddress $entity
* @return bool True on successful processing, false otherwise
*/
public function process(AbstractAddress $entity)
{
$this->form->setData($entity);
if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
$this->form->submit($this->request);
if ($this->form->isValid()) {
$this->onSuccess($entity);
return true;
}
}
return false;
}
/**
* "Success" form handler
*
* @param AbstractAddress $entity
*/
protected function onSuccess(AbstractAddress $entity)
{
$this->manager->persist($entity);
$this->manager->flush();
}
}
| <?php
namespace Oro\Bundle\AddressBundle\Form\Handler;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Oro\Bundle\AddressBundle\Entity\Address;
class AddressHandler
{
/**
* @var FormInterface
*/
protected $form;
/**
* @var Request
*/
protected $request;
/**
* @var ObjectManager
*/
protected $manager;
/**
*
* @param FormInterface $form
* @param Request $request
* @param ObjectManager $manager
*/
public function __construct(FormInterface $form, Request $request, ObjectManager $manager)
{
$this->form = $form;
$this->request = $request;
$this->manager = $manager;
}
/**
* Process form
*
* @param Address $entity
* @return bool True on successful processing, false otherwise
*/
public function process(Address $entity)
{
$this->form->setData($entity);
if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
$this->form->submit($this->request);
if ($this->form->isValid()) {
$this->onSuccess($entity);
return true;
}
}
return false;
}
/**
* "Success" form handler
*
* @param Address $entity
*/
protected function onSuccess(Address $entity)
{
$this->manager->persist($entity);
$this->manager->flush();
}
}
|
Fix cursor not closed in database single value query
The cursor was closed too late in DbOperationSingleValueByRawQuery,
after the value was returned. The only case where it was closed was when
there was an unsupported column type specified. This commit fixes this
issue. | package org.edx.mobile.module.db.impl;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
class DbOperationSingleValueByRawQuery<T> extends DbOperationBase<T> {
private String sqlQuery;
private String[] selectionArgs;
private Class<T> columnType;
DbOperationSingleValueByRawQuery(String sqlQuery, String[] selectionArgs, Class<T> valueType) {
this.sqlQuery = sqlQuery;
this.selectionArgs = selectionArgs;
this.columnType = valueType;
}
@Override
public T execute(SQLiteDatabase db) {
Cursor c = db.rawQuery(sqlQuery, selectionArgs);
T result = null;
if (c.moveToFirst()) {
if (columnType == Long.class) {
Long column = c.getLong(0);
result = (T) column;
} else if (columnType == String.class) {
String column = c.getString(0);
result = (T) column;
} else if (columnType == Integer.class) {
Integer column = c.getInt(0);
result = (T) column;
} else {
logger.warn("Class types does NOT match for: " + columnType);
}
}
c.close();
return result;
}
}
| package org.edx.mobile.module.db.impl;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
class DbOperationSingleValueByRawQuery<T> extends DbOperationBase<T> {
private String sqlQuery;
private String[] selectionArgs;
private Class<T> columnType;
DbOperationSingleValueByRawQuery(String sqlQuery, String[] selectionArgs, Class<T> valueType) {
this.sqlQuery = sqlQuery;
this.selectionArgs = selectionArgs;
this.columnType = valueType;
}
@Override
public T execute(SQLiteDatabase db) {
Cursor c = db.rawQuery(sqlQuery, selectionArgs);
if (c.moveToFirst()) {
if (columnType == Long.class) {
Long column = c.getLong(0);
return (T) column;
} else if (columnType == String.class) {
String column = c.getString(0);
return (T) column;
} else if (columnType == Integer.class) {
Integer column = c.getInt(0);
return (T) column;
} else {
logger.warn("Class types does NOT match for: " + columnType);
}
}
c.close();
return null;
}
}
|
Store overridden methods in _super | 'use strict';
var extendPrototypeWithThese = function (prototype, extendThese) {
/*
Helper method to implement a simple inheritance model for object prototypes.
*/
var outp = prototype;
if (extendThese) {
for (var i = extendThese.length - 1; i >= 0; i--) {
// I need to create the object in order to copy the prototype functions
var tmpObj = extendThese[i].prototype;
for (var key in tmpObj) {
if (key == '_implements') {
// Implements should be extended with later coming before earlier
// TODO: Filer so we remove duplicates from existing list (order makes difference)
outp.prototype._implements = tmpObj._implements.concat(outp.prototype._implements);
} else {
// All others added and lower indexes override higher
outp.prototype[key] = tmpObj[key];
}
}
}
}
return outp;
}
module.exports.extendPrototypeWithThese = extendPrototypeWithThese;
var addMembers = function (outp, params) {
/*
Helper method to add each item in params dictionary to the prototype of outp.
*/
for (var key in params) {
if (params.hasOwnProperty(key)) {
if (typeof outp.prototype[key] === 'function') {
// Store inherited functions that are overridden in the _super property
if (!outp.prototype._super) {
outp.prototype._super = {};
}
outp.prototype._super[key] = outp.prototype[key];
}
outp.prototype[key] = params[key];
}
}
return outp;
}
module.exports.addMembers = addMembers; | 'use strict';
var extendPrototypeWithThese = function (prototype, extendThese) {
/*
Helper method to implement a simple inheritance model for object prototypes.
*/
var outp = prototype;
if (extendThese) {
for (var i = extendThese.length - 1; i >= 0; i--) {
// I need to create the object in order to copy the prototype functions
var tmpObj = extendThese[i].prototype;
for (var key in tmpObj) {
if (key == '_implements') {
// Implements should be extended with later coming before earlier
// TODO: Filer so we remove duplicates from existing list (order makes difference)
outp.prototype._implements = tmpObj._implements.concat(outp.prototype._implements);
} else {
// All others added and lower indexes override higher
outp.prototype[key] = tmpObj[key];
}
}
}
}
return outp;
}
module.exports.extendPrototypeWithThese = extendPrototypeWithThese;
var addMembers = function (outp, params) {
/*
Helper method to add each item in params dictionary to the prototype of outp.
*/
for (var key in params) {
if (params.hasOwnProperty(key)) {
outp.prototype[key] = params[key];
}
}
return outp;
}
module.exports.addMembers = addMembers; |
Add a test that ensures commas are part of non-word runs. | import unittest
from halng.tokenizer import MegaHALTokenizer
class testMegaHALTokenizer(unittest.TestCase):
def setUp(self):
self.tokenizer = MegaHALTokenizer()
def testSplitEmpty(self):
self.assertEquals(len(self.tokenizer.split("")), 0)
def testSplitSentence(self):
words = self.tokenizer.split("hi.")
self.assertEquals(len(words), 2)
self.assertEquals(words[0], "HI")
self.assertEquals(words[1], ".")
def testSplitComma(self):
words = self.tokenizer.split("hi, hal")
self.assertEquals(len(words), 4)
self.assertEquals(words[0], "HI")
self.assertEquals(words[1], ", ")
self.assertEquals(words[2], "HAL")
self.assertEquals(words[3], ".")
def testSplitImplicitStop(self):
words = self.tokenizer.split("hi")
self.assertEquals(len(words), 2)
self.assertEquals(words[0], "HI")
self.assertEquals(words[1], ".")
def testSplitUrl(self):
words = self.tokenizer.split("http://www.google.com/")
self.assertEquals(len(words), 8)
self.assertEquals(words[0], "HTTP")
self.assertEquals(words[1], "://")
self.assertEquals(words[2], "WWW")
self.assertEquals(words[3], ".")
self.assertEquals(words[4], "GOOGLE")
self.assertEquals(words[5], ".")
self.assertEquals(words[6], "COM")
self.assertEquals(words[7], "/.")
if __name__ == '__main__':
unittest.main()
| import unittest
from halng.tokenizer import MegaHALTokenizer
class testMegaHALTokenizer(unittest.TestCase):
def setUp(self):
self.tokenizer = MegaHALTokenizer()
def testSplitEmpty(self):
self.assertEquals(len(self.tokenizer.split("")), 0)
def testSplitSentence(self):
words = self.tokenizer.split("hi.")
self.assertEquals(len(words), 2)
self.assertEquals(words[0], "HI")
self.assertEquals(words[1], ".")
def testSplitImplicitStop(self):
words = self.tokenizer.split("hi")
self.assertEquals(len(words), 2)
self.assertEquals(words[0], "HI")
self.assertEquals(words[1], ".")
def testSplitUrl(self):
words = self.tokenizer.split("http://www.google.com/")
self.assertEquals(len(words), 8)
self.assertEquals(words[0], "HTTP")
self.assertEquals(words[1], "://")
self.assertEquals(words[2], "WWW")
self.assertEquals(words[3], ".")
self.assertEquals(words[4], "GOOGLE")
self.assertEquals(words[5], ".")
self.assertEquals(words[6], "COM")
self.assertEquals(words[7], "/.")
if __name__ == '__main__':
unittest.main()
|
Add a new foreign key for the vehicle type | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateVehiclesTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('vehicles', function (Blueprint $table) {
$table->string('code')->primary();
$table->foreign('code')->references('code')->on('items');
$table->integer('year')->nullable();
$table->integer('engine_displacement')->nullable();
$table->string('reg_plate_code')->nullable();
$table->boolean('is_good_condition')->nullable();
$table->integer('make_id')->unsigned()->nullable();
$table->foreign('make_id')->references('id')->on('vehicles_makes');
$table->integer('model_id')->unsigned()->nullable();
$table->foreign('model_id')->references('id')->on('vehicles_models');
$table->integer('color_id')->unsigned()->nullable();
$table->foreign('color_id')->references('id')->on('vehicles_colors');
$table->integer('fuel_id')->unsigned()->nullable();
$table->foreign('fuel_id')->references('id')->on('vehicles_fuels');
$table->integer('type_id')->unsigned()->nullable();
$table->foreign('type_id')->references('id')->on('vehicles_types');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::dropIfExists('vehicles');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateVehiclesTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('vehicles', function (Blueprint $table) {
$table->string('code')->primary();
$table->foreign('code')->references('code')->on('items');
$table->integer('year')->nullable();
$table->integer('engine_displacement')->nullable();
$table->string('reg_plate_code')->nullable();
$table->boolean('is_good_condition')->nullable();
$table->integer('make_id')->unsigned()->nullable();
$table->foreign('make_id')->references('id')->on('vehicles_makes');
$table->integer('model_id')->unsigned()->nullable();
$table->foreign('model_id')->references('id')->on('vehicles_models');
$table->integer('color_id')->unsigned()->nullable();
$table->foreign('color_id')->references('id')->on('vehicles_colors');
$table->integer('fuel_id')->unsigned()->nullable();
$table->foreign('fuel_id')->references('id')->on('vehicles_fuels');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::dropIfExists('vehicles');
}
}
|
Use the engine-types to get the icon | "use strict";
// Dependencies
const Deffy = require("deffy")
, Typpy = require("typpy")
, SubElmId = require("./id")
;
class SubElm {
/**
* SubElm
* Creates a `SubElm` instance.
*
* @name SubElm
* @function
* @param {Type} type The subelement type.
* @param {Object} data An object containing the following fields:
* @param {Element} parent The element this subelement belongs to.
* @return {SubElm} The `SubElm` instance.
*/
constructor (data, parent) {
this.type = Typpy(data);
this.icon = data.constructor.types.normal.icon;
this.name = this._name(data);
this.label = Deffy(data.label, this.name);
this.id = new SubElmId(this, parent.id);
this.lines = {};
}
/**
* Name
* Gets the name from various inputs.
*
* @name Name
* @function
* @param {Object} input An object containing one of the following fields:
*
* - `name`
* - `event`
* - `serverMethod`
* - `method`
*
* @return {String} The subelement name.
*/
_name (input) {
return input.name || input.event_name || input.method;
}
}
SubElm.Id = SubElmId;
module.exports = SubElm;
| "use strict";
// Dependencies
const Deffy = require("deffy")
, Typpy = require("typpy")
, SubElmId = require("./id")
;
class SubElm {
/**
* SubElm
* Creates a `SubElm` instance.
*
* @name SubElm
* @function
* @param {Type} type The subelement type.
* @param {Object} data An object containing the following fields:
* @param {Element} parent The element this subelement belongs to.
* @return {SubElm} The `SubElm` instance.
*/
constructor (data, parent) {
this.type = Typpy(data);
this.index = 0;
this.icon = type.icon;
this.name = SubElm.Name(data);
this.label = Deffy(data.label, this.name);
this.disableInput = data.disableInput;
this.type = type.type;
this.id = new SubElmId(this, parent.id);
this.lines = {};
}
/**
* Name
* Gets the name from various inputs.
*
* @name Name
* @function
* @param {Object} input An object containing one of the following fields:
*
* - `name`
* - `event`
* - `serverMethod`
* - `method`
*
* @return {String} The subelement name.
*/
_name (input) {
return input.name || input.event || input.serverMethod || input.method;
}
}
SubElm.Id = SubElmId;
module.exports = SubElm;
|
Enable debug comments in grunt-sass output file | module.exports = function(grunt) {
//grunt-sass
grunt.config('sass', {
options: {
outputStyle: 'expanded',
//includePaths: ['<%= config.scss.includePaths %>'],
imagePath: '../<%= config.image.dir %>',
sourceComments: true
},
dist: {
files: {
'<%= config.css.dir %>/<%= config.css.fileExpanded %>': '<%= config.scss.dir %>/<%= config.scss.file %>'
}
}
});
//grunt-autoprefixer
grunt.config('autoprefixer', {
options: {
browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10']
},
dist: {
files: {
'<%= config.css.dir %>/<%= config.css.fileExpanded %>': '<%= config.css.dir %>/<%= config.css.fileExpanded %>'
}
}
});
//grunt-contrib-cssmin
grunt.config('cssmin', {
target: {
src: '<%= config.css.dir %>/<%= config.css.fileExpanded %>',
dest: '<%= config.css.dir %>/<%= config.css.file %>'
}
});
//grunt-contrib-csslint
grunt.config('csslint', {
options: {
csslintrc: 'grunt/.csslintrc'
},
strict: {
src: ['<%= config.css.dir %>/<%= config.css.file %>']
}
});
}; | module.exports = function(grunt) {
//grunt-sass
grunt.config('sass', {
options: {
outputStyle: 'expanded',
//includePaths: ['<%= config.scss.includePaths %>'],
imagePath: '../<%= config.image.dir %>'
},
dist: {
files: {
'<%= config.css.dir %>/<%= config.css.fileExpanded %>': '<%= config.scss.dir %>/<%= config.scss.file %>'
}
}
});
//grunt-autoprefixer
grunt.config('autoprefixer', {
options: {
browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10']
},
dist: {
files: {
'<%= config.css.dir %>/<%= config.css.fileExpanded %>': '<%= config.css.dir %>/<%= config.css.fileExpanded %>'
}
}
});
//grunt-contrib-cssmin
grunt.config('cssmin', {
target: {
src: '<%= config.css.dir %>/<%= config.css.fileExpanded %>',
dest: '<%= config.css.dir %>/<%= config.css.file %>'
}
});
//grunt-contrib-csslint
grunt.config('csslint', {
options: {
csslintrc: 'grunt/.csslintrc'
},
strict: {
src: ['<%= config.css.dir %>/<%= config.css.file %>']
}
});
}; |
Revert "maintain group draggability (why?)"
This reverts commit 5c851f3da1e055e10f9bfa8c44f8841e459835cc. | define([
'views/editor_collection_base',
'underscore',
'jquidrag',
'text!templates/groups.tpl',
'views/group_row',
'views/group_editor',
'models/group',
'models/game',
'vent',
],
function(
EditorCollectionView,
_,
jQueryUiDraggable,
Template,
GroupRowView,
GroupEditorView,
Group,
Game,
vent
)
{
return EditorCollectionView.extend(
{
template: _.template(Template),
itemView: GroupRowView,
itemViewContainer: '.groups',
className: 'groups-editor',
events:
{
"click .new": "onClickNew"
},
onClickNew: function()
{
var self = this;
var game = self.model;
var group = new Group({game_id:game.id});
var group_editor = new GroupEditorView({model:group});
group_editor.on("group:add", function(group)
{
self.collection.add(group);
});
vent.trigger("application:popup:show", group_editor, "Create Group");
},
onRender: function()
{
var sort_options = {
items: '.draggable-game-group',
handle: '.group-drag-handle',
stop: function( event, ui ) { vent.trigger("grouprow:released", ui.item, ui.item.index()); }
};
this.$el.find('.list-group.groups').sortable(sort_options);
}
});
});
| define([
'views/editor_collection_base',
'underscore',
'jquidrag',
'text!templates/groups.tpl',
'views/group_row',
'views/group_editor',
'models/group',
'models/game',
'vent',
],
function(
EditorCollectionView,
_,
jQueryUiDraggable,
Template,
GroupRowView,
GroupEditorView,
Group,
Game,
vent
)
{
return EditorCollectionView.extend(
{
template: _.template(Template),
itemView: GroupRowView,
itemViewContainer: '.groups',
className: 'groups-editor',
events:
{
"click .new": "onClickNew"
},
onClickNew: function()
{
var self = this;
var game = self.model;
var group = new Group({game_id:game.id});
var group_editor = new GroupEditorView({model:group});
group_editor.on("group:add", function(group)
{
self.collection.add(group);
});
vent.trigger("application:popup:show", group_editor, "Create Group");
},
onRender: function()
{
var sort_options = {
items: '.draggable-game-group',
handle: '.tab-drag-handle',
stop: function( event, ui ) { vent.trigger("grouprow:released", ui.item, ui.item.index()); }
};
this.$el.find('.list-group.groups').sortable(sort_options);
}
});
});
|
Use `collections` array for syncing databases. | // Dependencies
var MongoSyncFiles = require("../index")
, Faker = require("faker")
;
function generateFakeDataArray() {
var docs = [];
for (var i = 0; i < 30; ++i) {
docs.push({
name: Faker.Name.findName()
, email: Faker.Internet.email()
, age: Faker.Helpers.randomNumber(90)
});
}
return docs;
}
// Create database instance
var MyDatabase = new MongoSyncFiles({
collections: [{
inputFile: __dirname + "/docs-in.json"
, outputFile: __dirname + "/docs-out.json"
, uri: "mongodb://localhost:27017/test"
, collection: "myCol"
, autoInit: true
}]
}, function (err, collections) {
// Handle error
if (err) { throw err; }
var MyAwesomeCollection = collections.myCol;
// Run a Mongo request
MyAwesomeCollection.find({}).toArray(function (err, docs) {
// Handle error
if (err) { throw err; }
// Output
console.log("Documents: ", docs);
// Insert
MyAwesomeCollection.insert(generateFakeDataArray(), function (err, docs) {
// Handle error
if (err) { throw err; }
console.log("Successfully inserted a new document: ", docs);
console.log("Check out the content of the following file: ", MyAwesomeCollection._options.outputFile);
// Close database
MyAwesomeCollection.database.close();
});
});
});
| // Dependencies
var MongoSyncFiles = require("../index")
, Faker = require("faker")
;
// Create database instance
var MyDatabase = new MongoSyncFiles();
function generateFakeDataArray() {
var docs = [];
for (var i = 0; i < 30; ++i) {
docs.push({
name: Faker.Name.findName()
, email: Faker.Internet.email()
, age: Faker.Helpers.randomNumber(90)
});
}
return docs;
}
// Create collection instance
var MyAwesomeCollection = MyDatabase.initCollection({
inputFile: __dirname + "/docs-in.json"
, outputFile: __dirname + "/docs-out.json"
, uri: "mongodb://localhost:27017/test"
, collection: "myCol"
, autoInit: true
}, function (err) {
// Handle error
if (err) { throw err; }
// Run a Mongo request
MyAwesomeCollection.find({}).toArray(function (err, docs) {
// Handle error
if (err) { throw err; }
// Output
console.log("Documents: ", docs);
// Insert
MyAwesomeCollection.insert(generateFakeDataArray(), function (err, docs) {
// Handle error
if (err) { throw err; }
console.log("Successfully inserted a new document: ", docs);
console.log("Check out the content of the following file: ", MyAwesomeCollection._options.outputFile);
// Close database
MyAwesomeCollection.database.close();
});
});
});
|
Use environment variables for Redis connection | /**
* Notifications system server front-end.
*
* @package randy
* @author Andrew Sliwinski <[email protected]>
*/
/**
* Dependencies
*/
var _ = require('underscore'),
async = require('async'),
randy = require('./lib/index.js');
/**
* Server
*/
async.auto({
// Environment defaults
// ------------------------------------------
defaults: function (callback) {
_.defaults(process.env, {
PORT: 80,
REDIS_HOST: null,
REDIS_PORT: null,
REDIS_PASS: null
});
callback();
},
// Start listening
// ------------------------------------------
listen: ['defaults', function (callback) {
randy.listen(process.env.PORT, {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
pass: process.env.REDIS_PASS
}, function (err) {
if (err) {
callback(err);
} else {
console.log('Randy is listening on port', process.env.PORT);
callback(null);
}
});
}]
}, function (err, obj) {
if (err) {
throw new Error(err);
}
});
/**
* Process exit handler
*/
process.on('exit', function () {
randy.destroy(function (err) {
process.exit();
});
}); | /**
* Notifications system server front-end.
*
* @package randy
* @author Andrew Sliwinski <[email protected]>
*/
/**
* Dependencies
*/
var _ = require('underscore'),
async = require('async'),
randy = require('./lib/index.js');
/**
* Server
*/
async.auto({
// Defaults
// ------------------------------------------
defaults: function (callback) {
_.defaults(process.env, {
PORT: 80,
REDIS_HOST: null,
REDIS_PORT: null,
REDIS_PASS: null
});
callback();
},
// Start listening
// ------------------------------------------
listen: ['defaults', function (callback) {
randy.listen(process.env.PORT, function (err) {
if (err) {
callback(err);
} else {
console.log('Randy is listening on port', process.env.PORT);
callback(null);
}
});
}]
}, function (err, obj) {
if (err) {
throw new Error(err);
}
});
/**
* Process exit handler
*/
process.on('exit', function () {
randy.destroy(function (err) {
process.exit();
});
}); |
Fix typos in exception messages and use less specific exception in management commands. | import logging
l=logging.getLogger(__name__)
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from experiments.reports import (EngagementReportGenerator,
ConversionReportGenerator)
class Command(BaseCommand):
help = ('update_experiment_reports : Generate all the daily reports for'
' for the SplitTesting experiments')
def __init__(self):
super(self.__class__, self).__init__()
def handle(self, *args, **options):
if len(args):
raise CommandError("This command does not take any arguments")
engagement_calculator = _load_function(settings.LEAN_ENGAGEMENT_CALCULATOR)
EngagementReportGenerator(engagement_score_calculator=engagement_calculator).generate_all_daily_reports()
ConversionReportGenerator().generate_all_daily_reports()
def _load_function(fully_qualified_name):
i = fully_qualified_name.rfind('.')
module, attr = fully_qualified_name[:i], fully_qualified_name[i+1:]
try:
mod = __import__(module, globals(), locals(), [attr])
except ImportError, e:
raise Exception, 'Error importing engagement function %s: "%s"' % (module, e)
try:
func = getattr(mod, attr)
except AttributeError:
raise Exception, 'Module "%s does not define a "%s" attribute' % (module, attr)
return func
| import logging
l=logging.getLogger(__name__)
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from experiments.reports import (EngagementReportGenerator,
ConversionReportGenerator)
class Command(BaseCommand):
help = ('update_experiment_reports : Generate all the daily reports for'
' for the SplitTesting experiments')
def __init__(self):
super(self.__class__, self).__init__()
def handle(self, *args, **options):
if len(args):
raise CommandError("This command does not take any arguments")
engagement_calculator = _load_function(settings.LEAN_ENGAGEMENT_CALCULATOR)
EngagementReportGenerator(engagement_score_calculator=engagement_calculator).generate_all_daily_reports()
ConversionReportGenerator().generate_all_daily_reports()
def _load_function(fully_qualified_name):
i = fully_qualified_name.rfind('.')
module, attr = fully_qualified_name[:i], fully_qualified_name[i+1:]
try:
mod = __import__(module, globals(), locals(), [attr])
except ImportError, e:
raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e)
try:
func = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable template source loader' % (module, attr)
return func
|
Add check_same_thread argument to make_db_engine_component | __all__ = [
'make_db_engine_component',
]
import logging
import garage.sql.sqlite
from garage import components
from garage.startups.logging import LoggingComponent
def make_db_engine_component(
*, package_name,
argument_group, argument_prefix,
check_same_thread=False):
"""DbEngineComponent Generator."""
DB_URL = '%s_db_url' % argument_prefix.replace('-', '_')
class DbEngineComponent(components.Component):
require = components.ARGS
provide = components.make_fqname_tuple(package_name, 'engine')
def add_arguments(self, parser):
group = parser.add_argument_group(argument_group)
group.add_argument(
'--%s-db-url' % argument_prefix, required=True,
help="""set database URL""")
def check_arguments(self, parser, args):
db_url = getattr(args, DB_URL)
if not db_url.startswith('sqlite'):
parser.error('only support sqlite at the moment: %s' % db_url)
def make(self, require):
db_url = getattr(require.args, DB_URL)
echo = logging.getLogger().isEnabledFor(LoggingComponent.TRACE)
return garage.sql.sqlite.create_engine(
db_url,
check_same_thread=check_same_thread,
echo=echo,
)
# Hack for manipulating call order
DbEngineComponent.add_arguments.__module__ = package_name
DbEngineComponent.check_arguments.__module__ = package_name
return DbEngineComponent
| """Template of DbEngineComponent."""
__all__ = [
'make_db_engine_component',
]
import logging
import garage.sql.sqlite
from garage import components
from garage.startups.logging import LoggingComponent
def make_db_engine_component(
*,
package_name,
argument_group,
argument_prefix):
DB_URL = '%s_db_url' % argument_prefix.replace('-', '_')
class DbEngineComponent(components.Component):
require = components.ARGS
provide = components.make_fqname_tuple(package_name, 'engine')
def add_arguments(self, parser):
group = parser.add_argument_group(argument_group)
group.add_argument(
'--%s-db-url' % argument_prefix, required=True,
help="""set database URL""")
def check_arguments(self, parser, args):
db_url = getattr(args, DB_URL)
if not db_url.startswith('sqlite'):
parser.error('only support sqlite at the moment: %s' % db_url)
def make(self, require):
db_url = getattr(require.args, DB_URL)
echo = logging.getLogger().isEnabledFor(LoggingComponent.TRACE)
return garage.sql.sqlite.create_engine(db_url, echo=echo)
# Hack for manipulating call order.
DbEngineComponent.add_arguments.__module__ = package_name
DbEngineComponent.check_arguments.__module__ = package_name
return DbEngineComponent
|
Make pickup collisions more sensible. | package edu.stuy.starlorn.entities;
import java.awt.geom.Rectangle2D;
import edu.stuy.starlorn.upgrades.Upgrade;
public class Pickup extends Entity {
protected Upgrade upgrade;
protected double speed;
public Pickup(Upgrade up, double x, double y) {
super(x, y, up.getSpriteName());
upgrade = up;
speed = 5;
}
public Pickup(Upgrade up) {
this(up, 0, 0);
}
public Upgrade getUpgrade() {
return upgrade;
}
@Override
public void step() {
Rectangle2D.Double playerRect = world.getPlayer().getRect();
double playerx = playerRect.x + playerRect.width / 2,
playery = playerRect.y + playerRect.height / 2,
thisx = getRect().x + getRect().width / 2,
thisy = getRect().y + getRect().height / 2,
theta = Math.atan2(playery - thisy, playerx - thisx);
setXvel(speed * Math.cos(theta));
setYvel(speed * Math.sin(theta));
super.step();
if (playerRect.intersects(rect)) {
world.getPlayer().addUpgrade(getUpgrade());
kill();
}
}
}
| package edu.stuy.starlorn.entities;
import java.awt.geom.Rectangle2D;
import edu.stuy.starlorn.upgrades.Upgrade;
public class Pickup extends Entity {
protected Upgrade upgrade;
protected double speed;
public Pickup(Upgrade up, double x, double y) {
super(x, y, up.getSpriteName());
upgrade = up;
speed = 5;
}
public Pickup(Upgrade up) {
this(up, 0, 0);
}
public Upgrade getUpgrade() {
return upgrade;
}
@Override
public void step() {
Rectangle2D.Double playerRect = world.getPlayer().getRect();
double playerx = playerRect.x + playerRect.width / 2,
playery = playerRect.y + playerRect.height / 2,
thisx = getRect().x + getRect().width / 2,
thisy = getRect().y + getRect().height / 2,
theta = Math.atan2(playery - thisy, playerx - thisx),
dist = Math.sqrt(Math.pow(playerx - thisx, 2) + Math.pow(playery - thisy, 2));
setXvel(speed * Math.cos(theta));
setYvel(speed * Math.sin(theta));
super.step();
if (dist < 50) {
world.getPlayer().addUpgrade(getUpgrade());
kill();
}
}
}
|
Change encrypt to use byte array
Also cleaned up some code | package com.decentralizeddatabase.reno;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
public class CryptoBlock {
private final Cipher cipher;
public CryptoBlock() throws NoSuchPaddingException, NoSuchAlgorithmException {
this.cipher = Cipher.getInstance("AES");
}
/**
* Inputs: String (data block), String (16 byte secret key)
* Outputs: byte[] (encrypted data block)
*/
public byte[] encrypt(final byte[] block, final String key) throws NoSuchPaddingException,
NoSuchAlgorithmException,
InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
final Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
final byte[] encrypted = cipher.doFinal(block);
return encrypted;
}
/**
* Inputs: byte[] (encrypted data block), String (16 byte secret key)
* Outputs: String (decrypted data block)
*/
public String decrypt(final byte[] block, final String key) throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(block));
return decrypted;
}
}
| package com.decentralizeddatabase.reno;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
/*Initialize and use this class to deal with block encryption and decryption*/
public class CryptoBlock {
private Cipher cipher;
public CryptoBlock() throws NoSuchPaddingException, NoSuchAlgorithmException {
this.cipher = Cipher.getInstance("AES");
}
/*
Inputs: String (data block), String (16 byte secret key)
Outputs: byte[] (encrypted data block)
*/
public byte[] encrypt(String block, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(block.getBytes());
return encrypted;
}
/*
Inputs: byte[] (encrypted data block), String (16 byte secret key)
Outputs: String (decrypted data block)
*/
public String decrypt(byte[] block, String key) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(block));
return decrypted;
}
}
|
Add reaction while fetching logs | (function(){
"use strict";
$(function(){
if($('#fluent-log').length === 0) return;
new Vue({
el: "#fluent-log",
paramAttributes: ["logUrl"],
data: {
"autoFetch": false,
"logs": [],
"limit": 30,
"processing": false
},
created: function(){
this.fetchLogs();
var self = this;
var timer;
this.$watch("autoFetch", function(newValue){
if(newValue === true) {
timer = setInterval(function(){
self.fetchLogs();
var $log = $(".log", self.$el);
$log.scrollTop($log[0].scrollHeight);
}, 1000);
} else {
clearInterval(timer);
}
});
},
methods: {
fetchLogs: function() {
if(this.processing) return;
this.processing = true;
var self = this;
new Promise(function(resolve, reject) {
$.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject);
}).then(function(logs){
self.logs = logs;
setTimeout(function(){
self.processing = false;
}, 256); // delay to reduce flicking loading icon
});
},
}
});
});
})();
| (function(){
"use strict";
$(function(){
if($('#fluent-log').length === 0) return;
new Vue({
el: "#fluent-log",
paramAttributes: ["logUrl"],
data: {
"autoFetch": false,
"logs": [],
"limit": 30
},
created: function(){
this.fetchLogs();
var self = this;
var timer;
this.$watch("autoFetch", function(newValue){
if(newValue === true) {
timer = setInterval(function(){
self.fetchLogs();
var $log = $(".log", self.$el);
$log.scrollTop($log[0].scrollHeight);
}, 1000);
} else {
clearInterval(timer);
}
});
},
methods: {
fetchLogs: function() {
var self = this;
new Promise(function(resolve, reject) {
$.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject);
}).then(function(logs){
self.logs = logs;
});
},
}
});
});
})();
|
Add pyfits dependence and remove pytoml | #!/usr/bin/env python3
# -*- mode: python -*-
from setuptools import setup, find_packages
from setuptools.extension import Extension
from Cython.Build import cythonize
import os.path as path
modules = [Extension("pypolycomp._bindings",
sources=["pypolycomp/_bindings.pyx"],
libraries=["polycomp"])]
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst')) as f:
long_description = f.read()
setup(name="polycomp",
version="1.0",
author="Maurizio Tomasi",
author_email="[email protected]",
description="Python bindings to the libpolycomp C library",
long_description=long_description,
license="MIT",
url="",
install_requires=["cython", "pyfits", "docopt"],
ext_modules=cythonize(modules),
scripts=['polycomp'],
packages=['pypolycomp'],
keywords='compression astronomy fits',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'Topic :: System :: Archiving :: Compression',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
])
| #!/usr/bin/env python3
# -*- mode: python -*-
from setuptools import setup, find_packages
from setuptools.extension import Extension
from Cython.Build import cythonize
import os.path as path
modules = [Extension("pypolycomp._bindings",
sources=["pypolycomp/_bindings.pyx"],
libraries=["polycomp"])]
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst')) as f:
long_description = f.read()
setup(name="polycomp",
version="1.0",
author="Maurizio Tomasi",
author_email="[email protected]",
description="Python bindings to the libpolycomp C library",
long_description=long_description,
license="MIT",
url="",
install_requires=["cython", "pytoml", "docopt"],
ext_modules=cythonize(modules),
scripts=['polycomp'],
packages=['pypolycomp'],
keywords='compression astronomy fits',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'Topic :: System :: Archiving :: Compression',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
])
|
Allow Pydev launch shortcuts from context of Pydev project selection. | package org.python.pydev.debug.ui;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper;
import org.python.pydev.navigator.elements.IWrappedResource;
public class PythonTypePropertyTester extends PropertyTester {
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
IFile iFile = null;
if (receiver instanceof IWrappedResource) {
IWrappedResource wrappedResource = (IWrappedResource) receiver;
Object actualObject = wrappedResource.getActualObject();
if (actualObject instanceof IProject) {
return true;
} else if (actualObject instanceof IFile) {
iFile = (IFile) actualObject;
}
}
if (receiver instanceof IAdaptable) {
IAdaptable iAdaptable = (IAdaptable) receiver;
iFile = (IFile) iAdaptable.getAdapter(IFile.class);
}
if (iFile != null) {
if (PythonPathHelper.markAsPyDevFileIfDetected(iFile)) {
return true;
}
}
return false;
}
}
| package org.python.pydev.debug.ui;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper;
import org.python.pydev.navigator.elements.IWrappedResource;
public class PythonTypePropertyTester extends PropertyTester {
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
IFile iFile = getIFile(receiver);
if (iFile != null) {
if (PythonPathHelper.markAsPyDevFileIfDetected(iFile)) {
return true;
}
}
return false;
}
private IFile getIFile(Object receiver) {
if (receiver instanceof IWrappedResource) {
IWrappedResource wrappedResource = (IWrappedResource) receiver;
Object actualObject = wrappedResource.getActualObject();
if (actualObject instanceof IFile) {
return (IFile) actualObject;
}
}
if (receiver instanceof IAdaptable) {
IAdaptable iAdaptable = (IAdaptable) receiver;
return (IFile) iAdaptable.getAdapter(IFile.class);
}
return null;
}
}
|
Update to get newest nose version. | from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='[email protected]',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
| from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='[email protected]',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose==0.11.4',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
|
Use 'contains' instead of indexOf to find substrings | package org.jenkinsci.plugins.gitclient;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Recording log handler to allow assertions on logging. Not intended for use
* outside this package. Not intended for use outside tests.
*
* @author <a href="mailto:[email protected]">Mark Waite</a>
*/
public class LogHandler extends Handler {
private List<String> messages = new ArrayList<>();
@Override
public void publish(LogRecord lr) {
messages.add(lr.getMessage());
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
messages = new ArrayList<>();
}
/* package */ List<String> getMessages() {
return messages;
}
/* package */ boolean containsMessageSubstring(String messageSubstring) {
for (String message : messages) {
if (message.contains(messageSubstring)) {
return true;
}
}
return false;
}
/* package */ List<Integer> getTimeouts() {
List<Integer> timeouts = new ArrayList<>();
for (String message : getMessages()) {
int start = message.indexOf(CliGitAPIImpl.TIMEOUT_LOG_PREFIX);
if (start >= 0) {
String timeoutStr = message.substring(start + CliGitAPIImpl.TIMEOUT_LOG_PREFIX.length());
timeouts.add(Integer.parseInt(timeoutStr));
}
}
return timeouts;
}
}
| package org.jenkinsci.plugins.gitclient;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Recording log handler to allow assertions on logging. Not intended for use
* outside this package. Not intended for use outside tests.
*
* @author <a href="mailto:[email protected]">Mark Waite</a>
*/
public class LogHandler extends Handler {
private List<String> messages = new ArrayList<>();
@Override
public void publish(LogRecord lr) {
messages.add(lr.getMessage());
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
messages = new ArrayList<>();
}
/* package */ List<String> getMessages() {
return messages;
}
/* package */ boolean containsMessageSubstring(String messageSubstring) {
for (String message : messages) {
if (message.indexOf(messageSubstring) >= 0) {
return true;
}
}
return false;
}
/* package */ List<Integer> getTimeouts() {
List<Integer> timeouts = new ArrayList<>();
for (String message : getMessages()) {
int start = message.indexOf(CliGitAPIImpl.TIMEOUT_LOG_PREFIX);
if (start >= 0) {
String timeoutStr = message.substring(start + CliGitAPIImpl.TIMEOUT_LOG_PREFIX.length());
timeouts.add(Integer.parseInt(timeoutStr));
}
}
return timeouts;
}
}
|
Fix bug where tasks weren't rendered until running the first time. | var fs = require('fs');
var Backbone = require('backbone');
var swig = require('swig');
var templatePath = require('path').resolve(__dirname, 'taskview.swig');
var template = swig.compile(fs.readFileSync(templatePath, 'utf8'));
module.exports = Backbone.View.extend({
tagName: 'li',
template: template,
initialize: function() {
this.listenTo(this.model, 'change:isRunning', this.render.bind(this));
this.render(this.model);
},
render: function(task) {
var errObj = !task.isOK && task.lastError;
var timestamp = '';
if (task.lastRunAt instanceof Date) {
timestamp = '@' + task.lastRunAt.toTimeString().replace(/ .+/, '');
this.$('.timestamp').html(timestamp);
}
if (task.isRunning) this.$el.removeClass('ok error').addClass('running');
else {
if (task.isOK) this.$el.removeClass('running error').addClass('ok');
else this.$el.removeClass('running ok').addClass('error');
this.trigger('changeStatus');
var ctx = {
task: this.model,
err: errObj,
timestamp: timestamp,
runtime: this.model.lastRunDuration && (this.model.lastRunDuration / 1000).toFixed(2)
};
this.$el.html(this.template(ctx));
}
}
});
| var fs = require('fs');
var Backbone = require('backbone');
var swig = require('swig');
var templatePath = require('path').resolve(__dirname, 'taskview.swig');
var template = swig.compile(fs.readFileSync(templatePath, 'utf8'));
module.exports = Backbone.View.extend({
tagName: 'li',
template: template,
initialize: function() {
this.listenTo(this.model, 'change:isRunning', this.render.bind(this));
},
render: function(task) {
var errObj = !task.isOK && task.lastError;
var timestamp = null;
if (task.lastRunAt instanceof Date) {
timestamp = '@' + task.lastRunAt.toTimeString().replace(/ .+/, '');
this.$('.timestamp').html(timestamp);
}
if (task.isRunning) this.$el.removeClass('ok error').addClass('running');
else {
if (task.isOK) this.$el.removeClass('running error').addClass('ok');
else this.$el.removeClass('running ok').addClass('error');
this.trigger('changeStatus');
var ctx = {
task: this.model,
err: errObj,
timestamp: timestamp,
runtime: this.model.lastRunDuration && (this.model.lastRunDuration / 1000).toFixed(2)
};
this.$el.html(this.template(ctx));
}
}
});
|
Use exception renderable instead of uses of instanceof | <?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (ValidationException $e, $request) {
return response()->json([
'message' => trans('error.validation'),
'errors' => $e->errors(),
], 422);
});
$this->renderable(function (InvalidSignatureException $e, $request) {
return response()->json([
'message' => trans('error.signature'),
], 500);
});
return parent::render($request, $exception);
}
}
| <?php
namespace App\Exceptions;
use App\Exceptions\SolverException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\ValidationException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Throwable $exception)
{
if ($exception instanceof ValidationException) {
return response()->json([
'message' => trans('error.validation'),
'errors' => $exception->errors(),
], 422);
}
if ($exception instanceof SolverException) {
return response()->json([
'message' => trans('error.solution'),
], 422);
}
if ($exception instanceof InvalidSignatureException) {
return response()->json([
'message' => trans('error.signature'),
], 500);
}
return parent::render($request, $exception);
}
}
|
Remove extraneous hook, since it was moved from gobble-expression to gobble-token it doesn't need an after-token hook anymore | const OCURLY_CODE = 123; // {
const CCURLY_CODE = 125; // }
const OBJECT_EXP = 'ObjectExpression';
const PROPERTY = 'Property';
export default {
name: 'object',
init(jsep) {
jsep.addBinaryOp(':', 0.5);
// Object literal support
jsep.hooks.add('gobble-token', function gobbleObjectExpression(env) {
if (this.code === OCURLY_CODE) {
this.index++;
const properties = this.gobbleArguments(CCURLY_CODE)
.map((arg) => {
if (arg.type === jsep.IDENTIFIER) {
return {
type: PROPERTY,
computed: false,
key: arg,
shorthand: true,
};
}
if (arg.type === jsep.BINARY_EXP) {
const computed = arg.left.type === jsep.ARRAY_EXP;
return {
type: PROPERTY,
computed,
key: computed
? arg.left.elements[0]
: arg.left,
value: arg.right,
shorthand: false,
};
}
// complex value (i.e. ternary, spread)
return arg;
});
env.node = {
type: OBJECT_EXP,
properties,
};
}
});
}
};
| const OCURLY_CODE = 123; // {
const CCURLY_CODE = 125; // }
const OBJECT_EXP = 'ObjectExpression';
const PROPERTY = 'Property';
export default {
name: 'object',
init(jsep) {
jsep.addBinaryOp(':', 0.5);
// Object literal support
function gobbleObjectExpression(env) {
if (this.code === OCURLY_CODE) {
this.index++;
const properties = this.gobbleArguments(CCURLY_CODE)
.map((arg) => {
if (arg.type === jsep.IDENTIFIER) {
return {
type: PROPERTY,
computed: false,
key: arg,
shorthand: true,
};
}
if (arg.type === jsep.BINARY_EXP) {
const computed = arg.left.type === jsep.ARRAY_EXP;
return {
type: PROPERTY,
computed,
key: computed
? arg.left.elements[0]
: arg.left,
value: arg.right,
shorthand: false,
};
}
// complex value (i.e. ternary, spread)
return arg;
});
env.node = {
type: OBJECT_EXP,
properties,
};
}
}
jsep.hooks.add('gobble-token', gobbleObjectExpression);
jsep.hooks.add('after-token', gobbleObjectExpression);
}
};
|
Fix issue with tasks executing | 'use strict';
var path = require('path'),
Changes = require('../model/changes'),
TargetBase = function (options) {
this.init(options);
};
TargetBase.prototype = {
CACHE_DIR: path.join(process.cwd(), 'cache'),
SNAPSHOTS_DIR: path.join(process.cwd(), 'db', 'snapshots'),
KEY: {
NODE_PREFIX: 'nodes:',
DOCS_PREFIX: 'docs:',
PEOPLE_PREFIX: 'people:',
BLOCKS_PREFIX: 'blocks:',
URL_PREFIX: 'urls:',
VERSIONS_PEOPLE: 'versions:people',
AUTHORS: 'authors',
TRANSLATORS: 'translators',
TAGS: 'tags'
},
tasks: [],
options: undefined,
changes: undefined,
init: function (options) {
this.options = options || {};
this.changes = new Changes();
},
getName: function () {
return 'BASE';
},
addTask: function (task) {
this.tasks.push(task);
return this;
},
getTasks: function () {
return this.tasks;
},
getChanges: function () {
return this.changes;
},
getOptions: function () {
return this.options;
},
execute: function () {
var _this = this,
initial = this.getTasks()[0];
return this.getTasks().reduce(function (prev, item) {
return prev.then(function () {
return item(_this);
});
}, initial(_this));
}
};
exports.TargetBase = TargetBase;
| 'use strict';
var path = require('path'),
Changes = require('../model/changes'),
TargetBase = function (options) {
this.init(options);
};
TargetBase.prototype = {
CACHE_DIR: path.join(process.cwd(), 'cache'),
SNAPSHOTS_DIR: path.join(process.cwd(), 'db', 'snapshots'),
KEY: {
NODE_PREFIX: 'nodes:',
DOCS_PREFIX: 'docs:',
PEOPLE_PREFIX: 'people:',
BLOCKS_PREFIX: 'blocks:',
URL_PREFIX: 'urls:',
VERSIONS_PEOPLE: 'versions:people',
AUTHORS: 'authors',
TRANSLATORS: 'translators',
TAGS: 'tags'
},
tasks: [],
options: undefined,
changes: undefined,
init: function (options) {
this.options = options || {};
this.changes = new Changes();
},
getName: function () {
return 'BASE';
},
addTask: function (task) {
this.tasks.push(task);
return this;
},
getTasks: function () {
return this.tasks;
},
getChanges: function () {
return this.changes;
},
getOptions: function () {
return this.options;
},
execute: function () {
var _this = this,
initial = this.getTasks().shift();
return this.getTasks().reduce(function (prev, item) {
return prev.then(function () {
return item(_this);
});
}, initial(_this));
}
};
exports.TargetBase = TargetBase;
|
Throw Empty exception if BRPOP returns None.
Add priority argument so it works with the latest version. | from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message, priority = 0):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
try:
dest, item = self.client.brpop([queue], timeout=1)
except TypeError:
raise Empty
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
try:
item, dest = self.client.brpop(queues, timeout=1)
except TypeError:
raise Empty
return item
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
| from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
dest, item = self.client.brpop([queue], timeout=1)
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
dest, item = self.client.brpop(queues, timeout=timeout)
return item, dest
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
|
Fix bug where warnings were being printed as errors | package buildr.ipojo.cli;
import java.io.File;
import java.io.FileInputStream;
import org.apache.felix.ipojo.manipulator.Pojoization;
public class Main
{
public static void main( final String[] args )
{
if( 4 != args.length )
{
System.err.println("Usage: <input_file_name> <output_file_name> <metadata_file_name> <print_trace_messages?>");
System.exit( 42 );
}
final String inputFilename = args[0];
final String outputFilename = args[1];
final String metadataFilename = args[2];
final boolean printTraceMessage = args[3].equals( "true" );
boolean inError;
try
{
final Pojoization pojoizer = new Pojoization();
pojoizer.setUseLocalXSD();
pojoizer.pojoization( new File( inputFilename ),
new File( outputFilename ),
new FileInputStream( metadataFilename ) );
if( printTraceMessage )
{
for( final Object message : pojoizer.getWarnings() )
{
System.out.println( "Pojoizer Warning: " + message );
}
}
inError = pojoizer.getErrors().size() != 0;
for( final Object message : pojoizer.getErrors() )
{
System.err.println( "Pojoizer Error: " + message );
}
}
catch( final Exception e )
{
e.printStackTrace( System.err );
inError = true;
}
System.exit( inError ? 1 : 0 );
}
}
| package buildr.ipojo.cli;
import java.io.File;
import java.io.FileInputStream;
import org.apache.felix.ipojo.manipulator.Pojoization;
public class Main
{
public static void main( final String[] args )
{
if( 4 != args.length )
{
System.err.println("Usage: <input_file_name> <output_file_name> <metadata_file_name> <print_trace_messages?>");
System.exit( 42 );
}
final String inputFilename = args[0];
final String outputFilename = args[1];
final String metadataFilename = args[2];
final boolean printTraceMessage = args[3].equals( "true" );
boolean inError;
try
{
final Pojoization pojoizer = new Pojoization();
pojoizer.setUseLocalXSD();
pojoizer.pojoization( new File( inputFilename ),
new File( outputFilename ),
new FileInputStream( metadataFilename ) );
if( printTraceMessage )
{
for( final Object message : pojoizer.getWarnings() )
{
System.out.println( "Pojoizer Warning: " + message );
}
}
inError = pojoizer.getWarnings().size() != 0;
for( final Object message : pojoizer.getWarnings() )
{
System.err.println( "Pojoizer Error: " + message );
}
}
catch( final Exception e )
{
e.printStackTrace( System.err );
inError = true;
}
System.exit( inError ? 1 : 0 );
}
}
|
Add content_type to search results JSON. | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
from django.shortcuts import render
from wagtail.wagtailcore.models import Page
from wagtail.wagtailsearch.models import Query
def search(request):
do_json = 'json' in request.GET
search_query = request.GET.get('query', None)
page = request.GET.get('page', 1)
# Search
if search_query:
search_results = Page.objects.live().search(search_query)
query = Query.get(search_query)
# Record hit
query.add_hit()
else:
search_results = Page.objects.none()
# Pagination
paginator = Paginator(search_results, 10)
try:
search_results = paginator.page(page)
except PageNotAnInteger:
search_results = paginator.page(1)
except EmptyPage:
search_results = paginator.page(paginator.num_pages)
response = {
'search_query': search_query,
'search_results': search_results,
}
if do_json:
search_results_serializable = []
for res in response['search_results']:
res_serializable = {}
res_serializable['title'] = res.specific.title
res_serializable['url'] = res.specific.url
res_serializable['content_type'] = res.specific.content_type.name
search_results_serializable.append(res_serializable)
response['search_results'] = search_results_serializable
return JsonResponse(response)
else:
return render(request, 'search/search.html', response)
| from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
from django.shortcuts import render
from wagtail.wagtailcore.models import Page
from wagtail.wagtailsearch.models import Query
def search(request):
do_json = 'json' in request.GET
search_query = request.GET.get('query', None)
page = request.GET.get('page', 1)
# Search
if search_query:
search_results = Page.objects.live().search(search_query)
query = Query.get(search_query)
# Record hit
query.add_hit()
else:
search_results = Page.objects.none()
# Pagination
paginator = Paginator(search_results, 10)
try:
search_results = paginator.page(page)
except PageNotAnInteger:
search_results = paginator.page(1)
except EmptyPage:
search_results = paginator.page(paginator.num_pages)
response = {
'search_query': search_query,
'search_results': search_results,
}
if do_json:
response['search_results'] = [
dict(
(attr, getattr(result.specific, attr))
for attr in ['title', 'url']
if hasattr(result.specific, attr)
) for result in response['search_results']
]
return JsonResponse(response)
else:
return render(request, 'search/search.html', response)
|
Work around for unit test timeouts | module.exports = function (grunt) {
return {
options: {
frameworks: ['jasmine'],
files: [ //this files data is also updated in the watch handler, if updated change there too
'bower_components/jquery/dist/jquery.js',
'bower_components/boostrap/dist/js/bootstrap.js',
'<%= dom_munger.data.appjs %>',
'bower_components/angular-mocks/angular-mocks.js',
grunt.option('folderGlobs')('*-spec.js'),
'components/summary/**/*.html'
],
ngHtml2JsPreprocessor: {
moduleName: "app"
},
preprocessors: {
'components/summary/**/*.html': ['ng-html2js']
},
logLevel: 'ERROR',
reporters: ['mocha'],
autoWatch: false, //watching is handled by grunt-contrib-watch
singleRun: true,
browserDisconnectTimeout : 10000,
browserDisconnectTolerance: 2,
browserNoActivityTimeout: 60000
},
all_tests: {
browsers: ['PhantomJS']
},
during_watch: {
browsers: ['PhantomJS']
}
};
};
| module.exports = function (grunt) {
return {
options: {
frameworks: ['jasmine'],
files: [ //this files data is also updated in the watch handler, if updated change there too
'bower_components/jquery/dist/jquery.js',
'bower_components/boostrap/dist/js/bootstrap.js',
'<%= dom_munger.data.appjs %>',
'bower_components/angular-mocks/angular-mocks.js',
grunt.option('folderGlobs')('*-spec.js'),
'components/summary/**/*.html'
],
ngHtml2JsPreprocessor: {
moduleName: "app"
},
preprocessors: {
'components/summary/**/*.html': ['ng-html2js']
},
logLevel: 'ERROR',
reporters: ['mocha'],
autoWatch: false, //watching is handled by grunt-contrib-watch
singleRun: true,
browserNoActivityTimeout: 60000
},
all_tests: {
browsers: ['PhantomJS']
},
during_watch: {
browsers: ['PhantomJS']
}
};
};
|
Add donation field to calculation | Template.register.rendered = function () {
/*
* Reset form select field values
* to prevent an edge case bug for code push
* where accommodations value was undefined
*/
$('#age').val('');
$('#registration_type').val('');
$('#accommodations').val('');
$('#carbon-tax').val('');
};
Template.register.helpers({
'price': function () {
/*
* Get the dynamically calculated registration fee.
*/
//Set the registration object
// from current registration details.
try {
var registration = {
ageGroup: ageGroupVar.get(),
type: registrationTypeVar.get(),
accommodations: accommodationsVar.get(),
days: daysVar.get(),
firstTimeAttender: firstTimeAttenderVar.get(),
linens: linensVar.get(),
createdAt: new Date(),
carbonTax: carbonTaxVar.get(),
donation: donationVar.get()
};
} catch (error) {
console.log(error.message);
}
// Calculate the price
try {
var registrationPrice = calculateRegistrationPrice(registration);
} catch (error) {
console.log(error.message);
}
return registrationPrice;
}
});
Template.register.events({
'change form': function () {
// Make sure all reactive vars are up to date.
setReactiveVars();
},
'keyup #carbon-tax': function () {
setReactiveVars();
}
});
| Template.register.rendered = function () {
/*
* Reset form select field values
* to prevent an edge case bug for code push
* where accommodations value was undefined
*/
$('#age').val('');
$('#registration_type').val('');
$('#accommodations').val('');
$('#carbon-tax').val('');
};
Template.register.helpers({
'price': function () {
/*
* Get the dynamically calculated registration fee.
*/
//Set the registration object
// from current registration details.
try {
var registration = {
ageGroup: ageGroupVar.get(),
type: registrationTypeVar.get(),
accommodations: accommodationsVar.get(),
days: daysVar.get(),
firstTimeAttender: firstTimeAttenderVar.get(),
linens: linensVar.get(),
createdAt: new Date(),
carbonTax: carbonTaxVar.get()
};
} catch (error) {
console.log(error.message);
}
// Calculate the price
try {
var registrationPrice = calculateRegistrationPrice(registration);
} catch (error) {
console.log(error.message);
}
return registrationPrice;
}
});
Template.register.events({
'change form': function () {
// Make sure all reactive vars are up to date.
setReactiveVars();
},
'keyup #carbon-tax': function () {
setReactiveVars();
}
});
|
Improve test performance by using the md5 hasher for tests. | from django.conf import settings
import base64
import os
import os.path
def pytest_configure(config):
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server'
test_db = os.environ.get('DB', 'sqlite')
if test_db == 'mysql':
settings.DATABASES['default'].update({
'ENGINE': 'django.db.backends.mysql',
'NAME': 'sentry',
'USER': 'root',
})
elif test_db == 'postgres':
settings.DATABASES['default'].update({
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'postgres',
'NAME': 'sentry',
'OPTIONS': {
'autocommit': True,
}
})
elif test_db == 'sqlite':
settings.DATABASES['default'].update({
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
})
# Compressors is not fast, disable it in tests.
settings.COMPRESS_ENABLED = False
# override a few things with our test specifics
settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'tests',
)
settings.SENTRY_KEY = base64.b64encode(os.urandom(40))
settings.SENTRY_PUBLIC = False
# This speeds up the tests considerably, pbkdf2 is by design, slow.
settings.PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]
| from django.conf import settings
import base64
import os
import os.path
def pytest_configure(config):
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server'
test_db = os.environ.get('DB', 'sqlite')
if test_db == 'mysql':
settings.DATABASES['default'].update({
'ENGINE': 'django.db.backends.mysql',
'NAME': 'sentry',
'USER': 'root',
})
elif test_db == 'postgres':
settings.DATABASES['default'].update({
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'postgres',
'NAME': 'sentry',
'OPTIONS': {
'autocommit': True,
}
})
elif test_db == 'sqlite':
settings.DATABASES['default'].update({
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
})
# Compressors is not fast, disable it in tests.
settings.COMPRESS_ENABLED = False
# override a few things with our test specifics
settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
'tests',
)
settings.SENTRY_KEY = base64.b64encode(os.urandom(40))
settings.SENTRY_PUBLIC = False
|
Set viewport size to 640 x 480 | var page = require('webpage').create(),
system = require('system'),
address, output, size;
page.viewportSize = {
width: 640,
height: 480
};
if (system.args.length < 4 || system.args.length > 5) {
console.log('Usage: '+system.args[0]+' URL selector filename [zoom]');
phantom.exit(1);
} else {
address = system.args[1];
selector = system.args[2];
output = system.args[3];
if (system.args.length > 4) {
page.zoomFactor = system.args[4];
}
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
var rect = page.evaluate(function(selector) {
var el = document.querySelector(selector);
if (!el) {
return null;
}
return el.getBoundingClientRect();
}, selector);
if (!rect) {
console.log('Unabled to find the element!');
phantom.exit(2);
return false;
}
for (k in rect) {
rect[k] *= page.zoomFactor;
}
page.clipRect = rect;
page.render(output);
phantom.exit();
}, 500);
}
});
}
| var page = require('webpage').create(),
system = require('system'),
address, output, size;
if (system.args.length < 4 || system.args.length > 5) {
console.log('Usage: '+system.args[0]+' URL selector filename [zoom]');
phantom.exit(1);
} else {
address = system.args[1];
selector = system.args[2];
output = system.args[3];
if (system.args.length > 4) {
page.zoomFactor = system.args[4];
}
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
var rect = page.evaluate(function(selector) {
var el = document.querySelector(selector);
if (!el) {
return null;
}
return el.getBoundingClientRect();
}, selector);
if (!rect) {
console.log('Unabled to find the element!');
phantom.exit(2);
return false;
}
for (k in rect) {
rect[k] *= page.zoomFactor;
}
page.clipRect = rect;
page.render(output);
phantom.exit();
}, 500);
}
});
}
|
Remove test for rest controller. | from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
| from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_index(self):
response = self.app.get(url(controller='rest', action='index'))
for word in ['/cra', 'entries']:
assert word in response, response
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
|
Fix role restriction validation bug | const _ = require('underscore');
const logger = require('../log.js');
class CardService {
constructor(db) {
this.cards = db.get('cards');
this.packs = db.get('packs');
}
replaceCards(cards) {
return this.cards.remove({})
.then(() => this.cards.insert(cards));
}
replacePacks(cards) {
return this.packs.remove({})
.then(() => this.packs.insert(cards));
}
getAllCards(options) {
return this.cards.find({})
.then(result => {
let cards = {};
_.each(result, card => {
if(options && options.shortForm) {
cards[card.id] = _.pick(card, 'id', 'name', 'type', 'clan', 'side', 'deck_limit', 'element', 'unicity', 'influence_cost', 'influence_pool', 'pack_cards', 'role_restriction');
} else {
cards[card.id] = card;
}
});
return cards;
}).catch(err => {
logger.info(err);
});
}
getAllPacks() {
return this.packs.find({}).catch(err => {
logger.info(err);
});
}
}
module.exports = CardService;
| const _ = require('underscore');
const logger = require('../log.js');
class CardService {
constructor(db) {
this.cards = db.get('cards');
this.packs = db.get('packs');
}
replaceCards(cards) {
return this.cards.remove({})
.then(() => this.cards.insert(cards));
}
replacePacks(cards) {
return this.packs.remove({})
.then(() => this.packs.insert(cards));
}
getAllCards(options) {
return this.cards.find({})
.then(result => {
let cards = {};
_.each(result, card => {
if(options && options.shortForm) {
cards[card.id] = _.pick(card, 'id', 'name', 'type', 'clan', 'side', 'deck_limit', 'element', 'unicity', 'influence_cost', 'influence_pool', 'pack_cards');
} else {
cards[card.id] = card;
}
});
return cards;
}).catch(err => {
logger.info(err);
});
}
getAllPacks() {
return this.packs.find({}).catch(err => {
logger.info(err);
});
}
}
module.exports = CardService;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.