text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change the Mongo index to also use the actual field (thanks Jason!)
|
'use strict';
function storage (collection, ctx) {
var ObjectID = require('mongodb').ObjectID;
function create (obj, fn) {
obj.created_at = (new Date( )).toISOString( );
api().insert(obj, function (err, doc) {
fn(null, doc);
});
}
function save (obj, fn) {
obj._id = new ObjectID(obj._id);
if (!obj.created_at) {
obj.created_at = (new Date( )).toISOString( );
}
api().save(obj, function (err) {
//id should be added for new docs
fn(err, obj);
});
}
function list (fn) {
return api( ).find({ }).sort({startDate: -1}).toArray(fn);
}
function last (fn) {
return api().find().sort({startDate: -1}).limit(1).toArray(fn);
}
function api () {
return ctx.store.db.collection(collection);
}
api.list = list;
api.create = create;
api.save = save;
api.last = last;
api.indexedFields = ['startDate'];
return api;
}
module.exports = storage;
|
'use strict';
function storage (collection, ctx) {
var ObjectID = require('mongodb').ObjectID;
function create (obj, fn) {
obj.created_at = (new Date( )).toISOString( );
api().insert(obj, function (err, doc) {
fn(null, doc);
});
}
function save (obj, fn) {
obj._id = new ObjectID(obj._id);
if (!obj.created_at) {
obj.created_at = (new Date( )).toISOString( );
}
api().save(obj, function (err) {
//id should be added for new docs
fn(err, obj);
});
}
function list (fn) {
return api( ).find({ }).sort({startDate: -1}).toArray(fn);
}
function last (fn) {
return api().find().sort({startDate: -1}).limit(1).toArray(fn);
}
function api () {
return ctx.store.db.collection(collection);
}
api.list = list;
api.create = create;
api.save = save;
api.last = last;
api.indexedFields = ['validfrom'];
return api;
}
module.exports = storage;
|
Bring back String u function
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Formatter;
use Behat\Transliterator\Transliterator;
use function Symfony\Component\String\u;
final class StringInflector
{
public static function codeToName(string $value): string
{
return ucfirst(str_replace('_', ' ', $value));
}
public static function nameToCode(string $value): string
{
return str_replace([' ', '-', '\''], '_', $value);
}
public static function nameToSlug(string $value): string
{
return str_replace(['_'], '-', self::nameToLowercaseCode(Transliterator::transliterate($value)));
}
public static function nameToLowercaseCode(string $value): string
{
return strtolower(self::nameToCode($value));
}
public static function nameToUppercaseCode(string $value): string
{
return strtoupper(self::nameToCode($value));
}
public static function nameToCamelCase(string $value): string
{
return (string) u($value)->camel();
}
private function __construct()
{
}
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Formatter;
use Behat\Transliterator\Transliterator;
final class StringInflector
{
public static function codeToName(string $value): string
{
return ucfirst(str_replace('_', ' ', $value));
}
public static function nameToCode(string $value): string
{
return str_replace([' ', '-', '\''], '_', $value);
}
public static function nameToSlug(string $value): string
{
return str_replace(['_'], '-', self::nameToLowercaseCode(Transliterator::transliterate($value)));
}
public static function nameToLowercaseCode(string $value): string
{
return strtolower(self::nameToCode($value));
}
public static function nameToUppercaseCode(string $value): string
{
return strtoupper(self::nameToCode($value));
}
public static function nameToCamelCase(string $value): string
{
return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $value))));
}
private function __construct()
{
}
}
|
Fix service provider for Laravel 5.4
Closes #17
|
<?php
namespace Sven\FlexEnv;
use Illuminate\Support\ServiceProvider;
class FlexEnvServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->commands([
Commands\SetEnv::class,
Commands\GetEnv::class,
Commands\DeleteEnv::class,
Commands\ListEnv::class,
]);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [
Commands\SetEnv::class,
Commands\GetEnv::class,
Commands\DeleteEnv::class,
Commands\ListEnv::class,
];
}
}
|
<?php
namespace Sven\FlexEnv;
use Illuminate\Support\ServiceProvider;
class FlexEnvServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->app['env:set'] = $this->app->share(function () {
return new Commands\SetEnv();
});
$this->app['env:get'] = $this->app->share(function () {
return new Commands\GetEnv();
});
$this->app['env:delete'] = $this->app->share(function () {
return new Commands\DeleteEnv();
});
$this->app['env:list'] = $this->app->share(function () {
return new Commands\ListEnv();
});
$this->commands(
'env:set',
'env:get',
'env:delete',
'env:list'
);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
|
Update org URL for issue linkage
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
'rst.linker',
]
# General information about the project.
project = 'pytest-runner'
copyright = '2015,2016 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
link_files = {
'CHANGES.rst': dict(
using=dict(
GH='https://github.com',
project=project,
),
replace=[
dict(
pattern=r"(Issue )?#(?P<issue>\d+)",
url='{GH}/pytest-dev/{project}/issues/{issue}',
),
dict(
pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n",
with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n",
),
],
),
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
'rst.linker',
]
# General information about the project.
project = 'pytest-runner'
copyright = '2015,2016 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
link_files = {
'CHANGES.rst': dict(
using=dict(
GH='https://github.com',
project=project,
),
replace=[
dict(
pattern=r"(Issue )?#(?P<issue>\d+)",
url='{GH}/jaraco/{project}/issues/{issue}',
),
dict(
pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n",
with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n",
),
],
),
}
|
Make processing option in SVG builder
|
var _ = require('lodash'),
combine = require('stream-combiner'),
loadGulpPlugins = require('gulp-load-plugins');
module.exports = function buildSVG(options) {
var gulpPlugins = loadGulpPlugins();
options = _.defaults({}, options, {
doProcessing: true,
doMinify: false,
concatName: 'override_me.svg',
svgStoreOptions: {},
svgMinOptions: {
plugins: [
{
cleanupIDs: false
},
{
removeUnknownsAndDefaults: {
defaultAttrs: false
}
}
]
},
minifyRenameOptions: {
extname: '.min.svg'
}
});
return combine(_.compact([
// Processing pipeline (concat all files and store as symbols, for inclusion in HTML body)
options.doProcessing && gulpPlugins.svgstore(options.svgStoreOptions),
options.doProcessing && gulpPlugins.rename(options.concatName),
// Productionization pipeline
options.doMinify && gulpPlugins.svgmin(options.svgMinOptions),
options.doMinify && gulpPlugins.rename(options.minifyRenameOptions)
]));
};
|
var _ = require('lodash'),
combine = require('stream-combiner'),
loadGulpPlugins = require('gulp-load-plugins');
module.exports = function buildSVG(options) {
var gulpPlugins = loadGulpPlugins();
options = _.defaults({}, options, {
doMinify: false,
concatName: 'override_me.svg',
svgStoreOptions: {},
svgMinOptions: {
plugins: [
{
cleanupIDs: false
},
{
removeUnknownsAndDefaults: {
defaultAttrs: false
}
}
]
},
minifyRenameOptions: {
extname: '.min.svg'
}
});
return combine(_.compact([
// Processing pipeline
gulpPlugins.svgstore(options.svgStoreOptions),
gulpPlugins.rename(options.concatName),
// Productionization pipeline
options.doMinify && gulpPlugins.svgmin(options.svgMinOptions),
options.doMinify && gulpPlugins.rename(options.minifyRenameOptions)
]));
};
|
Change mongo connection to read from process.env OR use localhost
|
var keystone = require('keystone');
keystone.init({
'name': 'Mottram Evangelical Church',
'favicon': 'public/favicon.ico',
'less': 'public',
'static': 'public',
'views': 'templates/views',
'view engine': 'jade',
'auto update': true,
'mongo': 'mongodb://'+ (process.env.MOTTRAM_CONFIG_MONGO_CON || 'localhost')+'/mottramec',
'session': true,
'auth': true,
'user model': 'User',
'cookie secret': process.env.MOTTRAM_CONFIG_COOKIE_SECRET,
's3 config': {
'key' : process.env.MOTTRAM_CONFIG_S3_KEY,
'secret' : process.env.MOTTRAM_CONFIG_S3_SECRET,
'bucket' : 'mottramec'
},
'cloudinary config': {
'cloud_name' : 'jamlen',
'api_key' : process.env.MOTTRAM_CONFIG_CLOUDINARY_KEY,
'api_secret' : process.env.MOTTRAM_CONFIG_CLOUDINARY_SECRET
}
});
require('./models');
keystone.set('routes', require('./routes'));
keystone.start();
|
var keystone = require('keystone');
keystone.init({
'name': 'Mottram Evangelical Church',
'favicon': 'public/favicon.ico',
'less': 'public',
'static': 'public',
'views': 'templates/views',
'view engine': 'jade',
'auto update': true,
'mongo': 'mongodb://localhost/mottramec',
'session': true,
'auth': true,
'user model': 'User',
'cookie secret': process.env.MOTTRAM_CONFIG_COOKIE_SECRET,
's3 config': {
'key' : process.env.MOTTRAM_CONFIG_S3_KEY,
'secret' : process.env.MOTTRAM_CONFIG_S3_SECRET,
'bucket' : 'mottramec'
},
'cloudinary config': {
'cloud_name' : 'jamlen',
'api_key' : process.env.MOTTRAM_CONFIG_CLOUDINARY_KEY,
'api_secret' : process.env.MOTTRAM_CONFIG_CLOUDINARY_SECRET
}
});
require('./models');
keystone.set('routes', require('./routes'));
keystone.start();
|
Correct for problem on webfaction
|
import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_command.sh') as f:
raw_command = f.read()
if lines:
subject = 'Tube delays for commute'
body = ', '.join(': '.join([line.capitalize(), s]) for line, s in status.items())
else:
subject = 'Good service for commute'
body = 'Good service on all lines'
# We must have this running on PythonAnywhere - Monday to Sunday.
# Ignore Saturday and Sunday
if datetime.date.today().isoweekday() in range(1, 6):
os.system(raw_command.format(subject=subject, body=body))
def main():
commute_lines = ['metropolitan', 'jubilee', 'central']
status = update()
delays = {c: status[c] for c in commute_lines if status[c] != 'Good Service'}
email(delays)
if __name__ == '__main__':
main()
|
import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription']
for el in resp}
def email(lines):
with open('curl_raw_command.sh') as f:
raw_command = f.read()
if lines:
subject = 'Tube delays for commute'
body = ', '.join(': '.join([line.capitalize(), s]) for line, s in status.items())
else:
subject = 'Good service for commute'
body = 'Good service on all lines'
# We must have this running on PythonAnywhere - Monday to Sunday.
# Ignore Saturday and Sunday
if datetime.date.today().isoweekday() in range(1, 6):
os.system(raw_command.format(subject=subject, body=body))
def main():
commute_lines = ['metropolitan', 'jubilee', 'central']
status = update()
delays = {c: status[c] for c in commute_lines if status[c] != 'Good Service'}
email(delays)
if __name__ == '__main__':
main()
|
Create more precise check of timeout
|
/*eslint-env mocha,node*/
var babel = require('babel-core');
var vm = require('vm');
var expect = chai.expect;
describe('babel.test.js', function () {
it('should work together with babel/register', function (done) {
var resolvedPath = require.resolve('./utils/babel.mock.js');
var result = babel.transformFileSync(resolvedPath, {
optional: 'runtime'
});
var childModule = {};
// evaluating module
vm.runInNewContext(result.code, {
require: require,
y: require('yield-yield'),
module: childModule,
setTimeout: setTimeout
});
childModule.exports(function (err, result) {
expect(err).to.be.not.ok;
expect(result >= 100).to.be.true;
return done();
});
});
});
|
/*eslint-env mocha,node*/
var babel = require('babel-core');
var vm = require('vm');
var expect = chai.expect;
describe('babel.test.js', function () {
it('should work together with babel/register', function (done) {
var resolvedPath = require.resolve('./utils/babel.mock.js');
var result = babel.transformFileSync(resolvedPath, {
optional: 'runtime'
});
var childModule = {};
// evaluating module
vm.runInNewContext(result.code, {
require: require,
y: require('yield-yield'),
module: childModule,
setTimeout: setTimeout
});
childModule.exports(function (err, result) {
expect(err).to.be.not.ok;
expect(result > 100).to.be.true;
return done();
});
});
});
|
Delete a function to save LOC
|
WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = 225 + name.length * 6.305555555555555;
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
|
function calcWidth(name) {
return 225 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
|
Add long description for PyPi.
|
#!/usr/bin/env python
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="delcom904x",
version="0.2.1",
description="A python class to control Delcom USBLMP Products 904x multi-color, USB, visual signal indicators",
long_description=long_description,
long_description_content_type="text/markdown",
author="Aaron Linville",
author_email="aaron@linville.org",
url="https://github.com/linville/delcom904x",
py_modules=["delcom904x"],
classifiers=[
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Topic :: System :: Hardware :: Hardware Drivers",
"License :: OSI Approved :: ISC License (ISCL)",
],
license="ISC",
install_requires=["hidapi"],
python_requires=">=3.5",
setup_requires=["wheel"],
scripts=['control_delcom904x.py'],
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="delcom904x",
version="0.2",
description="A python class to control Delcom USBLMP Products 904x multi-color, USB, visual signal indicators",
author="Aaron Linville",
author_email="aaron@linville.org",
url="https://github.com/linville/delcom904x",
py_modules=["delcom904x"],
classifiers=[
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Topic :: System :: Hardware :: Hardware Drivers",
"License :: OSI Approved :: ISC License (ISCL)",
],
license="ISC",
install_requires=["hidapi"],
python_requires=">=3.5",
setup_requires=["wheel"],
scripts=['control_delcom904x.py'],
)
|
Clear log tab timeout on unmount
|
import React from 'react'
import LogTabMutation from 'js/mutations/LogTabMutation'
import PropTypes from 'prop-types'
import { incrementTabsOpenedToday } from 'js/utils/local-user-data-mgr'
import logger from 'js/utils/logger'
class LogTabComponent extends React.Component {
constructor(props) {
super(props)
this.timer = null
}
componentDidMount() {
// Delay so that:
// * the user sees their VC increment
// * ads are more likely to have loaded
const LOG_TAB_DELAY = 1000
this.timer = setTimeout(() => {
LogTabMutation({
userId: this.props.user.id,
tabId: this.props.tabId,
}).catch(e => {
logger.error(e)
})
}, LOG_TAB_DELAY)
// Update today's tab count in localStorage.
// This is useful when making rendering decisions before
// we fetch user data from the server (e.g., whether we
// should show ads or not).
incrementTabsOpenedToday()
}
componentWillUnmount() {
if (this.timer) {
clearTimeout(this.timer)
}
}
render() {
return null
}
}
LogTabComponent.propTypes = {
user: PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired,
tabId: PropTypes.string.isRequired,
relay: PropTypes.shape({
environment: PropTypes.object.isRequired,
}),
}
export default LogTabComponent
|
import React from 'react'
import LogTabMutation from 'js/mutations/LogTabMutation'
import PropTypes from 'prop-types'
import { incrementTabsOpenedToday } from 'js/utils/local-user-data-mgr'
import logger from 'js/utils/logger'
class LogTabComponent extends React.Component {
componentDidMount() {
// Delay so that:
// * the user sees their VC increment
// * ads are more likely to have loaded
const LOG_TAB_DELAY = 1000
setTimeout(() => {
LogTabMutation({
userId: this.props.user.id,
tabId: this.props.tabId,
}).catch(e => {
logger.error(e)
})
}, LOG_TAB_DELAY)
// Update today's tab count in localStorage.
// This is useful when making rendering decisions before
// we fetch user data from the server (e.g., whether we
// should show ads or not).
incrementTabsOpenedToday()
}
render() {
return null
}
}
LogTabComponent.propTypes = {
user: PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired,
tabId: PropTypes.string.isRequired,
relay: PropTypes.shape({
environment: PropTypes.object.isRequired,
}),
}
export default LogTabComponent
|
Change exception message to be same as stdlib.
|
from __future__ import absolute_import, division, print_function
from fastpbkdf2._fastpbkdf2 import ffi, lib
def pbkdf2_hmac(name, password, salt, rounds, dklen=None):
if name not in ["sha1", "sha256", "sha512"]:
raise ValueError("unsupported hash type")
algorithm = {
"sha1": (lib.fastpbkdf2_hmac_sha1, 20),
"sha256": (lib.fastpbkdf2_hmac_sha256, 32),
"sha512": (lib.fastpbkdf2_hmac_sha512, 64),
}
out_length = dklen or algorithm[name][1]
out = ffi.new("uint8_t[]", out_length)
algorithm[name][0](
password, len(password),
salt, len(salt),
rounds,
out, out_length
)
return ffi.buffer(out)[:]
|
from __future__ import absolute_import, division, print_function
from fastpbkdf2._fastpbkdf2 import ffi, lib
def pbkdf2_hmac(name, password, salt, rounds, dklen=None):
if name not in ["sha1", "sha256", "sha512"]:
raise ValueError(
"Algorithm {} not supported. "
"Please use sha1, sha256 or sha512".format(name)
)
algorithm = {
"sha1": (lib.fastpbkdf2_hmac_sha1, 20),
"sha256": (lib.fastpbkdf2_hmac_sha256, 32),
"sha512": (lib.fastpbkdf2_hmac_sha512, 64),
}
out_length = dklen or algorithm[name][1]
out = ffi.new("uint8_t[]", out_length)
algorithm[name][0](
password, len(password),
salt, len(salt),
rounds,
out, out_length
)
return ffi.buffer(out)[:]
|
Fix @DaVinci789's crappy spelling >:)
|
import os
vowels = ['a e i o u'].split(' ')
consonants = ['b c d f g h j k l m n p q r s t v w x y z 1 2 3 4 \
5 6 7 8 9 0'].split(' ')
def inInventory(itemClass, player):
for item in player.inventory:
if isinstance(item, itemClass):
return True
break
return False
def getItemFromName(itemName, itemList, player):
for item in itemList:
if itemName == item.name:
return item
return False
def getIndefArticle(noun):
if noun[0] in vowels:
return 'an'
elif noun[0] in consonants:
return 'a'
def clrscn():
os.system("cls" if os.name == "nt" else "clear")
|
import os
vowels = ['a e i o u']
constanents = ['b c d f g h j k l m n p q r s t v w x y z 1 2 3 4 \
5 6 7 8 9 0']
def inInventory(itemClass, player):
for item in player.inventory:
if isinstance(item, itemClass):
return True
break
return False
def getItemFromName(itemName, itemList, player):
for item in itemList:
if itemName == item.name:
return item
return False
def getIndefArticle(noun):
if noun[0] in vowels.split(' '):
return 'an'
elif noun[0] in constanents.split(' '):
return 'a'
def clrscn():
os.system("cls" if os.name == "nt" else "clear")
|
Modify client to read the socket concurrently
|
import sys, time
import socket
import threading
class ReadThread(threading.Thread):
def __init__(self, sockobj):
super().__init__()
self.sockobj = sockobj
self.bufsize = 8 * 1024
def run(self):
while True:
buf = self.sockobj.recv(self.bufsize)
print('Received:', buf)
if b'1111' in buf:
break
def make_new_connection(name, host, port):
sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockobj.connect((host, port))
rthread = ReadThread(sockobj)
rthread.start()
sockobj.send(b'foo^1234$jo')
time.sleep(1.0)
sockobj.send(b'sdfsdfsdfsdf^a')
time.sleep(1.0)
sockobj.send(b'fkfkf0000$dfk^$sdf^a$^kk$')
time.sleep(1.0)
sockobj.close()
rthread.join()
def main():
if len(sys.argv) <= 2:
print("Error, expecting <host> <port>")
sys.exit(1)
host = sys.argv[1]
port = int(sys.argv[2])
make_new_connection("foo", host, port)
if __name__ == '__main__':
main()
|
import sys, time
import socket
def make_new_connection(name, host, port):
sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockobj.connect((host, port))
sockobj.send(b'foo^1234$jo')
sockobj.send(b'sdfsdfsdfsdf^a')
sockobj.send(b'fkfkf0000$dfk^$sdf^a$^kk$')
buf = b''
while True:
buf += sockobj.recv(1024)
print(buf)
sockobj.close()
def main():
if len(sys.argv) <= 2:
print("Error, expecting <host> <port>")
sys.exit(1)
host = sys.argv[1]
port = int(sys.argv[2])
make_new_connection("foo", host, port)
if __name__ == '__main__':
main()
|
Use find_packages to deal with vendoring
|
import multiprocessing # noqa # stop tests breaking tox
from setuptools import find_packages, setup
import tvrenamr
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online databases',
long_description=open('README.rst').read() + '\n\n' +
open('CHANGELOG.rst').read(),
author=tvrenamr.__author__,
author_email='george@ghickman.co.uk',
url='http://tvrenamr.info',
license='MIT',
packages=find_packages(exclude=['docs', 'tests']),
entry_points={'console_scripts': ['tvr=tvrenamr.frontend:run']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Utilities',
],
)
|
import multiprocessing # noqa # stop tests breaking tox
from setuptools import setup
import tvrenamr
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online databases',
long_description=open('README.rst').read() + '\n\n' +
open('CHANGELOG.rst').read(),
author=tvrenamr.__author__,
author_email='george@ghickman.co.uk',
url='http://tvrenamr.info',
license='MIT',
packages=['tvrenamr'],
entry_points={'console_scripts': ['tvr=tvrenamr.frontend:run']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Utilities',
],
)
|
[security][symfony] Fix fatal error on old symfony versions.
PHP Fatal error: Undefined class constant 'ABSOLUTE_URL' in ....
|
<?php
namespace Payum\Core\Bridge\Symfony\Security;
use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class TokenFactory extends AbstractGenericTokenFactory
{
/**
* @var \Symfony\Component\Routing\RouterInterface
*/
protected $urlGenerator;
/**
* @param UrlGeneratorInterface $urlGenerator
* @param StorageInterface $tokenStorage
* @param StorageRegistryInterface $storageRegistry
* @param string $capturePath
* @param string $notifyPath
*/
public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
{
$this->urlGenerator = $urlGenerator;
parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
}
/**
* @param string $path
* @param array $parameters
*
* @return string
*/
protected function generateUrl($path, array $parameters = array())
{
return $this->urlGenerator->generate($path, $parameters, true);
}
}
|
<?php
namespace Payum\Core\Bridge\Symfony\Security;
use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Security\TokenInterface;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class TokenFactory extends AbstractGenericTokenFactory
{
/**
* @var \Symfony\Component\Routing\RouterInterface
*/
protected $urlGenerator;
/**
* @param UrlGeneratorInterface $urlGenerator
* @param StorageInterface $tokenStorage
* @param StorageRegistryInterface $storageRegistry
* @param string $capturePath
* @param string $notifyPath
*/
public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
{
$this->urlGenerator = $urlGenerator;
parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
}
/**
* @param string $path
* @param array $parameters
*
* @return string
*/
protected function generateUrl($path, array $parameters = array())
{
return $this->urlGenerator->generate($path, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
}
}
|
Use a unique key for each screenshot
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { Component, PropTypes } from 'react';
import s from './Result.scss';
import withStyles from '../../decorators/withStyles';
@withStyles(s)
class Result extends Component {
constructor(props) {
super(props)
}
static propTypes = {
maxLines: PropTypes.number,
};
static defaultProps = {
maxLines: 1,
};
render() {
const result = this.props.result;
const key = result.episode + ':' + result.id
const minutes = Number(result.startTime.slice(3,5));
const seconds = Number(result.startTime.slice(6,8));
const index = (minutes * 60) + seconds;
const src = "http://localhost:8000/" + result.episode + "/" + index + ".jpg";
return <div key={key} style={{backgroundImage: 'url(' + src + ')', backgroundSize: 'cover', marginTop: 20, position: 'relative', width: '400px', height: '225px'}}>
<p style={{position: 'relative', textAlign: 'center', color: 'white'}}>{result.text}</p>
</div>
}
}
export default Result;
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { Component, PropTypes } from 'react';
import s from './Result.scss';
import withStyles from '../../decorators/withStyles';
@withStyles(s)
class Result extends Component {
constructor(props) {
super(props)
}
static propTypes = {
maxLines: PropTypes.number,
};
static defaultProps = {
maxLines: 1,
};
render() {
const result = this.props.result;
const minutes = Number(result.startTime.slice(3,5));
const seconds = Number(result.startTime.slice(6,8));
const index = (minutes * 60) + seconds;
const src = "http://localhost:8000/" + result.episode + "/" + index + ".jpg";
return <div key={result.id} style={{backgroundImage: 'url(' + src + ')', backgroundSize: 'cover', marginTop: 20, position: 'relative', width: '400px', height: '225px'}}>
<p style={{position: 'absolute', bottom: 0, textAlign: 'center', color: 'white'}}>{result.text}</p>
</div>
}
}
export default Result;
|
Support environment variables for the extraction
|
from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.environ.get(
"SE_DATABASE_STRING",
"postgresql://graph-node:let-me-in@localhost:5432/graph-node",
),
help="The database string for connections. Defaults to SE_DATABASE_STRING if set, otherwise a local graph-node",
)
@click.option(
"--output-location",
default=os.environ.get("SE_OUTPUT_LOCATION", "data"),
help="The base output location, whether local or cloud. Defaults to SE_OUTPUT_LOCATION if set, otherwise a folder called data",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob("*.yaml"):
extract_from_config(file_name, database_string, output_location)
if __name__ == "__main__":
export()
|
from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://graph-node:let-me-in@localhost:5432/graph-node",
help="The database string for connections, defaults to a local graph-node",
)
@click.option(
"--output-location",
default="data",
help="The base output location, whether local or cloud",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob('*.yaml'):
extract_from_config(
file_name,
database_string,
output_location
)
if __name__ == "__main__":
export()
|
Declare functions before using them
- retrieveItem was used before it was defined.
|
'use strict';
/**
* Retrieve nested item from object/array (http://stackoverflow.com/a/16190716)
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function retrieveItem(obj, path, def) {
var i, len;
for (i = 0, path = path.split('.'), len = path.length; i < len; i++) {
if (!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if (obj === undefined) return def;
return obj;
}
/**
* Retrieve a localized configuration value or the default if the localization
* is unavailable.
*
* @param {String} configuration value
* @param {String} language
* @param {Object} Hexo configuration object
* @param {String} Hexo data object
* @returns {*} localized or default configuration value
*/
exports._c = function _c(value, lang, config, data) {
var localized;
if (data['config_' + lang] !== null && data['config_' + lang] !== undefined) {
localized = retrieveItem(data['config_' + lang], value);
return localized !== undefined ? localized : retrieveItem(config, value);
}
return retrieveItem(config, value);
};
|
'use strict';
/**
* Retrieve a localized configuration value or the default if the localization
* is unavailable.
*
* @param {String} configuration value
* @param {String} language
* @param {Object} Hexo configuration object
* @param {String} Hexo data object
* @returns {*} localized or default configuration value
*/
exports._c = function _c(value, lang, config, data) {
var localized;
if (data['config_' + lang] !== null && data['config_' + lang] !== undefined) {
localized = retrieveItem(data['config_' + lang], value);
return localized !== undefined ? localized : retrieveItem(config, value);
}
return retrieveItem(config, value);
};
/**
* Retrieve nested item from object/array (http://stackoverflow.com/a/16190716)
* @param {Object|Array} obj
* @param {String} path dot separated
* @param {*} def default value ( if result undefined )
* @returns {*}
*/
function retrieveItem(obj, path, def) {
var i, len;
for (i = 0, path = path.split('.'), len = path.length; i < len; i++) {
if (!obj || typeof obj !== 'object') return def;
obj = obj[path[i]];
}
if (obj === undefined) return def;
return obj;
}
|
Fix try to load generators allowing raw object
|
var _ = require('lodash');
function tryToLoadGenerator(nameOrObject, lookupTable, thingKind) {
var parsed = parseNameOrObject(nameOrObject);
if (!parsed) {
return nameOrObject;
}
var thing = lookupTable[parsed.name];
if (!thing){
throw new Error('Failed to resolve ' + nameOrObject + ' ' + thingKind);
return;
}
if (typeof thing === 'function') {
return thing(parsed.options);
}
return thing;
}
function parseNameOrObject(nameOrObject) {
if (typeof nameOrObject === 'string') {
return { name: nameOrObject, options: {} };
}
if (typeof nameOrObject === 'object') {
var name = nameOrObject.generator;
if (typeof name === 'string') {
return { name, options: _.omit(nameOrObject, 'name') };
}
}
}
module.exports = {
tryToLoadGenerator
};
|
var _ = require('lodash');
function tryToLoadGenerator(nameOrObject, lookupTable, thingKind) {
var parsed = parseNameOrObject(nameOrObject);
if (!parsed) {
return nameOrObject;
}
var thing = lookupTable[parsed.name];
if (!thing){
throw new Error('Failed to resolve ' + nameOrObject + ' ' + thingKind);
return;
}
if (typeof thing === 'function') {
return thing(parsed.options);
}
return thing;
}
function parseNameOrObject(nameOrObject) {
if (typeof nameOrObject === 'string') {
return { name: nameOrObject, options: {} };
}
if (typeof nameOrObject === 'object') {
var name = nameOrObject.generator;
if (typeof name === 'string') {
return { name, options: _.omit(nameOrObject, 'name') };
}
}
return nameOrObject;
}
module.exports = {
tryToLoadGenerator
};
|
Define date in docs dynamically
Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
|
import datetime
import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = f"2016-{datetime.date.today().year}, {author}"
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.viewcode"
]
source_suffix = ".rst"
master_doc = "index"
language = None
exclude_patterns = ["build", "*.egg*"]
# Output options
html_theme = "sphinx_rtd_theme"
html_show_sphinx = False
html_baseurl = "pymanopt.org"
htmlhelp_basename = "pymanoptdoc"
html_last_updated_fmt = ""
# autodoc
autodoc_default_options = {
"member-order": "bysource",
"members": True,
"undoc-members": True,
"show-inheritance": True
}
|
import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = "2016-2021, {:s}".format(author)
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.viewcode"
]
source_suffix = ".rst"
master_doc = "index"
language = None
exclude_patterns = ["build", "*.egg*"]
# Output options
html_theme = "sphinx_rtd_theme"
html_show_sphinx = False
html_baseurl = "www.pymanopt.org"
htmlhelp_basename = "pymanoptdoc"
html_last_updated_fmt = ""
# autodoc
autodoc_default_options = {
"member-order": "bysource",
"members": True,
"undoc-members": True,
"show-inheritance": True
}
|
Add arguments to addCommand method
|
<?php
/**
* @file
* Contains Drupal\AppConsole\Command\Helper\ChainCommandHelper.
*/
namespace Drupal\AppConsole\Command\Helper;
use Symfony\Component\Console\Helper\Helper;
class ChainCommandHelper extends Helper
{
/** @var $commands array */
private $commands;
/**
* @param $name string
* @param $inputs array
* @param $interactive boolean
* @param $learning boolean
*/
public function addCommand($name, $inputs = [], $interactive = null, $learning = null)
{
$inputs['command'] = $name;
if (!is_null($learning)) {
$inputs['--learning'] = $learning;
}
$this->commands[] = ['name' => $name, 'inputs' => $inputs, 'interactive' => $interactive];
}
/**
* @return array
*/
public function getCommands()
{
return $this->commands;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'chain';
}
}
|
<?php
/**
* @file
* Contains Drupal\AppConsole\Command\Helper\ChainCommandHelper.
*/
namespace Drupal\AppConsole\Command\Helper;
use Symfony\Component\Console\Helper\Helper;
class ChainCommandHelper extends Helper
{
/** @var $commands array */
private $commands;
/**
* @param $name string
* @param $inputs array
*/
public function addCommand($name, $inputs = [])
{
array_unshift($inputs, ['command' => $name]);
$this->commands[] = ['name' => $name, 'inputs' => $inputs];
}
/**
* @return array
*/
public function getCommands()
{
return $this->commands;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'chain';
}
}
|
rkvd: Set logger time format to RFC3339Nano
|
package main
import (
"os"
"time"
"github.com/Sirupsen/logrus"
)
var defaultFormater = &logrus.TextFormatter{
DisableColors: true,
TimestampFormat: time.RFC3339Nano,
}
// LogToFileHook saves log entries to a file after applying the Formatter.
type LogToFileHook struct {
Formatter logrus.Formatter
LogFile *os.File
}
// NewLogToFileHook creates a new hook for logrus that logs all entries to a
// file. It uses a logrus.TextFormatter with DisableColors set to true. So your
// log files will be clean even though you have colors enabled in the terminal
// output.
func NewLogToFileHook(file *os.File) logrus.Hook {
return &LogToFileHook{
LogFile: file,
Formatter: defaultFormater,
}
}
// Fire implements logrus.Hook.
func (l *LogToFileHook) Fire(entry *logrus.Entry) error {
b, err := l.Formatter.Format(entry)
if err != nil {
return err
}
_, err = l.LogFile.Write(b)
return err
}
// Levels implements logrus.Hook.
func (l *LogToFileHook) Levels() []logrus.Level {
return logrus.AllLevels
}
|
package main
import (
"os"
"github.com/Sirupsen/logrus"
)
var defaultFormater = &logrus.TextFormatter{DisableColors: true}
// LogToFileHook saves log entries to a file after applying the Formatter.
type LogToFileHook struct {
Formatter logrus.Formatter
LogFile *os.File
}
// NewLogToFileHook creates a new hook for logrus that logs all entries to a
// file. It uses a logrus.TextFormatter with DisableColors set to true. So your
// log files will be clean even though you have colors enabled in the terminal
// output.
func NewLogToFileHook(file *os.File) logrus.Hook {
return &LogToFileHook{
LogFile: file,
Formatter: defaultFormater,
}
}
// Fire implements logrus.Hook.
func (l *LogToFileHook) Fire(entry *logrus.Entry) error {
b, err := l.Formatter.Format(entry)
if err != nil {
return err
}
_, err = l.LogFile.Write(b)
return err
}
// Levels implements logrus.Hook.
func (l *LogToFileHook) Levels() []logrus.Level {
return logrus.AllLevels
}
|
Add version number to egg, will it blend?
|
#!/usr/bin/env python
from distutils.core import setup
setup(
version='0.10',
name="amcatscraping",
description="Scrapers for AmCAT",
author="Wouter van Atteveldt, Martijn Bastiaan, Toon Alfrink",
author_email="wouter@vanatteveldt.com",
packages=["amcatscraping"],
classifiers=[
"License :: OSI Approved :: MIT License",
],
install_requires=[
"html2text",
"cssselect",
"pyamf",
"jinja2",
"django",
"docopt",
"lxml",
"amcatclient",
],
dependency_links = [
"https://github.com/amcat/amcatclient#egg=amcatclient-0.10",
]
)
|
#!/usr/bin/env python
from distutils.core import setup
setup(
version='0.10',
name="amcatscraping",
description="Scrapers for AmCAT",
author="Wouter van Atteveldt, Martijn Bastiaan, Toon Alfrink",
author_email="wouter@vanatteveldt.com",
packages=["amcatscraping"],
classifiers=[
"License :: OSI Approved :: MIT License",
],
install_requires=[
"html2text",
"cssselect",
"pyamf",
"jinja2",
"django",
"docopt",
"lxml",
"amcatclient",
],
dependency_links = [
"https://github.com/amcat/amcatclient#egg=amcatclient",
]
)
|
Fix RSVP.Promise overriding Promise in native promise detection.
|
/* globals Promise */
import { Promise as RSVPPromise } from 'rsvp';
export const nextTick =
typeof Promise === 'undefined' ? setTimeout : cb => Promise.resolve().then(cb);
export const futureTick = setTimeout;
/**
@private
@returns {Promise<void>} Promise which can not be forced to be ran synchronously
*/
export function nextTickPromise() {
return new RSVPPromise(resolve => {
nextTick(resolve);
});
}
/**
Retrieves an array of destroyables from the specified property on the object
provided, iterates that array invoking each function, then deleting the
property (clearing the array).
@private
@param {Object} object an object to search for the destroyable array within
@param {string} property the property on the object that contains the destroyable array
*/
export function runDestroyablesFor(object, property) {
let destroyables = object[property];
if (!destroyables) {
return;
}
for (let i = 0; i < destroyables.length; i++) {
destroyables[i]();
}
delete object[property];
}
/**
Returns whether the passed in string consists only of numeric characters.
@private
@param {string} n input string
@returns {boolean} whether the input string consists only of numeric characters
*/
export function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
|
import { Promise } from 'rsvp';
export const nextTick =
typeof Promise === 'undefined' ? setTimeout : cb => Promise.resolve().then(cb);
export const futureTick = setTimeout;
/**
@private
@returns {Promise<void>} promise which resolves on the next turn of the event loop
*/
export function nextTickPromise() {
return new Promise(resolve => {
nextTick(resolve);
});
}
/**
Retrieves an array of destroyables from the specified property on the object
provided, iterates that array invoking each function, then deleting the
property (clearing the array).
@private
@param {Object} object an object to search for the destroyable array within
@param {string} property the property on the object that contains the destroyable array
*/
export function runDestroyablesFor(object, property) {
let destroyables = object[property];
if (!destroyables) {
return;
}
for (let i = 0; i < destroyables.length; i++) {
destroyables[i]();
}
delete object[property];
}
/**
Returns whether the passed in string consists only of numeric characters.
@private
@param {string} n input string
@returns {boolean} whether the input string consists only of numeric characters
*/
export function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
|
tests/periph_rtt: Correct the test script syntax
Previously the test was failing due to apparently incorrect Python syntax in
the testrunner script. This fix corrects this and the test now passes.
|
#!/usr/bin/env python3
# Copyright (C) 2019 Inria
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
import sys
import time
from testrunner import run
PRECISION = 0.05 # 5%
MAX_HELLOS = 5
def testfunc(child):
child.expect(r'This test will display \'Hello\' every (\d+) seconds')
period = int(child.match.group(1))
child.expect_exact('Initializing the RTT driver')
child.expect(r'RTT now: \d+')
child.expect(r'Setting initial alarm to now \+ {} s \(\d+\)'
.format(period))
child.expect_exact('Done setting up the RTT, wait for many Hellos')
start = time.time()
for _ in range(MAX_HELLOS):
child.expect_exact('Hello\r\n', timeout=period + 1)
# Verify timings
elapsed = time.time() - start
assert elapsed > (MAX_HELLOS * period * (1 - PRECISION))
assert elapsed < (MAX_HELLOS * period * (1 + PRECISION))
if __name__ == "__main__":
sys.exit(run(testfunc))
|
#!/usr/bin/env python3
# Copyright (C) 2019 Inria
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
import sys
import time
from testrunner import run
PRECISION = 0.05 # 5%
MAX_HELLOS = 5
def testfunc(child):
child.expect(r'This test will display \'Hello\' every (\d+) seconds')
period = int(child.match[1])
child.expect_exact('Initializing the RTT driver')
child.expect(r'RTT now: \d+')
child.expect(r'Setting initial alarm to now \+ {} s \(\d+\)'
.format(period))
child.expect_exact('Done setting up the RTT, wait for many Hellos')
start = time.time()
for _ in range(MAX_HELLOS):
child.expect_exact('Hello\r\n', timeout=period + 1)
# Verify timings
elapsed = time.time() - start
assert elapsed > (MAX_HELLOS * period * (1 - PRECISION))
assert elapsed < (MAX_HELLOS * period * (1 + PRECISION))
if __name__ == "__main__":
sys.exit(run(testfunc))
|
Support promise emitter in memoizeWatcher
|
'use strict';
var noop = require('es5-ext/lib/Function/noop')
, extend = require('es5-ext/lib/Object/extend')
, memoize = require('memoizee')
, ee = require('event-emitter')
, deferred = require('deferred')
, isPromise = deferred.isPromise;
module.exports = function (fn/*, options*/) {
var factory, memoized;
memoized = memoize(fn, extend(Object(arguments[1]), { gc: true }));
factory = function () {
var watcher, emitter, pipe, args, def;
args = arguments;
watcher = memoized.apply(this, arguments);
if (isPromise(watcher)) {
def = deferred();
emitter = def.promise;
def.resolve(watcher);
} else {
emitter = ee();
}
pipe = ee.pipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.clearRef.apply(this, args)) {
watcher.close();
}
};
return emitter;
};
factory.clear = memoized.clear;
return factory;
};
|
'use strict';
var noop = require('es5-ext/lib/Function/noop')
, extend = require('es5-ext/lib/Object/extend')
, memoize = require('memoizee')
, ee = require('event-emitter')
module.exports = function (fn/*, options*/) {
var factory, memoized;
memoized = memoize(fn, extend(Object(arguments[1]), { gc: true }));
factory = function () {
var watcher, emitter, pipe, args;
args = arguments;
watcher = memoized.apply(this, arguments);
emitter = ee();
pipe = ee.pipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.clearRef.apply(this, args)) {
watcher.close();
}
};
return emitter;
};
factory.clear = memoized.clear;
return factory;
};
|
Update for changes in alchemist.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division
from armet.connectors.flask import resources as flask_resources
from armet.connectors.sqlalchemy import resources as sqlalchemy_resources
from armet import utils
from alchemist import db
__all__ = [
'Resource',
'ModelResource',
]
class Resource(flask_resources.Resource):
@property
def session(self):
return db.session
def route(self, *args, **kwargs):
try:
# Continue on with the cycle.
result = utils.super(Resource, self).route(*args, **kwargs)
# Commit the session.
db.session.commit()
# Return the result.
return result
except:
# Something occurred; rollback the session.
db.session.rollback()
# Re-raise the exception.
raise
class ModelResource(sqlalchemy_resources.ModelResource):
def route(self, *args, **kwargs):
return utils.super(sqlalchemy_resources.ModelResource, self).route(
*args, **kwargs)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division
from armet.connectors.flask import resources as flask_resources
from armet.connectors.sqlalchemy import resources as sqlalchemy_resources
from armet import utils
from alchemist import db
__all__ = [
'Resource',
'ModelResource',
]
class Resource(flask_resources.Resource):
@property
def session(self):
return db.session
def route(self, *args, **kwargs):
try:
# Continue on with the cycle.
result = utils.super(Resource, self).route(*args, **kwargs)
# Commit the session.
db.commit()
# Return the result.
return result
except:
# Something occurred; rollback the session.
db.rollback()
# Re-raise the exception.
raise
class ModelResource(sqlalchemy_resources.ModelResource):
def route(self, *args, **kwargs):
return utils.super(sqlalchemy_resources.ModelResource, self).route(
*args, **kwargs)
|
Use sha1() instead of sha256 in twig trait
sha256 may not be available, and security is not really a concern here
(it is just to make an identifier string from a "template" content...)
|
<?php
namespace Behapi\Context;
use Twig_Environment;
trait TwigTrait
{
/** @var Twig_Environment */
private $twig;
public function renderString(string $string, array $context = []): string
{
if (null === $this->twig) {
return $string;
}
$key = sprintf('__behapi_tpl__%s', sha1($string));
// this is assuming that the loader is Twig_Loader_Array
// as this was privately set in the initializer, it should be OK
// to assume that this is still a Twig_Loader_Array
$loader = $this->twig->getLoader();
$loader->setTemplate($key, $string);
return $this->twig->load($key)->render($context);
}
}
|
<?php
namespace Behapi\Context;
use Twig_Environment;
trait TwigTrait
{
/** @var Twig_Environment */
private $twig;
public function renderString(string $string, array $context = []): string
{
if (null === $this->twig) {
return $string;
}
$key = sprintf('__behapi_tpl__%s', hash('sha256', $string));
// this is assuming that the loader is Twig_Loader_Array
// as this was privately set in the initializer, it should be OK
// to assume that this is still a Twig_Loader_Array
$loader = $this->twig->getLoader();
$loader->setTemplate($key, $string);
return $this->twig->load($key)->render($context);
}
}
|
Update user model to the more secure version.
|
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
|
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier() {
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword() {
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail() {
return $this->email;
}
}
|
Return promise if callback isn't supplied
|
'use strict';
var _ = require('lodash');
var P = require('bluebird');
var DeserializerUtils = require('./deserializer-utils');
module.exports = function (opts) {
if (!opts) { opts = {}; }
this.deserialize = function (jsonapi, callback) {
function collection() {
return P
.map(jsonapi.data, function (d) {
return new DeserializerUtils(jsonapi, d, opts).perform();
})
.then(function (result) {
if (_.isFunction(callback)) {
callback(null, result);
}
return result
});
}
function resource() {
return new DeserializerUtils(jsonapi, jsonapi.data, opts)
.perform()
.then(function (result) {
if (_.isFunction(callback)) {
callback(null, result);
}
return result
});
}
if (_.isArray(jsonapi.data)) {
return collection();
} else {
return resource();
}
};
};
|
'use strict';
var _ = require('lodash');
var P = require('bluebird');
var DeserializerUtils = require('./deserializer-utils');
module.exports = function (opts) {
if (!opts) { opts = {}; }
this.deserialize = function (jsonapi, callback) {
function collection() {
return P
.map(jsonapi.data, function (d) {
return new DeserializerUtils(jsonapi, d, opts).perform();
})
.then(function (result) {
callback(null, result);
});
}
function resource() {
return new DeserializerUtils(jsonapi, jsonapi.data, opts)
.perform()
.then(function (result) {
callback(null, result);
});
}
if (_.isArray(jsonapi.data)) {
return collection();
} else {
return resource();
}
};
};
|
Delete unused fields to reduce response size
|
import firebase from '@/config/firebase-admin';
import Tipp from '@/models/TippAdmin';
const ref = firebase.database().ref('/tipps');
export const getTipps = (req, res) => {
ref.once('value', (snapshot) => {
const tippsSnapshot = snapshot.val();
if (!tippsSnapshot) return res.error('Database error');
const tipps = Object.keys(tippsSnapshot).map((key) => {
const tipp = tippsSnapshot[key];
delete tipp.id;
delete tipp.created;
delete tipp.approved;
delete tipp.country;
delete tipp.user.email;
delete tipp.user.emailVerified;
delete tipp.user.isAnonymous;
return tipp;
});
// Send tipps as array
return res.send(tipps);
});
}
export const postTipp = (req, res) => {
const tipp = new Tipp(req.body);
return tipp.set()
.then(() => {
res.send('ok');
})
.catch((err) => {
res.error(err);
});
};
|
import firebase from '@/config/firebase-admin';
import Tipp from '@/models/TippAdmin';
const ref = firebase.database().ref('/tipps');
export const getTipps = (req, res) => {
ref.once('value', (snapshot) => {
const tipps = snapshot.val();
if (!tipps) return res.error('Database error');
// Send tipps as array
return res.send(Object.keys(tipps).map(tipp => tipps[tipp]));
});
}
export const postTipp = (req, res) => {
const tipp = new Tipp(req.body);
return tipp.set()
.then(() => {
res.send('ok');
})
.catch((err) => {
res.error(err);
});
};
|
Add function to extract surface elevation from a 2D array of surface elevations
|
def readFVCOM(file, varList, noisy=False):
"""
Read in the FVCOM results file and spit out numpy arrays for
each of the variables.
"""
from netCDF4 import Dataset, MFDataset
rootgrp = Dataset(file, 'r')
mfdata = MFDataset(file)
if noisy:
print "File format: " + rootgrp.file_format
FVCOM = {}
for key, var in rootgrp.variables.items():
if noisy:
print 'Found ' + key,
if key in varList:
if noisy:
print '(extracted)'
FVCOM[key] = mfdata.variables[key][:]
else:
if noisy:
print
return FVCOM
def getSurfaceElevation(Z, idx):
"""
Extract the surface elevation from Z at index ind. If ind is multiple
values, extract and return the surface elevations at all those locations.
Z is usually extracted from the dict created when using readFVCOM() on a
NetCDF file.
"""
import numpy as np
nt, nx = np.shape(Z)
surfaceElevation = np.empty([nt,np.shape(idx)[0]])
for cnt, i in enumerate(idx):
surfaceElevation[:,cnt] = Z[:,i]
return surfaceElevation
|
from netCDF4 import Dataset, MFDataset
def readFVCOM(file, varList, noisy=False):
"""
Read in the FVCOM results file and spit out numpy arrays for
each of the variables.
"""
rootgrp = Dataset(file, 'r')
mfdata = MFDataset(file)
if noisy:
print "File format: " + rootgrp.file_format
FVCOM = {}
for key, var in rootgrp.variables.items():
if noisy:
print 'Found ' + key,
if key in varList:
if noisy:
print '(extracted)'
FVCOM[key] = mfdata.variables[key][:]
else:
if noisy:
print
return FVCOM
|
Add list with list test.
|
import pytest
from eche.reader import read_str
from eche.printer import print_str
import math
@pytest.mark.parametrize("test_input", [
'1',
'-1',
'0',
str(math.pi),
str(math.e)
])
def test_numbers(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'*',
'+',
'abc',
'test1',
'abc-def',
])
def test_eche_type_symbol(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'((9 8))',
'()',
'(* 1 2)',
'(+ (* 1 5) (/ 1 0))'
])
def test_eche_type_list(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'nil',
])
def test_nil(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'true',
'false',
])
def test_bool(test_input):
assert print_str(read_str(test_input)) == test_input
|
import pytest
from eche.reader import read_str
from eche.printer import print_str
import math
@pytest.mark.parametrize("test_input", [
'1',
'-1',
'0',
str(math.pi),
str(math.e)
])
def test_numbers(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'*',
'+',
'abc',
'test1',
'abc-def',
])
def test_eche_type_symbol(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'()',
'(* 1 2)',
'(+ (* 1 5) (/ 1 0))'
])
def test_eche_type_list(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'nil',
])
def test_nil(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("test_input", [
'true',
'false',
])
def test_bool(test_input):
assert print_str(read_str(test_input)) == test_input
|
[DOC] Add documentation link for Flagged Revisions
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@39878 b456876b-0849-0410-b77d-98878d47e9d5
|
<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
function prefs_flaggedrev_list()
{
return array(
'flaggedrev_approval' => array(
'name' => tra('Revision Approval'),
'description' => tra('Uses flagged revisions to hide unapproved wiki page revisions from users with lower privileges.'),
'type' => 'flag',
'perspective' => false,
'default' => 'n',
'help' => 'Flagged Revisions',
),
'flaggedrev_approval_categories' => array(
'name' => tra('Revision Approval Categories'),
'description' => tra('List of categories on which revision approval is required.'),
'type' => 'text',
'filter' => 'int',
'separator' => ';',
'dependencies' => array(
'feature_categories',
),
'default' => array(''), //empty string needed to keep preference from setting unexpectedly
),
);
}
|
<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
function prefs_flaggedrev_list()
{
return array(
'flaggedrev_approval' => array(
'name' => tra('Revision Approval'),
'description' => tra('Uses flagged revisions to hide unapproved wiki page revisions from users with lower privileges.'),
'type' => 'flag',
'perspective' => false,
'default' => 'n',
),
'flaggedrev_approval_categories' => array(
'name' => tra('Revision Approval Categories'),
'description' => tra('List of categories on which revision approval is required.'),
'type' => 'text',
'filter' => 'int',
'separator' => ';',
'dependencies' => array(
'feature_categories',
),
'default' => array(''), //empty string needed to keep preference from setting unexpectedly
),
);
}
|
Fix for flake8 checks on new test file.
|
from nose.tools import assert_equal, assert_true, assert_false
from vispy.testing import assert_in, run_tests_if_main
from vispy.app import set_interactive
from vispy.ext.ipy_inputhook import inputhook_manager
# Expect the inputhook_manager to set boolean `_in_event_loop`
# on instances of this class when enabled.
class MockApp(object):
pass
def test_interactive():
f = MockApp()
set_interactive(enabled=True, app=f)
assert_equal('vispy', inputhook_manager._current_gui)
assert_true(f._in_event_loop)
assert_in('vispy', inputhook_manager.apps)
assert_equal(f, inputhook_manager.apps['vispy'])
set_interactive(enabled=False)
assert_equal(None, inputhook_manager._current_gui)
assert_false(f._in_event_loop)
run_tests_if_main()
|
from nose.tools import assert_equal, assert_true, assert_false, assert_raises
from vispy.testing import assert_in, run_tests_if_main
from vispy.app import set_interactive
from vispy.ext.ipy_inputhook import inputhook_manager
# Expect the inputhook_manager to set boolean `_in_event_loop`
# on instances of this class when enabled.
class MockApp(object):
pass
def test_interactive():
f = MockApp()
set_interactive(enabled=True, app=f)
assert_equal('vispy', inputhook_manager._current_gui)
assert_true(f._in_event_loop)
assert_in('vispy', inputhook_manager.apps)
assert_equal(f, inputhook_manager.apps['vispy'])
set_interactive(enabled=False)
assert_equal(None, inputhook_manager._current_gui)
assert_false(f._in_event_loop)
run_tests_if_main()
|
Switch to to use instead of
|
class MainController {
constructor($scope) {
'ngInject';
this.locations = [];
this.$scope = $scope;
}
addMarker(form) {
ymaps.geocode(form.location).then((res) => {
let geoObj = res.geoObjects.get(0);
if(!geoObj)
{
console.log('ERR: location is not found!');
return;
}
this.$scope.$apply(() => {
this.locations.push({
name: geoObj.properties.get('name'),
text: geoObj.properties.get('text'),
coordinates: geoObj.geometry.getCoordinates()
});
});
});
form.location = "";
}
removeMarker(index) {
this.locations.splice(index, 1);
}
}
export default MainController;
|
class MainController {
constructor($scope) {
'ngInject';
this.locations = [];
this.$scope = $scope;
}
addMarker(form) {
ymaps.geocode(form.location).then((res) => {
let geoObj = res.geoObjects.get(0);
if(!geoObj)
{
console.log('ERR: location is not found!');
return;
}
this.locations.push({
name: geoObj.properties.get('name'),
text: geoObj.properties.get('text'),
coordinates: geoObj.geometry.getCoordinates()
});
this.$scope.$apply();
});
form.location = "";
}
removeMarker(index) {
this.locations.splice(index, 1);
}
}
export default MainController;
|
Disable JHU kpoint generationt test.
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import unittest
import requests
from pymatgen.ext.jhu import get_kpoints
from pymatgen.io.vasp.inputs import Incar
from pymatgen.io.vasp.sets import MPRelaxSet
from pymatgen.util.testing import PymatgenTest
__author__ = "Joseph Montoya"
__copyright__ = "Copyright 2017, The Materials Project"
__maintainer__ = "Joseph Montoya"
__email__ = "montoyjh@lbl.gov"
__date__ = "June 22, 2017"
website_is_up = requests.get("http://muellergroup.jhu.edu:8080").status_code == 200
@unittest.skipIf(True, "This code is way too buggy to be tested.")
class JhuTest(PymatgenTest):
_multiprocess_shared_ = True
def test_get_kpoints(self):
si = PymatgenTest.get_structure("Si")
input_set = MPRelaxSet(si)
kpoints = get_kpoints(si, incar=input_set.incar)
if __name__ == "__main__":
unittest.main()
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import unittest
import requests
from pymatgen.ext.jhu import get_kpoints
from pymatgen.io.vasp.inputs import Incar
from pymatgen.io.vasp.sets import MPRelaxSet
from pymatgen.util.testing import PymatgenTest
__author__ = "Joseph Montoya"
__copyright__ = "Copyright 2017, The Materials Project"
__maintainer__ = "Joseph Montoya"
__email__ = "montoyjh@lbl.gov"
__date__ = "June 22, 2017"
website_is_up = requests.get("http://muellergroup.jhu.edu:8080").status_code == 200
@unittest.skipIf(not website_is_up, "http://muellergroup.jhu.edu:8080 is down.")
class JhuTest(PymatgenTest):
_multiprocess_shared_ = True
def test_get_kpoints(self):
si = PymatgenTest.get_structure("Si")
input_set = MPRelaxSet(si)
kpoints = get_kpoints(si, incar=input_set.incar)
if __name__ == "__main__":
unittest.main()
|
Add support for private fields
A field name accepts a single underscore prefix to indicate it’s private.
Private fields can only be used in a PrimaryCondition and are simple ignored for user-input.
|
<?php
declare(strict_types=1);
/*
* This file is part of the RollerworksSearch package.
*
* (c) Sebastiaan Stok <s.stok@rollerscapes.net>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Rollerworks\Component\Search\ApiPlatform\Tests\Mock;
use Rollerworks\Component\Search\ApiPlatform\Tests\Fixtures\BookFieldSet;
use Rollerworks\Component\Search\Field\FieldConfig;
use Rollerworks\Component\Search\FieldSet;
final class FieldSetStub implements FieldSet
{
public function getSetName(): ?string
{
return BookFieldSet::class;
}
public function get(string $name): FieldConfig
{
}
public function all(): array
{
return [];
}
public function has(string $name): bool
{
return false;
}
public function isPrivate(string $name): bool
{
return '_' === $name[0];
}
}
|
<?php
declare(strict_types=1);
/*
* This file is part of the RollerworksSearch package.
*
* (c) Sebastiaan Stok <s.stok@rollerscapes.net>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Rollerworks\Component\Search\ApiPlatform\Tests\Mock;
use Rollerworks\Component\Search\ApiPlatform\Tests\Fixtures\BookFieldSet;
use Rollerworks\Component\Search\Field\FieldConfig;
use Rollerworks\Component\Search\FieldSet;
final class FieldSetStub implements FieldSet
{
public function getSetName(): ?string
{
return BookFieldSet::class;
}
public function get(string $name): FieldConfig
{
}
public function all(): array
{
return [];
}
public function has(string $name): bool
{
return false;
}
}
|
Remove version requirement for numpy
|
#!/usr/bin/env python
# coding=utf-8
from setuptools import setup, find_packages
import os
def find_scripts(scriptdir):
"""scrape all available scripts from 'bin' folder"""
return [os.path.join(scriptdir, s) for s in os.listdir(scriptdir) if not s.endswith(".pyc")]
setup(
name = "veros",
version = "0.0.1b0",
packages = find_packages(),
install_requires = [
"numpy",
"scipy",
"netCDF4",
"h5py",
"pillow"
],
author = "Dion Häfner (NBI Copenhagen)",
author_email = "dion.haefner@nbi.ku.dk",
scripts = find_scripts("bin")
)
|
#!/usr/bin/env python
# coding=utf-8
from setuptools import setup, find_packages
import os
def find_scripts(scriptdir):
"""scrape all available scripts from 'bin' folder"""
return [os.path.join(scriptdir, s) for s in os.listdir(scriptdir) if not s.endswith(".pyc")]
setup(
name = "veros",
version = "0.0.1b0",
packages = find_packages(),
install_requires = [
"numpy<1.12",
"scipy",
"netCDF4",
"h5py",
"pillow"
],
author = "Dion Häfner (NBI Copenhagen)",
author_email = "dion.haefner@nbi.ku.dk",
scripts = find_scripts("bin")
)
|
Make use of chai's lengthOf assertion and simplify test
|
import React from 'react';
import {Segment, Segments} from 'stardust';
describe('Segments', () => {
it('should render children', () => {
const [segmentOne, segmentTwo] = render(
<Segments>
<Segment>Top</Segment>
<Segment>Bottom</Segment>
</Segments>
).scryClass('sd-segment');
segmentOne
.textContent
.should.equal('Top');
segmentTwo
.textContent
.should.equal('Bottom');
});
it('renders expected number of children', () => {
render(
<Segments>
<Segment>Top</Segment>
<Segment>Middle</Segment>
<Segment>Bottom</Segment>
</Segments>
)
.scryClass('sd-segment')
.should.have.a.lengthOf(3);
});
});
|
import React from 'react';
import {Segment, Segments} from 'stardust';
describe('Segments', () => {
it('should render children', () => {
const [segmentOne, segmentTwo] = render(
<Segments>
<Segment>Top</Segment>
<Segment>Bottom</Segment>
</Segments>
).scryClass('sd-segment');
segmentOne
.textContent
.should.equal('Top');
segmentTwo
.textContent
.should.equal('Bottom');
});
it('renders expected number of children', () => {
const [component] = render(
<Segments>
<Segment>Top</Segment>
<Segment>Middle</Segment>
<Segment>Bottom</Segment>
</Segments>
).scryClass('sd-segments');
expect(
component.querySelectorAll('.sd-segment').length
).to.equal(3);
});
});
|
Handle arrays as parameters in the DBAL executor
|
<?php
namespace RulerZ\Executor\DoctrineDBAL;
use Doctrine\DBAL\Connection;
use RulerZ\Context\ExecutionContext;
use RulerZ\Result\IteratorTools;
trait FilterTrait
{
abstract protected function execute($target, array $operators, array $parameters);
/**
* {@inheritDoc}
*/
public function applyFilter($target, array $parameters, array $operators, ExecutionContext $context)
{
/** @var \Doctrine\DBAL\Query\QueryBuilder $target */
// this will return DQL code
$sql = $this->execute($target, $operators, $parameters);
// so we apply it to the query builder
$target->andWhere($sql);
// now we define the parameters
foreach ($parameters as $name => $value) {
$target->setParameter($name, $value, is_array($value) ? Connection::PARAM_STR_ARRAY : null);
}
return $target;
}
/**
* {@inheritDoc}
*/
public function filter($target, array $parameters, array $operators, ExecutionContext $context)
{
/** @var \Doctrine\DBAL\Query\QueryBuilder $target */
$this->applyFilter($target, $parameters, $operators, $context);
// and return the results
return IteratorTools::fromArray($target->execute()->fetchAll());
}
}
|
<?php
namespace RulerZ\Executor\DoctrineDBAL;
use RulerZ\Context\ExecutionContext;
use RulerZ\Result\IteratorTools;
trait FilterTrait
{
abstract protected function execute($target, array $operators, array $parameters);
/**
* {@inheritDoc}
*/
public function applyFilter($target, array $parameters, array $operators, ExecutionContext $context)
{
/** @var \Doctrine\DBAL\Query\QueryBuilder $target */
// this will return DQL code
$sql = $this->execute($target, $operators, $parameters);
// so we apply it to the query builder
$target->andWhere($sql);
// now we define the parameters
foreach ($parameters as $name => $value) {
$target->setParameter($name, $value);
}
return $target;
}
/**
* {@inheritDoc}
*/
public function filter($target, array $parameters, array $operators, ExecutionContext $context)
{
/** @var \Doctrine\DBAL\Query\QueryBuilder $target */
$this->applyFilter($target, $parameters, $operators, $context);
// and return the results
return IteratorTools::fromArray($target->execute()->fetchAll());
}
}
|
Update barcode scanner example to reference plugin "phonegap-plugin-barcodescanner"
Previously the incorrect plugin "cordova-plugin-barcodescanner" has been referenced
Change-Id: I2e318fdf66ba8186a135a28d8ddc92a94ee63ea4
|
var PluginPage = require('./PluginPage');
var page = new PluginPage('BarcodeScanner', 'phonegap-plugin-barcodescanner', function(parent) {
new tabris.Button({
layoutData: {left: 10, top: 10, right: 10},
text: 'Scan Barcode'
}).on('select', scanBarcode).appendTo(parent);
var resultView = new tabris.TextView({
layoutData: {top: 'prev() 20', left: 20, right: 20},
markupEnabled: true
}).appendTo(parent);
function scanBarcode() {
cordova.plugins.barcodeScanner.scan(function(result) {
resultView.set('text', result.cancelled ?
'<b>Scan cancelled</b>' :
'<b>Scan result:</b> ' + result.text + ' (' + result.format + ')');
}, function(error) {
resultView.set('text', '<b>Error:</b> ' + error);
});
}
});
module.exports = page;
|
var PluginPage = require('./PluginPage');
var page = new PluginPage('BarcodeScanner', 'cordova-plugin-barcodescanner', function(parent) {
new tabris.Button({
layoutData: {left: 10, top: 10, right: 10},
text: 'Scan Barcode'
}).on('select', scanBarcode).appendTo(parent);
var resultView = new tabris.TextView({
layoutData: {top: 'prev() 20', left: 20, right: 20},
markupEnabled: true
}).appendTo(parent);
function scanBarcode() {
cordova.plugins.barcodeScanner.scan(function(result) {
resultView.set('text', result.cancelled ?
'<b>Scan cancelled</b>' :
'<b>Scan result:</b> ' + result.text + ' (' + result.format + ')');
}, function(error) {
resultView.set('text', '<b>Error:</b> ' + error);
});
}
});
module.exports = page;
|
Revert that last change.. and do a proper fix
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach" if vol.get('volume_id') else ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
Fix incorrect notification channel ids,
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package info.zamojski.soft.towercollector.utils;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.widget.Toast;
import info.zamojski.soft.towercollector.CollectorService;
import info.zamojski.soft.towercollector.R;
import info.zamojski.soft.towercollector.UploaderService;
import info.zamojski.soft.towercollector.tasks.ExportFileAsyncTask;
public class NotificationHelperBase {
protected static final String COLLECTOR_NOTIFICATION_CHANNEL_ID = "collector_notification_channel";
protected static final String UPLOADER_NOTIFICATION_CHANNEL_ID = "uploader_notification_channel";
protected static final String OTHER_NOTIFICATION_CHANNEL_ID = "other_notification_channel";
protected boolean isUsingNotificationChannel() {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O);
}
protected boolean isUsingNotificationPriority() {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.O);
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package info.zamojski.soft.towercollector.utils;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.widget.Toast;
import info.zamojski.soft.towercollector.CollectorService;
import info.zamojski.soft.towercollector.R;
import info.zamojski.soft.towercollector.UploaderService;
import info.zamojski.soft.towercollector.tasks.ExportFileAsyncTask;
public class NotificationHelperBase {
protected static final String COLLECTOR_NOTIFICATION_CHANNEL_ID = "collector_notification_channel";
protected static final String UPLOADER_NOTIFICATION_CHANNEL_ID = "collector_notification_channel";
protected static final String OTHER_NOTIFICATION_CHANNEL_ID = "collector_notification_channel";
protected boolean isUsingNotificationChannel() {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O);
}
protected boolean isUsingNotificationPriority() {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.O);
}
}
|
Fix author_email UNKNOWN in pip show
Signed-off-by: Fabio Utzig <66676b1ceaf93296e098708c09494361103aa635@apache.org>
|
import setuptools
from imgtool import imgtool_version
setuptools.setup(
name="imgtool",
version=imgtool_version,
author="The MCUboot commiters",
author_email="None",
description=("MCUboot's image signing and key management"),
license="Apache Software License",
url="http://github.com/JuulLabs-OSS/mcuboot",
packages=setuptools.find_packages(),
install_requires=[
'cryptography>=2.4.2',
'intelhex>=2.2.1',
'click',
],
entry_points={
"console_scripts": ["imgtool=imgtool.main:imgtool"]
},
classifiers=[
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Topic :: Software Development :: Build Tools",
"License :: OSI Approved :: Apache Software License",
],
)
|
import setuptools
from imgtool import imgtool_version
setuptools.setup(
name="imgtool",
version=imgtool_version,
author="The MCUboot commiters",
description=("MCUboot's image signing and key management"),
license="Apache Software License",
url="http://github.com/JuulLabs-OSS/mcuboot",
packages=setuptools.find_packages(),
install_requires=[
'cryptography>=2.4.2',
'intelhex>=2.2.1',
'click',
],
entry_points={
"console_scripts": ["imgtool=imgtool.main:imgtool"]
},
classifiers=[
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Topic :: Software Development :: Build Tools",
"License :: OSI Approved :: Apache Software License",
],
)
|
Update nullability on location based on what API sends back.
|
package com.kickstarter.models;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import com.kickstarter.libs.qualifiers.AutoGson;
import auto.parcel.AutoParcel;
@AutoGson
@AutoParcel
public abstract class Location implements Parcelable {
public abstract long id();
public abstract String displayableName();
public abstract String name();
@Nullable public abstract String city();
public abstract String state();
public abstract String country();
@Nullable public abstract int projectsCount();
@AutoParcel.Builder
public abstract static class Builder {
public abstract Builder displayableName(String __);
public abstract Builder id(long __);
public abstract Builder name(String __);
public abstract Builder city(String __);
public abstract Builder state(String __);
public abstract Builder country(String __);
public abstract Builder projectsCount(int __);
public abstract Location build();
}
public static Builder builder() {
return new AutoParcel_Location.Builder();
}
public abstract Builder toBuilder();
}
|
package com.kickstarter.models;
import android.os.Parcelable;
import com.kickstarter.libs.qualifiers.AutoGson;
import auto.parcel.AutoParcel;
@AutoGson
@AutoParcel
public abstract class Location implements Parcelable {
public abstract String displayableName();
public abstract long id();
public abstract String name();
public abstract String city();
public abstract String state();
public abstract String country();
public abstract int projectsCount();
@AutoParcel.Builder
public abstract static class Builder {
public abstract Builder displayableName(String __);
public abstract Builder id(long __);
public abstract Builder name(String __);
public abstract Builder city(String __);
public abstract Builder state(String __);
public abstract Builder country(String __);
public abstract Builder projectsCount(int __);
public abstract Location build();
}
public static Builder builder() {
return new AutoParcel_Location.Builder();
}
public abstract Builder toBuilder();
}
|
Add delayed popup when mentor logs in for the first time
|
app.controller('LoginController', ['$scope', '$mdDialog', '$firebaseAuth', 'AuthFactory', function($scope, $mdDialog, $firebaseAuth, AuthFactory){
console.log('login controller is running');
var auth = $firebaseAuth();
var self = this;
self.isLoggedIn = AuthFactory.userStatus.isLoggedIn;
console.log(self.isLoggedIn);
self.logIn = function(userType) {
console.log('logging user in');
console.log(userType);
AuthFactory.logIn(userType).then(function(response){
console.log('Logged In: ', AuthFactory.userStatus.isLoggedIn);
})
.then(function(){
// TODO This isn't working because user type isn't set in time
if(AuthFactory.userStatus.newUser === false && AuthFactory.userStatus.userType == 'mentor') {
console.log('duh');
self.cancel();
}
setTimeout(firstTimeMentor, 1000);
});
};
function firstTimeMentor() {
console.log('and here, AuthFactory.userStatus.newUser: ', AuthFactory.userStatus);
if (AuthFactory.userStatus.newUser === true && AuthFactory.userStatus.userType == 'mentor') {
alert('fill out yer profile');
}
}
self.logOut = function() {
console.log('logging user out');
AuthFactory.logOut();
};
self.cancel = function() {
$mdDialog.cancel();
};
}]);
|
app.controller('LoginController', ['$scope', '$mdDialog', '$firebaseAuth', 'AuthFactory', function($scope, $mdDialog, $firebaseAuth, AuthFactory){
console.log('login controller is running');
var auth = $firebaseAuth();
var self = this;
self.isLoggedIn = AuthFactory.userStatus.isLoggedIn;
console.log(self.isLoggedIn);
self.logIn = function(userType) {
console.log('logging user in');
console.log(userType);
AuthFactory.logIn(userType).then(function(response){
console.log('Logged In: ', AuthFactory.userStatus.isLoggedIn);
})
.then(function(){
// TODO This isn't working because user type isn't set in time
if(AuthFactory.userStatus.newUser === false && AuthFactory.userStatus.userType == 'mentor') {
console.log('duh');
self.cancel();
}
});
};
self.logOut = function() {
console.log('logging user out');
AuthFactory.logOut();
};
self.cancel = function() {
$mdDialog.cancel();
};
}]);
|
Use var in favour of let and const.
|
module.exports = function shallowEqual(objA, objB, compare, compareContext) {
var ret = compare ? compare.call(compareContext, objA, objB) : void 0;
if(ret !== void 0) {
return !!ret;
}
if(objA === objB) {
return true;
}
if(typeof objA !== 'object' || !objA ||
typeof objB !== 'object' || !objB) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if(keysA.length !== keysB.length) {
return false;
}
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
// Test for A's keys different from B.
for(var idx = 0; idx < keysA.length; idx++) {
var key = keysA[idx];
if(!bHasOwnProperty(key)) {
return false;
}
var valueA = objA[key];
var valueB = objB[key];
ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;
if(ret === false ||
ret === void 0 && valueA !== valueB) {
return false;
}
}
return true;
};
|
module.exports = function shallowEqual(objA, objB, compare, compareContext) {
let ret = compare ? compare.call(compareContext, objA, objB) : void 0;
if(ret !== void 0) {
return !!ret;
}
if(objA === objB) {
return true;
}
if(typeof objA !== 'object' || !objA ||
typeof objB !== 'object' || !objB) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if(keysA.length !== keysB.length) {
return false;
}
const bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
// Test for A's keys different from B.
for(let idx = 0; idx < keysA.length; idx++) {
const key = keysA[idx];
if(!bHasOwnProperty(key)) {
return false;
}
const valueA = objA[key];
const valueB = objB[key];
ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;
if(ret === false ||
ret === void 0 && valueA !== valueB) {
return false;
}
}
return true;
};
|
Add 'final' in a few places
|
{{java_copyright}}
package {{reversed_domain}};
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class Container
{
public Container()
{
}
public void addName(String name)
{
_names.add(name);
}
public List<String> names()
{
return _namesImmutable;
}
private final ArrayList<String> _names = new ArrayList<String>();
private final List<String> _namesImmutable = Collections.unmodifiableList(_names);
}
/**
* App class
*/
public final class App
{
public static void main(String[] args)
{
for (final String arg : args)
{
System.out.println("arg=" + arg);
}
System.out.println("Hello from {{project_name}}");
final Container items = new Container();
items.addName("One");
items.addName("Two");
items.addName("Three");
for (final String name : items.names())
{
System.out.println("name=" + name);
}
}
}
|
{{java_copyright}}
package {{reversed_domain}};
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class Container
{
public Container()
{
}
public void addName(String name)
{
_names.add(name);
}
public List<String> names()
{
return _namesImmutable;
}
private ArrayList<String> _names = new ArrayList<String>();
private List<String> _namesImmutable = Collections.unmodifiableList(_names);
}
/**
* App class
*/
public final class App
{
public static void main(String[] args)
{
for (String arg : args)
{
System.out.println("arg=" + arg);
}
System.out.println("Hello from {{project_name}}");
Container items = new Container();
items.addName("One");
items.addName("Two");
items.addName("Three");
for (String name : items.names())
{
System.out.println("name=" + name);
}
}
}
|
Fix parent app package.json resolution
|
/* jshint node: true */
'use strict';
var walkSync = require('walk-sync');
var relative = require('require-relative');
var merge = require('merge');
module.exports = {
name: 'ember-local-config',
config: function (env, baseConfig) {
var combinedLocalConfig = {};
// Get the ember-addon field from the host app's package.json
var emberAddonConfig = relative('./package')['ember-addon'];
// Set the default config path
var configPath = './config';
// Use the config path from host app's package.json if it exists
if (emberAddonConfig && emberAddonConfig.configPath) {
configPath = './' + emberAddonConfig.configPath;
}
walkSync(configPath).filter(function(path) {
// We only want to pull in files that end in .local.js
return path.split('/').pop().substr(-9) === '.local.js';
}).forEach(function(path) {
var fullPath = configPath + '/' + path;
var localConfig = relative(fullPath)(env);
merge(combinedLocalConfig, localConfig);
});
return combinedLocalConfig;
}
};
|
/* jshint node: true */
'use strict';
var walkSync = require('walk-sync');
var relative = require('require-relative');
var merge = require('merge');
module.exports = {
name: 'ember-local-config',
config: function (env, baseConfig) {
var combinedLocalConfig = {};
// Get the ember-addon field from the host app's package.json
var emberAddonConfig = require('./package')['ember-addon'];
// Set the default config path
var configPath = './config';
// Use the config path from host app's package.json if it exists
if (emberAddonConfig && emberAddonConfig.configPath) {
configPath = './' + emberAddonConfig.configPath;
}
walkSync(configPath).filter(function(path) {
// We only want to pull in files that end in .local.js
return path.split('/').pop().substr(-9) === '.local.js';
}).forEach(function(path) {
var fullPath = configPath + '/' + path;
var localConfig = relative(fullPath)(env);
merge(combinedLocalConfig, localConfig);
});
return combinedLocalConfig;
}
};
|
Fix bug of test code
|
'use strict';
var jf = require('../../'),
expect = require('chai').expect,
http = require('http');
var count = 0;
function testValue(){
count ++;
return { num: count }
}
let server = http.createServer(
(request, response) => {
response.writeHead(200, {'Content-Type': 'application/json'});
response.end( JSON.stringify( testValue() ) );
}).listen(8080);
describe('Download function ', function () {
this.timeout(10000);
it('should download JSON from web server for each exec()', function (done) {
let downloadedJson =
jf.download(
'http://localhost:8080',
function * (){ yield './' + Math.random() + '.json'; } );
downloadedJson
.io( ( json ) => { expect( json.num ).to.equal( 1 ) })
.pass( () => {
downloadedJson
.io( ( json ) => { expect( json.num ).to.equal( 2 ) })
.pass( () => {
done();
server.close();
} )
.exec();
})
.exec();
setTimeout(
function(){
},
100);
});
});
|
'use strict';
var jf = require('../../'),
expect = require('chai').expect,
http = require('http');
var count = 0;
function testValue(){
count ++;
return { num: count }
}
let server = http.createServer(
(request, response) => {
response.writeHead(200, {'Content-Type': 'application/json'});
response.end( JSON.stringify( testValue() ) );
}).listen(8080);
describe('Download function ', function () {
this.timeout(10000);
it('should download JSON from web server for each exec()', function (done) {
let downloadedJson =
jf.download(
'http://localhost:8080',
function * (){ yield './' + Math.random() + '.json'; } );
downloadedJson
.io( ( json ) => { expect( json.num ).to.equal( 1 ) }).exec();
setTimeout(
function(){
},
100);
downloadedJson
.io( ( json ) => { expect( json.num ).to.equal( 2 ) })
.pass( () => {
done();
server.close();
} )
.exec();
});
});
|
Make the broadcast module more versatile.
|
package com.skcraft.plume.module;
import com.sk89q.intake.Command;
import com.sk89q.intake.Require;
import com.sk89q.intake.parametric.annotation.Text;
import com.skcraft.plume.command.Sender;
import com.skcraft.plume.common.util.module.Module;
import com.skcraft.plume.util.Messages;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
@Module(name = "broadcast", desc = "Server wide message broadcasting for operators")
public class Broadcast {
@Command(aliases = {"broadcast", "bc"}, desc = "Send out a broadcast message")
@Require("plume.broadcast.broadcast")
public void broadcast(@Sender ICommandSender sender, @Text String msg) {
Messages.broadcast(Messages.info("SERVER: " + msg));
}
@Command(aliases = {"alert"}, desc = "Send out a broadcast message")
@Require("plume.broadcast.broadcast")
public void alert(@Sender ICommandSender sender, @Text String msg) {
Messages.broadcast(Messages.error("SERVER: " + msg));
}
@Command(aliases = {"print"}, desc = "Print an unformatted message to chat")
@Require("plume.broadcast.print")
public void print(@Sender ICommandSender sender, @Text String msg) {
Messages.broadcast(new ChatComponentText(msg));
}
}
|
package com.skcraft.plume.module;
import com.sk89q.intake.Command;
import com.sk89q.intake.Require;
import com.sk89q.intake.parametric.annotation.Switch;
import com.sk89q.intake.parametric.annotation.Text;
import com.skcraft.plume.command.Sender;
import com.skcraft.plume.common.util.module.Module;
import com.skcraft.plume.util.Messages;
import net.minecraft.command.ICommandSender;
import static com.skcraft.plume.common.util.SharedLocale.tr;
@Module(name = "broadcast", desc = "Server wide message broadcasting for operators")
public class Broadcast {
@Command(aliases = {"broadcast", "bc"}, desc = "Send out a broadcast message")
@Require("plume.broadcast.bc")
public void broadcast(@Sender ICommandSender sender, @Text String msg, @Switch('t') String type) {
if (type == null || type.equalsIgnoreCase("type")) {
Messages.broadcastInfo(msg);
} else if (type.equalsIgnoreCase("alert")) {
Messages.broadcastAlert(msg);
} else {
sender.addChatMessage(Messages.error(tr("broadcast.invalidType")));
}
}
}
|
Fix a warning in chrome
|
/*
* - scrolled.js -
* Licence MIT
* Written by Gabriel Delépine
* Current version 0.2 (2014-02-12)
* Requirement : No one, it is a framework-free fonction (ie : You do not need to include any other file in your page such as jQuery)
* fork me on github : https://github.com/Yappli/scrolled.js (and don't forget to pull request !)
* */
(function(undefined) // Code in a function to create an isolate scope
{
'use strict';
var fn;
(fn = function(e){
var body = document.getElementsByTagName('body')[0],
indexOfScrolledClass = body.className.indexOf('scrolled');
if(parseInt(document.documentElement.scrollTop !== undefined ? document.documentElement.scrollTop : document.body.scrollTop) > 0)
{
if(indexOfScrolledClass == -1)
body.className += (body.className.length == 0 ? '' : ' ')+'scrolled';
}
else
{
if(indexOfScrolledClass != -1)
body.className = body.className.replace('scrolled', '');
}
})();
window.onscroll = fn;
})();
|
/*
* - scrolled.js -
* Licence MIT
* Written by Gabriel Delépine
* Current version 0.1 (2014-02-12)
* Requirement : No one, it is a framework-free fonction (ie : You do not need to include any other file in your page such as jQuery)
* fork me on github : https://github.com/Yappli/scrolled.js (and don't forget to pull request !)
* */
(function(undefined) // Code in a function to create an isolate scope
{
'use strict';
var fn;
(fn = function(e){
var body = document.getElementsByTagName('body')[0],
indexOfScrolledClass = body.className.indexOf('scrolled');
if(parseInt(document.documentElement.scrollTop || document.body.scrollTop) > 0)
{
if(indexOfScrolledClass == -1)
body.className += (body.className.length == 0 ? '' : ' ')+'scrolled';
}
else
{
if(indexOfScrolledClass != -1)
body.className = body.className.replace('scrolled', '');
}
})();
window.onscroll = fn;
})();
|
Change max number of children from 20 to 3
- did some performance testing after @brynary comment in GitHub and found that 3 performs best on my large code bases
|
<?php
declare(ticks=1);
namespace PHPMD\TextUI;
use CodeClimate\PHPMD\Runner;
error_reporting(E_ERROR | E_PARSE | E_NOTICE);
date_default_timezone_set('UTC');
ini_set('memory_limit', -1);
require_once __DIR__.'/vendor/autoload.php';
require_once "JSONRenderer.php";
require_once "Runner.php";
use PHPMD\PHPMD;
use PHPMD\RuleSetFactory;
use PHPMD\Writer\StreamWriter;
use PHPMD\Renderer\JSONRenderer;
// obtain the config
$config = json_decode(file_get_contents('/config.json'), true);
// setup forking daemon
$server = new \fork_daemon();
$server->max_children_set(3);
$server->max_work_per_child_set(50);
$server->store_result_set(true);
$runner = new Runner($config, $server);
$server->register_child_run(array($runner, "run"));
$runner->queueDirectory("/code");
$server->process_work(true);
foreach ($server->get_all_results() as $result_file) {
echo file_get_contents($result_file);
unlink($result_file);
}
|
<?php
declare(ticks=1);
namespace PHPMD\TextUI;
use CodeClimate\PHPMD\Runner;
error_reporting(E_ERROR | E_PARSE | E_NOTICE);
date_default_timezone_set('UTC');
ini_set('memory_limit', -1);
require_once __DIR__.'/vendor/autoload.php';
require_once "JSONRenderer.php";
require_once "Runner.php";
use PHPMD\PHPMD;
use PHPMD\RuleSetFactory;
use PHPMD\Writer\StreamWriter;
use PHPMD\Renderer\JSONRenderer;
// obtain the config
$config = json_decode(file_get_contents('/config.json'), true);
// setup forking daemon
$server = new \fork_daemon();
$server->max_children_set(20);
$server->max_work_per_child_set(50);
$server->store_result_set(true);
$runner = new Runner($config, $server);
$server->register_child_run(array($runner, "run"));
$runner->queueDirectory("/code");
$server->process_work(true);
foreach ($server->get_all_results() as $result_file) {
echo file_get_contents($result_file);
unlink($result_file);
}
|
Make dough_currency as twig filter instead of the function.
And the filter returns a raw value of the Money instead of
formatted string. This allows use chain filters.
|
<?php
namespace Dough\Twig;
use Dough\Bank\BankInterface;
use Dough\Money\MoneyInterface;
class DoughExtension extends \Twig_Extension
{
private $bank;
public function __construct(BankInterface $bank = null)
{
$this->bank = $bank;
}
public function getFilters()
{
return array(
'dough_currency' => new \Twig_Filter_Method($this, 'getAmount', array('is_safe' => array('html'))),
);
}
public function getAmount(MoneyInterface $money, $currency = null)
{
$reduced = $this->bank->reduce($money, $currency);
return $reduced->getAmount();
}
public function getName()
{
return 'merk_dough';
}
}
|
<?php
namespace Dough\Twig;
use Dough\Bank\BankInterface;
use Dough\Money\MoneyInterface;
class DoughExtension extends \Twig_Extension
{
private $bank;
public function __construct(BankInterface $bank = null)
{
$this->bank = $bank;
}
public function getFunctions()
{
return array(
'dough_currency' => new \Twig_Function_Method($this, 'renderCurrency'),
);
}
public function renderCurrency(MoneyInterface $money)
{
$reduced = $money->reduce($this->bank);
return number_format($reduced->getAmount(), 2);
}
public function getName()
{
return 'merk_dough';
}
}
|
Simplify get AdminUserDetails from nullable UserDetails
|
package com.drumonii.loltrollbuild.api.admin;
import com.drumonii.loltrollbuild.api.status.BadRequestException;
import com.drumonii.loltrollbuild.security.AdminUserDetails;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
/**
* REST controller for administration authentication.
*/
@RestController
@RequestMapping("${api.base-path}/admin")
public class AdminAuthenticationRestController {
/**
* Gets the current authentication principal - {@link AdminUserDetails}.
*
* @param userDetails the {@link User}
* @return the {@link AdminUserDetails} if authenticated, otherwise {@code null}
*/
@GetMapping("/authentication")
public AdminUserDetails getAuthentication(@AuthenticationPrincipal User userDetails) {
return Optional.ofNullable(userDetails)
.map(AdminUserDetails::from)
.orElseThrow(() -> new BadRequestException("Authentication was not found"));
}
}
|
package com.drumonii.loltrollbuild.api.admin;
import com.drumonii.loltrollbuild.api.status.BadRequestException;
import com.drumonii.loltrollbuild.security.AdminUserDetails;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
/**
* REST controller for administration authentication.
*/
@RestController
@RequestMapping("${api.base-path}/admin")
public class AdminAuthenticationRestController {
/**
* Gets the current authentication principal - {@link AdminUserDetails}.
*
* @param userDetails the {@link User}
* @return the {@link AdminUserDetails} if authenticated, otherwise {@code null}
*/
@GetMapping("/authentication")
public AdminUserDetails getAuthentication(@AuthenticationPrincipal User userDetails) {
User user = Optional.ofNullable(userDetails)
.orElseThrow(() -> new BadRequestException("Authentication was not found"));
return AdminUserDetails.from(user);
}
}
|
Fix output path in webpack config
|
import path from 'path';
export default {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'python-range.umd.js',
library: 'pythonRange',
libraryTarget: 'umd',
umdNamedDefine: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
['latest', {
modules: false,
}],
],
plugins: ['transform-object-rest-spread', 'transform-runtime'],
},
},
],
},
};
|
export default {
entry: './src/index.js',
output: {
path: __dirname + './dist',
filename: 'python-range.umd.js',
library: 'pythonRange',
libraryTarget: 'umd',
umdNamedDefine: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
['latest', {
modules: false,
}],
],
plugins: ['transform-object-rest-spread', 'transform-runtime'],
},
},
],
},
};
|
Add iOS implementation to get uncalibrated values
|
'''
iOS Compass
-----------
'''
from plyer.facades import Compass
from pyobjus import autoclass
class IosCompass(Compass):
def __init__(self):
super(IosCompass, self).__init__()
self.bridge = autoclass('bridge').alloc().init()
self.bridge.motionManager.setMagnetometerUpdateInterval_(0.1)
self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1)
def _enable(self):
self.bridge.startMagnetometer()
self.bridge.startDeviceMotionWithReferenceFrame()
def _disable(self):
self.bridge.stopMagnetometer()
self.bridge.stopDeviceMotion()
def _get_orientation(self):
return (
self.bridge.mf_x,
self.bridge.mf_y,
self.bridge.mf_z)
def _get_field_uncalib(self):
return (
self.bridge.mg_x,
self.bridge.mg_y,
self.bridge.mg_z,
self.bridge.mg_x - self.bridge.mf_x,
self.bridge.mg_y - self.bridge.mf_y,
self.bridge.mg_z - self.bridge.mf_z)
def instance():
return IosCompass()
|
'''
iOS Compass
---------------------
'''
from plyer.facades import Compass
from pyobjus import autoclass
class IosCompass(Compass):
def __init__(self):
super(IosCompass, self).__init__()
self.bridge = autoclass('bridge').alloc().init()
self.bridge.motionManager.setMagnetometerUpdateInterval_(0.1)
def _enable(self):
self.bridge.startMagnetometer()
def _disable(self):
self.bridge.stopMagnetometer()
def _get_orientation(self):
return (
self.bridge.mg_x,
self.bridge.mg_y,
self.bridge.mg_z)
def instance():
return IosCompass()
|
Remove (no longer needed) dependency link for daploader
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='Dapi',
version='1.0',
description='DevAssistant Package Index',
author='Miro Hroncok',
author_email='mhroncok@redhat.com',
url='https://github.com/hroncok/dapi',
license='AGPLv3',
install_requires=[
'Django==1.6',
'psycopg2',
'South',
'daploader>=0.0.5',
'PyYAML',
'python-social-auth',
'django-taggit',
'django-simple-captcha',
'django-haystack',
'whoosh',
'djangorestframework',
'django-gravatar2',
'markdown2',
'Markdown',
],
dependency_links = [
'git+git://github.com/omab/python-social-auth.git@c5dd3339#egg=python-social-auth',
'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework',
]
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='Dapi',
version='1.0',
description='DevAssistant Package Index',
author='Miro Hroncok',
author_email='mhroncok@redhat.com',
url='https://github.com/hroncok/dapi',
license='AGPLv3',
install_requires=[
'Django==1.6',
'psycopg2',
'South',
'daploader>=0.0.5',
'PyYAML',
'python-social-auth',
'django-taggit',
'django-simple-captcha',
'django-haystack',
'whoosh',
'djangorestframework',
'django-gravatar2',
'markdown2',
'Markdown',
],
dependency_links = [
'git+git://github.com/omab/python-social-auth.git@c5dd3339#egg=python-social-auth',
'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework',
'https://pypi.python.org/packages/source/d/daploader/daploader-0.0.5.tar.gz'
]
)
|
Change display of /f version
|
package io.github.aquerr.eaglefactions.commands;
import io.github.aquerr.eaglefactions.PluginInfo;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
public class VersionCommand implements CommandExecutor
{
@Override
public CommandResult execute(CommandSource source, CommandContext context) throws CommandException
{
source.sendMessage (Text.of (TextColors.AQUA, PluginInfo.Name, TextColors.WHITE, " - Version ", PluginInfo.Version));
return CommandResult.success ();
}
}
|
package io.github.aquerr.eaglefactions.commands;
import io.github.aquerr.eaglefactions.PluginInfo;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
public class VersionCommand implements CommandExecutor
{
@Override
public CommandResult execute(CommandSource source, CommandContext context) throws CommandException
{
source.sendMessage (Text.of (TextColors.AQUA, PluginInfo.Name + " - ", TextColors.WHITE, "version ", PluginInfo.Version));
return CommandResult.success ();
}
}
|
Fix state editFramecontroller goes to after save is successful.
Fixes #6
|
/**
* Controller responsible for editing a specific frame in a specific game.
*/
var EditFrameController = function($state, $stateParams, MatchService, league, week, match, scoreSheet) {
var controller = this;
controller.scoreSheet = scoreSheet;
controller.frameNumber = $stateParams.frameId;
controller.gameNumber = $stateParams.gameId;
controller.submit = function() {
MatchService.cleanUpScoresheet(scoreSheet);
match.one('scoresheet').customPUT(scoreSheet).then(function() {
$state.go('^.detail');
});
};
};
angular.module('bowling.entry.core')
.controller('EditFrameController', ['$state', '$stateParams', 'MatchService', 'league', 'week', 'match', 'scoreSheet', EditFrameController])
.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('bowling.league.week.match.game.frame', {
url: '/:frameId/',
templateUrl: 'partials/entry/leagues/matches/games/frames/frame.html',
title: 'Frame Details',
controller: 'EditFrameController',
controllerAs: 'frameController'
});
}]);
|
/**
* Controller responsible for editing a specific frame in a specific game.
*/
var EditFrameController = function($state, $stateParams, MatchService, league, week, match, scoreSheet) {
var controller = this;
controller.scoreSheet = scoreSheet;
controller.frameNumber = $stateParams.frameId;
controller.gameNumber = $stateParams.gameId;
controller.submit = function() {
MatchService.cleanUpScoresheet(scoreSheet);
match.one('scoresheet').customPUT(scoreSheet).then(function() {
$state.go('^');
});
};
};
angular.module('bowling.entry.core')
.controller('EditFrameController', ['$state', '$stateParams', 'MatchService', 'league', 'week', 'match', 'scoreSheet', EditFrameController])
.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('bowling.league.week.match.game.frame', {
url: '/:frameId/',
templateUrl: 'partials/entry/leagues/matches/games/frames/frame.html',
title: 'Frame Details',
controller: 'EditFrameController',
controllerAs: 'frameController'
});
}]);
|
Improve the readability of this SQL
|
<?php
#
# $Id: ports-expired.php,v 1.2 2006-12-17 12:06:14 dan Exp $
#
# Copyright (c) 1998-2004 DVL Software Limited
#
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/common.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/databaselogin.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/getvalues.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports_page_expiration_ports.php');
# not using this yet, but putting it in here.
if (IsSet($_REQUEST['branch'])) {
$Branch = htmlspecialchars($_REQUEST['branch']);
} else {
$Branch = BRANCH_HEAD;
}
$attributes = array('branch' => $Branch);
$page = new freshports_page_expiration_ports($attributes);
$page->setDebug(0);
$page->setDB($db);
$page->setTitle('Ports that have expired');
$page->setDescription('These ports are past their expiration date. This list never includes deleted ports.');
$page->setSQL("ports.expiration_date IS NOT NULL AND CURRENT_DATE > ports.expiration_date", $User->id);
$page->display();
|
<?php
#
# $Id: ports-expired.php,v 1.2 2006-12-17 12:06:14 dan Exp $
#
# Copyright (c) 1998-2004 DVL Software Limited
#
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/common.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/databaselogin.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/getvalues.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports_page_expiration_ports.php');
# not using this yet, but putting it in here.
if (IsSet($_REQUEST['branch'])) {
$Branch = htmlspecialchars($_REQUEST['branch']);
} else {
$Branch = BRANCH_HEAD;
}
$attributes = array('branch' => $Branch);
$page = new freshports_page_expiration_ports($attributes);
$page->setDebug(0);
$page->setDB($db);
$page->setTitle('Ports that have expired');
$page->setDescription('These ports are past their expiration date. This list never includes deleted ports.');
$page->setSQL("ports.expiration_date is not null and ports.expiration_date <= CURRENT_DATE", $User->id);
$page->display();
|
Add a comment to explain why the uid subtracts two
|
import * as ACTION_TYPES from '../constants/action_types'
import { get } from 'lodash'
function uploadAsset(type, file, editorId, uid) {
return {
type,
meta: {},
payload: {
editorId,
file,
uid,
},
}
}
function temporaryPostImageCreated(objectURL, editorId) {
return {
type: ACTION_TYPES.EDITOR.TMP_IMAGE_CREATED,
meta: {},
payload: {
url: objectURL,
editorId,
},
}
}
export const editor = store => next => action => {
const { payload, type } = action
if (type === ACTION_TYPES.EDITOR.SAVE_ASSET) {
const editorId = get(payload, 'editorId')
const file = get(payload, 'file')
// The - 2 should always be consistent. The reason is that when a tmp image
// gets created at say uid 1 an additional text block is added to the bottom
// of the editor at uid 2 and the uid of the editor is now sitting at 3
// since it gets incremented after a block is added. So the - 2 gets us from
// the 3 back to the 1 where the image should reconcile back to.
if (editorId && file) {
store.dispatch(temporaryPostImageCreated(URL.createObjectURL(file), editorId))
const uid = store.getState().editor[editorId].uid - 2
store.dispatch(uploadAsset(ACTION_TYPES.EDITOR.SAVE_IMAGE, file, editorId, uid))
}
}
return next(action)
}
|
import * as ACTION_TYPES from '../constants/action_types'
import { get } from 'lodash'
function uploadAsset(type, file, editorId, uid) {
return {
type,
meta: {},
payload: {
editorId,
file,
uid,
},
}
}
function temporaryPostImageCreated(objectURL, editorId) {
return {
type: ACTION_TYPES.EDITOR.TMP_IMAGE_CREATED,
meta: {},
payload: {
url: objectURL,
editorId,
},
}
}
export const editor = store => next => action => {
const { payload, type } = action
if (type === ACTION_TYPES.EDITOR.SAVE_ASSET) {
const editorId = get(payload, 'editorId')
const file = get(payload, 'file')
if (editorId && file) {
store.dispatch(temporaryPostImageCreated(URL.createObjectURL(file), editorId))
const uid = store.getState().editor[editorId].uid - 2
store.dispatch(uploadAsset(ACTION_TYPES.EDITOR.SAVE_IMAGE, file, editorId, uid))
}
}
return next(action)
}
|
Remove Disallow /kwf/util/kwc/render from robots.txt
GoogleBot executes JavaScript and complains about this resource being blocked
|
<?php
class Kwf_Util_RobotsTxt
{
public static function output()
{
$baseUrl = Kwf_Setup::getBaseUrl();
$contents = "User-agent: *\n".
"Disallow: $baseUrl/admin/\n";
$contents .= "Sitemap: http".(isset($_SERVER['HTTPS']) ? 's' : '')."://"
.$_SERVER['HTTP_HOST'].$baseUrl."/sitemap.xml\n";
Kwf_Media_Output::output(array(
'contents' => $contents,
'mimeType' => 'text/plain'
));
}
}
|
<?php
class Kwf_Util_RobotsTxt
{
public static function output()
{
$baseUrl = Kwf_Setup::getBaseUrl();
$contents = "User-agent: *\n".
"Disallow: $baseUrl/admin/\n".
"Disallow: $baseUrl/kwf/util/kwc/render\n"; //used to load eg. lightbox content async, we don't want getting that indexed
$contents .= "Sitemap: http".(isset($_SERVER['HTTPS']) ? 's' : '')."://"
.$_SERVER['HTTP_HOST'].$baseUrl."/sitemap.xml\n";
Kwf_Media_Output::output(array(
'contents' => $contents,
'mimeType' => 'text/plain'
));
}
}
|
Set clear color to black
|
package net.mueller_martin.turirun.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import net.mueller_martin.turirun.Turirun;
import net.mueller_martin.turirun.WorldController;
public class GameScreen extends ScreenAdapter {
Turirun game;
WorldController world;
public GameScreen (Turirun game) {
this.game = game;
this.world = new WorldController(game);
}
public void draw() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.draw(game.batch);
}
public void update(float deltaTime) {
world.update(deltaTime);
}
@Override
public void render (float delta) {
update(delta);
draw();
}
}
|
package net.mueller_martin.turirun.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import net.mueller_martin.turirun.Turirun;
import net.mueller_martin.turirun.WorldController;
public class GameScreen extends ScreenAdapter {
Turirun game;
WorldController world;
public GameScreen (Turirun game) {
this.game = game;
this.world = new WorldController(game);
}
public void draw() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.draw(game.batch);
}
public void update(float deltaTime) {
world.update(deltaTime);
}
@Override
public void render (float delta) {
update(delta);
draw();
}
}
|
Remove `error_stream`; Add `on_stderr` to make it works
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, WARNING
class PugLint(NodeLinter):
"""Provides an interface to pug-lint."""
cmd = 'pug-lint ${temp_file} ${args}'
regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)'
multiline = False
on_stderr = None
tempfile_suffix = 'pug'
defaults = {
'selector': 'text.pug, source.pypug, text.jade',
'--reporter=': 'inline'
}
default_type = WARNING
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, WARNING
class PugLint(NodeLinter):
"""Provides an interface to pug-lint."""
cmd = 'pug-lint ${temp_file} ${args}'
regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)'
multiline = False
tempfile_suffix = 'pug'
error_stream = util.STREAM_BOTH
defaults = {
'selector': 'text.pug, source.pypug, text.jade',
'--reporter=': 'inline'
}
default_type = WARNING
|
Rename in map reduce sync test
|
var simplemapreduce = require('../'),
assert = require('assert');
// mapReduceSync defined
assert.ok(simplemapreduce.mapReduceSync);
assert.equal(typeof simplemapreduce.mapReduceSync, 'function');
// Run count words
var result = simplemapreduce.mapReduceSync(
["A", "word", "is", "a", "word"], // items to process
function (key, value, ctx) { ctx.emit(value.toLowerCase(), 1); }, // map
function (key, values, ctx) { // reduce
var total = 0;
values.forEach(function (value) {
total += value;
});
ctx.emit(key, total);
}
);
assert.ok(result);
assert.ok(result.a);
assert.equal(result.a, 2);
assert.ok(result.word);
assert.equal(result.word, 2);
assert.ok(result.is);
assert.equal(result.is, 1);
|
var simplemapreduce = require('../'),
assert = require('assert');
// mapReduceSync defined
assert.ok(simplemapreduce.mapReduceSync);
assert.equal(typeof simplemapreduce.mapReduceSync, 'function');
// Run count words
var result = simplemapreduce.mapReduceSync(
["A", "word", "is", "a", "word"], // items to process
function (key, item, ctx) { ctx.emit(item.toLowerCase(), 1); }, // map
function (key, values, ctx) { // reduce
var total = 0;
values.forEach(function (value) {
total += value;
});
ctx.emit(key, total);
}
);
assert.ok(result);
assert.ok(result.a);
assert.equal(result.a, 2);
assert.ok(result.word);
assert.equal(result.word, 2);
assert.ok(result.is);
assert.equal(result.is, 1);
|
Change dict declaration to inline
|
from __future__ import print_function, unicode_literals
import logging
from celery.task import task
from temba.orgs.models import Org
from .models import Chatbase
logger = logging.getLogger(__name__)
@task(track_started=True, name='send_chatbase_event')
def send_chatbase_event(org, channel, msg, contact):
try:
org = Org.objects.get(id=org)
if org.is_connected_to_chatbase():
chatbase_args = dict(org=org.id, channel=channel, msg=msg, contact=contact)
chatbase = Chatbase.create(**chatbase_args)
chatbase.trigger_chatbase_event()
except Exception as e:
logger.error("Error for chatbase event: %s" % e.args, exc_info=True)
|
from __future__ import print_function, unicode_literals
import logging
from celery.task import task
from temba.orgs.models import Org
from .models import Chatbase
logger = logging.getLogger(__name__)
@task(track_started=True, name='send_chatbase_event')
def send_chatbase_event(org, channel, msg, contact):
try:
org = Org.objects.get(id=org)
if org.is_connected_to_chatbase():
chatbase_args = dict(org=org.id,
channel=channel,
msg=msg,
contact=contact)
chatbase = Chatbase.create(**chatbase_args)
chatbase.trigger_chatbase_event()
except Exception as e:
logger.error("Error for chatbase event: %s" % e.args, exc_info=True)
|
Fix - pass composer loader inside app factory
|
<?php
/** @var object $loader - defined in composer Autoload */
// check if loader is initialized
if (!defined('root')) {
die('Hack attempt');
}
// global environment
define('env_name', 'Front');
define('env_no_uri', true);
define('env_type', 'html');
require_once(root . '/Loader/Autoload.php');
// make fast-access alias \App::$Object
// class_alias('Ffcms\Core\App', 'App');
class App extends Ffcms\Core\App {}
/**
* Alias for translate function for fast usage. Example: __('Welcome my friend')
* @param string $text
* @param array $params
* @return string
*/
function __($text, array $params = []) {
return \App::$Translate->translate($text, $params);
}
try {
$app = \App::factory([
'Database' => true,
'Session' => true,
'Debug' => true,
'User' => true,
'Mailer' => true,
'Captcha' => true,
'Cache' => true
], $loader);
$app->run();
} catch (Exception $e) {
(new \Ffcms\Core\Exception\NativeException($e->getMessage()))->display();
}
|
<?php
/** @var object $loader - defined in composer Autoload */
// check if loader is initialized
if (!defined('root')) {
die('Hack attempt');
}
// global environment
define('env_name', 'Front');
define('env_no_uri', true);
define('env_type', 'html');
require_once(root . '/Loader/Autoload.php');
// make fast-access alias \App::$Object
// class_alias('Ffcms\Core\App', 'App');
class App extends Ffcms\Core\App {}
/**
* Alias for translate function for fast usage. Example: __('Welcome my friend')
* @param string $text
* @param array $params
* @return string
*/
function __($text, array $params = []) {
return \App::$Translate->translate($text, $params);
}
try {
$app = \App::factory([
'Database' => true,
'Session' => true,
'Debug' => true,
'User' => true,
'Mailer' => true,
'Captcha' => true,
'Cache' => true
]);
$app->run();
} catch (Exception $e) {
(new \Ffcms\Core\Exception\NativeException($e->getMessage()))->display();
}
|
Improve malformed db error messages
|
package main
import (
"errors"
"fmt"
)
type ErrMalformedDB struct {
Bucket string
}
func (e ErrMalformedDB) Error() string {
return fmt.Sprintf("malformed database no %s bucket, initialise a service try 'rest help service init' for init help", e.Bucket)
}
type ErrNoService struct {
Name string
}
func (e ErrNoService) Error() string {
return fmt.Sprintf("no service %s found", e.Name)
}
type ErrInvalidPath struct {
Path string
}
func (e ErrInvalidPath) Error() string {
return fmt.Sprintf("path %s not valid", e.Path)
}
type ErrNoAlias struct {
Alias string
}
func (e ErrNoAlias) Error() string {
return fmt.Sprintf("no alias %s defined", e.Alias)
}
var (
ErrInitDB = errors.New("no services, run service init")
ErrNoInfoBucket = ErrMalformedDB{Bucket: "info"}
ErrNoServicesBucket = ErrMalformedDB{Bucket: "services"}
ErrNoPaths = ErrMalformedDB{Bucket: "paths"}
ErrNoServiceSet = errors.New("no service set, use 'rest service use <service>' to set the current service to use")
ErrNoAliases = errors.New("no aliases defined")
)
|
package main
import (
"errors"
"fmt"
)
type ErrMalformedDB struct {
Bucket string
}
func (e ErrMalformedDB) Error() string {
return fmt.Sprintf("malformed database no %s bucket", e.Bucket)
}
type ErrNoService struct {
Name string
}
func (e ErrNoService) Error() string {
return fmt.Sprintf("no service %s found", e.Name)
}
type ErrInvalidPath struct {
Path string
}
func (e ErrInvalidPath) Error() string {
return fmt.Sprintf("path %s not valid", e.Path)
}
type ErrNoAlias struct {
Alias string
}
func (e ErrNoAlias) Error() string {
return fmt.Sprintf("no alias %s defined", e.Alias)
}
var (
ErrInitDB = errors.New("no services, run service init")
ErrNoInfoBucket = ErrMalformedDB{Bucket: "info"}
ErrNoServicesBucket = ErrMalformedDB{Bucket: "services"}
ErrNoPaths = ErrMalformedDB{Bucket: "paths"}
ErrNoServiceSet = errors.New("no service set, use 'rest service use <service>' to set the current service to use")
ErrNoAliases = errors.New("no aliases defined")
)
|
Fix isList to check recursively.
BiwaScheme.isList (also used by assert_list) only checked to see if the
obj was a pair. It now properly checks the list recursively, ending
with the (new) empty list. It still does not check if it's cyclic.
This is believed to cause a few test cases to fail where the test cases
were relying on the old, incorrect implementation of assert_list.
|
//
// types.js - type predicators
//
BiwaScheme.isNil = function(obj){
return (obj === BiwaScheme.nil);
};
BiwaScheme.isUndef = function(obj){
return (obj === BiwaScheme.undef);
};
BiwaScheme.isChar = function(obj){
return (obj instanceof BiwaScheme.Char);
};
BiwaScheme.isSymbol = function(obj){
return (obj instanceof BiwaScheme.Symbol);
};
BiwaScheme.isPort = function(obj){
return (obj instanceof BiwaScheme.Port);
};
// Note: '() is not a pair in scheme
BiwaScheme.isPair = function(obj){
return (obj instanceof BiwaScheme.Pair) && (obj !== BiwaScheme.nil);
};
// Note: isList returns true for '()
BiwaScheme.isList = function(obj){
if(obj === BiwaScheme.nil) return true; // null base case
if(!(obj instanceof BiwaScheme.Pair)) return false;
return BiwaScheme.isList(obj.cdr);
//TODO: should check if it is not cyclic..
};
BiwaScheme.isVector = function(obj){
return (obj instanceof Array) && (obj.closure_p !== true);
};
BiwaScheme.isHashtable = function(obj){
return (obj instanceof BiwaScheme.Hashtable);
};
BiwaScheme.isMutableHashtable = function(obj){
return (obj instanceof BiwaScheme.Hashtable) && obj.mutable;
};
BiwaScheme.isClosure = function(obj){
return (obj instanceof Array) && (obj.closure_p === true);
};
|
//
// types.js - type predicators
//
BiwaScheme.isNil = function(obj){
return (obj === BiwaScheme.nil);
};
BiwaScheme.isUndef = function(obj){
return (obj === BiwaScheme.undef);
};
BiwaScheme.isChar = function(obj){
return (obj instanceof BiwaScheme.Char);
};
BiwaScheme.isSymbol = function(obj){
return (obj instanceof BiwaScheme.Symbol);
};
BiwaScheme.isPort = function(obj){
return (obj instanceof BiwaScheme.Port);
};
// Note: '() is not a pair in scheme
BiwaScheme.isPair = function(obj){
return (obj instanceof BiwaScheme.Pair) && (obj !== BiwaScheme.nil);
};
// Note: isList returns true for '()
BiwaScheme.isList = function(obj){
return (obj instanceof BiwaScheme.Pair);
// should check it is proper and not cyclic..
};
BiwaScheme.isVector = function(obj){
return (obj instanceof Array) && (obj.closure_p !== true);
};
BiwaScheme.isHashtable = function(obj){
return (obj instanceof BiwaScheme.Hashtable);
};
BiwaScheme.isMutableHashtable = function(obj){
return (obj instanceof BiwaScheme.Hashtable) && obj.mutable;
};
BiwaScheme.isClosure = function(obj){
return (obj instanceof Array) && (obj.closure_p === true);
};
|
Adjust writerIndex to highest value if putting a single character using array-index notation.
|
/*
* Copyright 2014 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nodyn.buffer;
import io.netty.buffer.ByteBuf;
import org.dynjs.runtime.ExternalIndexedData;
/**
* @author Bob McWhirter
*/
public class NettyExternalIndexedData implements ExternalIndexedData {
private final ByteBuf buf;
public NettyExternalIndexedData(ByteBuf buf) {
this.buf = buf;
}
public ByteBuf buffer() {
return this.buf;
}
@Override
public Object get(long l) {
return this.buf.getUnsignedByte((int) l);
}
@Override
public void put(long l, Object o) {
if (o instanceof Number) {
int value = ((Number) o).intValue() & 0xFF;
this.buf.setByte((int) l, value);
this.buf.writerIndex((int) Math.max( this.buf.writerIndex(), l ));
}
}
}
|
/*
* Copyright 2014 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nodyn.buffer;
import io.netty.buffer.ByteBuf;
import org.dynjs.runtime.ExternalIndexedData;
/**
* @author Bob McWhirter
*/
public class NettyExternalIndexedData implements ExternalIndexedData {
private final ByteBuf buf;
public NettyExternalIndexedData(ByteBuf buf) {
this.buf = buf;
}
public ByteBuf buffer() {
return this.buf;
}
@Override
public Object get(long l) {
return this.buf.getUnsignedByte((int) l);
}
@Override
public void put(long l, Object o) {
if (o instanceof Number) {
int value = ((Number) o).intValue() & 0xFF;
this.buf.setByte((int) l, value );
} else {
System.err.println("ATTEMPT TO PUT: " + o);
}
}
}
|
Make it clear that a few example tests fail on purpose
|
''' NOTE: This test suite contains 2 passing tests and 2 failing tests. '''
from seleniumbase import BaseCase
class MyTestSuite(BaseCase):
def test_1(self):
self.open("http://xkcd.com/1663/")
self.find_text("Garden", "div#ctitle", timeout=3)
for p in xrange(4):
self.click('a[rel="next"]')
self.find_text("Algorithms", "div#ctitle", timeout=3)
def test_2(self):
# This test should FAIL
print "\n(This test fails on purpose)"
self.open("http://xkcd.com/1675/")
raise Exception("FAKE EXCEPTION: This test fails on purpose.")
def test_3(self):
self.open("http://xkcd.com/1406/")
self.find_text("Universal Converter Box", "div#ctitle", timeout=3)
self.open("http://xkcd.com/608/")
self.find_text("Form", "div#ctitle", timeout=3)
def test_4(self):
# This test should FAIL
print "\n(This test fails on purpose)"
self.open("http://xkcd.com/1670/")
self.find_element("FakeElement.DoesNotExist", timeout=0.5)
|
''' NOTE: This test suite contains 2 passing tests and 2 failing tests. '''
from seleniumbase import BaseCase
class MyTestSuite(BaseCase):
def test_1(self):
self.open("http://xkcd.com/1663/")
self.find_text("Garden", "div#ctitle", timeout=3)
for p in xrange(4):
self.click('a[rel="next"]')
self.find_text("Algorithms", "div#ctitle", timeout=3)
def test_2(self):
# This test should FAIL
self.open("http://xkcd.com/1675/")
raise Exception("FAKE EXCEPTION: This test fails on purpose.")
def test_3(self):
self.open("http://xkcd.com/1406/")
self.find_text("Universal Converter Box", "div#ctitle", timeout=3)
self.open("http://xkcd.com/608/")
self.find_text("Form", "div#ctitle", timeout=3)
def test_4(self):
# This test should FAIL
self.open("http://xkcd.com/1670/")
self.find_element("FakeElement.DoesNotExist", timeout=0.5)
|
Add survey title and subtitle to questionnaires
|
<?php
class QuestionnairesController extends Controller {
function view($token) {
$this->Questionnaire = new Database();
$this->Questionnaire->query('SELECT * FROM questionnaires WHERE token = :token');
$this->Questionnaire->bind(':token', $token);
$questionnaire = $this->Questionnaire->single();
$this->set('questionnaire', $questionnaire);
$this->Questionnaire = new Database();
$this->Questionnaire->query('SELECT * FROM surveys WHERE id = :survey_id');
$this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
$survey = $this->Questionnaire->single();
$this->set('survey', $survey);
$this->Questionnaire = new Database();
$this->Questionnaire->query('SELECT * FROM questions WHERE survey_id = :survey_id');
$this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
$questions = $this->Questionnaire->resultSet();
if ($this->Questionnaire->rowCount() >= 1) {
$this->set('questions', $questions);
} else {
$this->set('error', __('missing-questions'));
}
$this->set('title', $survey['title']);
$this->set('subtitle', $survey['subtitle']);
}
}
|
<?php
class QuestionnairesController extends Controller {
function view($token) {
$this->Questionnaire = new Database();
$this->Questionnaire->query('SELECT * FROM questionnaires WHERE token = :token');
$this->Questionnaire->bind(':token', $token);
$questionnaire = $this->Questionnaire->single();
$this->set('questionnaire', $questionnaire);
$this->Questionnaire = new Database();
$this->Questionnaire->query('SELECT * FROM surveys WHERE id = :survey_id');
$this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
$survey = $this->Questionnaire->single();
$this->set('survey', $survey);
$this->Questionnaire = new Database();
$this->Questionnaire->query('SELECT * FROM questions WHERE survey_id = :survey_id');
$this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
$questions = $this->Questionnaire->resultSet();
if ($this->Questionnaire->rowCount() >= 1) {
$this->set('questions', $questions);
} else {
$this->set('error', __('missing-questions'));
}
$this->set('title', $survey['name']);
}
}
|
Set base class for view mixin to MultipleObjectMixin
|
from django.views.generic.list import MultipleObjectMixin
__all__ = ('FilterFormMixin',)
class FilterFormMixin(MultipleObjectMixin):
"""
Mixin that adds filtering behaviour for Class Based Views.
Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
get_context_data(self, **kwargs) method.
"""
filter_form_cls = None
use_filter_chaining = False
def get_filter(self):
return self.filter_form_cls(self.request.GET,
runtime_context=self.get_runtime_context(),
use_filter_chaining=self.use_filter_chaining)
def get_queryset(self):
qs = super(FilterFormMixin, self).get_queryset()
qs = self.get_filter().filter(qs).distinct()
return qs
def get_context_data(self, **kwargs):
context = super(FilterFormMixin, self).get_context_data(**kwargs)
context['filterform'] = self.get_filter()
return context
def get_runtime_context(self):
return {'user': self.request.user}
|
try:
from django.views.generic.base import ContextMixin as mixin_base
except ImportError:
mixin_base = object
__all__ = ('FilterFormMixin',)
class FilterFormMixin(mixin_base):
"""
Mixin that adds filtering behaviour for Class Based Views.
Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
get_context_data(self, **kwargs) method.
"""
filter_form_cls = None
use_filter_chaining = False
def get_filter(self):
return self.filter_form_cls(self.request.GET,
runtime_context=self.get_runtime_context(),
use_filter_chaining=self.use_filter_chaining)
def get_queryset(self):
qs = super(FilterFormMixin, self).get_queryset()
qs = self.get_filter().filter(qs).distinct()
return qs
def get_context_data(self, **kwargs):
context = super(FilterFormMixin, self).get_context_data(**kwargs)
context['filterform'] = self.get_filter()
return context
def get_runtime_context(self):
return {'user': self.request.user}
|
Use templates for stat properties.
|
import Transform from './Transform';
import Stats from '../server/Stats';
export default class StatsTransform extends Transform {
constructor(opts, config) {
super(opts);
this._stats = new Stats(config);
this._type = this.getOption('type', 'increment');
this._name = this.getOption('name');
this._value = this.getOption('value', '1');
}
close() {
this._stats.close();
}
process(event) {
try {
const value = parseInt(this._value.render(event), 10);
const type = this._type.render(event);
const name = this._name.render(event);
switch (type) {
case 'increment':
this._stats.increment(key, value);
break;
case 'gauge':
this._stats.gauge(name, value);
break;
}
return this.emit();
} catch (e) {
return this.fail(e);
}
}
}
|
import Transform from './Transform';
import Stats from '../server/Stats';
export default class StatsTransform extends Transform {
constructor(opts, config) {
super(opts);
this._stats = new Stats(config);
this._type = this.getOption('type', 'increment');
this._name = this.getOption('name');
this._value = this.getOption('value', '1');
}
close() {
this._stats.close();
}
process(event) {
const type = this._type.render(event);
const name = this._name.render(event);
let value;
try {
value = parseInt(this._value.render(event), 10);
} catch (e) {
return this.fail(e);
}
switch (type) {
case 'increment':
this._stats.increment(key, value);
break;
case 'gauge':
this._stats.gauge(name, value);
break;
}
return this.emit();
}
}
|
Update the echo Function to be similar to the template Function
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = False
verbose = False
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
return event
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
dumps(event, indent=4)
))
return event
# Comment or remove everything below before deploying to Lambda.
def local_testing():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print("Event:\n\n{}\n\nFunction Output:\n".format(
dumps(
event,
indent=4
)
))
lambda_handler(event, context)
local_testing()
|
Correct caja global var. caja___ is what is used, and not having this declared will cause dynamic JS compilation warnings/errors.
git-svn-id: 84334937b86421baa0e582c4ab1a9d358324cbeb@1084408 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* @namespace The global safeJSON namespace
* @type {Object}
*/
var safeJSON = window['safeJSON'];
/**
* @namespace The global tamings___ namespace
* @type {Array.<Function>}
*/
var tamings___ = window['tamings___'] || [];
/**
* @namespace The global bridge___ namespace
* @type {Object}
*/
var bridge___;
/**
* @namespace The global caja___ namespace
* @type {Object}
*/
var caja___ = window['caja___'];
/**
* @namespace The global ___ namespace
* @type {Object}
*/
var ___ = window['___'];
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* @namespace The global safeJSON namespace
* @type {Object}
*/
var safeJSON = window['safeJSON'];
/**
* @namespace The global tamings___ namespace
* @type {Array.<Function>}
*/
var tamings___ = window['tamings___'] || [];
/**
* @namespace The global bridge___ namespace
* @type {Object}
*/
var bridge___;
/**
* @namespace The global caja___ namespace
* @type {Object}
*/
var caja = window['caja___'];
/**
* @namespace The global ___ namespace
* @type {Object}
*/
var ___ = window['___'];
|
Fix typo in bucket name
|
# Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'licensing_journey': 'licensing_journey-bearer-token',
'licensing_monitoring': 'licensing_monitoring_bearer_token',
'licence_finder_monitoring': 'licence_finder_monitoring_bearer_token',
'govuk_realtime': 'govuk_realtime-bearer-token',
'licensing_realtime': 'licensing_realtime-bearer-token',
}
PERMISSIONS = {}
OAUTH_CLIENT_ID = \
"1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844"
OAUTH_CLIENT_SECRET = \
"8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a"
OAUTH_BASE_URL = "http://signon.dev.gov.uk"
|
# Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'licensing_journey': 'licensing_journey-bearer-token',
'licensing__monitoring': 'licensing_monitoring_bearer_token',
'licence_finder_monitoring': 'licence_finder_monitoring_bearer_token',
'govuk_realtime': 'govuk_realtime-bearer-token',
'licensing_realtime': 'licensing_realtime-bearer-token',
}
PERMISSIONS = {}
OAUTH_CLIENT_ID = \
"1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844"
OAUTH_CLIENT_SECRET = \
"8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a"
OAUTH_BASE_URL = "http://signon.dev.gov.uk"
|
Sort bar elements properly to make sure that they are always visible.
|
'use strict';
// External
import * as d3 from 'd3';
// Internal
import Bar from './bar';
import * as config from './config';
const BARS_CLASS = 'bars';
class Bars {
constructor (selection, visData) {
let that = this;
this.visData = visData;
this.selection = selection.append('g')
.attr('class', BARS_CLASS);
this.selection.each(function (datum) {
new Bar(d3.select(this), datum.data.bars, datum, that.visData);
});
}
update (selection, sortBy) {
selection.each(function () {
let el = d3.select(this);
if (el.classed('active')) {
el.classed('active', false);
} else {
el.classed('active', false);
// Ensure that the active bars we are places before any other bar,
// thus placing them in the background
this.parentNode.insertBefore(
this,
d3.select(this.parentNode).select('.bar').node()
);
}
});
selection.selectAll('.bar-magnitude')
.transition()
.duration(config.TRANSITION_SEMI_FAST)
.attr('d', data => {
return Bar.generatePath(data, sortBy, this.visData);
});
}
inactivate (selection) {
}
}
export default Bars;
|
'use strict';
// External
import * as d3 from 'd3';
// Internal
import Bar from './bar';
import * as config from './config';
const BARS_CLASS = 'bars';
class Bars {
constructor (selection, visData) {
let that = this;
this.visData = visData;
this.selection = selection.append('g')
.attr('class', BARS_CLASS);
this.selection.each(function (datum) {
new Bar(d3.select(this), datum.data.bars, datum, that.visData);
});
}
update (selection, sortBy) {
let actualBars = selection
.classed('active', true)
.selectAll('.bar-magnitude');
selection.each(data => {
// this.bar
});
actualBars
.transition()
.duration(config.TRANSITION_SEMI_FAST)
.attr('d', data => {
return Bar.generatePath(data, sortBy, this.visData);
});
}
inactivate (selection) {
}
}
export default Bars;
|
Add checking for zero distance
|
import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
distance = jellyfish.jaro_winkler(string1, string2)
if distance > 0.:
return round(distance, 3)
def __call__(self, unique_event_id):
distance = self.__jarowinkler(unique_event_id)
distance_with_id = (unique_event_id[0], unique_event_id[1], distance)
return distance_with_id
def get_jarowinkler(self):
# get unique event id combination
event_id_combination = list(combinations(xrange(self.event_length), 2))
# get distance with multiprocessing
pool = multiprocessing.Pool(processes=4)
distances = pool.map(self, event_id_combination)
pool.close()
pool.join()
return distances
|
import jellyfish
import multiprocessing
from itertools import combinations
class JaroWinkler(object):
def __init__(self, event_attributes, event_length):
self.event_attributes = event_attributes
self.event_length = event_length
def __jarowinkler(self, unique_event_id):
string1 = unicode(self.event_attributes[unique_event_id[0]]['preprocessed_event'], 'utf-8')
string2 = unicode(self.event_attributes[unique_event_id[1]]['preprocessed_event'], 'utf-8')
return jellyfish.jaro_winkler(string1, string2)
def __call__(self, unique_event_id):
distance = self.__jarowinkler(unique_event_id)
if distance > 0:
distance_with_id = (unique_event_id[0], unique_event_id[1], distance)
return distance_with_id
def get_jarowinkler(self):
# get unique event id combination
event_id_combination = list(combinations(xrange(self.event_length), 2))
# get distance with multiprocessing
pool = multiprocessing.Pool(processes=4)
distances = pool.map(self, event_id_combination)
pool.close()
pool.join()
return distances
|
Disable source mapping to speed up build time
|
var pkg = require('./package.json');
var node_modules = __dirname + '/node_modules';
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var environment = process.env.NODE_ENV;
module.exports = {
cache: true,
resolve: {
extensions: ['', '.jsx', '.scss', '.js', '.json']
},
context: __dirname,
entry: {
commons: ['./components/commons'],
test: ['webpack/hot/dev-server', './spec/index.jsx']
},
output: {
path: environment === 'production' ? './dist' : './build',
filename: pkg.name + '.[name].js',
publicPath: '/build/'
},
devServer: {
host: '0.0.0.0',
port: 8080,
inline: true
},
module: {
noParse: [node_modules + '/react/dist/*.js'],
loaders: [
{ test: /(\.js|\.jsx)$/, exclude: /(node_modules)/, loaders: ['babel'] },
{ test: /(\.scss|\.css)$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader!sass') }
]
},
postcss: [require('autoprefixer-core')],
plugins: [new ExtractTextPlugin(pkg.name + '.[name].css', {allChunks: true})]
};
|
var pkg = require('./package.json');
var node_modules = __dirname + '/node_modules';
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var environment = process.env.NODE_ENV;
module.exports = {
devtool: 'inline-source-map',
cache: true,
resolve: {
extensions: ['', '.jsx', '.scss', '.js', '.json']
},
context: __dirname,
entry: {
commons: ['./components/commons'],
test: ['webpack/hot/dev-server', './spec/index.jsx']
},
output: {
path: environment === 'production' ? './dist' : './build',
filename: pkg.name + '.[name].js',
publicPath: '/build/'
},
devServer: {
host: '0.0.0.0',
port: 8080,
inline: true
},
module: {
noParse: [node_modules + '/react/dist/*.js'],
loaders: [
{ test: /(\.js|\.jsx)$/, exclude: /(node_modules)/, loaders: ['babel'] },
{ test: /(\.scss|\.css)$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]&sourceMap!postcss-loader!sass?sourceMap') }
]
},
postcss: [require('autoprefixer-core')],
plugins: [new ExtractTextPlugin(pkg.name + '.[name].css', {allChunks: true})]
};
|
Use given parent graph, not stored one.
|
package com.coatedmoose.daggerizedandroid;
import android.app.Application;
import java.util.ArrayList;
import java.util.List;
import dagger.ObjectGraph;
/**
* Extend this class to have your application inject off of its graph
*/
public class DaggerApplication extends Application implements Injector, GraphHolder {
private ObjectGraph applicationGraph;
@Override
public void onCreate() {
super.onCreate();
applicationGraph = createObjectGraph(ObjectGraph.create());
inject(this);
}
@Override
public <T> T inject(T o) {
if (applicationGraph == null) {
throw new IllegalStateException("Application object graph needs to be initialized before calling inject");
}
return applicationGraph.inject(o);
}
@Override
public <T> T get(Class<T> classType) {
return applicationGraph.get(classType);
}
@Override
public List<Object> getModules() {
List<Object> modules = new ArrayList<>();
modules.add(new ApplicationModule(this));
return modules;
}
@Override
public ObjectGraph createObjectGraph(ObjectGraph parentGraph) {
return parentGraph.plus(getModules().toArray());
}
@Override
public ObjectGraph getObjectGraph() {
return applicationGraph;
}
}
|
package com.coatedmoose.daggerizedandroid;
import android.app.Application;
import java.util.ArrayList;
import java.util.List;
import dagger.ObjectGraph;
/**
* Extend this class to have your application inject off of its graph
*/
public class DaggerApplication extends Application implements Injector, GraphHolder {
private ObjectGraph applicationGraph;
@Override
public void onCreate() {
super.onCreate();
applicationGraph = createObjectGraph(ObjectGraph.create());
inject(this);
}
@Override
public <T> T inject(T o) {
if (applicationGraph == null) {
throw new IllegalStateException("Application object graph needs to be initialized before calling inject");
}
return applicationGraph.inject(o);
}
@Override
public <T> T get(Class<T> classType) {
return applicationGraph.get(classType);
}
@Override
public List<Object> getModules() {
List<Object> modules = new ArrayList<>();
modules.add(new ApplicationModule(this));
return modules;
}
@Override
public ObjectGraph createObjectGraph(ObjectGraph parentGraph) {
return applicationGraph.plus(getModules().toArray());
}
@Override
public ObjectGraph getObjectGraph() {
return applicationGraph;
}
}
|
Change ActivityType::getType() method to a non-static method
|
<?php
namespace Igniter\Flame\ActivityLog\Contracts;
use Igniter\Flame\ActivityLog\Models\Activity;
interface ActivityInterface
{
/**
* Get the type of this activity.
*
* @return string
*/
public function getType();
/**
* Get the user that triggered the activity.
*
* @return mixed
*/
public function getCauser();
/**
* Get the model that is the subject of this activity.
*
* @return mixed
*/
public function getSubject();
/**
* Get the data to be stored with the activity.
*
* @return array|null
*/
public function getProperties();
public static function getUrl(Activity $activity);
public static function getMessage(Activity $activity);
/**
* Get the name of the model class for the subject of this activity.
*
* @return string
*/
public static function getSubjectModel();
}
|
<?php
namespace Igniter\Flame\ActivityLog\Contracts;
use Igniter\Flame\ActivityLog\Models\Activity;
interface ActivityInterface
{
/**
* Get the user that triggered the activity.
*
* @return mixed
*/
public function getCauser();
/**
* Get the model that is the subject of this activity.
*
* @return mixed
*/
public function getSubject();
/**
* Get the data to be stored with the activity.
*
* @return array|null
*/
public function getProperties();
/**
* Get the type of this activity.
*
* @return string
*/
public static function getType();
public static function getUrl(Activity $activity);
public static function getMessage(Activity $activity);
/**
* Get the name of the model class for the subject of this activity.
*
* @return string
*/
public static function getSubjectModel();
}
|
Use defaultValue as a template, fix critical sync issue
|
const Sequelize = require('sequelize');
module.exports = {
JSONType: (fieldName, {defaultValue = {}} = {}) => ({
type: Sequelize.TEXT,
get: function get() {
const val = this.getDataValue(fieldName);
if (!val) {
return defaultValue ? Object.assign({}, defaultValue) : null;
}
return JSON.parse(val);
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
JSONARRAYType: (fieldName) => ({
type: Sequelize.TEXT,
get: function get() {
const val = this.getDataValue(fieldName);
if (!val) {
return [];
}
return JSON.parse(val);
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
}
|
const Sequelize = require('sequelize');
module.exports = {
JSONType: (fieldName, {defaultValue = {}} = {}) => ({
type: Sequelize.TEXT,
get: function get() {
const val = this.getDataValue(fieldName);
if (!val) { return defaultValue }
return JSON.parse(val);
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
JSONARRAYType: (fieldName, {defaultValue = []} = {}) => ({
type: Sequelize.TEXT,
get: function get() {
const val = this.getDataValue(fieldName);
if (!val) { return defaultValue }
return JSON.parse(val);
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
}
|
Reduce the width of dependency from analytic_operating_unit to operating_unit
|
# © 2019 Eficent Business and IT Consulting Services S.L.
# © 2019 Serpent Consulting Services Pvt. Ltd.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Accounting with Operating Units",
"summary": "Introduces Operating Unit (OU) in invoices and "
"Accounting Entries with clearing account",
"version": "13.0.1.1.0",
"author": "Eficent, "
"Serpent Consulting Services Pvt. Ltd.,"
"WilldooIT Pty Ltd,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/operating-unit",
"category": "Accounting & Finance",
"depends": ["account", "operating_unit"],
"license": "LGPL-3",
"data": [
"security/account_security.xml",
"views/account_move_view.xml",
"views/account_journal_view.xml",
"views/company_view.xml",
"views/account_payment_view.xml",
"views/account_invoice_report_view.xml",
],
}
|
# © 2019 Eficent Business and IT Consulting Services S.L.
# © 2019 Serpent Consulting Services Pvt. Ltd.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Accounting with Operating Units",
"summary": "Introduces Operating Unit (OU) in invoices and "
"Accounting Entries with clearing account",
"version": "13.0.1.1.0",
"author": "Eficent, "
"Serpent Consulting Services Pvt. Ltd.,"
"WilldooIT Pty Ltd,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/operating-unit",
"category": "Accounting & Finance",
"depends": ["account", "analytic_operating_unit"],
"license": "LGPL-3",
"data": [
"security/account_security.xml",
"views/account_move_view.xml",
"views/account_journal_view.xml",
"views/company_view.xml",
"views/account_payment_view.xml",
"views/account_invoice_report_view.xml",
],
}
|
Add check for if mobilenav exists
|
/* global document window */
import { focusFirstEl } from '../../../../../packages/spark-core/utilities/elementState';
const hideMobileNav = (nav) => {
document.body.classList.remove('sprk-u-OverflowHidden');
nav.classList.remove('is-active');
};
const focusTrap = (nav, mainNav) => {
if (nav.classList.contains('is-active')) {
focusFirstEl(mainNav);
}
};
const bindUIEvents = () => {
const nav = document.querySelector('.drizzle-o-Layout__nav');
if (nav === null) return;
const mainNav = nav.querySelector('.drizzle-c-Navigation__main');
const mainLayout = document.querySelector('.drizzle-o-Layout__main');
window.addEventListener('resize', () => {
hideMobileNav(nav);
});
mainLayout.addEventListener('focusin', () => {
focusTrap(nav, mainNav);
});
};
const mobileNav = () => {
bindUIEvents();
};
export { mobileNav, hideMobileNav, focusTrap };
|
/* global document window */
import { focusFirstEl } from '../../../../../packages/spark-core/utilities/elementState';
const hideMobileNav = (nav) => {
document.body.classList.remove('sprk-u-OverflowHidden');
nav.classList.remove('is-active');
};
const focusTrap = (nav, mainNav) => {
if (nav.classList.contains('is-active')) {
focusFirstEl(mainNav);
}
};
const bindUIEvents = () => {
const nav = document.querySelector('.drizzle-o-Layout__nav');
const mainNav = nav.querySelector('.drizzle-c-Navigation__main');
const mainLayout = document.querySelector('.drizzle-o-Layout__main');
window.addEventListener('resize', () => {
hideMobileNav(nav);
});
mainLayout.addEventListener('focusin', () => {
focusTrap(nav, mainNav);
});
};
const mobileNav = () => {
bindUIEvents();
};
export { mobileNav, hideMobileNav, focusTrap };
|
Fix wrong prop type in prop validation
useWrapper now validated as boolean value, instead of string
|
import React from "react";
class Button extends React.Component {
buttonWithWrapper () {
return (
<ButtonWrapper>
<button onClick={this.props.onClick}
style={buttonStyle}
>
{this.props.text}
</button>
</ButtonWrapper>
);
}
buttonWithoutWrapper () {
return (
<button onClick={this.props.onClick}
style={buttonStyle}
>
{this.props.text}
</button>
);
}
render () {
return (
this.props.useWrapper ?
this.buttonWithWrapper() :
this.buttonWithoutWrapper()
);
}
}
Button.propTypes = {
onClick: React.PropTypes.func.isRequired,
text: React.PropTypes.string,
useWrapper: React.PropTypes.bool
};
let buttonStyle = {
fontSize: "1.5rem",
boxShadow: "0.2rem 0.2rem 0.2rem rgba(0,0,0,0.8)"
};
const ButtonWrapper = (props) => {
let wrapperStyle = {
margin: "1rem auto"
}
return (
<div style={wrapperStyle}>
{props.children}
</div>
);
}
export default Button;
|
import React from "react";
class Button extends React.Component {
buttonWithWrapper () {
return (
<ButtonWrapper>
<button onClick={this.props.onClick}
style={buttonStyle}
>
{this.props.text}
</button>
</ButtonWrapper>
);
}
buttonWithoutWrapper () {
return (
<button onClick={this.props.onClick}
style={buttonStyle}
>
{this.props.text}
</button>
);
}
render () {
return (
this.props.useWrapper ?
this.buttonWithWrapper() :
this.buttonWithoutWrapper()
);
}
}
Button.propTypes = {
onClick: React.PropTypes.func.isRequired,
text: React.PropTypes.string,
useWrapper: React.PropTypes.string
};
let buttonStyle = {
fontSize: "1.5rem",
boxShadow: "0.2rem 0.2rem 0.2rem rgba(0,0,0,0.8)"
};
const ButtonWrapper = (props) => {
let wrapperStyle = {
margin: "1rem auto"
}
return (
<div style={wrapperStyle}>
{props.children}
</div>
);
}
export default Button;
|
Revert "fixed rendering of Sass and Coffee"
This reverts commit b21834c9d439603f666d17aea338934bae063ef4.
|
from os.path import join, splitext, basename
from bricks.staticfiles import StaticCss, StaticJs, StaticFile
class _BuiltStatic(StaticFile):
has_build_stage = True
def __init__(self, *args):
StaticFile.__init__(self, *args)
self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type
class Sass(_BuiltStatic):
relpath = 'scss'
target_type = 'css'
class Coffee(_BuiltStatic):
relpath = 'coffee'
target_type = 'js'
class StaticLib(StaticFile):
"""A static asset or a directory with static assets that's needed
to build other static assets but is not directly used by the page."""
has_build_stage = True
def __call__(self):
return ''
class SassLib(StaticLib):
relpath = 'scss'
|
from os.path import join, splitext, basename
from bricks.staticfiles import StaticCss, StaticJs, StaticFile
class _BuiltStatic(StaticFile):
has_build_stage = True
def __init__(self, *args):
StaticFile.__init__(self, *args)
self.url = self.url.rsplit('.', 1)[0] + '.' + self.target_type
class Sass(_BuiltStatic):
relpath = 'scss'
target_type = 'css'
def __call__(self):
return '<link rel="stylesheet" href="{}" />'.format(self.url)
class Coffee(_BuiltStatic):
relpath = 'coffee'
target_type = 'js'
def __call__(self):
return '<script src="{}"></script>'.format(self.url)
class StaticLib(StaticFile):
"""A static asset or a directory with static assets that's needed
to build other static assets but is not directly used by the page."""
has_build_stage = True
def __call__(self):
return ''
class SassLib(StaticLib):
relpath = 'scss'
|
Fix remove query causing tests to hang
|
if (Meteor.isServer) {
const _resetDatabase = function (options) {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'resetDatabase is not allowed outside of a development mode. ' +
'Aborting.'
);
}
options = options || {};
var excludedCollections = ['system.indexes'];
if (options.excludedCollections) {
excludedCollections = excludedCollections.concat(options.excludedCollections);
}
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var getCollections = Meteor.wrapAsync(db.collections, db);
var collections = getCollections();
var appCollections = _.reject(collections, function (col) {
return col.collectionName.indexOf('velocity') === 0 ||
excludedCollections.indexOf(col.collectionName) !== -1;
});
_.each(appCollections, function (appCollection) {
var remove = Meteor.wrapAsync(appCollection.remove, appCollection);
remove();
});
};
Meteor.methods({
'xolvio:cleaner/resetDatabase': function (options) {
_resetDatabase(options);
}
});
resetDatabase = function(options, callback) {
_resetDatabase(options);
if (typeof callback === 'function') { callback(); }
}
}
if (Meteor.isClient) {
resetDatabase = function(options, callback) {
Meteor.call('xolvio:cleaner/resetDatabase', options, callback);
}
}
|
if (Meteor.isServer) {
const _resetDatabase = function (options) {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'resetDatabase is not allowed outside of a development mode. ' +
'Aborting.'
);
}
options = options || {};
var excludedCollections = ['system.indexes'];
if (options.excludedCollections) {
excludedCollections = excludedCollections.concat(options.excludedCollections);
}
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var getCollections = Meteor.wrapAsync(db.collections, db);
var collections = getCollections();
var appCollections = _.reject(collections, function (col) {
return col.collectionName.indexOf('velocity') === 0 ||
excludedCollections.indexOf(col.collectionName) !== -1;
});
_.each(appCollections, function (appCollection) {
var remove = Meteor.wrapAsync(appCollection.remove, appCollection);
remove({});
});
};
Meteor.methods({
'xolvio:cleaner/resetDatabase': function (options) {
_resetDatabase(options);
}
});
resetDatabase = function(options, callback) {
_resetDatabase(options);
if (typeof callback === 'function') { callback(); }
}
}
if (Meteor.isClient) {
resetDatabase = function(options, callback) {
Meteor.call('xolvio:cleaner/resetDatabase', options, callback);
}
}
|
Add missing --name flag to 'envy snapshot'
|
from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.set_defaults(func=self.run)
subparser.add_argument('-n', '--name', action='store', default='',
help='Specify custom name for an ENVy.')
return subparser
#TODO(jakedahn): The entire UX for this needs to be talked about, refer to
# https://github.com/bcwaldon/cloudenvy/issues/27 for any
# discussion, if you're curious.
def run(self, config, args):
envy = Envy(config)
envy.snapshot('%s-snapshot' % envy.name)
|
from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.set_defaults(func=self.run)
return subparser
#TODO(jakedahn): The entire UX for this needs to be talked about, refer to
# https://github.com/bcwaldon/cloudenvy/issues/27 for any
# discussion, if you're curious.
def run(self, config, args):
envy = Envy(config)
envy.snapshot('%s-snapshot' % envy.name)
|
Add insurance shape to blacklist
|
import AsyncStorage from '@react-native-community/async-storage';
import { persistStore, persistReducer } from 'redux-persist';
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { createReactNavigationReduxMiddleware } from 'react-navigation-redux-helpers';
import reducers from './reducers';
// Create middleware and connect
const appNavigatorMiddleware = createReactNavigationReduxMiddleware(state => state.nav, 'root');
const persistConfig = {
keyPrefix: '',
key: 'root',
storage: AsyncStorage,
blacklist: [
'nav',
'pages',
'user',
'prescription',
'patient',
'form',
'prescriber',
'wizard',
'payment',
'insurance',
],
};
const persistedReducer = persistReducer(persistConfig, reducers);
const store = createStore(persistedReducer, {}, applyMiddleware(thunk, appNavigatorMiddleware));
const persistedStore = persistStore(store);
export { store, persistedStore };
|
import AsyncStorage from '@react-native-community/async-storage';
import { persistStore, persistReducer } from 'redux-persist';
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { createReactNavigationReduxMiddleware } from 'react-navigation-redux-helpers';
import reducers from './reducers';
// Create middleware and connect
const appNavigatorMiddleware = createReactNavigationReduxMiddleware(state => state.nav, 'root');
const persistConfig = {
keyPrefix: '',
key: 'root',
storage: AsyncStorage,
blacklist: [
'nav',
'pages',
'user',
'prescription',
'patient',
'form',
'prescriber',
'wizard',
'payment',
],
};
const persistedReducer = persistReducer(persistConfig, reducers);
const store = createStore(persistedReducer, {}, applyMiddleware(thunk, appNavigatorMiddleware));
const persistedStore = persistStore(store);
export { store, persistedStore };
|
Use json.Decoder instead of json.Unmarshal.
|
package fleet
import (
"encoding/json"
"net"
"net/http"
)
type Client struct {
http *http.Client
}
type Unit struct {
CurrentState string `json:"currentState"`
DesiredState string `json:"desiredState"`
MachineID string `json:"machineID"`
Name string `json:"name"`
}
type UnitsResponse struct {
Units []Unit `json:"units"`
}
func NewClient(path string) Client {
dialFunc := func(string, string) (net.Conn, error) {
return net.Dial("unix", path)
}
httpClient := http.Client{
Transport: &http.Transport{
Dial: dialFunc,
},
}
return Client{&httpClient}
}
func (self *Client) Units() ([]Unit, error) {
response, err := self.http.Get("http://sock/fleet/v1/units")
if err != nil {
return nil, err
}
decoder := json.NewDecoder(response.Body)
var parsedResponse UnitsResponse
err = decoder.Decode(&parsedResponse)
if err != nil {
return nil, err
}
return parsedResponse.Units, nil
}
|
package fleet
import (
"encoding/json"
"io/ioutil"
"net"
"net/http"
)
type Client struct {
http *http.Client
}
type Unit struct {
CurrentState string `json:"currentState"`
DesiredState string `json:"desiredState"`
MachineID string `json:"machineID"`
Name string `json:"name"`
}
type UnitsResponse struct {
Units []Unit `json:"units"`
}
func NewClient(path string) Client {
dialFunc := func(string, string) (net.Conn, error) {
return net.Dial("unix", path)
}
httpClient := http.Client{
Transport: &http.Transport{
Dial: dialFunc,
},
}
return Client{&httpClient}
}
func (self *Client) Units() ([]Unit, error) {
response, err := self.http.Get("http://sock/fleet/v1/units")
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
var parsedResponse UnitsResponse
err = json.Unmarshal(body, &parsedResponse)
if err != nil {
return nil, err
}
return parsedResponse.Units, nil
}
|
Refactor - modify file require
|
const indexer = require('../../src/inverted-index');
describe('Inverted Index Tests', function() {
let fileName = './books.json';
beforeEach(function(done) {
indexer.createIndex(fileName);
done();
});
describe('Read book data', function() {
it('asserts that the file content is actually a valid JSON Array', function() {
expect(indexer.createIndex).toBeDefined();
});
it('asserts that json file is not empty', function() {
expect(indexer.createIndex).not.toEqual([]);
});
});
describe('Populate index', function() {
it('ensures that the index is correct', function() {
expect(indexer.getIndex.length).not.toBe(null);
});
it('verifies that the index is created once the JSON file has been read', function() {
expect(indexer.getIndex).toBeDefined();
});
it('index maps the string keys to the correct objects in the JSON array', function() {
expect(indexer.searchIndex(fileName, 'alice').alice).toEqual([1]);
expect(indexer.searchIndex(fileName, 'ring').ring).toEqual([2]);
});
});
describe('Search Index', function() {
it('verifies that searching the index returns an array of the indices of the correct objects', function() {
expect(indexer.searchIndex(fileName, 'alice').alice).toEqual([1]);
expect(indexer.searchIndex(fileName, 'ring').ring).toEqual([2]);
});
});
});
|
const indexer = require('../../src/Inverted-index');
describe('Inverted Index Tests', function() {
let fileName = './books.json';
beforeEach(function(done) {
indexer.createIndex(fileName);
done();
});
describe('Read book data', function() {
it('asserts that the file content is actually a valid JSON Array', function() {
expect(indexer.createIndex).toBeDefined();
});
it('asserts that json file is not empty', function() {
expect(indexer.createIndex).not.toEqual([]);
});
});
describe('Populate index', function() {
it('ensures that the index is correct', function() {
expect(indexer.getIndex.length).not.toBe(null);
});
it('verifies that the index is created once the JSON file has been read', function() {
expect(indexer.getIndex).toBeDefined();
});
it('index maps the string keys to the correct objects in the JSON array', function() {
expect(indexer.searchIndex(fileName, 'alice').alice).toEqual([1]);
expect(indexer.searchIndex(fileName, 'ring').ring).toEqual([2]);
});
});
describe('Search Index', function() {
it('verifies that searching the index returns an array of the indices of the correct objects', function() {
expect(indexer.searchIndex(fileName, 'alice').alice).toEqual([1]);
expect(indexer.searchIndex(fileName, 'ring').ring).toEqual([2]);
});
});
});
|
Remove comment in the while loop
|
!function(){
window.attachSpinnerEvents = function () {
var spinners = document.querySelectorAll('.toggle-spinner'),
i = spinners.length;
while (i--) {
var s = spinners[i];
s.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
var target = e.target;
if (e.target.nodeName === 'I') {
target = e.target.parentNode;
}
var spinner = target.parentNode.querySelectorAll('.spinner')[0];
spinner.classList.toggle('active');
});
}
// Close spinner event handler
document.addEventListener('click', function (e) {
var els = document.querySelectorAll('.spinner'),
o = els.length;
while (o--) els[o].classList.remove('active');
});
}
attachSpinnerEvents();
}();
|
!function(){
window.attachSpinnerEvents = function () {
var spinners = document.querySelectorAll('.toggle-spinner'),
i = spinners.length;
while (i--) {
console.log('Attaching spinners');
var s = spinners[i];
s.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
var target = e.target;
if (e.target.nodeName === 'I') {
target = e.target.parentNode;
}
var spinner = target.parentNode.querySelectorAll('.spinner')[0];
spinner.classList.toggle('active');
});
}
// Close spinner event handler
document.addEventListener('click', function (e) {
var els = document.querySelectorAll('.spinner'),
o = els.length;
while (o--) els[o].classList.remove('active');
});
}
attachSpinnerEvents();
}();
|
Check dropped file is a GPX file
|
( function() {
var runMaker = new RunMaker();
var fileDropArea = document.getElementById( 'drop_zone' );
fileDropArea.addEventListener( 'drop', dropFile, false );
fileDropArea.addEventListener( 'dragover', cancel, false );
fileDropArea.addEventListener( 'dragenter', cancel, false );
fileDropArea.addEventListener( 'dragexit', cancel, false );
function dropFile( evt ) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
if( files.length ) {
var extension = files[ 0 ].name.split( '.' ).pop().toLowerCase();
if( extension === 'gpx' ) {
go( files[ 0 ] );
} else {
alert( 'GPX file please!' );
}
}
}
function go( file ) {
runMaker.makeRun( file );
fileDropArea.classList.add( 'dropped' );
}
function cancel( evt ) {
evt.preventDefault();
}
} )();
|
( function() {
var runMaker = new RunMaker();
var fileDropArea = document.getElementById( 'drop_zone' );
fileDropArea.addEventListener( 'drop', dropFile, false );
fileDropArea.addEventListener( 'dragover', cancel, false );
fileDropArea.addEventListener( 'dragenter', cancel, false );
fileDropArea.addEventListener( 'dragexit', cancel, false );
function dropFile( evt ) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
if( files.length ) {
go( files[ 0 ] );
}
}
function go( file ) {
runMaker.makeRun( file );
fileDropArea.classList.add( 'dropped' );
}
function cancel( evt ) {
evt.preventDefault();
}
} )();
|
Update GitHub repos from blancltd to developersociety
|
#!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/developersociety/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
|
#!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
|
Add colored time in output
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import time
import datetime
start_time = 0
def start_timer():
global start_time
start_time = int(round(time.time()*1000))
def log(operation=None, message=None, timestamp=True):
current_time = int(round(time.time() * 1000))
d = datetime.timedelta(milliseconds=current_time-start_time)
m = d.seconds // 60
s = d.seconds - (m * 60)
ms = d.microseconds // 10000
timestamp = "{:2}:{:02}.{:02}".format(m, s, ms)
if operation:
print("\033[34m{}\033[0m {:^15s} {}".format(timestamp, operation, message))
else:
print("\033[34m{}\033[0m {}".format(timestamp, message))
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import time
import datetime
start_time = 0
def start_timer():
global start_time
start_time = int(round(time.time()*1000))
def log(operation=None, message=None, timestamp=True):
current_time = int(round(time.time()*1000))
d = datetime.timedelta(milliseconds=current_time-start_time)
m = d.seconds // 60
s = d.seconds - (m * 60)
ms = d.microseconds//10000
timestamp = "{:02}:{:02}.{:02}".format(m, s, ms)
if operation:
print("{} {:^15s} {}".format(timestamp, operation, message))
else:
print("{} {}".format(timestamp, message))
|
Check err from feed.FetchBytes in test
|
package main
import (
"fmt"
"io/ioutil"
"testing"
rss "github.com/jteeuwen/go-pkg-rss"
"github.com/stretchr/testify/require"
)
var items []*rss.Item
var fixtures = []string{
"aws-ec2-us-east-1",
"crossfitwc",
"github-status",
"heroku-status",
"weather.gov-KPHL",
}
func Test_formatContent(t *testing.T) {
for _, fixture := range fixtures {
feed := rss.New(1, true, nil, testItemHandler)
items = []*rss.Item{}
xml, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.xml", fixture))
require.NoError(t, err)
b, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.out", fixture))
require.NoError(t, err)
expected := string(b)
err = feed.FetchBytes("http://example.com", xml, charsetReader)
require.NoError(t, err)
require.NotEmpty(t, items)
item := items[0]
c, err := extractContent(item)
require.NoError(t, err)
require.Equal(t, expected, formatContent(c))
}
}
func testItemHandler(feed *rss.Feed, ch *rss.Channel, newitems []*rss.Item) {
items = newitems
}
|
package main
import (
"fmt"
"io/ioutil"
"testing"
rss "github.com/jteeuwen/go-pkg-rss"
"github.com/stretchr/testify/require"
)
var items []*rss.Item
var fixtures = []string{
"aws-ec2-us-east-1",
"crossfitwc",
"github-status",
"heroku-status",
"weather.gov-KPHL",
}
func Test_formatContent(t *testing.T) {
for _, fixture := range fixtures {
feed := rss.New(1, true, nil, testItemHandler)
items = []*rss.Item{}
xml, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.xml", fixture))
require.NoError(t, err)
b, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s.out", fixture))
require.NoError(t, err)
expected := string(b)
feed.FetchBytes("http://example.com", xml, charsetReader)
require.NotEmpty(t, items)
item := items[0]
c, err := extractContent(item)
require.NoError(t, err)
require.Equal(t, expected, formatContent(c))
}
}
func testItemHandler(feed *rss.Feed, ch *rss.Channel, newitems []*rss.Item) {
items = newitems
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.