text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Test script to UTF-8 and output category. | #!/usr/bin/python -O
# -*- coding: utf-8 -*-
import sqlite3
from parser import SQLITE3_DB_NAME
from random import randint, randrange
def main():
""" Ouputs a random clue (with game ID) from 10 random games for checking. """
sql = sqlite3.connect(SQLITE3_DB_NAME)
# list of random game id numbers
gids = [randint(1, 3790) for i in xrange(10)]
# output format
print "GID".rjust(5), "R -> Category -> Clue text -> Answer"
for gid in gids:
rows = sql.execute("select * from clues where game = ?", (gid, ))
rows = rows.fetchall()
# some games were skipped over
if len(rows) > 0:
meta = "#%d" % gid
print meta.rjust(5),
row = randrange(0, len(rows))
print rows[row][2], "->", rows[row][3], "->", rows[row][5], "->", rows[row][6]
if __name__ == "__main__":
main()
| #!/usr/bin/python -O
import sqlite3
from parser import SQLITE3_DB_NAME
from random import randint, randrange
def main():
""" Ouputs a random clue (with game ID) from 10 random games for checking. """
sql = sqlite3.connect(SQLITE3_DB_NAME)
# list of random game id numbers
gids = [randint(1, 3790) for i in xrange(10)]
# output format
print "GID".rjust(5), "R -> Clue text -> Answer"
for gid in gids:
rows = sql.execute("select * from clues where game = ?", (gid, ))
rows = rows.fetchall()
# some games were skipped over
if len(rows) > 0:
meta = "#%d" % gid
print meta.rjust(5),
row = randrange(0, len(rows))
print rows[row][2], "->", rows[row][5], "->", rows[row][6]
if __name__ == "__main__":
main()
|
Add fallback for electron <0.35 | 'use strict';
// Electron doesn't automatically show notifications in Windows yet, and it's not easy to polyfill.
// So we have to hijack the Notification API.
let ipc;
try {
// Using electron >=0.35
ipc = require('electron').ipcRenderer;
} catch (e) {
// Assume it's electron <0.35
ipc = require('ipc');
}
module.exports = () => {
const OldNotification = Notification;
Notification = function (title, options) {
// Send this to main thread.
// Catch it in your main 'app' instance with `ipc.on`.
// Then send it back to the view, if you want, with `event.returnValue` or `event.sender.send()`.
ipc.send('notification-shim', {
title,
options
});
// Send the native Notification.
// You can't catch it, that's why we're doing all of this. :)
return new OldNotification(title, options);
};
Notification.prototype = OldNotification.prototype;
Notification.permission = OldNotification.permission;
Notification.requestPermission = OldNotification.requestPermission;
};
| 'use strict';
// Electron doesn't support notifications in Windows yet. https://github.com/atom/electron/issues/262
// So we hijack the Notification API.'
const ipc = require('electron').ipcRenderer;
module.exports = () => {
const OldNotification = Notification;
Notification = function (title, options) {
// Send this to main thread.
// Catch it in your main 'app' instance with `ipc.on`.
// Then send it back to the view, if you want, with `event.returnValue` or `event.sender.send()`.
ipc.send('notification-shim', {
title,
options
});
// Send the native Notification.
// You can't catch it, that's why we're doing all of this. :)
return new OldNotification(title, options);
};
Notification.prototype = OldNotification.prototype;
Notification.permission = OldNotification.permission;
Notification.requestPermission = OldNotification.requestPermission;
};
|
Fix add:url command not importing User | <?php
namespace App\Console\Commands;
use App\Models\Factories\ItemFactory;
use App\Models\User;
use Illuminate\Console\Command;
class AddItem extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'add:url {url}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Add a new Item to the queue by providing a URL';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Fetch plausible user
$owner = User::all()->first();
// Create an item from the URL and try to save it
$item = ItemFactory::create([
'user_id' => $owner->id,
'details' => ['url' => $this->argument('url')]
]);
$item->save();
}
}
| <?php
namespace App\Console\Commands;
use App\Models\Factories\ItemFactory;
use Illuminate\Console\Command;
class AddItem extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'add:url {url}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Add a new Item to the queue by providing a URL';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Fetch plausible user
$owner = User::all()->first();
// Create an item from the URL and try to save it
$item = ItemFactory::create([
'user_id' => $owner->id,
'details' => ['url' => $this->argument('url')]
]);
$item->save();
}
}
|
Fix for test included_data_on_list included types check | import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.content).get('included')
assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
assert [x.get('type') for x in included] == ['comments', 'comments'], 'List included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
expected_comment_count = sum([entry.comment_set.count() for entry in multiple_entries])
assert comment_count == expected_comment_count, 'List comment count is incorrect'
def test_included_data_on_detail(single_entry, client):
response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) + '?include=comments')
included = load_json(response.content).get('included')
assert [x.get('type') for x in included] == ['comments'], 'Detail included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
expected_comment_count = single_entry.comment_set.count()
assert comment_count == expected_comment_count, 'Detail comment count is incorrect'
| import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.content).get('included')
assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
assert [x.get('type') for x in included] == ['comments'], 'List included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
expected_comment_count = sum([entry.comment_set.count() for entry in multiple_entries])
assert comment_count == expected_comment_count, 'List comment count is incorrect'
def test_included_data_on_detail(single_entry, client):
response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) + '?include=comments')
included = load_json(response.content).get('included')
assert [x.get('type') for x in included] == ['comments'], 'Detail included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
assert comment_count == single_entry.comment_set.count(), 'Detail comment count is incorrect'
|
Make sure we are compatible with common 0.3 | <?php
/*
* This file is part of php-cache\apcu-adapter package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\Adapter\Apcu;
use Cache\Adapter\Common\AbstractCachePool;
use Psr\Cache\CacheItemInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ApcuCachePool extends AbstractCachePool
{
protected function fetchObjectFromCache($key)
{
$success = false;
$data = apcu_fetch($key, $success);
return [$success, $data];
}
protected function clearAllObjectsFromCache()
{
return apcu_clear_cache();
}
protected function clearOneObjectFromCache($key)
{
apcu_delete($key);
return true;
}
protected function storeItemInCache($key, CacheItemInterface $item, $ttl)
{
return apcu_store($key, $item->get(), $ttl);
}
}
| <?php
/*
* This file is part of php-cache\apcu-adapter package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\Adapter\Apcu;
use Cache\Adapter\Common\AbstractCachePool;
use Psr\Cache\CacheItemInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ApcuCachePool extends AbstractCachePool
{
protected function fetchObjectFromCache($key)
{
return apcu_fetch($key);
}
protected function clearAllObjectsFromCache()
{
return apcu_clear_cache();
}
protected function clearOneObjectFromCache($key)
{
apcu_delete($key);
return true;
}
protected function storeItemInCache($key, CacheItemInterface $item, $ttl)
{
return apcu_store($key, $item, $ttl);
}
}
|
Use the new \MongoClient class
Use the new \MongoClient class instead of the deprecated \Mongo | <?php
namespace ServerGrove\Bundle\TranslationEditorBundle;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class MongoStorageManager extends ContainerAware
{
protected $mongo;
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
}
function getMongo()
{
if (!$this->mongo) {
$this->mongo = new \MongoClient($this->container->getParameter('translation_editor.mongodb'));
}
if (!$this->mongo) {
throw new \Exception("failed to connect to mongo");
}
return $this->mongo;
}
public function getDB()
{
return $this->getMongo()->translations;
}
public function getCollection()
{
return $this->getDB()->selectCollection($this->container->getParameter('translation_editor.collection'));
}
}
| <?php
namespace ServerGrove\Bundle\TranslationEditorBundle;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class MongoStorageManager extends ContainerAware
{
protected $mongo;
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
}
function getMongo()
{
if (!$this->mongo) {
$this->mongo = new \Mongo($this->container->getParameter('translation_editor.mongodb'));
}
if (!$this->mongo) {
throw new \Exception("failed to connect to mongo");
}
return $this->mongo;
}
public function getDB()
{
return $this->getMongo()->translations;
}
public function getCollection()
{
return $this->getDB()->selectCollection($this->container->getParameter('translation_editor.collection'));
}
} |
Add spawn method to Apply; initialise clones by calling super().__init__() | from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
super().__init__()
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
self.arg_gens = [g.clone() for g in arg_gens]
self.kwarg_gens = {name: g.clone() for name, g in kwarg_gens.items()}
def __next__(self):
next_args = (next(g) for g in self.arg_gens)
next_kwargs = {name: next(g) for name, g in self.kwarg_gens.items()}
return self.func(*next_args, **next_kwargs)
def reset(self, seed=None):
super().reset(seed)
def spawn(self):
return Apply(self.func, *self.orig_arg_gens, **self.orig_kwarg_gens) | from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
self.arg_gens = [g.clone() for g in arg_gens]
self.kwarg_gens = {name: g.clone() for name, g in kwarg_gens.items()}
def __next__(self):
next_args = (next(g) for g in self.arg_gens)
next_kwargs = {name: next(g) for name, g in self.kwarg_gens.items()}
return self.func(*next_args, **next_kwargs)
def reset(self, seed=None):
pass |
Make maximum buffer size larger. Should perform a little better, at the expense of higher memory usage, and a higher minimum delay length. | /**
* @depends AudioletGroup.js
*/
var AudioletDestination = new Class({
Extends: AudioletGroup,
initialize: function(audiolet, sampleRate, numberOfChannels, bufferSize) {
AudioletGroup.prototype.initialize.apply(this, [audiolet, 1, 0]);
this.device = new AudioletDevice(audiolet, sampleRate,
numberOfChannels, bufferSize);
audiolet.device = this.device; // Shortcut
this.scheduler = new Scheduler(audiolet);
audiolet.scheduler = this.scheduler; // Shortcut
this.blockSizeLimiter = new BlockSizeLimiter(audiolet,
Math.pow(2, 15));
audiolet.blockSizeLimiter = this.blockSizeLimiter; // Shortcut
this.upMixer = new UpMixer(audiolet, this.device.numberOfChannels);
this.inputs[0].connect(this.blockSizeLimiter);
this.blockSizeLimiter.connect(this.scheduler);
this.scheduler.connect(this.upMixer);
this.upMixer.connect(this.device);
}
});
| /**
* @depends AudioletGroup.js
*/
var AudioletDestination = new Class({
Extends: AudioletGroup,
initialize: function(audiolet, sampleRate, numberOfChannels, bufferSize) {
AudioletGroup.prototype.initialize.apply(this, [audiolet, 1, 0]);
this.device = new AudioletDevice(audiolet, sampleRate,
numberOfChannels, bufferSize);
audiolet.device = this.device; // Shortcut
this.scheduler = new Scheduler(audiolet);
audiolet.scheduler = this.scheduler; // Shortcut
this.blockSizeLimiter = new BlockSizeLimiter(audiolet,
Math.pow(2, 12));
audiolet.blockSizeLimiter = this.blockSizeLimiter; // Shortcut
this.upMixer = new UpMixer(audiolet, this.device.numberOfChannels);
this.inputs[0].connect(this.blockSizeLimiter);
this.blockSizeLimiter.connect(this.scheduler);
this.scheduler.connect(this.upMixer);
this.upMixer.connect(this.device);
}
});
|
Add terminal . at end of sentence in looselyMatches documentation string | "use strict";
const flow = require("lodash.flow");
const deburr = require("lodash.deburr");
const toLower = require("lodash.tolower");
const looseMatchTransform = flow(deburr, toLower);
/**
* Function that returns true when `needle` is found in `haystack`.
* The main advantages of this function are that it removes accented characters and that
* it is case-insensitive.
*
* Powered by lodash's {@link https://lodash.com/docs/#deburr deburr}.
*
* @function looselyMatches
*
* @param haystack {String} The string to inspect.
* @param needle {String} The substring to look for.
*
* @return {Boolean} True when variations of `needle` can be found inside `haystack`.
*/
module.exports = (haystack, needle) => {
return looseMatchTransform(haystack).indexOf(looseMatchTransform(needle)) !== -1;
};
| "use strict";
const flow = require("lodash.flow");
const deburr = require("lodash.deburr");
const toLower = require("lodash.tolower");
const looseMatchTransform = flow(deburr, toLower);
/**
* Function that returns true when `needle` is found in `haystack`.
* The main advantages of this function are that it removes accented characters and that
* it is case-insensitive.
*
* Powered by lodash's {@link https://lodash.com/docs/#deburr deburr}
*
* @function looselyMatches
*
* @param haystack {String} The string to inspect.
* @param needle {String} The substring to look for.
*
* @return {Boolean} True when variations of `needle` can be found inside `haystack`.
*/
module.exports = (haystack, needle) => {
return looseMatchTransform(haystack).indexOf(looseMatchTransform(needle)) !== -1;
};
|
Implement loop for menu items, but order is reversed | console.log("menu-fill");
var menu_env = $("#menu-env");
var item1 = menu_env_data[0];
var item2 = menu_env_data[1];
function createLinkItem (item) {
var _a = $("<a/>", { href: item.link });
$("<i/>", { class: item.icon }).appendTo(_a);
$("<span/>", { text: " " + item.name }).appendTo(_a);
return _a;
}
function createSingleLevelMenuItem (item) {
return $("<li/>").append(createLinkItem(item));
}
function createMultiLevelMenuItem (item) {
item.link = "#";
var _a = createLinkItem(item);
$("<span/>", { class: "label label-primary pull-right", text: item.sub.length - 1 }).appendTo(_a);
var _ul = $("<ul/>", { class: "treeview-menu" });
$.each(item.sub, function (index) {
this.icon = index == 0 ? "fa fa-certificate" : "fa fa-circle-o";
_ul.append(createSingleLevelMenuItem(this));
});
return $("<li/>", { class: "treeview" }).append(_a).append(_ul);
}
$.each(menu_env_data, function (index) {
if (this.sub) {
menu_env.after(createMultiLevelMenuItem(this));
}
else {
menu_env.after(createSingleLevelMenuItem(this));
}
});
| console.log("menu-fill");
var menu_env = $("#menu-env");
var item1 = menu_env_data[0];
var item2 = menu_env_data[1];
function createSingleLevelMenuItem (item) {
var _a = $("<a/>", { href: item.link });
$("<i/>", { class: item.icon }).appendTo(_a);
$("<span/>", { text: " " + item.name }).appendTo(_a);
return $("<li/>").append(_a);
}
function createMultiLevelMenuItem (item) {
var _a = $("<a/>", { href: "#" });
$("<i/>", { class: item.icon }).appendTo(_a);
$("<span/>", { text: " " + item.name }).appendTo(_a);
$("<span/>", { class: "label label-primary pull-right", text: item.sub.length - 1 }).appendTo(_a);
var _li = $("<li/>", { class: "treeview" }).append(_a);
return _li;
}
var div1 = createSingleLevelMenuItem(item1);
menu_env.after(div1);
var div2 = createMultiLevelMenuItem(item2);
menu_env.after(div2);
|
Add : to the id:jobs set key | '''
Return data to a redis server
This is a VERY simple example for pushing data to a redis server and is not
nessisarily intended as a usable interface.
'''
import redis
import json
__opts__ = {
'redis.host': 'mcp',
'redis.port': 6379,
'redis.db': '0',
}
def returner(ret):
'''
Return data to a redis data store
'''
serv = redis.Redis(
host=__opts__['redis.host'],
port=__opts__['redis.port'],
db=__opts__['redis.db'])
serv.sadd(ret['id'] + ':' + 'jobs', ret['jid'])
serv.set(ret['jid'] + ':' + ret['id'], json.dumps(ret['return']))
serv.sadd('jobs', ret['jid'])
serv.sadd(ret['jid'], ret['id'])
| '''
Return data to a redis server
This is a VERY simple example for pushing data to a redis server and is not
nessisarily intended as a usable interface.
'''
import redis
import json
__opts__ = {
'redis.host': 'mcp',
'redis.port': 6379,
'redis.db': '0',
}
def returner(ret):
'''
Return data to a redis data store
'''
serv = redis.Redis(
host=__opts__['redis.host'],
port=__opts__['redis.port'],
db=__opts__['redis.db'])
serv.sadd(ret['id'] + 'jobs', ret['jid'])
serv.set(ret['jid'] + ':' + ret['id'], json.dumps(ret['return']))
serv.sadd('jobs', ret['jid'])
serv.sadd(ret['jid'], ret['id'])
|
Allow sub-commands to use same main function | #!/usr/bin/env python
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=None):
if args is None:
args = sys.argv[1:]
cmd = os.path.basename(sys.argv[0])
if cmd.startswith('dr-'):
args.insert(0, cmd[3:])
prog = 'dr'
else:
prog = None
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser(prog=prog)
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args(args)
args.app_cls(parser, args)()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=sys.argv[1:]):
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser()
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args()
args.app_cls(parser, args)()
if __name__ == '__main__':
main(sys.argv[1:])
|
Fix gateway lag being negative in d?ping | """
Commands used to check the health of the bot.
"""
import datetime
from time import monotonic
from dog import Cog
from discord.ext import commands
class Health(Cog):
@commands.command()
async def ping(self, ctx):
""" Pong! """
# measure gateway delay
before = monotonic()
msg = await ctx.send('\u200b')
after = monotonic()
pong_ws = round(ctx.bot.latency * 1000, 2)
pong_rest = round((after - before) * 1000, 2)
pong_gateway_lag = round((datetime.datetime.utcnow() - msg.created_at).total_seconds() * 1000, 2)
pong = f'Pong! WS: {pong_ws}ms, REST: {pong_rest}ms, GW lag: {pong_gateway_lag}ms'
await msg.edit(content=pong)
def setup(bot):
bot.add_cog(Health(bot))
| """
Commands used to check the health of the bot.
"""
import datetime
from time import monotonic
from dog import Cog
from discord.ext import commands
class Health(Cog):
@commands.command()
async def ping(self, ctx):
""" Pong! """
# measure gateway delay
before = monotonic()
msg = await ctx.send('\u200b')
after = monotonic()
pong_ws = round(ctx.bot.latency * 1000, 2)
pong_rest = round((after - before) * 1000, 2)
pong_gateway_lag = round((msg.created_at - datetime.datetime.utcnow()).total_seconds() * 1000, 2)
pong = f'Pong! WS: {pong_ws}ms, REST: {pong_rest}ms, GW lag: {pong_gateway_lag}ms'
await msg.edit(content=pong)
def setup(bot):
bot.add_cog(Health(bot))
|
Add python environment to cron qualtrics script | #!/usr/bin/env python
import getopt
import sys
import os
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
# sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
source_dir = [os.path.join(os.path.dirname(os.path.abspath(__file__)), "../json_to_relation/")]
source_dir.extend(sys.path)
sys.path = source_dir
from surveyextractor import QualtricsExtractor
qe = QualtricsExtractor()
opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses'])
for opt, arg in opts:
if opt in ('-a', '--reset'):
qe.resetMetadata()
qe.resetSurveys()
qe.resetResponses()
elif opt in ('-m', '--loadmeta'):
qe.loadSurveyMetadata()
elif opt in ('-s', '--loadsurvey'):
qe.resetSurveys()
qe.loadSurveyData()
elif opt in ('-r', '--loadresponses'):
qe.loadResponseData()
| import getopt
import sys
import os
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
# sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
source_dir = [os.path.join(os.path.dirname(os.path.abspath(__file__)), "../json_to_relation/")]
source_dir.extend(sys.path)
sys.path = source_dir
from surveyextractor import QualtricsExtractor
qe = QualtricsExtractor()
opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses'])
for opt, arg in opts:
if opt in ('-a', '--reset'):
qe.resetMetadata()
qe.resetSurveys()
qe.resetResponses()
elif opt in ('-m', '--loadmeta'):
qe.loadSurveyMetadata()
elif opt in ('-s', '--loadsurvey'):
qe.resetSurveys()
qe.loadSurveyData()
elif opt in ('-r', '--loadresponses'):
qe.loadResponseData()
|
Test coverage for unknown options | <?php namespace Archon\Tests\DataFrame\CSV;
use Archon\DataFrame;
class CSVDataFrameExceptionsTest extends \PHPUnit_Framework_TestCase {
public function testOverwriteFailCSV() {
$fileName = __DIR__.DIRECTORY_SEPARATOR.'TestFiles'.DIRECTORY_SEPARATOR.'testCSVOverwrite.csv';
$df = DataFrame::fromArray([
['a' => 1, 'b' => 2, 'c' => 3],
['a' => 4, 'b' => 5, 'c' => 6],
['a' => 7, 'b' => 8, 'c' => 9],
]);
$this->setExpectedException('RuntimeException');
$df->toCSV($fileName);
}
public function testInvalidOption() {
$fileName = __DIR__.DIRECTORY_SEPARATOR.'TestFiles'.DIRECTORY_SEPARATOR.'testCSVOverwrite.csv';
$this->setExpectedException('Archon\Exceptions\UnknownOptionException');
DataFrame::fromCSV($fileName, ['invalid_option' => 0]);
}
}
| <?php namespace Archon\Tests\DataFrame\CSV;
use Archon\DataFrame;
class CSVDataFrameExceptionsTest extends \PHPUnit_Framework_TestCase {
public function testOverwriteFailCSV() {
$fileName = __DIR__.DIRECTORY_SEPARATOR.'TestFiles'.DIRECTORY_SEPARATOR.'testCSVOverwrite.csv';
$df = DataFrame::fromArray([
['a' => 1, 'b' => 2, 'c' => 3],
['a' => 4, 'b' => 5, 'c' => 6],
['a' => 7, 'b' => 8, 'c' => 9],
]);
$this->setExpectedException('RuntimeException');
$df->toCSV($fileName);
}
}
|
Update package docstring for PEP number. | # -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
""" Library to implement a well-behaved Unix daemon process
This library implements PEP 3143: Standard daemon process library.
A well-behaved Unix daemon process is tricky to get right, but the
required steps are much the same for every daemon program. A
`DaemonContext` instance holds the behaviour and configured
process environment for the program; use the instance as a context
manager to enter a daemon state.
Simple example of usage::
import daemon
from spam import do_main_program
with daemon.DaemonContext():
do_main_program()
"""
from daemon import DaemonContext
version = "1.4.4"
| # -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
""" Library to implement a well-behaved Unix daemon process
This library implements PEP [no number yet], Standard daemon
process library.
A well-behaved Unix daemon process is tricky to get right, but the
required steps are much the same for every daemon program. An
instance of the `DaemonContext` holds the behaviour and configured
process environment for the program; use the instance as a context
manager to enter a daemon state.
Simple example of usage::
import daemon
from spam import do_main_program
with daemon.DaemonContext() as daemon_context:
do_main_program()
"""
from daemon import DaemonContext
version = "1.4.4"
|
Fix output paths so they do not include input tree paths. | var _ = require('lodash');
var GlobFilter = require('broccoli-glob-filter');
var path = require('path');
function LodashRenderer(inputTree, options) {
if (!(this instanceof LodashRenderer)) {
return new LodashRenderer(inputTree, options);
}
GlobFilter.apply(this, arguments);
}
LodashRenderer.prototype = Object.create(GlobFilter.prototype);
LodashRenderer.prototype.constructor = LodashRenderer;
LodashRenderer.prototype.processFileContent = function(content, relPath, srcDir) {
return [
{
path: popExtension(relPath),
content: _.template(content)(this.options.context)
}
];
};
function popExtension(x) {
return path.join(path.dirname(x), path.basename(x, path.extname(x)));
}
module.exports = LodashRenderer;
| var _ = require('lodash');
var GlobFilter = require('broccoli-glob-filter');
var path = require('path');
function LodashRenderer(inputTree, options) {
if (!(this instanceof LodashRenderer)) {
return new LodashRenderer(inputTree, options);
}
GlobFilter.apply(this, arguments);
}
LodashRenderer.prototype = Object.create(GlobFilter.prototype);
LodashRenderer.prototype.constructor = LodashRenderer;
LodashRenderer.prototype.processFileContent = function(content, relPath, srcDir) {
return [
{
path: popExtension(path.join(srcDir, relPath)),
content: _.template(content)(this.options.context)
}
];
};
function popExtension(x) {
return path.join(path.dirname(x), path.basename(x, path.extname(x)));
}
module.exports = LodashRenderer;
|
Add firebase urls to envService. | (function() {
'use strict';
angular
.module('davisCru')
.config(config);
/** @ngInject */
function config($logProvider, envServiceProvider) {
envServiceProvider.config({
domains: {
development: ['localhost', 'staging.daviscru.com', 'staging.daviscru.divshot.io', 'daviscru-staging.firebaseapp.com'],
production: ['daviscru.com', 'www.daviscru.com', 'production.daviscru.divshot.io', 'daviscru.firebaseapp.com']
},
vars: {
development: {
firebaseUrl: 'https://daviscru-staging.firebaseio.com/'
},
production: {
firebaseUrl: 'https://daviscru.firebaseio.com/'
}
}
});
// run the environment check, so the comprobation is made
// before controllers and services are built
envServiceProvider.check();
if (envServiceProvider.is('production')) {
/// Disable log
$logProvider.debugEnabled(false);
} else {
// Enable log
$logProvider.debugEnabled(true);
}
}
})();
| (function() {
'use strict';
angular
.module('davisCru')
.config(config);
/** @ngInject */
function config($logProvider, envServiceProvider) {
envServiceProvider.config({
domains: {
development: ['localhost', 'staging.daviscru.com', 'staging.daviscru.divshot.io'],
production: ['daviscru.com', 'www.daviscru.com', 'production.daviscru.divshot.io']
},
vars: {
development: {
firebaseUrl: 'https://daviscru-staging.firebaseio.com/'
},
production: {
firebaseUrl: 'https://daviscru.firebaseio.com/'
}
}
});
// run the environment check, so the comprobation is made
// before controllers and services are built
envServiceProvider.check();
if (envServiceProvider.is('production')) {
/// Disable log
$logProvider.debugEnabled(false);
} else {
// Enable log
$logProvider.debugEnabled(true);
}
}
})();
|
Revert "adding source code compatibility" | package logmatic
import (
"encoding/json"
"fmt"
"time"
log "github.com/Sirupsen/logrus"
)
const defaultTimestampFormat = time.RFC3339
var markers = [2]string{"sourcecode", "golang"}
type JSONFormatter struct {
}
func (f *JSONFormatter) Format(entry *log.Entry) ([]byte, error) {
data := make(log.Fields, len(entry.Data) + 3)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/Sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
//prefixFieldClashes(data)
data["date"] = entry.Time.Format(defaultTimestampFormat)
data["message"] = entry.Message
data["level"] = entry.Level.String()
data["@marker"] = markers
serialized, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
| package logmatic
import (
"encoding/json"
"fmt"
"time"
log "github.com/Sirupsen/logrus"
"os"
)
const defaultTimestampFormat = time.RFC3339
var markers = [2]string{"sourcecode", "golang"}
type JSONFormatter struct {
}
func (f *JSONFormatter) Format(entry *log.Entry) ([]byte, error) {
data := make(log.Fields, len(entry.Data) + 3)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/Sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
//prefixFieldClashes(data)
data["date"] = entry.Time.Format(defaultTimestampFormat)
data["message"] = entry.Message
data["level"] = entry.Level.String()
data["@marker"] = markers
data["appname"] = os.Args[0]
h, err := os.Hostname()
if err == nil {
data["hostname"] = h
}
serialized, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
|
Add correct filename in OnionLauncher ui directory | #!/usr/bin/env python
from setuptools import setup
import sys
setup(name="OnionLauncher",
version="0.0.1",
description="Launcher for Tor",
license = "BSD",
author="Neel Chauhan",
author_email="neel@neelc.org",
url="https://www.github.com/neelchauhan/OnionLauncher/",
packages=["OnionLauncher"],
entry_points={'gui_scripts': ['OnionLauncher=OnionLauncher.main:main_loop']},
package_data={"OnionLauncher": ["ui_files/*"]},
install_requires=[
"stem",
],
data_files=[
(sys.prefix + "/share/pixmaps", ["icons/scalable/onionlauncher.svg"]),
(sys.prefix + "/share/applications", ["data/onionlauncher.desktop"]),
],
classifiers=[
"Environment :: X11 Applications :: Qt",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
],
)
| #!/usr/bin/env python
from setuptools import setup
import sys
setup(name="OnionLauncher",
version="0.0.1",
description="Launcher for Tor",
license = "BSD",
author="Neel Chauhan",
author_email="neel@neelc.org",
url="https://www.github.com/neelchauhan/OnionLauncher/",
packages=["OnionLauncher"],
entry_points={'gui_scripts': ['OnionLauncher=OnionLauncher.main:main_loop']},
package_data={"OnionLauncher": ["data/*"]},
install_requires=[
"stem",
],
data_files=[
(sys.prefix + "/share/pixmaps", ["icons/scalable/onionlauncher.svg"]),
(sys.prefix + "/share/applications", ["data/onionlauncher.desktop"]),
],
classifiers=[
"Environment :: X11 Applications :: Qt",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
],
)
|
[Python] Complete 'About Decorating with functions' koans | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), "o/~ We all live in a broken submarine o/~")
self.assertEqual("COWBELL BABY!", self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual("<llama/>", self.render_tag('llama'))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), __)
self.assertEqual(__, self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual(__, self.render_tag('llama'))
|
Add namespace to repository plugin | <?php
namespace SnowIO\AttributeSetCode\Plugin;
use Magento\Catalog\Api\Data\ProductInterface;
class AttributeSetCodeProductRepositoryPlugin
{
private $attributeSetCodeRepository;
public function __construct(\SnowIO\AttributeSetCode\Model\AttributeSetCodeRepository $attributeSetCodeRepository)
{
$this->attributeSetCodeRepository = $attributeSetCodeRepository;
}
public function beforeSave(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
ProductInterface $product,
$saveOptions = false
) {
if (!$extensionAttributes = $product->getExtensionAttributes()) {
return [$product, $saveOptions];
}
if (null === ($attributeSetCode = $extensionAttributes->getAttributeSetCode())) {
return [$product, $saveOptions];
}
$attributeSetId = $this->attributeSetCodeRepository->getAttributeSetId(4, $attributeSetCode);
$product->setAttributeSetId($attributeSetId);
return [$product, $saveOptions];
}
} | <?php
use Magento\Catalog\Api\Data\ProductInterface;
class AttributeSetCodeProductRepositoryPlugin
{
private $attributeSetCodeRepository;
public function __construct(\SnowIO\AttributeSetCode\Model\AttributeSetCodeRepository $attributeSetCodeRepository)
{
$this->attributeSetCodeRepository = $attributeSetCodeRepository;
}
public function beforeSave(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
ProductInterface $product,
$saveOptions = false
) {
if (!$extensionAttributes = $product->getExtensionAttributes()) {
return [$product, $saveOptions];
}
if (null === ($attributeSetCode = $extensionAttributes->getAttributeSetCode())) {
return [$product, $saveOptions];
}
$attributeSetId = $this->attributeSetCodeRepository->getAttributeSetId(4, $attributeSetCode);
$product->setAttributeSetId($attributeSetId);
return [$product, $saveOptions];
}
} |
Use app() instead of $this->app.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
namespace Orchestra\Database;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\ServiceProvider;
class CachableQueryServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*/
public function register()
{
QueryBuilder::macro('remember', function ($duration, $key = null) {
return (new CacheDecorator($this, \app('cache.store')))->remember($duration, $key);
});
QueryBuilder::macro('rememberForever', function ($key = null) {
return (new CacheDecorator($this, \app('cache.store')))->rememberForever($key);
});
EloquentBuilder::macro('remember', function ($duration, $key = null) {
return (new CacheDecorator($this, \app('cache.store')))->remember($duration, $key);
});
EloquentBuilder::macro('rememberForever', function ($key = null) {
return (new CacheDecorator($this, \app('cache.store')))->rememberForever($key);
});
}
}
| <?php
namespace Orchestra\Database;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\ServiceProvider;
class CachableQueryServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*/
public function register()
{
QueryBuilder::macro('remember', function ($duration, $key = null) {
return (new CacheDecorator($this, $this->app->make('cache.store')))->remember($duration, $key);
});
QueryBuilder::macro('rememberForever', function ($key = null) {
return (new CacheDecorator($this, $this->app->make('cache.store')))->rememberForever($key);
});
EloquentBuilder::macro('remember', function ($duration, $key = null) {
return (new CacheDecorator($this, $this->app->make('cache.store')))->remember($duration, $key);
});
EloquentBuilder::macro('rememberForever', function ($key = null) {
return (new CacheDecorator($this, $this->app->make('cache.store')))->rememberForever($key);
});
}
}
|
Remove dispatcher and unwanted boilerplate | import React from 'react';
import { connect } from 'react-redux';
// Components
import { Route, Redirect } from 'react-router';
import DashNav from '../components/dashboard/DashNav';
// Styles
import '../styles/dashboard/index.css';
const DashboardContainer = (props) => {
if(props.loggedIn){
return (
<div className="page-dashboard">
<DashNav />
<div className="dashboard">
</div>
</div>
)
} else {
return <Redirect to="/login"/>
}
}
function mapStateToProps(state, ownProps) {
return {
loggedIn: state.login.logged_in,
}
}
export default connect(mapStateToProps)(DashboardContainer) | import React from 'react';
import { connect } from 'react-redux';
// Components
import { Route, Redirect } from 'react-router';
import { Button, Glyphicon } from 'react-bootstrap';
import DashNav from '../components/dashboard/DashNav'
// actions
import { logOut } from '../actions/login'
const DashboardContainer = (props) => {
if(props.loggedIn){
return (
<div className="dashboard">
<DashNav />
<Button onClick={props.logOut}>Log out <Glyphicon glyph="log-out" /></Button>
</div>
)
} else {
return <Redirect to="/login"/>
}
}
function mapStateToProps(state, ownProps) {
return {
loggedIn: state.login.logged_in,
}
}
export default connect(mapStateToProps, { logOut })(DashboardContainer) |
Add semicolons to end of program statements | import os; # needed for opening/compiling file
import time; # needed for delay
def getPath(allowCancel = True):
"""Ask the user for lilypond file path and return it as string.
Takes one boolean argument as to whether message should say cancelling is allowed or not. Defaults to true, however this may not be suitable for where the path is needed for initialisation."""
if allowCancel == True:
question = "Enter path of lilypond file (including file but without extension), or enter nothing to cancel: ";
else:
question = "Enter path of lilypond file (including file but without extension): ";
path = raw_input(question);
return path;
logwait = 5; # how long the program waits before opening the log
answer = "";
path = "";
while path == "":
path = getPath(False);
while answer.lower() != "e":
answer = raw_input("Enter Y or C to compile, E to exit, or P to change file path: ");
if answer.lower() == "y" or answer.lower() == "c":
os.startfile(path + ".ly");
print "Opening log file in " + str(logwait) + " seconds...";
time.sleep(logwait);
print "Log file: ==========================";
logfile = open(path + ".log", "r");
print logfile.read();
print "End of log file: ===================";
print "====================================";
elif answer.lower() == "p":
path = getPath();
| import os # needed for opening/compiling file
import time # needed for delay
def getPath(allowCancel = True):
"""Ask the user for lilypond file path and return it as string.
Takes one boolean argument as to whether message should say cancelling is allowed or not. Defaults to true, however this may not be suitable for where the path is needed for initialisation."""
if allowCancel == True:
question = "Enter path of lilypond file (including file but without extension), or enter nothing to cancel: "
else:
question = "Enter path of lilypond file (including file but without extension): "
path = raw_input(question)
return path
logwait = 5 # how long the program waits before opening the log
answer = ""
path = ""
while path == "":
path = getPath(False)
while answer.lower() != "e":
answer = raw_input("Enter Y or C to compile, E to exit, or P to change file path: ")
if answer.lower() == "y" or answer.lower() == "c":
os.startfile(path + ".ly")
print "Opening log file in " + str(logwait) + " seconds..."
time.sleep(logwait)
print "Log file: =========================="
logfile = open(path + ".log", "r")
print logfile.read()
print "End of log file: ==================="
print "===================================="
elif answer.lower() == "p":
path = getPath()
|
Use hash history in routing
Makes routing use hash history instead of HTML5 history
to better work in staging environment.
Refs #34. | import createHistory from 'history/lib/createHashHistory';
import { compose, createStore, applyMiddleware } from 'redux';
import { apiMiddleware } from 'redux-api-middleware';
import loggerMiddleware from 'redux-logger';
import { reduxReactRouter } from 'redux-react-router';
import routes from 'app/routes';
import rootReducer from 'reducers/index';
let finalCreateStore;
if (__DEVTOOLS__) {
const { devTools, persistState } = require('redux-devtools');
finalCreateStore = compose(
applyMiddleware(apiMiddleware),
reduxReactRouter({ routes, createHistory }),
applyMiddleware(loggerMiddleware),
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(createStore);
} else {
finalCreateStore = compose(
applyMiddleware(apiMiddleware),
reduxReactRouter({ routes, createHistory })
)(createStore);
}
export default function configureStore(initialState) {
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('reducers', () => {
const nextRootReducer = require('reducers/index');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
| import createHistory from 'history/lib/createBrowserHistory';
import { compose, createStore, applyMiddleware } from 'redux';
import { apiMiddleware } from 'redux-api-middleware';
import loggerMiddleware from 'redux-logger';
import { reduxReactRouter } from 'redux-react-router';
import routes from 'app/routes';
import rootReducer from 'reducers/index';
let finalCreateStore;
if (__DEVTOOLS__) {
const { devTools, persistState } = require('redux-devtools');
finalCreateStore = compose(
applyMiddleware(apiMiddleware),
reduxReactRouter({ routes, createHistory }),
applyMiddleware(loggerMiddleware),
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(createStore);
} else {
finalCreateStore = compose(
applyMiddleware(apiMiddleware),
reduxReactRouter({ routes, createHistory })
)(createStore);
}
export default function configureStore(initialState) {
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('reducers', () => {
const nextRootReducer = require('reducers/index');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
|
Make Nao say its name and the programming language | """Export long monologues for Nao.
Functions:
introduction -- Make Nao introduce itself.
"""
import time
from say import say
def introduction(tts):
"""Make Nao introduce itself.
Keyword arguments:
tts - Nao proxy.
"""
say("Hello world!", tts)
say("I'm Leyva and I will teach you how to program in a programming\
language called python", tts)
say("Computer Science is one of the coolest subjects to study in the\
modern world.", tts)
say("Programming is a tool used by Scientists and Engineers to create\
all kinds of interesting things.", tts)
say("For example, you can program mobile phones, laptops, cars, the\
Internet and more. Every day more things are being enhanced by\
Artificial Intelligence, like me.", tts)
say("Now I want to talk about what programming is like.", tts)
say("Programming is about solving puzzles of the real world and helping\
people deal with important problems to make the world a better\
place.", tts)
time.sleep(2)
say("Now, what topic would you like to learn about? Show me a number to\
choose the activity.", tts)
say("Number one to practice input and output.", tts)
| """Export long monologues for Nao.
Functions:
introduction -- Make Nao introduce itself.
"""
import time
from say import say
def introduction(tts):
"""Make Nao introduce itself.
Keyword arguments:
tts - Nao proxy.
"""
say("Hello world!", tts)
say("Computer Science is one of the coolest subjects to study in the\
modern world.", tts)
say("Programming is a tool used by Scientists and Engineers to create\
all kinds of interesting things.", tts)
say("For example, you can program mobile phones, laptops, cars, the\
Internet and more. Every day more things are being enhanced by\
Artificial Intelligence, like me.", tts)
say("Now I want to talk about what programming is like.", tts)
say("Programming is about solving puzzles of the real world and helping\
people deal with important problems to make the world a better\
place.", tts)
time.sleep(2)
say("Now, what topic would you like to learn about? Show me a number to\
choose the activity.", tts)
say("Number one to practice input and output.", tts)
|
Fix return values to match old logic | <?php
/**
* @package plugins.reach
* @subpackage Admin
*/
class Form_DictionariesSubForm extends ConfigureSubForm
{
private $ignore = array('relatedObjects', 'type', 'gs');
private $prefix = "Dictionary_";
private $type;
public function __construct($type)
{
$this->type = $type;
parent::__construct();
}
public function init()
{
$this->setAttrib('id', 'frmDictionariesSubForm');
$this->setMethod('post');
$this->addDecorator('ViewScript', array(
'viewScript' => 'dictionary-sub-form.phtml',
));
$obj = new $this->type();
$this->addObjectProperties($obj, $this->ignore, $this->prefix);
}
public function isValid($data)
{
if(!$data['ReachProfileDictionaries'])
return true;
$jsonData = json_decode($data['ReachProfileDictionaries'], true);
if(!empty($jsonData))
return true;
return false;
}
} | <?php
/**
* @package plugins.reach
* @subpackage Admin
*/
class Form_DictionariesSubForm extends ConfigureSubForm
{
private $ignore = array('relatedObjects', 'type', 'gs');
private $prefix = "Dictionary_";
private $type;
public function __construct($type)
{
$this->type = $type;
parent::__construct();
}
public function init()
{
$this->setAttrib('id', 'frmDictionariesSubForm');
$this->setMethod('post');
$this->addDecorator('ViewScript', array(
'viewScript' => 'dictionary-sub-form.phtml',
));
$obj = new $this->type();
$this->addObjectProperties($obj, $this->ignore, $this->prefix);
}
public function isValid($data)
{
if(!$data['ReachProfileDictionaries'])
return false;
$jsonData = json_decode($data['ReachProfileDictionaries'], true);
if(!$jsonData)
return false;
return true;
}
} |
Fix the 'contribution/all' or 'contribution/' URL. | from django.conf.urls import patterns, url
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from .models import Contribution
from .views import ContributionCreate, ContributionDelete, ContributionUpdate, ContributionRDF
urlpatterns = patterns('',
url(r'^(all/)?$', ListView.as_view(model=Contribution, queryset=Contribution.published.all()), name='list'),
# example: /contribution/
# example: /contribution/all/
url(r'^add/$', ContributionCreate.as_view(), name='add'),
# example: /contribution/add/
url(r'^(?P<pk>\d+)/update/$', ContributionUpdate.as_view(), name='update'),
# example: /contribution/5/update/
url(r'^(?P<pk>\d+)/delete/$', ContributionDelete.as_view(), name='delete'),
# example: /contribution/5/delete/
url(r'^(?P<pk>\d+)\.xml$', ContributionRDF.as_view(), name='detail_rdf'),
# example: /contribution/detail_rdf/5/
url(r'^(?P<pk>\d+)/$', DetailView.as_view(model=Contribution, queryset=Contribution.published.all()), name='detail'),
# example: /contribution/5/
)
| from django.conf.urls import patterns, url
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from .models import Contribution
from .views import ContributionCreate, ContributionDelete, ContributionUpdate, ContributionRDF
urlpatterns = patterns('',
url(r'^(all)?/$', ListView.as_view(model=Contribution, queryset=Contribution.published.all()), name='list'),
# example: /contribution/
# example: /contribution/all/
url(r'^add/$', ContributionCreate.as_view(), name='add'),
# example: /contribution/add/
url(r'^(?P<pk>\d+)/update/$', ContributionUpdate.as_view(), name='update'),
# example: /contribution/5/update/
url(r'^(?P<pk>\d+)/delete/$', ContributionDelete.as_view(), name='delete'),
# example: /contribution/5/delete/
url(r'^(?P<pk>\d+)\.xml$', ContributionRDF.as_view(), name='detail_rdf'),
# example: /contribution/detail_rdf/5/
url(r'^(?P<pk>\d+)/$', DetailView.as_view(model=Contribution, queryset=Contribution.published.all()), name='detail'),
# example: /contribution/5/
)
|
Add include to be ignored | module.exports = {
extends: 'stylelint-config-standard',
plugins: ['stylelint-order', 'stylelint-scss'],
rules: {
'at-rule-empty-line-before': [
'always',
{
except: ['inside-block', 'blockless-after-blockless', 'first-nested'],
ignore: ['after-comment']
}
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'block-closing-brace-newline-after': [
'always',
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'color-hex-case': ['lower', { severity: 'warning' }],
indentation: 4,
'order/order': ['custom-properties', 'declarations'],
'order/properties-alphabetical-order': true,
'number-leading-zero': 'never',
'selector-list-comma-newline-after': null,
'scss/at-rule-no-unknown': true
}
};
| module.exports = {
extends: 'stylelint-config-standard',
plugins: ['stylelint-order', 'stylelint-scss'],
rules: {
'at-rule-empty-line-before': [
'always',
{
except: ['inside-block', 'blockless-after-blockless', 'first-nested'],
ignore: ['after-comment']
}
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
}
],
'block-closing-brace-newline-after': [
'always',
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
}
],
'color-hex-case': ['lower', { severity: 'warning' }],
indentation: 4,
'order/order': ['custom-properties', 'declarations'],
'order/properties-alphabetical-order': true,
'number-leading-zero': 'never',
'selector-list-comma-newline-after': null,
'scss/at-rule-no-unknown': true
}
};
|
Update feature version to 0.1.0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
setup(
name='django_excel_tools',
version='0.1.0',
description="Common function when working with excel.",
long_description=readme + '\n\n' + history,
author="Khemanorak Khath",
author_email='khath.khemanorak@gmail.com',
url='https://github.com/NorakGithub/django_excel_tools',
packages=find_packages(include=['django_excel_tools']),
include_package_data=True,
license="MIT license",
zip_safe=False,
keywords='django, excel, tools',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
setup(
name='django_excel_tools',
version='0.0.13',
description="Common function when working with excel.",
long_description=readme + '\n\n' + history,
author="Khemanorak Khath",
author_email='khath.khemanorak@gmail.com',
url='https://github.com/NorakGithub/django_excel_tools',
packages=find_packages(include=['django_excel_tools']),
include_package_data=True,
license="MIT license",
zip_safe=False,
keywords='django, excel, tools',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Set the diff-match-patch timeout to 100ms
This might result in worse diffs, but we don't want to spend a second
blocking the event loop while we figure out nicer diffs when comparing
documents. | const DMP = require('diff-match-patch')
const dmp = new DMP()
// Do not attempt to produce a diff for more than 100ms
dmp.Diff_Timeout = 0.1
module.exports = {
ADDED: 1,
REMOVED: -1,
UNCHANGED: 0,
diffAsShareJsOp(before, after, callback) {
const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
dmp.diff_cleanupSemantic(diffs)
const ops = []
let position = 0
for (const diff of diffs) {
const type = diff[0]
const content = diff[1]
if (type === this.ADDED) {
ops.push({
i: content,
p: position
})
position += content.length
} else if (type === this.REMOVED) {
ops.push({
d: content,
p: position
})
} else if (type === this.UNCHANGED) {
position += content.length
} else {
throw new Error('Unknown type')
}
}
callback(null, ops)
}
}
| const DMP = require('diff-match-patch')
const dmp = new DMP()
module.exports = {
ADDED: 1,
REMOVED: -1,
UNCHANGED: 0,
diffAsShareJsOp(before, after, callback) {
const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
dmp.diff_cleanupSemantic(diffs)
const ops = []
let position = 0
for (const diff of diffs) {
const type = diff[0]
const content = diff[1]
if (type === this.ADDED) {
ops.push({
i: content,
p: position
})
position += content.length
} else if (type === this.REMOVED) {
ops.push({
d: content,
p: position
})
} else if (type === this.UNCHANGED) {
position += content.length
} else {
throw new Error('Unknown type')
}
}
callback(null, ops)
}
}
|
Use protocols to parse the protocols | // Dependencies
var Protocols = require("protocols");
/**
* IsSsh
* Checks if an input value is a ssh url or not.
*
* @name IsSsh
* @function
* @param {String} input The input url.
* @return {Boolean} `true` if the input is a ssh url, `false` otherwise.
*/
function IsSsh(input) {
if (typeof input !== "string") {
return false;
}
var protocols = Protocols(input);
input = input.substring(input.indexOf("://") + 3);
if (protocols.indexOf("ssh") !== -1 || protocols.indexOf("rsync") !== -1) {
return true;
}
// TODO This probably could be improved :)
return input.indexOf("@") < input.indexOf(":");
}
module.exports = IsSsh;
| /**
* IsSsh
* Checks if an input value is a ssh url or not.
*
* @name IsSsh
* @function
* @param {String} input The input url.
* @return {Boolean} `true` if the input is a ssh url, `false` otherwise.
*/
function IsSsh(input) {
if (typeof input !== "string") {
return false;
}
var index = input.indexOf("://")
, protocol = input.substring(0, index).split("+")
;
input = input.substring(index + 3);
if (protocol.indexOf("ssh") !== -1 || protocol.indexOf("rsync") !== -1) {
return true;
}
// TODO This probably could be improved :)
return input.indexOf("@") < input.indexOf(":");
}
module.exports = IsSsh;
|
Halt on unrecognized constant pool tag | #!/usr/bin/python
import argparse
import os
import struct
import sys
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
###################
### SUBROUTINES ###
###################
def lenCpStruct(tag):
if tag == 0xa:
return 3
else:
return -1
############
### MAIN ###
############
parser = MyParser('Run bytecode in jjvm')
parser.add_argument('path', help='path to class')
args = parser.parse_args()
with open(args.path, "rb") as c:
c.seek(8)
cpCount = struct.unpack(">H", c.read(2))[0] - 1
print "Constant pool count: %d" % cpCount;
while cpCount >= 0:
cpTag = ord(c.read(1))
print "Got tag: %d" % cpTag
cpStructSize = lenCpStruct(cpTag)
if cpStructSize < 0:
print "ERROR: cpStructSize %d for tag %d" % (cpStructSize, cpTag)
sys.exit(1)
print "Size: %d" % cpStructSize
cpCount -= 1
c.seek(cpStructSize, os.SEEK_CUR)
| #!/usr/bin/python
import argparse
import struct
import sys
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
###################
### SUBROUTINES ###
###################
def lenCpItem(tag):
if tag == 0xa:
return 3
else:
return -1
############
### MAIN ###
############
parser = MyParser('Run bytecode in jjvm')
parser.add_argument('path', help='path to class')
args = parser.parse_args()
with open(args.path, "rb") as c:
c.seek(8)
cpcount = struct.unpack(">H", c.read(2))[0] - 1
print "Constant pool count: %d" % cpcount;
cpTag = ord(c.read(1))
print "Got tag: %d" % cpTag
print "Size: %d" % lenCpItem(cpTag)
|
Upgrade to support PHP 7.2 | <?php
/**
* @copyright Copyright (c) 2012 - 2015 SHENL.COM
* @license http://www.shenl.com/license/
*/
namespace hustshenl\metronic\widgets;
use yii\base\InvalidCallException;
use yii\base\BaseObject;
/**
* Decorator outputs buffering content between [[begin()]] and [[end()]]
*/
class Decorator extends BaseObject
{
/**
* @var array this property is maintained by [[begin()]] and [[end()]] methods.
* @internal
*/
public static $stack = [];
/**
* Turn on output buffering
*/
public static function begin()
{
self::$stack[] = get_called_class();
ob_start();
ob_implicit_flush(false);
}
/**
* Get current buffer contents and delete current output buffer.
* @return string the content between [[begin()]] and [[end()]]
* @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
*/
public static function end()
{
if (!empty(self::$stack)) {
return ob_get_clean();
} else {
throw new InvalidCallException("Unexpected " . get_called_class() . '::end() call. A matching begin() is not found.');
}
}
}
| <?php
/**
* @copyright Copyright (c) 2012 - 2015 SHENL.COM
* @license http://www.shenl.com/license/
*/
namespace hustshenl\metronic\widgets;
use yii\base\InvalidCallException;
use yii\base\Object;
/**
* Decorator outputs buffering content between [[begin()]] and [[end()]]
*/
class Decorator extends Object
{
/**
* @var array this property is maintained by [[begin()]] and [[end()]] methods.
* @internal
*/
public static $stack = [];
/**
* Turn on output buffering
*/
public static function begin()
{
self::$stack[] = get_called_class();
ob_start();
ob_implicit_flush(false);
}
/**
* Get current buffer contents and delete current output buffer.
* @return string the content between [[begin()]] and [[end()]]
* @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
*/
public static function end()
{
if (!empty(self::$stack)) {
return ob_get_clean();
} else {
throw new InvalidCallException("Unexpected " . get_called_class() . '::end() call. A matching begin() is not found.');
}
}
} |
Bump version to prepare for next release. | #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.9.0.12'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredispy',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://www.github.com/locationlabs/mockredis',
license='Apache2',
packages=find_packages(exclude=['*.tests']),
setup_requires=[
'nose'
],
extras_require={
'lua': ['lunatic-python-bugfix==1.1.1'],
},
tests_require=[
'redis>=2.9.0'
],
test_suite='mockredis.tests',
entry_points={
'nose.plugins.0.10': [
'with_redis = mockredis.noseplugin:WithRedis'
]
})
| #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.9.0.11'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredispy',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://www.github.com/locationlabs/mockredis',
license='Apache2',
packages=find_packages(exclude=['*.tests']),
setup_requires=[
'nose'
],
extras_require={
'lua': ['lunatic-python-bugfix==1.1.1'],
},
tests_require=[
'redis>=2.9.0'
],
test_suite='mockredis.tests',
entry_points={
'nose.plugins.0.10': [
'with_redis = mockredis.noseplugin:WithRedis'
]
})
|
Use /join instead of /accept invite. | from plumeria.command import commands, CommandError
from plumeria.message.lists import build_list
from plumeria.perms import owners_only
from plumeria.transport import transports
@commands.register('join', category='Discord')
@owners_only
async def join(message):
"""
Accept an invite to join a server.
Example::
/join https://discord.gg/00000
"""
url = message.content.strip()
results = []
if not len(url):
raise CommandError("Supply an invite URL.")
for transport in transports.transports.values():
if hasattr(transport, 'accept_invite'):
try:
await transport.accept_invite(url)
results.append((transport.id, 'Success \N{WHITE HEAVY CHECK MARK}'))
except Exception as e:
results.append((transport.id, '\N{WARNING SIGN} {}'.format(str(e))))
else:
results.append((transport.id, "\N{WARNING SIGN} No support for invite links"))
if len(results):
return build_list(["**{}:** {}".format(e[0], e[1]) for e in results])
else:
raise CommandError("No transports available.")
| from plumeria.command import commands, CommandError
from plumeria.message.lists import build_list
from plumeria.perms import owners_only
from plumeria.transport import transports
@commands.register('accept invite', category='Discord')
@owners_only
async def accept_invite(message):
"""
Accept an invite to join a server.
Example::
/accept invite https://discord.gg/00000
"""
url = message.content.strip()
results = []
if not len(url):
raise CommandError("Supply an invite URL.")
for transport in transports.transports.values():
if hasattr(transport, 'accept_invite'):
try:
await transport.accept_invite(url)
results.append((transport.id, 'Success \N{WHITE HEAVY CHECK MARK}'))
except Exception as e:
results.append((transport.id, '\N{WARNING SIGN} {}'.format(str(e))))
else:
results.append((transport.id, "\N{WARNING SIGN} No support for invite links"))
if len(results):
return build_list(["**{}:** {}".format(e[0], e[1]) for e in results])
else:
raise CommandError("No transports available.")
|
Change server port to 4000 | var express = require('express')
var app = express()
var session = require('express-session')
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var passport = require('./passportConfig')
var userRouter = require('./auth/router')
var config = require('./config')
// clean datebase and create sample user
// require('./utils/cleandb')()
app.use(cookieParser())
app.use(session({
secret: config.session.secret,
resave: false,
saveUninitialized: false,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use('/auth', userRouter);
app.get('/', function(req, res) {
res.send('Hello world')
})
var server = app.listen(4000, function() {
console.log('Server running at http://localhost:' + server.address().port)
})
module.exports = app
| var express = require('express')
var app = express()
var session = require('express-session')
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var passport = require('./passportConfig')
var userRouter = require('./auth/router')
var config = require('./config')
// clean datebase and create sample user
// require('./utils/cleandb')()
app.use(cookieParser())
app.use(session({
secret: config.session.secret,
resave: false,
saveUninitialized: false,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use('/auth', userRouter);
app.get('/', function(req, res) {
res.send('Hello world')
})
var server = app.listen(3000, function() {
console.log('Server running at http://localhost:' + server.address().port)
})
module.exports = app
|
Add server-side logging utility function | var moment = require('moment');
var geolib = require('geolib');
// Use moment.js to calculate how much time has elapsed since some prior time
exports.getTimeElapsedSince = function(time) {
return moment(time).fromNow();
};
// Use geolib.js to calculate distance from the mark to the user
exports.getDistanceFrom = function(mark, user) {
var dist = geolib.getDistance(
{latitude: user.x, longitude: user.y},
{latitude: mark.x, longitude: mark.y}
);
return dist + 'm';
};
// The object we pull from the database has specific data (time/location)
// Here we create a new object that has data that is relevant to the user
exports.createResponseObjects = function(marks, user) {
var responseObjects = [];
var responseObject;
marks.forEach(function(mark) {
responseObject = {
messageId: mark.messageId,
timestamp: exports.getTimeElapsedSince(mark.timestamp),
distance: exports.getDistanceFrom(mark, user),
messageString: mark.messageString
};
responseObjects.push(responseObject);
});
return responseObjects;
};
exports.log = function(message, content) {
console.log('\n--------------------------------------------------------');
console.log(moment().format("dddd, MMMM Do YYYY, h:mm:ss a") + message);
console.log(content);
console.log('--------------------------------------------------------');
};
| var moment = require('moment');
var geolib = require('geolib');
// Use moment.js to calculate how much time has elapsed since some prior time
exports.getTimeElapsedSince = function(time) {
return moment(time).fromNow();
};
// Use geolib.js to calculate distance from the mark to the user
exports.getDistanceFrom = function(mark, user) {
var dist = geolib.getDistance(
{latitude: user.x, longitude: user.y},
{latitude: mark.x, longitude: mark.y}
);
return dist + 'm';
};
// The object we pull from the database has specific data (time/location)
// Here we create a new object that has data that is relevant to the user
exports.createResponseObjects = function(marks, user) {
var responseObjects = [];
var responseObject;
marks.forEach(function(mark) {
responseObject = {
messageId: mark.messageId,
timestamp: exports.getTimeElapsedSince(mark.timestamp),
distance: exports.getDistanceFrom(mark, user),
messageString: mark.messageString
};
responseObjects.push(responseObject);
});
return responseObjects;
};
|
Add test for ‘run’ method | define(function(require) {
var registerSuite = require('intern!object'),
assert = require('intern/chai!assert'),
el;
require('js/tests/support/exports.js');
registerSuite({
name: 'Screen',
setup: function() {
el = document.createElement('style');
el.textContent = 'html {font-family: "5"}';
document.head.appendChild(el);
},
teardown: function() {
document.head.removeChild(el);
},
size: function() {
assert.strictEqual(Wee.screen.size(), 5,
'Screen size should return 5'
);
},
map: function() {
// TODO: Complete
assert.strictEqual(Wee.screen.map({
size: 1,
callback: function() {}
}), undefined,
'Single event was not mapped successfully'
);
assert.strictEqual(Wee.screen.map([{
size: 1,
callback: function() {}
}, {
size: 2,
callback: function() {}
}]), undefined,
'Multiple events were not mapped successfully'
);
},
run: function() {
assert.isFunction(Wee.screen.run, true,
'"run" did not evaluate as a function'
);
}
});
}); | define(function(require) {
var registerSuite = require('intern!object'),
assert = require('intern/chai!assert'),
el;
require('js/tests/support/exports.js');
registerSuite({
name: 'Screen',
setup: function() {
el = document.createElement('style');
el.textContent = 'html {font-family: "5"}';
document.head.appendChild(el);
},
teardown: function() {
document.head.removeChild(el);
},
size: function() {
assert.strictEqual(Wee.screen.size(), 5,
'Screen size should return 5'
);
},
map: function() {
// TODO: Complete
assert.strictEqual(Wee.screen.map({
size: 1,
callback: function() {}
}), undefined,
'Single event was not mapped successfully'
);
assert.strictEqual(Wee.screen.map([{
size: 1,
callback: function() {}
}, {
size: 2,
callback: function() {}
}]), undefined,
'Multiple events were not mapped successfully'
);
}
});
}); |
Add a check for printing results | /*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.bench.remote.sp;
import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;
public class VanillaDbSpResultSet implements SutResultSet {
private String message;
private boolean isCommitted;
public VanillaDbSpResultSet(SpResultSet result) {
Record[] records = result.getRecords();
if (records.length > 0)
message = records[0].toString();
else
message = "";
isCommitted = result.isCommitted();
}
@Override
public boolean isCommitted() {
return isCommitted;
}
@Override
public String outputMsg() {
return message;
}
}
| /*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.bench.remote.sp;
import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;
public class VanillaDbSpResultSet implements SutResultSet {
private String message;
private boolean isCommitted;
public VanillaDbSpResultSet(SpResultSet result) {
Record[] records = result.getRecords();
message = records[0].toString();
isCommitted = result.isCommitted();
}
@Override
public boolean isCommitted() {
return isCommitted;
}
@Override
public String outputMsg() {
return message;
}
}
|
Read binary data file location from commandline | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
| import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
data=np.fromfile("../datadir/windings1.bin", dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
Remove depecated --dev composer argument | #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru(
'./vendor/bin/phpcs --standard=PSR2 src tests *.php',
$returnStatus
);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
fputs(STDERR, "Code coverage was NOT 100%\n");
exit(1);
}
}
echo "Code coverage was 100%\n";
| #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru(
'./vendor/bin/phpcs --standard=PSR2 src tests *.php',
$returnStatus
);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
fputs(STDERR, "Code coverage was NOT 100%\n");
exit(1);
}
}
echo "Code coverage was 100%\n";
|
Fix i2mx namespace typo (hopefully loads now)
It was written im2x instead of i2mx. | /*
#
# img2musicXML.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = i2mx || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divClassName = "i2mx-checkup";
this.activate = function() {
var divList = document.getElementsByClassName(this.divClassName);
// @TODO: Implement multiple divs support
divList[0].innerHTML = "No checlist for now, but img2musicXML loaded successfully!"; // @TODO: Multi-line
}
}
var jsCheckup = new JsCheckup();
// @TODO: Check window.onload vs document.onload
// @TODO: Use event listener instead of onload
document.onload = function() {
jsCheckup.activate();
}
| /*
#
# img2musicXML.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = im2x || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divClassName = "i2mx-checkup";
this.activate = function() {
var divList = document.getElementsByClassName(this.divClassName);
// @TODO: Implement multiple divs support
divList[0].innerHTML = "No checlist for now, but img2musicXML loaded successfully!"; // @TODO: Multi-line
}
}
var jsCheckup = new JsCheckup();
// @TODO: Check window.onload vs document.onload
// @TODO: Use event listener instead of onload
document.onload = function() {
jsCheckup.activate();
}
|
Move repo code to vendor installer. | <?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Core\Units;
use Jivoo\Core\UnitBase;
use Jivoo\Core\App;
use Jivoo\Core\Store\Document;
use Jivoo\Vendor\ComposerPackageReader;
use Jivoo\Vendor\VendorLoader;
use Jivoo\Vendor\VendorCommand;
use Jivoo\Vendor\VendorInstaller;
use Jivoo\Vendor\LocalRepository;
/**
* Initializes the third-party library loading system.
*/
class VendorUnit extends UnitBase {
/**
* {@inheritdoc}
*/
public function run(App $app, Document $config) {
$app->m->vendor = new VendorLoader($app);
$vendor = $this->p('app/../vendor');
if (is_dir($vendor))
$app->m->vendor->addPath($vendor, new ComposerPackageReader());
$vendor = $this->p('share/vendor');
if (is_dir($vendor))
$app->m->vendor->addPath($vendor, new ComposerPackageReader());
$app->m->addProperty('vendor', $app->m->vendor);
$app->m->vendorInstaller = new VendorInstaller($app);
$app->m->vendorInstaller->addRepository('share', new LocalRepository($this->app, $this->p('share/vendor')));
$this->m->lazy('shell')->addCommand('vendor', new VendorCommand($app));
}
} | <?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Core\Units;
use Jivoo\Core\UnitBase;
use Jivoo\Core\App;
use Jivoo\Core\Store\Document;
use Jivoo\Vendor\ComposerPackageReader;
use Jivoo\Vendor\VendorLoader;
use Jivoo\Vendor\VendorCommand;
/**
* Initializes the third-party library loading system.
*/
class VendorUnit extends UnitBase {
/**
* {@inheritdoc}
*/
public function run(App $app, Document $config) {
$app->m->vendor = new VendorLoader($app);
$vendor = $this->p('app/../vendor');
if (is_dir($vendor))
$app->m->vendor->addPath($vendor, new ComposerPackageReader());
$vendor = $this->p('share/vendor');
if (is_dir($vendor))
$app->m->vendor->addPath($vendor, new ComposerPackageReader());
$app->m->addProperty('vendor', $app->m->vendor);
$this->m->lazy('shell')->addCommand('vendor', new VendorCommand($app));
}
} |
Introduce some logging in screens to aid in the debugging | package starpunk.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import starpunk.StarPunkGame;
public abstract class BaseScreen
implements Screen
{
private final StarPunkGame _game;
protected BaseScreen( final StarPunkGame game )
{
_game = game;
}
protected final StarPunkGame getGame()
{
return _game;
}
public abstract void update( float delta );
public abstract void draw( float delta );
@Override
public void render( final float delta )
{
update( delta );
draw( delta );
}
@Override
public void resize( final int width, final int height )
{
log( "Resizing screen to: " + width + " x " + height );
}
@Override
public void show()
{
log( "Showing screen" );
}
@Override
public void hide()
{
log( "Hiding screen" );
}
@Override
public void pause()
{
log( "Pausing screen" );
}
@Override
public void resume()
{
log( "Resuming screen" );
}
@Override
public void dispose()
{
log( "Disposing screen" );
}
private void log( final String message )
{
Gdx.app.log( getClass().getSimpleName(), message );
}
} | package starpunk.screens;
import com.badlogic.gdx.Screen;
import starpunk.StarPunkGame;
public abstract class BaseScreen
implements Screen
{
private final StarPunkGame _game;
protected BaseScreen( final StarPunkGame game )
{
_game = game;
}
protected final StarPunkGame getGame()
{
return _game;
}
public abstract void update( float delta );
public abstract void draw( float delta );
@Override
public void render( final float delta )
{
update( delta );
draw( delta );
}
@Override
public void resize( final int width, final int height )
{
}
@Override
public void show()
{
}
@Override
public void hide()
{
}
@Override
public void pause()
{
}
@Override
public void resume()
{
}
@Override
public void dispose()
{
}
} |
Add more tests to see where fault is. | <?php
namespace Mimic\Test;
use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;
/**
* Unit Test for true Mimic library function.
*
* @since 0.1.0
*
* @todo Need to use QuickTest library.
*/
class CompareFuncTest extends PHPUnit_Framework_TestCase {
public function dataProvider() {
return array(
array(true, 1, 1, true),
array(false, 1, true, true),
array(false, '1', 1, true),
array(true, '1', 1, false),
array(false, 0, 1, true),
);
}
/**
* @dataProvider dataProvider
* @covers ::Mimic\Functional\compare
*/
public function testResults($expected, $check, $value, $strict) {
$callback = F\compare($value, $strict);
$this->assertEquals($expected, $callback($check));
}
}
| <?php
namespace Mimic\Test;
use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;
/**
* Unit Test for true Mimic library function.
*
* @since 0.1.0
*
* @todo Need to use QuickTest library.
*/
class CompareFuncTest extends PHPUnit_Framework_TestCase {
public function dataProvider() {
return array(
array(true, 1, 1, true),
array(true, '1', 1, false),
array(false, 0, 1, true),
array(false, '1', 1, true),
);
}
/**
* @dataProvider dataProvider
* @covers ::Mimic\Functional\compare
*/
public function testResults($expected, $check, $value, $strict) {
$callback = F\compare($value, $strict);
$this->assertEquals($expected, $callback($check));
}
}
|
Make admin feedback easier understandable | <div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>">
<div class="updateOverview">
<h2 class="title"><?php p($l->t('Update needed')) ?></h2>
<div class="infogroup">
<?php if ($_['tooBig']) {
p($l->t('Your instance possibly hosts many users and files. To ensure a smooth upgrade process, please use the command line updater (occ upgrade).'));
} else {
p($l->t('Automatic updating was disabled in config.php. To upgrade your instance, please use the command line updater (occ upgrade).'));
} ?><br><br>
<?php
print_unescaped($l->t('For help, see the <a target="_blank" rel="noreferrer" href="%s">documentation</a>.', [link_to_docs('admin-cli-upgrade')])); ?><br><br>
</div>
</div>
</div>
| <div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>">
<div class="updateOverview">
<h2 class="title"><?php p($l->t('Update needed')) ?></h2>
<div class="infogroup">
<?php if ($_['tooBig']) {
p($l->t('Please use the command line updater because you have a big instance.'));
} else {
p($l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
} ?><br><br>
<?php
print_unescaped($l->t('For help, see the <a target="_blank" rel="noreferrer" href="%s">documentation</a>.', [link_to_docs('admin-cli-upgrade')])); ?><br><br>
</div>
</div>
</div>
|
StringTable: Revert to using ResourceUtil to load icons | /*******************************************************************************
* Copyright (c) 2015-2016 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.javafx;
import java.util.logging.Logger;
import org.csstudio.display.builder.util.ResourceUtil;
import javafx.scene.image.Image;
/** Plugin information
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class Activator // Could become plugin activator
{
/** Plugin ID */
public static final String ID = "org.csstudio.javafx";
/** Logger for plugin */
public static final Logger logger = Logger.getLogger(ID);
/** @param base_name Icon base name (no path, no extension)
* @return Image
* @throws Exception on error
*/
public static Image getIcon(final String base_name) throws Exception
{
String path = "platform:/plugin/org.csstudio.javafx/icons/" + base_name + ".png";
return new Image(ResourceUtil.openPlatformResource(path));
}
}
| /*******************************************************************************
* Copyright (c) 2015-2016 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.javafx;
import java.util.logging.Logger;
/** Plugin information
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class Activator // Could become plugin activator
{
/** Plugin ID */
public static final String ID = "org.csstudio.javafx";
/** Logger for plugin */
public static final Logger logger = Logger.getLogger(ID);
/** @param base_name Icon base name (no path, no extension)
* @return Icon path
*/
public static String getIcon(final String base_name)
{
return "platform:/plugin/org.csstudio.javafx/icons/" + base_name + ".png";
}
}
|
Fix typo in migration. Didn't bother with new migration, nothing was ever deployed | 'use strict'
var db = require('../app/db');
exports.up = function(next) {
db.Semester.create([
{
name: 'סתיו תשע"ז', year: 2017, semester: 1,
startDate: new Date("2016-10-29T00:00:00.000Z"),
endDate: new Date("2017-01-26T00:00:00.000Z"),
examsStart: new Date("2017-01-28T00:00:00.000Z"),
examsEnd: new Date("2017-03-09T00:00:00.000Z")
},
{
name: 'אביב תשע"ז', year: 2017, semester: 2,
startDate: new Date("2017-03-11T00:00:00.000Z"),
endDate: new Date("2017-06-29T00:00:00.000Z"),
examsStart: new Date("2017-07-01T00:00:00.000Z"),
}
], function(err) {
if (err)
throw err;
next();
});
};
exports.down = function(next) {
next();
};
| 'use strict'
var db = require('../app/db');
exports.up = function(next) {
db.Semester.create([
{
name: 'סתיז תשע"ז', year: 2017, semester: 1,
startDate: new Date("2016-10-29T00:00:00.000Z"),
endDate: new Date("2017-01-26T00:00:00.000Z"),
examsStart: new Date("2017-01-28T00:00:00.000Z"),
examsEnd: new Date("2017-03-09T00:00:00.000Z")
},
{
name: 'אביב תשע"ז', year: 2017, semester: 2,
startDate: new Date("2017-03-11T00:00:00.000Z"),
endDate: new Date("2017-06-29T00:00:00.000Z"),
examsStart: new Date("2017-07-01T00:00:00.000Z"),
}
], function(err) {
if (err)
throw err;
next();
});
};
exports.down = function(next) {
next();
};
|
Drop support for Python 2.6 | #!/usr/bin/env python
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import with_statement
import json
import sys
import six
import thutils
import tcconfig
import tcconfig.traffic_control
from ._common import verify_network_interface
def parse_option():
parser = thutils.option.ArgumentParserObject()
parser.make(version=tcconfig.VERSION)
group = parser.add_argument_group("Traffic Control")
group.add_argument(
"--device", action="append", required=True,
help="network device name (e.g. eth0)")
return parser.parse_args()
@thutils.main.Main
def main():
options = parse_option()
thutils.initialize_library(__file__, options)
thutils.common.verify_install_command(["tc"])
subproc_wrapper = thutils.subprocwrapper.SubprocessWrapper()
tc_param = {}
for device in options.device:
verify_network_interface(device)
tc = tcconfig.traffic_control.TrafficControl(
subproc_wrapper, device)
tc_param.update(tc.get_tc_parameter())
six.print_(json.dumps(tc_param, indent=4))
return 0
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import with_statement
import sys
try:
import json
except ImportError:
import simplejson as json
import six
import thutils
import tcconfig
import tcconfig.traffic_control
from ._common import verify_network_interface
def parse_option():
parser = thutils.option.ArgumentParserObject()
parser.make(version=tcconfig.VERSION)
group = parser.add_argument_group("Traffic Control")
group.add_argument(
"--device", action="append", required=True,
help="network device name (e.g. eth0)")
return parser.parse_args()
@thutils.main.Main
def main():
options = parse_option()
thutils.initialize_library(__file__, options)
thutils.common.verify_install_command(["tc"])
subproc_wrapper = thutils.subprocwrapper.SubprocessWrapper()
tc_param = {}
for device in options.device:
verify_network_interface(device)
tc = tcconfig.traffic_control.TrafficControl(
subproc_wrapper, device)
tc_param.update(tc.get_tc_parameter())
six.print_(json.dumps(tc_param, indent=4))
return 0
if __name__ == '__main__':
sys.exit(main())
|
Add the ability to use inet socket as well.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1236 a8f5125c-1e01-0410-8897-facf34644b8e | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
if _client:
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
address != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
else:
host = address
port = DEFAULT_EPG_PORT
# create socket, pass it to client
_client = GuideClient((host, port))
else:
# EPG is local, only use unix socket
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
_client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
2, GuideClient, "epg")
return _client
| import os
import logging
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect' ]
# connected client object
_client = None
def connect(epgdb, logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
if epgdb.find(':') >= 0:
# epg is remote: host:port
# TODO: create socket, pass it to client
_client = GuideClient("epg")
else:
# epg is local
_client = ipc.launch([server, logfile, str(loglevel), epgdb], 2, GuideClient, "epg")
return _client
|
Put code-style checks after unit tests | 'use strict';
module.exports = function(grunt) {
var config = {
jscs: {
src: [
'lib/*.js',
'test/**/*.js',
'gruntFile.js',
'index.js'
],
options: {
config: '.jscsrc',
requireCurlyBraces: [ 'if', 'for', 'while' ]
}
},
mochaTest: {
unit: {
options: {
reporter: 'spec'
},
src: ['test/unit/**/*.js']
}
}
};
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.initConfig(config);
grunt.registerTask('test', [ 'mochaTest', 'jscs' ]);
};
| 'use strict';
module.exports = function(grunt) {
var config = {
jscs: {
src: [
'lib/*.js',
'test/**/*.js',
'gruntFile.js',
'index.js'
],
options: {
config: '.jscsrc',
requireCurlyBraces: [ 'if', 'for', 'while' ]
}
},
mochaTest: {
unit: {
options: {
reporter: 'spec'
},
src: ['test/unit/**/*.js']
}
}
};
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.initConfig(config);
grunt.registerTask('test', [ 'jscs', 'mochaTest' ]);
};
|
Use < instead of <= in environment markers. | from buckle.version import VERSION
from setuptools import setup, find_packages
setup(
name='buckle',
version=VERSION,
description='Buckle: It ties your toolbelt together',
author='Nextdoor',
author_email='eng@nextdoor.com',
packages=find_packages(exclude=['ez_setup']),
scripts=['bin/buckle',
'bin/buckle-init',
'bin/buckle-help',
'bin/buckle-_help-helper',
'bin/buckle-readme',
'bin/buckle-version',
],
test_suite="tests",
install_requires=[
'future>=0.15.2',
],
tests_require=[
'pytest',
],
extras_require={
':python_version < "3.3"': [
'subprocess32',
],
},
url='https://github.com/Nextdoor/buckle',
include_package_data=True
)
| from buckle.version import VERSION
from setuptools import setup, find_packages
setup(
name='buckle',
version=VERSION,
description='Buckle: It ties your toolbelt together',
author='Nextdoor',
author_email='eng@nextdoor.com',
packages=find_packages(exclude=['ez_setup']),
scripts=['bin/buckle',
'bin/buckle-init',
'bin/buckle-help',
'bin/buckle-_help-helper',
'bin/buckle-readme',
'bin/buckle-version',
],
test_suite="tests",
install_requires=[
'future>=0.15.2',
],
tests_require=[
'pytest',
],
extras_require={
':python_version <= "3.2"': [
'subprocess32',
],
},
url='https://github.com/Nextdoor/buckle',
include_package_data=True
)
|
Increment version for django 1.9 support | from setuptools import setup
setup(
name='jsonate',
version='0.4.0',
author='James Robert',
author_email='jiaaro@gmail.com',
description=('Django library that can make ANYTHING into json'),
long_description=open('README.markdown').read(),
license='MIT',
keywords='django json templatetags',
url='http://jsonate.com',
install_requires=[
"django>=1.7",
],
packages=[
'jsonate',
'jsonate.templatetags',
],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Utilities'
]
)
| from setuptools import setup
setup(
name='jsonate',
version='0.3.2',
author='James Robert',
author_email='jiaaro@gmail.com',
description=('Django library that can make ANYTHING into json'),
long_description=open('README.markdown').read(),
license='MIT',
keywords='django json templatetags',
url='http://jsonate.com',
install_requires=[
"django>=1.4",
],
packages=[
'jsonate',
'jsonate.templatetags',
],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Utilities'
]
)
|
Add `published=all` query param to client request | /*
* Copyright 2015 Studentmediene i Trondheim AS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* @ngdoc service
* @name barteguidenMarkedsWebApp.eventService
* @description
* # eventService
* Factory in the barteguidenMarkedsWebApp.
*/
angular.module('barteguidenMarkedsWebApp.services')
.factory('Event', function ($resource) {
return $resource('http://localhost:4004/api/events/:id', { id: '@_id' }, {
update: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: true,
params: { published: 'all' }
}
});
});
| /*
* Copyright 2015 Studentmediene i Trondheim AS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* @ngdoc service
* @name barteguidenMarkedsWebApp.eventService
* @description
* # eventService
* Factory in the barteguidenMarkedsWebApp.
*/
angular.module('barteguidenMarkedsWebApp.services')
.factory('Event', function ($resource) {
return $resource('http://localhost:4004/api/events/:id', { id: '@_id' }, {
update: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: true
}
});
});
|
Fix a test case and add another. | import unittest
from .exceptions import InvalidURI
from .uri import *
VALID_URIS = [
('ws://localhost/', (False, 'localhost', 80, '/')),
('wss://localhost/', (True, 'localhost', 443, '/')),
('ws://localhost/path?query', (False, 'localhost', 80, '/path?query')),
('WS://LOCALHOST/PATH?QUERY', (False, 'localhost', 80, '/PATH?QUERY')),
]
INVALID_URIS = [
'http://localhost/',
'https://localhost/',
'ws://localhost/path#fragment',
'ws://user:pass@localhost/',
]
class URITests(unittest.TestCase):
def test_success(self):
for uri, parsed in VALID_URIS:
# wrap in `with self.subTest():` when dropping Python 3.3
self.assertEqual(parse_uri(uri), parsed)
def test_error(self):
for uri in INVALID_URIS:
# wrap in `with self.subTest():` when dropping Python 3.3
with self.assertRaises(InvalidURI):
parse_uri(uri)
| import unittest
from .exceptions import InvalidURI
from .uri import *
VALID_URIS = [
('ws://localhost/', (False, 'localhost', 80, '/')),
('wss://localhost/', (True, 'localhost', 443, '/')),
('ws://localhost/path?query', (False, 'localhost', 80, '/path?query')),
('WS://LOCALHOST/PATH?QUERY', (False, 'localhost', 80, '/PATH?QUERY')),
]
INVALID_URIS = [
'http://localhost/',
'https://localhost/',
'http://localhost/path#fragment'
]
class URITests(unittest.TestCase):
def test_success(self):
for uri, parsed in VALID_URIS:
# wrap in `with self.subTest():` when dropping Python 3.3
self.assertEqual(parse_uri(uri), parsed)
def test_error(self):
for uri in INVALID_URIS:
# wrap in `with self.subTest():` when dropping Python 3.3
with self.assertRaises(InvalidURI):
parse_uri(uri)
|
Fix magnitudes test for Python 2.7 in CI | from skyfield.api import load
from skyfield.magnitudelib import planetary_magnitude
def test_magnitudes():
ts = load.timescale()
#t = ts.utc(1995, 5, 22) # Rings edge-on from Earth.
t = ts.utc(2021, 10, 4)
eph = load('de421.bsp')
names = [
'mercury', 'venus', 'mars', 'jupiter barycenter',
'saturn barycenter', 'uranus barycenter', 'neptune barycenter',
]
e = eph['earth'].at(t)
positions = [e.observe(eph[name]) for name in names]
magnitudes = [planetary_magnitude(position) for position in positions]
assert ['%.3f' % m for m in magnitudes] == [
'2.393', '-4.278', '1.592', '-2.693', '0.508', '5.701', '7.690',
]
| from skyfield.api import load
from skyfield.magnitudelib import planetary_magnitude
def test_magnitudes():
ts = load.timescale()
#t = ts.utc(1995, 5, 22) # Rings edge-on from Earth.
t = ts.utc(2021, 10, 4)
eph = load('de421.bsp')
names = [
'mercury', 'venus', 'mars', 'jupiter barycenter',
'saturn barycenter', 'uranus barycenter', 'neptune barycenter',
]
e = eph['earth'].at(t)
positions = [e.observe(eph[name]) for name in names]
magnitudes = [planetary_magnitude(position) for position in positions]
assert [f'{m:.3f}' for m in magnitudes] == [
'2.393', '-4.278', '1.592', '-2.693', '0.508', '5.701', '7.690',
]
|
Replace NewDirectory() with LookupDirectory() that reuses *Directory for same path. | package exp12
import (
"sync"
"github.com/shurcooL/go/exp/13"
"github.com/shurcooL/go/vcs"
. "gist.github.com/7802150.git"
)
// TODO: Use FileUri or similar type instead of string for clean path to repo root.
// rootPath -> *VcsState
var repos = make(map[string]*exp13.VcsState)
var reposLock sync.Mutex
// TODO: Use FileUri or similar type instead of string for clean path to repo root.
// path -> *Directory
var directories = make(map[string]*Directory)
var directoriesLock sync.Mutex
type Directory struct {
path string
Repo *exp13.VcsState
DepNode2
}
func (this *Directory) Update() {
if vcs := vcs.New(this.path); vcs != nil {
reposLock.Lock()
if repo, ok := repos[vcs.RootPath()]; ok {
this.Repo = repo
} else {
this.Repo = exp13.NewVcsState(vcs)
repos[vcs.RootPath()] = this.Repo
}
reposLock.Unlock()
}
}
func newDirectory(path string) *Directory {
this := &Directory{path: path}
// No DepNode2I sources, so each instance can only be updated (i.e. initialized) once
return this
}
func LookupDirectory(path string) *Directory {
directoriesLock.Lock()
defer directoriesLock.Unlock()
if dir := directories[path]; dir != nil {
return dir
} else {
dir = newDirectory(path)
directories[path] = dir
return dir
}
}
| package exp12
import (
"sync"
"github.com/shurcooL/go/exp/13"
"github.com/shurcooL/go/vcs"
. "gist.github.com/7802150.git"
)
// TODO: Use FileUri or similar type instead of string for clean path to repo root.
// rootPath -> *VcsState
var repos = make(map[string]*exp13.VcsState)
var reposLock sync.Mutex
type Directory struct {
path string
Repo *exp13.VcsState
DepNode2
}
func (this *Directory) Update() {
if vcs := vcs.New(this.path); vcs != nil {
reposLock.Lock()
if repo, ok := repos[vcs.RootPath()]; ok {
this.Repo = repo
} else {
this.Repo = exp13.NewVcsState(vcs)
repos[vcs.RootPath()] = this.Repo
}
reposLock.Unlock()
}
}
func NewDirectory(path string) *Directory {
this := &Directory{path: path}
// No DepNode2I sources, so each instance can only be updated (i.e. initialized) once
return this
}
|
Fix version number from the cli | #!/usr/bin/env node
global.__base = __dirname + '/src/';
var pjson = require('./package.json');
// Commands
var cli = require('commander');
cli
.version(pjson.version)
.option('-p, --port <port>' , 'Change static server port [8000]', 8000)
.option('-P, --livereload-port <port>' , 'Change livereload port [35729]', 35729)
.option('-d, --directory <path>' , 'Change the default directory for serving files [.]', process.cwd())
.option('-s, --spa' , 'Return index.html when HTML request is not found', false)
.parse(process.argv);
// Start Asset server
var AssetServer = require(__base + 'assets_server');
var assetServer = new AssetServer({
port: cli.port,
directory: cli.directory,
livereloadPort: cli.livereloadPort,
spa: cli.spa
});
assetServer.start();
// Start Livereload server
var LivereloadServer = require(__base + 'livereload_server');
var livereloadServer = new LivereloadServer({
port: cli.livereloadPort
});
livereloadServer.start();
// Start Monitor
var Monitor = require(__base + 'monitor');
var monitor = new Monitor({
directory: cli.directory,
livereloadPort: cli.livereloadPort
})
monitor.start();
| #!/usr/bin/env node
global.__base = __dirname + '/src/';
// Commands
var cli = require('commander');
cli
.version('0.0.1')
.option('-p, --port <port>' , 'Change static server port [8000]', 8000)
.option('-P, --livereload-port <port>' , 'Change livereload port [35729]', 35729)
.option('-d, --directory <path>' , 'Change the default directory for serving files [.]', process.cwd())
.option('-s, --spa' , 'Return index.html when HTML request is not found', false)
.parse(process.argv);
// Start Asset server
var AssetServer = require(__base + 'assets_server');
var assetServer = new AssetServer({
port: cli.port,
directory: cli.directory,
livereloadPort: cli.livereloadPort,
spa: cli.spa
});
assetServer.start();
// Start Livereload server
var LivereloadServer = require(__base + 'livereload_server');
var livereloadServer = new LivereloadServer({
port: cli.livereloadPort
});
livereloadServer.start();
// Start Monitor
var Monitor = require(__base + 'monitor');
var monitor = new Monitor({
directory: cli.directory,
livereloadPort: cli.livereloadPort
})
monitor.start();
|
Add CCS811 to device factory | from src.Sensors.BME280 import BME280
from src.Sensors.BME680 import BME680
from src.Sensors.DS18B20 import DS18B20
from src.Sensors.CCS811 import CCS811
from src.Notification.Subscriber.LED.RGB import RGB
class Factory:
@staticmethod
def create_sensor(device, address):
if device == 'BME280':
return BME280(address=address)
elif device == 'BME680':
return BME680(address=address)
elif device == 'DS18B20':
return DS18B20(address=address)
elif device == 'CCS811':
return CCS811(address=address)
@staticmethod
def create_led(device, configuration, notification_manager):
if device == 'rgb':
return RGB(configuration=configuration, notification_manager=notification_manager)
| from src.Sensors.BME280 import BME280
from src.Sensors.BME680 import BME680
from src.Sensors.DS18B20 import DS18B20
from src.Notification.Subscriber.LED.RGB import RGB
class Factory:
@staticmethod
def create_sensor(device, address):
if device == 'BME280':
return BME280(address=address)
elif device == 'BME680':
return BME680(address=address)
elif device == 'DS18B20':
return DS18B20(address=address)
@staticmethod
def create_led(device, configuration, notification_manager):
if device == 'rgb':
return RGB(configuration=configuration, notification_manager=notification_manager)
|
Add local for htmlLang into template | module.exports = {
htmlLang: '{{htmlLang}}',
assetPath: '{{govukAssetPath}}',
afterHeader: '{{$afterHeader}}{{/afterHeader}}',
bodyClasses: '{{$bodyClasses}}{{/bodyClasses}}',
bodyEnd: '{{$bodyEnd}}{{/bodyEnd}}',
content: '{{$main}}{{/main}}',
cookieMessage: '{{$cookieMessage}}{{/cookieMessage}}',
footerSupportLinks: '{{$footerSupportLinks}}{{/footerSupportLinks}}',
footerTop: '{{$footerTop}}{{/footerTop}}',
head: '{{$head}}{{/head}}',
headerClass: '{{$headerClass}}{{/headerClass}}',
insideHeader: '{{$insideHeader}}{{/insideHeader}}',
pageTitle: '{{$pageTitle}}{{/pageTitle}}',
propositionHeader: '{{$propositionHeader}}{{/propositionHeader}}',
skipLinkMessage: '{{$skipLinkMessage}}Skip to main content{{/skipLinkMessage}}',
globalHeaderText: '{{$globalHeaderText}}GOV.UK{{/globalHeaderText}}',
licenceMessage: '{{$licenceMessage}}<p>All content is available under the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" rel="license">Open Government Licence v3.0</a>, except where otherwise stated</p>{{/licenceMessage}}',
crownCopyrightMessage: '{{$crownCopyrightMessage}}© Crown copyright{{/crownCopyrightMessage}}'
};
| module.exports = {
assetPath: '{{govukAssetPath}}',
afterHeader: '{{$afterHeader}}{{/afterHeader}}',
bodyClasses: '{{$bodyClasses}}{{/bodyClasses}}',
bodyEnd: '{{$bodyEnd}}{{/bodyEnd}}',
content: '{{$main}}{{/main}}',
cookieMessage: '{{$cookieMessage}}{{/cookieMessage}}',
footerSupportLinks: '{{$footerSupportLinks}}{{/footerSupportLinks}}',
footerTop: '{{$footerTop}}{{/footerTop}}',
head: '{{$head}}{{/head}}',
headerClass: '{{$headerClass}}{{/headerClass}}',
insideHeader: '{{$insideHeader}}{{/insideHeader}}',
pageTitle: '{{$pageTitle}}{{/pageTitle}}',
propositionHeader: '{{$propositionHeader}}{{/propositionHeader}}',
skipLinkMessage: '{{$skipLinkMessage}}Skip to main content{{/skipLinkMessage}}',
globalHeaderText: '{{$globalHeaderText}}GOV.UK{{/globalHeaderText}}',
licenceMessage: '{{$licenceMessage}}<p>All content is available under the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" rel="license">Open Government Licence v3.0</a>, except where otherwise stated</p>{{/licenceMessage}}',
crownCopyrightMessage: '{{$crownCopyrightMessage}}© Crown copyright{{/crownCopyrightMessage}}'
};
|
Allow loading code from a CGI parameter
Closes #62 | /* global process:false */
import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore, compose } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import persistState from 'redux-localstorage';
import url from 'url';
import { configureRustErrors } from './highlighting';
import { serialize, deserialize } from './local_storage';
import playgroundApp from './reducers';
import { gotoPosition, editCode, performGistLoad } from './actions';
import Playground from './Playground';
const mw = [thunk];
if (process.env.NODE_ENV !== 'production') {
mw.push(createLogger());
}
const middlewares = applyMiddleware(...mw);
const enhancers = compose(middlewares, persistState(undefined, { serialize, deserialize }));
const store = createStore(playgroundApp, enhancers);
configureRustErrors((line, col) => store.dispatch(gotoPosition(line, col)));
// Process query parameters
const urlObj = url.parse(window.location.href, true);
const query = urlObj.query;
if (query.code) {
store.dispatch(editCode(query.code));
} else if (query.gist) {
store.dispatch(performGistLoad(query.gist));
}
ReactDOM.render(
<Provider store={store}>
<Playground />
</Provider>,
document.getElementById('playground')
);
| /* global process:false */
import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore, compose } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import persistState from 'redux-localstorage';
import url from 'url';
import { configureRustErrors } from './highlighting';
import { serialize, deserialize } from './local_storage';
import playgroundApp from './reducers';
import { gotoPosition, performGistLoad } from './actions';
import Playground from './Playground';
const mw = [thunk];
if (process.env.NODE_ENV !== 'production') {
mw.push(createLogger());
}
const middlewares = applyMiddleware(...mw);
const enhancers = compose(middlewares, persistState(undefined, { serialize, deserialize }));
const store = createStore(playgroundApp, enhancers);
configureRustErrors((line, col) => store.dispatch(gotoPosition(line, col)));
// Process query parameters
const urlObj = url.parse(window.location.href, true);
const query = urlObj.query;
if (query.gist) {
store.dispatch(performGistLoad(query.gist));
}
ReactDOM.render(
<Provider store={store}>
<Playground />
</Provider>,
document.getElementById('playground')
);
|
Use a host specified in the config file. | <?php
include_once __DIR__ . '/_config.php';
function url_for($href, $abs = false)
{
$url = '';
if ($abs)
{
$url = 'http';
if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off'))
{
$url .= 's';
}
$url .= '://' . ENVIS_DOMAIN;
}
return $url . '/' . ltrim((strpos($href, ENVIS_BASE_URL) === 0 ? '' : ENVIS_BASE_URL) . ltrim($href, '/'), '/');
}
function url_for_media($href, $local = false)
{
if ($local)
{
return url_for('_static_/' . ltrim($href, '/'));
}
return ENVIS_MEDIA_URL . ltrim($href, '/');
}
| <?php
include_once __DIR__ . '/_config.php';
function url_for($href, $abs = false)
{
$url = '';
if ($abs)
{
$url = 'http';
if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off'))
{
$url .= 's';
}
$url .= '://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ENVIS_DOMAIN);
}
return $url . '/' . ltrim((strpos($href, ENVIS_BASE_URL) === 0 ? '' : ENVIS_BASE_URL) . ltrim($href, '/'), '/');
}
function url_for_media($href, $local = false)
{
if ($local)
{
return url_for('_static_/' . ltrim($href, '/'));
}
return ENVIS_MEDIA_URL . ltrim($href, '/');
}
|
Fix last namespace typos and casing (Rmiller -> RMiller) | <?php
namespace RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CommandRunner;
use RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder;
class CliFunctionChecker
{
/**
* @var \RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder
*/
private $executableFinder;
/**
* @param \RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder $executableFinder
*/
public function __construct(CachingExecutableFinder $executableFinder)
{
$this->executableFinder = $executableFinder;
}
/**
* @param string $function
*
* @return bool
*/
public function functionCanBeUsed($function)
{
return (php_sapi_name() == 'cli')
&& $this->executableFinder->getExecutablePath()
&& function_exists($function);
}
}
| <?php
namespace RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CommandRunner;
use RMiller\BehatSpec\Extension\PhpSpecRunExtension\Process\CachingExecutableFinder;
class CliFunctionChecker
{
/**
* @var \Rmiller\PhpSpecRunExtension\Process\CachingExecutableFinder
*/
private $executableFinder;
/**
* @param \Rmiller\PhpSpecRunExtension\Process\CachingExecutableFinder $executableFinder
*/
public function __construct(CachingExecutableFinder $executableFinder)
{
$this->executableFinder = $executableFinder;
}
/**
* @param string $function
*
* @return bool
*/
public function functionCanBeUsed($function)
{
return (php_sapi_name() == 'cli')
&& $this->executableFinder->getExecutablePath()
&& function_exists($function);
}
}
|
Allow admin to delete stuff (bugfix). | 'use strict'
module.exports = function (newDoc, oldDoc, userCtx, secObj) {
const ouch = (err) => { throw err }
const adminDelete = newDoc._deleted && userCtx.roles.indexOf('_admin') !== -1
if (userCtx.roles.indexOf('teacher') === -1 && userCtx.roles.indexOf('_admin') === -1) { ouch({ unauthorized: 'not a teacher' }) }
if (!adminDelete && userCtx.name !== newDoc.creator) { ouch({ forbidden: 'wrong creator' }) }
if (!adminDelete && !newDoc.createdAt) { ouch({ forbidden: 'missing field: createdAt' }) }
if (!adminDelete && oldDoc) {
if (!newDoc.updatedAt) { ouch({ forbidden: 'missing field: updatedAt' }) }
if (oldDoc.updatedAt >= newDoc.updatedAt) { ouch({ forbidden: 'field updatedAt went back in time' }) }
}
}
| 'use strict'
module.exports = function (newDoc, oldDoc, userCtx, secObj) {
const ouch = (err) => { throw err }
const adminDelete = newDoc._deleted && userCtx.roles.indexOf('_admin') -== -1
if (userCtx.roles.indexOf('teacher') === -1 && userCtx.roles.indexOf('_admin') === -1) { ouch({ unauthorized: 'not a teacher' }) }
if (!adminDelete && userCtx.name !== newDoc.creator) { ouch({ forbidden: 'wrong creator' }) }
if (!adminDelete && !newDoc.createdAt) { ouch({ forbidden: 'missing field: createdAt' }) }
if (!adminDelete && oldDoc) {
if (!newDoc.updatedAt) { ouch({ forbidden: 'missing field: updatedAt' }) }
if (oldDoc.updatedAt >= newDoc.updatedAt) { ouch({ forbidden: 'field updatedAt went back in time' }) }
}
}
|
Fix ember-flexberry blueprint delete dependencies | /* globals module */
module.exports = {
afterInstall: function() {
var _this = this;
return this.addBowerPackagesToProject([
{ name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
{ name: 'blueimp-file-upload', target: '9.11.2' },
{ name: 'devicejs', target: '0.2.7' },
{ name: 'localforage', target: '1.3.3' }
]).then(function() {
return _this.addAddonsToProject({
packages: [
{ name: 'semantic-ui-ember', target: '0.9.3' },
{ name: 'ember-moment', target: '6.0.0' },
{ name: 'ember-link-action', target: '0.0.34' },
{ name: 'broccoli-jscs', target: '1.2.2' },
'https://github.com/Flexberry/ember-localforage-adapter.git'
]
});
});
},
normalizeEntityName: function() {}
};
| /* globals module */
module.exports = {
afterInstall: function() {
var _this = this;
return this.addBowerPackagesToProject([
{ name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
{ name: 'blueimp-file-upload', target: '9.11.2' },
{ name: 'devicejs', target: '0.2.7' },
{ name: 'localforage', target: '1.3.3' }
]).then(function() {
return _this.addAddonsToProject({
packages: [
{ name: 'semantic-ui-ember', target: '0.9.3' },
{ name: 'ember-moment', target: '6.0.0' },
{ name: 'ember-link-action', target: '0.0.34' },
{ name: 'broccoli-jscs', target: '1.2.2' },
{ name: 'localforage', target: '1.3.3' },
'https://github.com/Flexberry/ember-localforage-adapter.git'
]
});
});
},
normalizeEntityName: function() {}
};
|
Test modified to use UI component instead of controller | describe('Actions triggered by buttons', function() {
var listController;
var listWidget;
beforeEach(function() {
listController = Application.getController('KR.controller.EntryController');
listWidget = listController.getEntriesList();
expect(listWidget).toBeDefined();
});
it('toggle table columns visibility', function() {
var columns = listWidget.columns;
var button = Ext.ComponentQuery.query('buttongroup > button') [0];
button.fireEvent('click', button);
var hiddenColumns = Ext.Array.filter(columns, function(elem) {
return elem.hidden;
});
expect(Ext.Array.pluck(hiddenColumns, 'dataIndex')).toBeArray([]);
button.fireEvent('click', button);
hiddenColumns = Ext.Array.filter(columns, function(elem) {
return elem.hidden;
});
expect(Ext.Array.pluck(hiddenColumns, 'dataIndex')).toBeArray(['cleartext_user', 'cleartext_password']);
button.fireEvent('click', button);
hiddenColumns = Ext.Array.filter(columns, function(elem) {
return elem.hidden;
});
expect(Ext.Array.pluck(hiddenColumns, 'dataIndex')).toBeArray([]);
});
});
| describe('Actions triggered by buttons', function() {
var listController;
var listWidget;
beforeEach(function() {
listController = Application.getController('KR.controller.EntryController');
listWidget = listController.getEntriesList();
expect(listWidget).toBeDefined();
});
it('toggle table columns visibility', function() {
var columns = listWidget.columns;
//var toolbar = Ext.widget('main').getDockedItems()[0];
listController.setColumnsVisible(false);
var hiddenColumns = Ext.Array.filter(columns, function(elem) {
return elem.hidden;
});
expect(Ext.Array.pluck(hiddenColumns, 'dataIndex')).toBeArray(['cleartext_user', 'cleartext_password']);
listController.setColumnsVisible(true);
hiddenColumns = Ext.Array.filter(columns, function(elem) {
return elem.hidden;
});
expect(Ext.Array.pluck(hiddenColumns, 'dataIndex')).toBeArray([]);
listController.setColumnsVisible(false);
hiddenColumns = Ext.Array.filter(columns, function(elem) {
return elem.hidden;
});
expect(Ext.Array.pluck(hiddenColumns, 'dataIndex')).toBeArray(['cleartext_user', 'cleartext_password']);
});
});
|
Convert refresh token correctly, fixes bad request error | import { atob } from 'Base64';
import { PrivateAPI } from '@r/private';
import Session from '../../app/models/Session';
import makeSessionFromData from './makeSessionFromData';
import setSessionCookies from './setSessionCookies';
import * as sessionActions from '../../app/actions/session';
export default async (ctx, dispatch, apiOptions) => {
// try to create a session from the existing cookie
// if the session is malformed somehow, the catch will trigger when trying
// to access it
const tokenCookie = ctx.cookies.get('token');
if (!tokenCookie) {
return;
}
const sessionData = JSON.parse(atob(tokenCookie));
let session = new Session(sessionData);
// if the session is invalid, try to use the refresh token to grab a new
// session.
if (!session.isValid) {
const data = await PrivateAPI.refreshToken(apiOptions, sessionData.refreshToken);
session = makeSessionFromData({ ...data, refresh_token: sessionData.refreshToken });
// don't forget to set the cookies with the new session, or the session
// will remain invalid the next time the page is fetched
setSessionCookies(ctx, session);
}
// push the session into the store
dispatch(sessionActions.setSession(session));
};
| import { atob } from 'Base64';
import { PrivateAPI } from '@r/private';
import Session from '../../app/models/Session';
import makeSessionFromData from './makeSessionFromData';
import setSessionCookies from './setSessionCookies';
import * as sessionActions from '../../app/actions/session';
export default async (ctx, dispatch, apiOptions) => {
// try to create a session from the existing cookie
// if the session is malformed somehow, the catch will trigger when trying
// to access it
const tokenCookie = ctx.cookies.get('token');
if (!tokenCookie) {
return;
}
const sessionData = JSON.parse(atob(tokenCookie));
let session = new Session(sessionData);
// if the session is invalid, try to use the refresh token to grab a new
// session.
if (!session.isValid) {
const data = await PrivateAPI.refreshToken(apiOptions, sessionData.refreshToken);
session = makeSessionFromData({ ...data, refreshToken: sessionData.refreshToken });
// don't forget to set the cookies with the new session, or the session
// will remain invalid the next time the page is fetched
setSessionCookies(ctx, session);
}
// push the session into the store
dispatch(sessionActions.setSession(session));
};
|
BUG/PERF: Fix and speedup pure-Python fallback for C filter. | try:
from _Cfilters import nullify_secondary_maxima
except ImportError:
import numpy as np
# Because of the way C imports work, nullify_secondary_maxima
# is *called*, as in nullify_secondary_maxima().
# For the pure Python variant, we do not want to call the function,
# so we make nullify_secondary_maxima a wrapper than returns
# the pure Python function that does the actual filtering.
def _filter(a):
target = a.size // 2
target_val = a[target]
if target_val == 0:
return 0 # speedup trivial case
if np.any(a[:target] > target_val):
return 0
if np.any(a[target + 1:] >= target_val):
return 0
return target_val
def nullify_secondary_maxima():
return _filter
| try:
from _Cfilters import nullify_secondary_maxima
except ImportError:
import numpy as np
# Because of the way C imports work, nullify_secondary_maxima
# is *called*, as in nullify_secondary_maxima().
# For the pure Python variant, we do not want to call the function,
# so we make nullify_secondary_maxima a wrapper than returns
# the pure Python function that does the actual filtering.
def _filter(a):
target = a.size // 2 + 1
target_val = a[target]
if np.any(a[:target] > target_val):
return 0
if np.any(a[target + 1:] >= target_val):
return 0
return target
def nullify_secondary_maxima():
return _filter
|
Update SessioHistoryListener to create a LinkedList | package org.chtijbug.drools.platform.core.droolslistener;
import org.chtijbug.drools.entity.history.HistoryEvent;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by nheron on 07/06/15.
*/
public class SessionHistoryListener implements PlatformHistoryListener{
private List<HistoryEvent> historyEvents= new LinkedList<>();
public SessionHistoryListener() {
}
public List<HistoryEvent> getHistoryEvents() {
return historyEvents;
}
@Override
public void shutdown() {
this.historyEvents.clear();
}
@Override
public void fireEvent(HistoryEvent newHistoryEvent) throws DroolsChtijbugException {
if (this.historyEvents!=null){
this.historyEvents.add(newHistoryEvent);
}
}
}
| package org.chtijbug.drools.platform.core.droolslistener;
import org.chtijbug.drools.entity.history.HistoryEvent;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nheron on 07/06/15.
*/
public class SessionHistoryListener implements PlatformHistoryListener{
private List<HistoryEvent> historyEvents= new ArrayList<>();
public SessionHistoryListener() {
}
public List<HistoryEvent> getHistoryEvents() {
return historyEvents;
}
@Override
public void shutdown() {
this.historyEvents.clear();
}
@Override
public void fireEvent(HistoryEvent newHistoryEvent) throws DroolsChtijbugException {
if (this.historyEvents!=null){
this.historyEvents.add(newHistoryEvent);
}
}
}
|
Add URL base for image URL endpoints. | module.exports = {
contacts : '2.0/contacts/',
favorites : '2.0/favorites/',
folders : '2.0/folders/',
groups : '2.0/groups/',
home : '2.0/home/',
imageUrls : '2.0/imageurls',
reports : '2.0/reports/',
search : '2.0/search/',
server : '2.0/serverinfo/',
sheets : '2.0/sheets/',
sights : '2.0/sights/',
templates : '2.0/templates/',
templatesPublic : '2.0/templates/public',
users : '2.0/users/',
webhooks : '2.0/webhooks/',
workspaces : '2.0/workspaces/'
};
| module.exports = {
contacts : '2.0/contacts/',
favorites : '2.0/favorites/',
folders : '2.0/folders/',
groups : '2.0/groups/',
home : '2.0/home/',
reports : '2.0/reports/',
search : '2.0/search/',
server : '2.0/serverinfo/',
sheets : '2.0/sheets/',
sights : '2.0/sights/',
templates : '2.0/templates/',
templatesPublic : '2.0/templates/public',
users : '2.0/users/',
webhooks : '2.0/webhooks/',
workspaces : '2.0/workspaces/'
};
|
Include simulate in development env | /* jshint node: true */
'use strict';
var path = require('path');
module.exports = {
name: 'ember-calendar',
included: function(app) {
this._super.included(app);
app.import(path.join(app.bowerDirectory, 'lodash/lodash.js'));
app.import(path.join(app.bowerDirectory, 'interact/interact.js'));
app.import(path.join(app.bowerDirectory, 'moment/moment.js'));
app.import(path.join(app.bowerDirectory, 'moment-timezone/builds/moment-timezone-with-data.js'));
app.import('vendor/ember-calendar/lodash.js', {
type: 'vendor',
exports: { 'lodash': ['default'] }
});
app.import('vendor/ember-calendar/interact.js', {
type: 'vendor',
exports: { 'interact': ['default'] }
});
if (app.env === 'test' || app.env === 'development') {
app.import(path.join(app.bowerDirectory, 'jquery-simulate/jquery.simulate.js'));
}
}
};
| /* jshint node: true */
'use strict';
var path = require('path');
module.exports = {
name: 'ember-calendar',
included: function(app) {
this._super.included(app);
app.import(path.join(app.bowerDirectory, 'lodash/lodash.js'));
app.import(path.join(app.bowerDirectory, 'interact/interact.js'));
app.import(path.join(app.bowerDirectory, 'moment/moment.js'));
app.import(path.join(app.bowerDirectory, 'moment-timezone/builds/moment-timezone-with-data.js'));
app.import('vendor/ember-calendar/lodash.js', {
type: 'vendor',
exports: { 'lodash': ['default'] }
});
app.import('vendor/ember-calendar/interact.js', {
type: 'vendor',
exports: { 'interact': ['default'] }
});
if (app.env === 'test') {
app.import(path.join(app.bowerDirectory, 'jquery-simulate/jquery.simulate.js'));
}
}
};
|
Update to not use Facade alias |
<?php
if (!function_exists('backend_router')) {
/**
* Retrieve router
*
* @author Casper Rasmussen <cr@nodes.dk>
*
* @return \Nodes\Backend\Routing\Router
*/
function backend_router()
{
return app('nodes.backend.router');
}
}
if (!function_exists('backend_router_pattern')) {
/**
* Match route by pattern
*
* @author Casper Rasmussen <cr@nodes.dk>
*
* @param string|array $patterns
* @return string
*/
function backend_router_pattern($patterns)
{
return app('nodes.backend.router')->pattern($patterns);
}
}
if (!function_exists('backend_router_alias')) {
/**
* Match route by pattern
*
* @author Casper Rasmussen <cr@nodes.dk>
*
* @param string|array $aliases
* @return string
*/
function backend_router_alias($aliases)
{
return app('nodes.backend.router')->alias($aliases);
}
}
| <?php
if (!function_exists('backend_router')) {
/**
* Retrieve router
*
* @author Casper Rasmussen <cr@nodes.dk>
*
* @return \Nodes\Backend\Routing\Router
*/
function backend_router()
{
return \NodesBackend::router();
}
}
if (!function_exists('backend_router_pattern')) {
/**
* Match route by pattern
*
* @author Casper Rasmussen <cr@nodes.dk>
*
* @param string|array $patterns
* @return string
*/
function backend_router_pattern($patterns)
{
return \NodesBackend::router()->pattern($patterns);
}
}
if (!function_exists('backend_router_alias')) {
/**
* Match route by pattern
*
* @author Casper Rasmussen <cr@nodes.dk>
*
* @param string|array $aliases
* @return string
*/
function backend_router_alias($aliases)
{
return \NodesBackend::router()->alias($aliases);
}
} |
Update time now 10 seconds. | function updateMeters()
{
x_cpu_usage(updateCPU);
x_mem_usage(updateMemory);
x_get_uptime(updateUptime);
x_get_pfstate(updateState);
window.setTimeout('updateMeters()', 10000);
}
function updateMemory(x)
{
document.getElementById("memusagemeter").value = x + '%';
document.getElementById("memwidtha").style.width = x + 'px';
document.getElementById("memwidthb").style.width = (100 - x) + 'px';
}
function updateCPU(x)
{
document.getElementById("cpumeter").value = x + '%';
document.getElementById("cpuwidtha").style.width = x + 'px';
document.getElementById("cpuwidthb").style.width = (100 - x) + 'px';
}
function updateUptime(x)
{
document.getElementById("uptime").value = x;
}
function updateState(x)
{
document.getElementById("pfstate").value = x;
}
window.setTimeout('updateMeters()', 10000); | function updateMeters()
{
x_cpu_usage(updateCPU);
x_mem_usage(updateMemory);
x_get_uptime(updateUptime);
x_get_pfstate(updateState);
window.setTimeout('updateMeters()', 1500);
}
function updateMemory(x)
{
document.getElementById("memusagemeter").value = x + '%';
document.getElementById("memwidtha").style.width = x + 'px';
document.getElementById("memwidthb").style.width = (100 - x) + 'px';
}
function updateCPU(x)
{
document.getElementById("cpumeter").value = x + '%';
document.getElementById("cpuwidtha").style.width = x + 'px';
document.getElementById("cpuwidthb").style.width = (100 - x) + 'px';
}
function updateUptime(x)
{
document.getElementById("uptime").value = x;
}
function updateState(x)
{
document.getElementById("pfstate").value = x;
}
window.setTimeout('updateMeters()', 1500); |
Fix input stream completing early | import { Observable } from 'rxjs/Observable'
import { of } from 'rxjs/observable/of'
import { merge } from 'rxjs/observable/merge'
import { delay } from 'rxjs/operator/delay'
import { takeUntil } from 'rxjs/operator/takeUntil'
import { share } from 'rxjs/operator/share'
const makeVirtualEmission = (scheduler, value, delay) => {
return new Observable(observer => {
scheduler.schedule(() => {
observer.next(value)
}, delay, value)
})
}
const makeVirtualStream = (scheduler, diagram) => {
const { emissions, completion } = diagram
const partials = emissions.map(({ x, d }) => (
makeVirtualEmission(scheduler, d, x)
))
const completion$ = of(null)::delay(completion, scheduler)
const emission$ = merge(...partials)
::takeUntil(completion$)
::share()
return emission$
}
export default makeVirtualStream
| import { Observable } from 'rxjs/Observable'
import { of } from 'rxjs/observable/of'
import { merge } from 'rxjs/observable/merge'
import { delay } from 'rxjs/operator/delay'
import { takeUntil } from 'rxjs/operator/takeUntil'
import { share } from 'rxjs/operator/share'
const makeVirtualEmission = (scheduler, value, delay) => {
return new Observable(observer => {
scheduler.schedule(() => {
observer.next(value)
observer.complete()
}, delay, value)
})
}
const makeVirtualStream = (scheduler, diagram) => {
const { emissions, completion } = diagram
const partials = emissions.map(({ x, d }) => (
makeVirtualEmission(scheduler, d, x)
))
const completion$ = of(null)::delay(completion, scheduler)
const emission$ = merge(...partials)
::takeUntil(completion$)
::share()
return emission$
}
export default makeVirtualStream
|
Fix version and classifiers tuple to list | from distutils.core import setup
setup(
name = 'pycolors2',
py_modules = ['colors',],
version = '0.0.4',
author = 'Chris Gilmer',
author_email = 'chris.gilmer@gmail.com',
maintainer = 'Chris Gilmer',
maintainer_email = 'chris.gilmer@gmail.com',
url = 'http://github.com/chrisgilmerproj/pycolors2',
license = 'MIT license',
description = """ Tool to color code python output """,
long_description = open('README.markdown').read(),
requires = [],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System',
'Topic :: Terminals',
'Topic :: Utilities',
],
)
| from distutils.core import setup
setup(
name = 'pycolors2',
py_modules = ['colors',],
version = '0.0.3',
author = 'Chris Gilmer',
author_email = 'chris.gilmer@gmail.com',
maintainer = 'Chris Gilmer',
maintainer_email = 'chris.gilmer@gmail.com',
url = 'http://github.com/chrisgilmerproj/pycolors2',
license = 'MIT license',
description = """ Tool to color code python output """,
long_description = open('README.markdown').read(),
requires = [],
classifiers = (
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System',
'Topic :: Terminals',
'Topic :: Utilities',
),
)
|
Add author to doctrine migrations | <?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20150920220909 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE post (identifier INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, gfycat_key VARCHAR(255) NOT NULL, base_url VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, author VARCHAR(255) NOT NULL, PRIMARY KEY(identifier)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE post');
}
}
| <?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20150920220909 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE post (identifier INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, gfycat_key VARCHAR(255) NOT NULL, base_url VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, PRIMARY KEY(identifier)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE post');
}
}
|
Stop the server configs from overwriting the global one | package config;
import heufybot.core.Logger;
import heufybot.utils.FileUtils;
import java.util.HashMap;
import org.yaml.snakeyaml.Yaml;
public class ServerConfig extends GlobalConfig
{
@SuppressWarnings("unchecked")
public void loadServerConfig(String fileName, HashMap<String, Object> globalSettings)
{
this.settings = (HashMap<String, Object>) globalSettings.clone();
if(fileName == null)
{
Logger.error("Config", "No seperate server configs found. Using the settings from the global config instead.");
return;
}
Yaml yaml = new Yaml();
String settingsYaml = FileUtils.readFile(fileName);
HashMap<String, Object> serverSettings = (HashMap<String, Object>) yaml.load(settingsYaml);
for(String setting : serverSettings.keySet())
{
settings.put(setting, serverSettings.get(setting));
}
}
} | package config;
import heufybot.core.Logger;
import heufybot.utils.FileUtils;
import java.util.HashMap;
import org.yaml.snakeyaml.Yaml;
public class ServerConfig extends GlobalConfig
{
@SuppressWarnings("unchecked")
public void loadServerConfig(String fileName, HashMap<String, Object> globalSettings)
{
this.settings = globalSettings;
if(fileName == null)
{
Logger.error("Config", "No seperate server configs found. Using the settings from the global config instead.");
return;
}
Yaml yaml = new Yaml();
String settingsYaml = FileUtils.readFile(fileName);
HashMap<String, Object> serverSettings = (HashMap<String, Object>) yaml.load(settingsYaml);
for(String setting : serverSettings.keySet())
{
settings.put(setting, serverSettings.get(setting));
}
}
} |
Add keypad and New comment | package emu
const (
memorySize = 4096
vramSize = 64 * 32
registersNumber = 16
stackSize = 16
)
// Chip8 is the main struct holding all data relevant to the emulator.
// This includes registers (V0 to VF, PC, etc.), ram and framebuffer.
type Chip8 struct {
I uint16
pc uint16
sp uint16
stack []uint16
V []uint8
memory []uint8
vram []uint8
keypad []uint8
delayt uint8
soundt uint8
}
// New initializes basic Chip8 data, but the emulator won't be in a runnable
// state until something is loaded.
func New() Chip8 {
return Chip8{
0,
0,
0,
make([]uint16, stackSize, stackSize),
make([]uint8, registersNumber, registersNumber),
make([]uint8, memorySize, memorySize),
make([]uint8, vramSize, vramSize),
make([]uint8, 16, 16),
0,
0,
}
}
| package emu
const (
memorySize = 4096
vramSize = 64 * 32
registersNumber = 16
stackSize = 16
)
// Chip8 is the main struct holding all data relevant to the emulator.
// This includes registers (V0 to VF, PC, etc.), ram and framebuffer.
type Chip8 struct {
I uint16
pc uint16
sp uint16
stack []uint16
V []uint8
memory []uint8
vram []uint8
delayt uint8
soundt uint8
}
func New() Chip8 {
return Chip8{
0,
0,
0,
make([]uint16, stackSize, stackSize),
make([]uint8, registersNumber, registersNumber),
make([]uint8, memorySize, memorySize),
make([]uint8, vramSize, vramSize),
0,
0,
}
}
|
Fix the syntax for catching multiple exceptions
Previously, this would only catch ImportError exceptions, due
to the way the amiguity described here:
http://legacy.python.org/dev/peps/pep-3110/#rationale
... is resolved. | from django.conf import settings
# Add to this list anything country-specific you want to be available
# through an import from pombola.country.
imports_and_defaults = (
('significant_positions_filter', lambda qs: qs),
)
# Note that one could do this without the dynamic import and use of
# globals() by switching on country names and importing * from each
# country specific module, as MapIt does. [1] I slightly prefer the
# version here since you can explicitly list the names to be imported,
# and provide a default value.
#
# [1] https://github.com/mysociety/mapit/blob/master/mapit/countries/__init__.py
for name_to_import, default_value in imports_and_defaults:
if settings.COUNTRY_APP:
try:
globals()[name_to_import] = \
getattr(__import__('pombola.' + settings.COUNTRY_APP + '.lib',
fromlist=[name_to_import]),
name_to_import)
except (ImportError, AttributeError):
globals()[name_to_import] = default_value
else:
globals()[name_to_import] = default_value
| from django.conf import settings
# Add to this list anything country-specific you want to be available
# through an import from pombola.country.
imports_and_defaults = (
('significant_positions_filter', lambda qs: qs),
)
# Note that one could do this without the dynamic import and use of
# globals() by switching on country names and importing * from each
# country specific module, as MapIt does. [1] I slightly prefer the
# version here since you can explicitly list the names to be imported,
# and provide a default value.
#
# [1] https://github.com/mysociety/mapit/blob/master/mapit/countries/__init__.py
for name_to_import, default_value in imports_and_defaults:
if settings.COUNTRY_APP:
try:
globals()[name_to_import] = \
getattr(__import__('pombola.' + settings.COUNTRY_APP + '.lib',
fromlist=[name_to_import]),
name_to_import)
except ImportError, AttributeError:
globals()[name_to_import] = default_value
else:
globals()[name_to_import] = default_value
|
Add padding to inline styles. | import React from 'react';
import Board from '../containers/board';
import { Grid, Row, Col } from 'react-flexbox-grid';
import BlackPieceStand from '../containers/blackPieceStand';
import WhitePieceStand from '../containers/whitePieceStand';
const App = () => {
return (
<div className="app" style={{padding: '4em'}}>
<Grid>
<Row center="xs">
<Col xs={1}>
<WhitePieceStand />
</Col>
<Col xs={6}>
<Board />
</Col>
<Col xs={1}>
<BlackPieceStand />
</Col>
</Row>
</Grid>
</div>
);
};
export default App;
| import React from 'react';
import Board from '../containers/board';
import { Grid, Row, Col } from 'react-flexbox-grid';
import BlackPieceStand from '../containers/blackPieceStand';
import WhitePieceStand from '../containers/whitePieceStand';
const App = () => {
return (
<div>
<Grid>
<Row center="xs">
<Col xs={1}>
<WhitePieceStand />
</Col>
<Col xs={6}>
<Board />
</Col>
<Col xs={1}>
<BlackPieceStand />
</Col>
</Row>
</Grid>
</div>
);
};
export default App;
|
Remove base svg from exported svg | import Ember from "ember";
var container = '<g transform="scale(%s)">%h</g>';
export default Ember.Mixin.create({
exportToSvg: function(){
var svg = this.$("svg").clone(),
width = +svg.find("desc.width")[0].innerHTML,
div = document.createElement("div"),
svgContent,
promise;
// clean up a little
svg.find("image.base").remove();
svg.find("defs").remove();
svg.find("desc").remove();
svg.find("#base-svg").remove();
div.appendChild(svg[0]);
svgContent = div.innerHTML;
svgContent = svgContent.replace(svgContent.match(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/)[0], "");
svgContent = svgContent.replace("</svg>", "");
promise = new Ember.RSVP.Promise(function(resolve, reject){
resolve(container.replace("%s", 1/width )
.replace("%h", svgContent) );
});
return promise;
}
});
| import Ember from "ember";
var container = '<g transform="scale(%s)">%h</g>';
export default Ember.Mixin.create({
exportToSvg: function(){
var svg = this.$("svg").clone(),
width = +svg.find("desc.width")[0].innerHTML,
div = document.createElement("div"),
svgContent,
promise;
// clean up a little
svg.find("image.base").remove();
svg.find("defs").remove();
svg.find("desc").remove();
div.appendChild(svg[0]);
svgContent = div.innerHTML;
svgContent = svgContent.replace(svgContent.match(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/)[0], "");
svgContent = svgContent.replace("</svg>", "");
promise = new Ember.RSVP.Promise(function(resolve, reject){
resolve(container.replace("%s", 1/width )
.replace("%h", svgContent) );
});
return promise;
}
});
|
Mark test as xfail since it requires a fork of pyregion | import os
import pytest
import numpy as np
from astropy import wcs
from astropy.io import fits
from .. import pvregions
def data_path(filename):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
return os.path.join(data_dir, filename)
@pytest.mark.xfail
def test_wcspath():
p1,p2 = pvregions.paths_from_regfile(data_path('tests.reg'))
w = wcs.WCS(fits.Header.fromtextfile(data_path('w51.hdr')))
p1.set_wcs(w)
shouldbe = (61.593585, 75.950471, 88.911616, 72.820463, 96.025686,
88.470505, 113.95314, 95.868707, 186.80123, 76.235017,
226.35546, 100.99054)
xy = (np.array(zip(shouldbe[::2],shouldbe[1::2])) - 1)
np.testing.assert_allclose(np.array((p1.xy)), xy, rtol=1e-5)
| from .. import pvregions
from astropy import wcs
from astropy.io import fits
import numpy as np
import os
def data_path(filename):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
return os.path.join(data_dir, filename)
def test_wcspath():
p1,p2 = pvregions.paths_from_regfile(data_path('tests.reg'))
w = wcs.WCS(fits.Header.fromtextfile(data_path('w51.hdr')))
p1.set_wcs(w)
shouldbe = (61.593585, 75.950471, 88.911616, 72.820463, 96.025686,
88.470505, 113.95314, 95.868707, 186.80123, 76.235017,
226.35546, 100.99054)
xy = (np.array(zip(shouldbe[::2],shouldbe[1::2])) - 1)
np.testing.assert_allclose(np.array((p1.xy)), xy, rtol=1e-5)
|
Fix up callbacks in jQuery | /*! [replace-name] v[replace-version] */
/***************************************************************************************************************************************************************
*
* mainNav function
*
* Horizontal list of links to key areas on the website. Usually located in the header.
*
**************************************************************************************************************************************************************/
/**
* The main nav jquery function to add attributes and event listeners
*
* Public functions are:
*/
$.fn.AUmainNav = function( callbacks ) {
$elements = this;
$callbacks = callbacks;
var mainNavObject = {
addListeners: function() {
// Toggle the menu
$( $elements )
.not( '.js-au-main-nav-rendered' )
.each( function( i, mainNav ) {
$( mainNav ).find( '.au-main-nav__toggle--open, .au-main-nav__toggle--close, .au-main-nav__overlay' )
.on( 'click', function() {
event.preventDefault();
// Get the speed
var speed = $( this ).closest( '.au-main-nav__content' ).attr( 'data-speed' );
// Run the open close toggle
AU.mainNav.Toggle( this, speed, $callbacks );
});
$( mainNav ).addClass( 'js-au-main-nav-rendered' );
});
return this;
},
};
mainNavObject
.addListeners();
return mainNavObject;
};
| /*! [replace-name] v[replace-version] */
/***************************************************************************************************************************************************************
*
* mainNav function
*
* Horizontal list of links to key areas on the website. Usually located in the header.
*
**************************************************************************************************************************************************************/
/**
* The main nav jquery function to add attributes and event listeners
*
* Public functions are:
*/
$.fn.AUmainNav = function( callbacks ) {
var mainNavObject = {
addListeners: function() {
// Toggle the menu
$( '.au-main-nav__toggle--open, .au-main-nav__toggle--close, .au-main-nav__overlay' )
.not( '.js-au-main-nav-rendered' )
.on( 'click', function() {
// Get the speed
var speed = $( this ).closest( '.au-main-nav__content' ).attr( 'data-speed' );
// Run the open close toggle
AU.mainNav.Toggle( this, speed, callbacks );
}).addClass( 'js-au-main-nav-rendered' );
return this;
},
};
mainNavObject
.addListeners();
return mainNavObject;
};
|
Remove some unused code that unnecessarily introduced depends
This should be regarded as an update to 9aa5b02e12a2287642a285541c43790a10d6444f
that removes unnecessary dependencies for the lqr.py example.
In the example provided by 9aa5b02e12a2287642a285541c43790a10d6444f
Python code was introduced that led to dependencies on NumPy and
the Python Control System Library (control), yet the state-feedback
gains were hard-coded. We will re-introduce these dependencies in the
next changeset, but having this checkpoint without them seems useful. | #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
class LQRController(rospy.Subscriber):
def __init__(self, intopic, outtopic):
rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state)
self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1)
def read_state(self, vs):
self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])]))
if __name__ == "__main__":
rospy.init_node("lqr", anonymous=True)
lqrc = LQRController("input", "output")
rospy.spin()
| #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
from control import lqr
import numpy as np
class LQRController(rospy.Subscriber):
def __init__(self, intopic, outtopic):
rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state)
self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1)
A = np.array([[0., 1, 0], [0,0,1], [0,0,0]])
B = np.array([[0.],[0],[1]])
Q = np.diag([1.,1,1])
R = np.diag([1.])
K, S, E = lqr(A,B,Q,R)
self.K = K
def read_state(self, vs):
self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])]))
if __name__ == "__main__":
rospy.init_node("lqr", anonymous=True)
lqrc = LQRController("input", "output")
rospy.spin()
|
Fix missing }} in stylesheet url
Woops. :^) | @extends ('layout')
@section ('title')
:: Dashboard
@endsection
@section ('stylesheets')
<link href="{{ URL::to('/public/css/admin.css') }}" rel="stylesheet">
@endsection
@section ('content')
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Dashboard</h2>
</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item">
<label>Number of admins:</label> {{ $admin_count }} <br>
<label>Number of users:</label> {{ $user_count }} <br>
</li>
</ul>
</div>
</div>
@endsection
| @extends ('layout')
@section ('title')
:: Dashboard
@endsection
@section ('stylesheets')
<link href="{{ URL::to('/public/css/admin.css') rel="stylesheet">
@endsection
@section ('content')
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Dashboard</h2>
</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item">
<label>Number of admins:</label> {{ $admin_count }} <br>
<label>Number of users:</label> {{ $user_count }} <br>
</li>
</ul>
</div>
</div>
@endsection
|
Load Backbone app on selective pages | <?php
function theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_script( 'jquery' );
wp_enqueue_style( 'bootstrap-css', get_stylesheet_directory_uri().'/bootstrap/css/bootstrap.css' );
wp_enqueue_script( 'bootstrap-js', get_stylesheet_directory_uri().'/bootstrap/js/bootstrap.js' );
wp_enqueue_script( 'backbone' );
if ( is_page( 'Participants', 'series' ) ) {
wp_enqueue_script( 'app-js', get_stylesheet_directory_uri().'/scripts/app.js' );
};
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css'
);
wp_enqueue_style('theme-extra',
get_stylesheet_directory_uri().'/styles/custom.less',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', 'theme_enqueue_scripts' );
/* Removes jQuery Migrate dependency console log */
add_action( 'wp_default_scripts', function( $scripts ) {
if ( ! empty( $scripts->registered['jquery'] ) ) {
$jquery_dependencies = $scripts->registered['jquery']->deps;
$scripts->registered['jquery']->deps = array_diff( $jquery_dependencies, array( 'jquery-migrate' ) );
}
} );
?> | <?php
function theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_script( 'jquery' );
wp_enqueue_style( 'bootstrap-css', get_stylesheet_directory_uri().'/bootstrap/css/bootstrap.css' );
wp_enqueue_script( 'bootstrap-js', get_stylesheet_directory_uri().'/bootstrap/js/bootstrap.js' );
wp_enqueue_script( 'backbone' );
wp_enqueue_script( 'app-js', get_stylesheet_directory_uri().'/scripts/app.js' );
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css'
);
wp_enqueue_style('theme-extra',
get_stylesheet_directory_uri().'/styles/custom.less',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', 'theme_enqueue_scripts' );
/* Removes jQuery Migrate dependency console log */
add_action( 'wp_default_scripts', function( $scripts ) {
if ( ! empty( $scripts->registered['jquery'] ) ) {
$jquery_dependencies = $scripts->registered['jquery']->deps;
$scripts->registered['jquery']->deps = array_diff( $jquery_dependencies, array( 'jquery-migrate' ) );
}
} );
?> |
Add Bitbucket to skipif marker reason | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError:
no_network = False
else:
no_network = True
# For some reason pytest incorrectly uses the first reason text regardless of
# which condition matches. Using a unified message for now
# travis_reason = 'Works locally with tox but fails on Travis.'
# no_network_reason = 'Needs a network connection to GitHub.'
reason = (
'Fails on Travis or else there is no network connection to '
'GitHub/Bitbucket.'
)
skipif_travis = pytest.mark.skipif(travis, reason=reason)
skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError:
no_network = False
else:
no_network = True
# For some reason pytest incorrectly uses the first reason text regardless of
# which condition matches. Using a unified message for now
# travis_reason = 'Works locally with tox but fails on Travis.'
# no_network_reason = 'Needs a network connection to GitHub.'
reason = 'Fails on Travis or else there is no network connection to GitHub'
skipif_travis = pytest.mark.skipif(travis, reason=reason)
skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
|
Update label sanitizer regex to add parenthesis | package com.todoist.model;
import java.util.regex.Pattern;
public class Sanitizers {
public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:@()";
public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";
public static final Pattern PROJECT_NAME_INVALID_PATTERN =
Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+");
public static final Pattern LABEL_NAME_INVALID_PATTERN =
Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+");
public static final Pattern FILTER_NAME_INVALID_PATTERN =
Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+");
public static final String REPLACEMENT = "_";
}
| package com.todoist.model;
import java.util.regex.Pattern;
public class Sanitizers {
public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:@";
public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";
public static final Pattern PROJECT_NAME_INVALID_PATTERN =
Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+");
public static final Pattern LABEL_NAME_INVALID_PATTERN =
Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+");
public static final Pattern FILTER_NAME_INVALID_PATTERN =
Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+");
public static final String REPLACEMENT = "_";
}
|
Disable reduceIndents on CSS optimization package to fix animation issues | // NOTE: this configuration file MUST NOT be loaded with `-p` or `--optimize-minimize` option.
// This option includes an implicit call to UglifyJsPlugin and LoaderOptionsPlugin. Instead,
// an explicit call is made in this file to these plugins with customized options that enables
// more control of the output bundle in order to fix unexpected behavior in old browsers.
const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const baseConfig = require('./webpack.base.config.js');
module.exports = merge(baseConfig, {
mode: 'production',
plugins: [
new webpack.DefinePlugin({
__IN_DEV__: JSON.stringify(false),
__ENV__: JSON.stringify('prod')
})
],
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: false,
parallel: true,
uglifyOptions: {
sourceMap: true,
keep_fnames: true,
output: {
ascii_only: true,
beautify: false
}
}
}),
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
zindex: false,
reduceIdents: false
}
})
]
}
});
| // NOTE: this configuration file MUST NOT be loaded with `-p` or `--optimize-minimize` option.
// This option includes an implicit call to UglifyJsPlugin and LoaderOptionsPlugin. Instead,
// an explicit call is made in this file to these plugins with customized options that enables
// more control of the output bundle in order to fix unexpected behavior in old browsers.
const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const baseConfig = require('./webpack.base.config.js');
module.exports = merge(baseConfig, {
mode: 'production',
plugins: [
new webpack.DefinePlugin({
__IN_DEV__: JSON.stringify(false),
__ENV__: JSON.stringify('prod')
})
],
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: false,
parallel: true,
uglifyOptions: {
sourceMap: true,
keep_fnames: true,
output: {
ascii_only: true,
beautify: false
}
}
}),
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
zindex: false
}
})
]
}
});
|
Make test name more accurate. | import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
moduleFor('controller:nodes.detail.files.provider.file', 'Unit | Controller | file', {
// Specify the other units that are required for this test.
needs: ['controller:nodes.detail.index']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
test('add a node tag', function(assert) {
var ctrl = this.subject();
ctrl.set('model', Ember.Object.create({tags: ['one']}));
ctrl.set('model.save', function() {return;});
ctrl.send('addATag', 'new tag');
assert.deepEqual(ctrl.model.get('tags'), ['one', 'new tag']);
});
test('remove a node tag', function(assert) {
var ctrl = this.subject();
ctrl.set('model', Ember.Object.create({tags: ['one', 'two']}));
ctrl.set('model.save', function() {return;});
ctrl.send('removeATag', 'one');
assert.deepEqual(ctrl.model.get('tags'), ['two']);
});
| import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
moduleFor('controller:nodes.detail.files.provider.file', 'Unit | Controller | file', {
// Specify the other units that are required for this test.
needs: ['controller:nodes.detail.index']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
test('add a file tag', function(assert) {
var ctrl = this.subject();
ctrl.set('model', Ember.Object.create({tags: ['one']}));
ctrl.set('model.save', function() {return;});
ctrl.send('addATag', 'new tag');
assert.deepEqual(ctrl.model.get('tags'), ['one', 'new tag']);
});
test('remove a file tag', function(assert) {
var ctrl = this.subject();
ctrl.set('model', Ember.Object.create({tags: ['one', 'two']}));
ctrl.set('model.save', function() {return;});
ctrl.send('removeATag', 'one');
assert.deepEqual(ctrl.model.get('tags'), ['two']);
});
|
Add missing dependency on six | """
Flask-Twilio
-------------
Make Twilio voice/SMS calls with Flask
"""
from setuptools import setup
exec(open('flask_twilio.py').readline())
setup(
name='Flask-Twilio',
version=__version__,
url='http://example.com/flask-twilio/',
license='BSD',
author='Leo Singer',
author_email='leo.singer@ligo.org',
description='Make Twilio voice/SMS calls with Flask',
long_description=__doc__,
py_modules=['flask_twilio'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'itsdangerous',
'Flask',
'six',
'twilio'
],
setup_requires=[
'pytest-runner',
],
tests_require=[
'pytest',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Telephony'
]
) | """
Flask-Twilio
-------------
Make Twilio voice/SMS calls with Flask
"""
from setuptools import setup
exec(open('flask_twilio.py').readline())
setup(
name='Flask-Twilio',
version=__version__,
url='http://example.com/flask-twilio/',
license='BSD',
author='Leo Singer',
author_email='leo.singer@ligo.org',
description='Make Twilio voice/SMS calls with Flask',
long_description=__doc__,
py_modules=['flask_twilio'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'itsdangerous',
'Flask',
'twilio'
],
setup_requires=[
'pytest-runner',
],
tests_require=[
'pytest',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Telephony'
]
) |
Add search get url test | package search_test
import (
"testing"
"github.com/wasanx25/sreq/search"
)
func TestNew(t *testing.T) {
actual := search.New("testK", "testS")
if actual.Keyword != "testK" {
t.Errorf("expected=%q, got=%q", "testK", actual.Keyword)
}
if actual.Sort != "testS" {
t.Errorf("expected=%q, got=%q", "testS", actual.Sort)
}
}
func TestGetURL(t *testing.T) {
s := search.New("testK", "testS")
expectedURL := "https://qiita.com/search?pagenation=0&q=testK&sort=testS"
actual := s.GetURL()
if actual != expectedURL {
t.Errorf("expected=%q, got=%q", expectedURL, actual)
}
}
func TestExec(t *testing.T) {
s := search.New("testK", "testS")
t.Run("return content", func(t *testing.T) {
actualC, actualE := s.Exec()
expectedContents := []*search.Content{}
var expectedError *error
if actualC != expectedContents {
t.Errorf("expected=%q, got=%q", expectedContents, actualC)
}
if actualE != expectedError {
t.Errorf("expected=%q, got=%q", expectedError, actualE)
}
})
}
| package search_test
import (
"testing"
"github.com/wasanx25/sreq/search"
)
func TestNew(t *testing.T) {
actual := search.New("testK", "testS")
if actual.Keyword != "testK" {
t.Errorf("expected=%q, got=%q", "testK", actual.Keyword)
}
if actual.Sort != "testS" {
t.Errorf("expected=%q, got=%q", "testS", actual.Sort)
}
}
func TestExec(t *testing.T) {
s := search.New("testK", "testS")
t.Run("return content", func(t *testing.T) {
actualC, actualE := s.Exec()
expectedContents := []*search.Content{}
var expectedError *error
if actualC != expectedContents {
t.Errorf("expected=%q, got=%q", expectedContents, actualC)
}
if actualE != expectedError {
t.Errorf("expected=%q, got=%q", expectedError, actualE)
}
})
}
|
Remove phantomjs fudge factor which is no longer necessary | var PubSub = require('pubsub-js');
var events = {
fonts: false,
leaflet: false
};
// Wait for webfonts to load
PubSub.subscribe('webfonts.active', function() {
events.fonts = true;
});
// Poll to see if Leaflet maps have loaded yet
// This doesn't expose an event so we have to manually wait and hope
// If leaflet ever exposes an event this could be refactored and the tests
// sped up significantly
var hasMap = (document.querySelectorAll('.map').length > 0);
setTimeout(function() {
events.leaflet = true;
}, (hasMap ? 10000 : 0))
// Wait for window load event
window.addEventListener('load', function() {
// Poll to see whether things have loaded yet
var poll = setInterval(function() {
// If things haven't loaded yet, go round again
if(!(events.leaflet && events.fonts)) {
return;
}
// Once things have loaded, stop polling
clearInterval(poll);
// And tell phantom to get on with it
if (typeof window.callPhantom === 'function') {
window.callPhantom('takeShot');
}
}, 100);
});
| var PubSub = require('pubsub-js');
var events = {
fonts: false,
leaflet: false
};
// Wait for webfonts to load
PubSub.subscribe('webfonts.active', function() {
events.fonts = true;
});
// Poll to see if Leaflet maps have loaded yet
// This doesn't expose an event so we have to manually wait and hope
// If leaflet ever exposes an event this could be refactored and the tests
// sped up significantly
var hasMap = (document.querySelectorAll('.map').length > 0);
setTimeout(function() {
events.leaflet = true;
}, (hasMap ? 10000 : 0))
// Wait for window load event
window.addEventListener('load', function() {
// Poll to see whether things have loaded yet
var poll = setInterval(function() {
// If things haven't loaded yet, go round again
if(!(events.leaflet && events.fonts)) {
return;
}
// Once things have loaded, stop polling
clearInterval(poll);
// And tell phantom to get on with it
// But give it an extra second of readiness fudge factor :-|
if (typeof window.callPhantom === 'function') {
setTimeout(function() {
window.callPhantom('takeShot');
}, 1000);
}
}, 100);
});
|
Add in a missing change from r67143 for print preview options.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/5334002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@67155 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('click', function(e) {
window.close();
});
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('noPrinter');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
| // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('click', function(e) {
window.close();
});
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('no-printer');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
|
Use console.error to print functional test errors
This allows them to show up in tap-dot output | var fs = require( 'fs' );
var path = require( 'path');
var tape = require( 'tape' );
var event_stream = require( 'event-stream' );
var deep = require( 'deep-diff' );
var importModule = require( '../lib/tasks/import' );
var basePath = path.resolve(__dirname);
var expectedPath = basePath + '/data/expected.json';
var inputFile = basePath + '/data/SG.zip';
tape('functional test importing Singapore', function(t) {
var sourceStream = fs.createReadStream(inputFile);
var expected = JSON.parse(fs.readFileSync(expectedPath));
var endStream = event_stream.writeArray(function(err, results) {
// uncomment this to write the actual results to the expected file
// make sure they look ok though. comma left off so jshint reminds you
// not to commit this line
//fs.writeFileSync(expectedPath, JSON.stringify(results, null, 2))
var diff = deep(expected, results);
if (diff) {
t.fail('expected and actual output are the same');
console.error(diff);
} else {
t.pass('expected and actual output are the same');
}
t.end();
});
var fakePeliasConfig = {
imports: {
geonames: {
adminLookup: false // its not currently feasible to do admin lookup in this test
}
}
};
importModule(sourceStream, endStream, fakePeliasConfig);
});
| var fs = require( 'fs' );
var path = require( 'path');
var tape = require( 'tape' );
var event_stream = require( 'event-stream' );
var deep = require( 'deep-diff' );
var importModule = require( '../lib/tasks/import' );
var basePath = path.resolve(__dirname);
var expectedPath = basePath + '/data/expected.json';
var inputFile = basePath + '/data/SG.zip';
tape('functional test importing Singapore', function(t) {
var sourceStream = fs.createReadStream(inputFile);
var expected = JSON.parse(fs.readFileSync(expectedPath));
var endStream = event_stream.writeArray(function(err, results) {
// uncomment this to write the actual results to the expected file
// make sure they look ok though. comma left off so jshint reminds you
// not to commit this line
//fs.writeFileSync(expectedPath, JSON.stringify(results, null, 2))
var diff = deep(expected, results);
if (diff) {
t.fail('expected and actual output are the same');
console.log(diff);
} else {
t.pass('expected and actual output are the same');
}
t.end();
});
var fakePeliasConfig = {
imports: {
geonames: {
adminLookup: false // its not currently feasible to do admin lookup in this test
}
}
};
importModule(sourceStream, endStream, fakePeliasConfig);
});
|
Use real message and address | /**
* text-message
* Service to send text message to summoners notifying
* them to do something more useful with their free time.
*
*/
// Twilio API creds
var API_KEY;
var AUTH_TOKEN;
var PHONE_NUMBER;
// Read the API Key
var KEY_FILE = require('./api_key.js');
if (!API_KEY) {
API_KEY = KEY_FILE.API_KEY;
AUTH_TOKEN = KEY_FILE.AUTH_TOKEN;
PHONE_NUMBER = KEY_FILE.PHONE_NUMBER;
}
// Create text message service
var twilio = require('twilio')(API_KEY, AUTH_TOKEN);
module.exports = TEXT_MESSAGE = {}; // expose the module
/**
* sendMessage {function}
* message {String}
* address {String}
*
* Send a text message to the specified address
*
*/
TEXT_MESSAGE.sendMessage = function(message, address, cb) {
client.messages.create({
body: message,
to: address,
from: PHONE_NUMBER,
}, function(err, message) {
console.log(message.sid);
});
};
| /**
* text-message
* Service to send text message to summoners notifying
* them to do something more useful with their free time.
*
*/
// Twilio API creds
var API_KEY;
var AUTH_TOKEN;
var PHONE_NUMBER;
// Read the API Key
var KEY_FILE = require('./api_key.js');
if (!API_KEY) {
API_KEY = KEY_FILE.API_KEY;
AUTH_TOKEN = KEY_FILE.AUTH_TOKEN;
PHONE_NUMBER = KEY_FILE.PHONE_NUMBER;
}
// Create text message service
var twilio = require('twilio')(API_KEY, AUTH_TOKEN);
module.exports = TEXT_MESSAGE = {}; // expose the module
/**
* sendMessage {function}
* message {String}
* address {String}
*
* Send a text message to the specified address
*
*/
TEXT_MESSAGE.sendMessage = function(message, address, cb) {
client.messages.create({
body: "Sent from twilio API",
to: '+16318276915',
from: PHONE_NUMBER,
}, function(err, message) {
console.log(message.sid);
});
};
|
Add average_roundoff to rounding base class. | '''
Created on Oct 6, 2013
@author: dmaust
'''
import math
class RounderBase(object):
'''
Abstract base class for rounding
'''
def __init__(self, precision=0):
'''
Constructor
'''
self.precision = precision
self.cumulative_error = 0
self.count = 0
def _get_fraction(self, x):
scale = 10.0**self.precision
scaled_x = x * scale
fraction = scaled_x - math.floor(scaled_x)
return fraction, scaled_x, scale
def _record_roundoff_error(self, x, result):
self.cumulative_error += result - x
self.count += 1
@property
def roundoff_error(self):
return self.cumulative_error
@property
def average_roundoff(self):
return self.cumulative_error / self.count
| '''
Created on Oct 6, 2013
@author: dmaust
'''
import math
class RounderBase(object):
'''
Abstract base class for rounding
'''
def __init__(self, precision=0):
'''
Constructor
'''
self.precision = precision
self.cumulative_error = 0
def _get_fraction(self, x):
scale = 10.0**self.precision
scaled_x = x * scale
fraction = scaled_x - math.floor(scaled_x)
return fraction, scaled_x, scale
def _record_roundoff_error(self, x, result):
self.cumulative_error += result - x
@property
def roundoff_error(self):
return self.cumulative_error |
Test formatting errors with log level being emitted
The test to ensure that formatting errors are handled properly was being
run using info level logging, but the default log configuration for
tests does not emit messages at that level, so switch to error.
Change-Id: Ie11a51deea65627b45a11d7dfca36d16c1b5949e | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.error,
'pid of first child is %(foo)s',
1)
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.info,
'pid of first child is %(foo)s',
1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.