text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use stat instead of this. | import os
import site
import sys
import stat
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
| import os
import site
import sys
import this
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(this.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
|
Allow newer neo4j driver versions (<2) | from setuptools import setup, find_packages
version = '1.1.3'
requires = [
'neo4j-driver<2.0',
'six>=1.10.0',
]
testing_requires = [
'nose',
'coverage',
'nosexcover',
]
setup(
name='norduniclient',
version=version,
url='https://github.com/NORDUnet/python-norduniclient',
license='Apache License, Version 2.0',
author='Johan Lundberg',
author_email='lundberg@nordu.net',
description='Neo4j (>=3.2.2) database client using bolt for NORDUnet network inventory',
packages=find_packages(),
zip_safe=False,
install_requires=requires,
tests_require=testing_requires,
test_suite='nose.collector',
extras_require={
'testing': testing_requires
}
)
| from setuptools import setup, find_packages
version = '1.1.3'
requires = [
'neo4j-driver<1.5.0',
'six>=1.10.0',
]
testing_requires = [
'nose',
'coverage',
'nosexcover',
]
setup(
name='norduniclient',
version=version,
url='https://github.com/NORDUnet/python-norduniclient',
license='Apache License, Version 2.0',
author='Johan Lundberg',
author_email='lundberg@nordu.net',
description='Neo4j (>=3.2.2) database client using bolt for NORDUnet network inventory',
packages=find_packages(),
zip_safe=False,
install_requires=requires,
tests_require=testing_requires,
test_suite='nose.collector',
extras_require={
'testing': testing_requires
}
)
|
Improve the metadata describing the package | # -*- encoding: utf-8 -*-
'''A setuptools script to install strip_recipes
'''
from setuptools import setup
setup(
name='strip_recipes',
version='1.0.0',
description='Create recipes for the LSPE/Strip tester software',
long_description='''
Python library to easily create complex recipes to be used with the LSPE/Strip
tester software. All the Python control structures (if, while, for) can be used.
(LSPE is a balloon/ground experiment to search for the B-mode signal in the
polarization pattern of the Cosmic Microwave Background. Strip is the low-frequency
polarimetric instrument that will measure the sky from the ground.)''',
author='Maurizio Tomasi',
author_email='maurizio.tomasi@unimiREMOVETHIS.it',
url='https://github.com/ziotom78/strip_recipes',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Topic :: Scientific/Engineering :: Astronomy',
'Topic :: Scientific/Engineering :: Physics',
'Topic :: Software Development :: Code Generators'
],
keywords='cosmology laboratory',
test_suite='nose.collector',
tests_require=['nose']
)
| # -*- encoding: utf-8 -*-
'''A setuptools script to install strip_recipes
'''
from setuptools import setup
setup(
name='strip_recipes',
version='1.0.0',
description='Create recipes for the LSPE/Strip tester software',
long_description='''
Python library to easily create complex recipes to be used with the LSPE/Strip
tester software. All the Python control structures (if, while, for) can be used''',
author='Maurizio Tomasi',
author_email='maurizio.tomasi@unimiREMOVETHIS.it',
url='https://github.com/ziotom78/strip_recipes',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers'
],
keywords='cosmology laboratory',
test_suite='nose.collector',
tests_require=['nose']
)
|
Fix external link file selection handler referer
REDMINE-17703 | import {editor} from 'pageflow-scrolled/editor';
import {SidebarRouter} from './SidebarRouter';
import {SidebarController} from './SidebarController';
import {SidebarListView} from './SidebarListView';
import {ExternalLinkCollection} from './models/ExternalLinkCollection';
//register sidebar router to handle multiple sidebar views of this content element
//router defines the URL hash path mapping and controller provides functions for the paths
editor.registerSideBarRouting({
router: SidebarRouter,
controller: SidebarController
});
// register external link list content element configuration editor for sidebar
editor.contentElementTypes.register('externalLinkList', {
configurationEditor({entry}) {
this.tab('general', function() {
this.view(SidebarListView, {
contentElement: this.model.parent,
collection: ExternalLinkCollection.forContentElement(this.model.parent, entry)
});
});
}
});
// register file handler for thumbnail of external link
editor.registerFileSelectionHandler('contentElement.externalLinks.link', function (options) {
const contentElement = options.entry.contentElements.get(options.contentElementId);
const links = ExternalLinkCollection.forContentElement(contentElement, options.entry)
this.call = function(file) {
const link = links.get(options.id);
link.setReference('thumbnail', file);
};
this.getReferer = function() {
return '/scrolled/external_links/' + contentElement.id + '/' + options.id;
};
});
| import {editor} from 'pageflow-scrolled/editor';
import {SidebarRouter} from './SidebarRouter';
import {SidebarController} from './SidebarController';
import {SidebarListView} from './SidebarListView';
import {ExternalLinkCollection} from './models/ExternalLinkCollection';
//register sidebar router to handle multiple sidebar views of this content element
//router defines the URL hash path mapping and controller provides functions for the paths
editor.registerSideBarRouting({
router: SidebarRouter,
controller: SidebarController
});
// register external link list content element configuration editor for sidebar
editor.contentElementTypes.register('externalLinkList', {
configurationEditor({entry}) {
this.tab('general', function() {
this.view(SidebarListView, {
contentElement: this.model.parent,
collection: ExternalLinkCollection.forContentElement(this.model.parent, entry)
});
});
}
});
// register file handler for thumbnail of external link
editor.registerFileSelectionHandler('contentElement.externalLinks.link', function (options) {
const contentElement = options.entry.contentElements.get(options.contentElementId);
const links = ExternalLinkCollection.forContentElement(contentElement, options.entry)
this.call = function(file) {
const link = links.get(options.id);
link.setReference('thumbnail', file);
};
this.getReferer = function() {
return '/scrolled/' + contentElement.id + '/' + options.id;
};
});
|
Fix missing row iteration in HTMLExporter | from django.template import Context
from django.template.loader import get_template
from _base import BaseExporter
class HTMLExporter(BaseExporter):
preferred_formats = ('html', 'string')
def write(self, iterable, buff=None, template=None):
if not buff and not template:
raise Exception('Either a file-like object or template must be supplied')
generator = self.read(iterable)
if buff:
for row in generator:
for item in row:
buff.write(item)
return buff
context = Context({'rows': generator})
if isinstance(template, basestring):
template = get_template(template)
return template.render(context)
| from django.template import Context
from django.template.loader import get_template
from _base import BaseExporter
class HTMLExporter(BaseExporter):
preferred_formats = ('html', 'string')
def write(self, iterable, buff=None, template=None):
if not buff and not template:
raise Exception('Either a file-like object or template must be supplied')
generator = self.read(iterable)
if buff:
for row in generator:
buff.write(row)
return buff
context = Context({'rows': generator})
if isinstance(template, basestring):
template = get_template(template)
return template.render(context)
|
Remove indent with spaces option | var mumuki = mumuki || {};
(function (mumuki) {
function CodeMirrorBuilder(textarea) {
this.textarea = textarea;
this.$textarea = $(textarea);
}
CodeMirrorBuilder.prototype = {
setupEditor: function () {
this.editor = CodeMirror.fromTextArea(this.textarea);
},
setupLanguage: function () {
var language = this.$textarea.data('editor-language');
if (language === 'dynamic') {
mumuki.page.dynamicEditors.push(this.editor);
} else {
mumuki.editor.setOption('mode', language);
}
},
setupPlaceholder: function (text) {
this.editor.setOption('placeholder', text);
},
setupOptions: function (minLines) {
this.editor.setOption('tabSize', 2);
this.editor.setOption('lineWrapping', true);
this.editor.setOption('lineNumbers', true);
this.editor.setOption('showCursorWhenSelecting', true);
this.editor.setOption('lineWiseCopyCut', true);
this.editor.setOption('cursorHeight', 1);
},
build: function () {
return this.editor;
}
};
mumuki.editor = mumuki.editor || {};
mumuki.editor.CodeMirrorBuilder = CodeMirrorBuilder;
}(mumuki));
| var mumuki = mumuki || {};
(function (mumuki) {
function CodeMirrorBuilder(textarea) {
this.textarea = textarea;
this.$textarea = $(textarea);
}
CodeMirrorBuilder.prototype = {
setupEditor: function () {
this.editor = CodeMirror.fromTextArea(this.textarea);
},
setupLanguage: function () {
var language = $(this.textarea).data('editor-language');
if (language === 'dynamic') {
mumuki.page.dynamicEditors.push(this.editor);
} else {
mumuki.editor.setOption('mode', language);
}
},
setupPlaceholder: function (text) {
this.editor.setOption('placeholder', text);
},
setupOptions: function (minLines) {
this.editor.setOption('tabSize', 2);
this.editor.setOption('indentWithTabs', true);
this.editor.setOption('lineWrapping', true);
this.editor.setOption('lineNumbers', true);
this.editor.setOption('showCursorWhenSelecting', true);
this.editor.setOption('lineWiseCopyCut', true);
this.editor.setOption('cursorHeight', 1);
},
build: function () {
return this.editor;
}
};
mumuki.editor = mumuki.editor || {};
mumuki.editor.CodeMirrorBuilder = CodeMirrorBuilder;
}(mumuki));
|
Add prefill_cache to make test_categorie_fiscale pass | # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# OpenFisca is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from openfisca_core.tools import assert_near
from .. import init_country
__all__ = [
'assert_near',
'tax_benefit_system',
'TaxBenefitSystem',
]
TaxBenefitSystem = init_country()
tax_benefit_system = TaxBenefitSystem()
tax_benefit_system.prefill_cache()
| # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# OpenFisca is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from openfisca_core.tools import assert_near
from .. import init_country
__all__ = [
'assert_near',
'tax_benefit_system',
'TaxBenefitSystem',
]
TaxBenefitSystem = init_country()
tax_benefit_system = TaxBenefitSystem()
|
Delete module from cache when requiring again | var http = require('http')
, path = require('path')
, fs = require('fs')
, requireAgain = function(event,filename){
var ext = path.extname(filename)
, name = path.basename(filename,ext)
if (require.cache[name]) delete require.cache[name]
require(filename)
}
, requireAll = function(dir,callback){
fs.readdir(dir,function(e,files){
if (!e) files.forEach(function(filename,filenumber){
requireAgain('rename',filename)
if (filenumber===files.length-1) callback()
})
})
}
, router = function(req,res){
require.main.exports.get()
}
exports = function(port){
var dir = path.dirname(require.main.filename)
requireAll(dir,function(){
fs.watch(dir,requireAgain)
http.createServer(router).listen(port)
})
}
| var http = require('http')
, path = require('path')
, fs = require('fs')
, modules = {}
, requireAgain = function(event,filename){
var ext = path.extname(filename)
, name = path.basename(filename,ext)
modules[name] = require(filename)
}
, requireAll = function(dir,callback){
fs.readdir(dir,function(e,files){
if (!e) files.forEach(function(filename,filenumber){
requireAgain('rename',filename)
if (filenumber===files.length-1) callback()
})
})
}
, router = function(req,res){
require.main.exports.get()
}
exports = function(port){
var dir = path.dirname(require.main.filename)
requireAll(dir,function(){
fs.watch(dir,requireAgain)
http.createServer(router).listen(port)
})
}
|
Increase WebSocket limit in FF to be as in Chrome | /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.
*/
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
basePath: '../../',
files: ['lib/browser/neo4j-web.test.js'],
reporters: ['spec'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_DEBUG,
browsers: ['FirefoxHeadless'],
autoWatch: false,
singleRun: true,
concurrency: 1,
browserNoActivityTimeout: 30 * 60 * 1000,
customLaunchers: {
FirefoxHeadless: {
base: 'Firefox',
flags: [ '-headless' ],
prefs: {
'network.websocket.max-connections': 256 // as in Chrome
}
},
},
})
}
| /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.
*/
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
basePath: '../../',
files: ['lib/browser/neo4j-web.test.js'],
reporters: ['spec'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_DEBUG,
browsers: ['FirefoxHeadless'],
autoWatch: false,
singleRun: true,
concurrency: 1,
browserNoActivityTimeout: 30 * 60 * 1000,
customLaunchers: {
FirefoxHeadless: {
base: 'Firefox',
flags: [ '-headless' ],
},
},
})
}
|
Support endpoint name in route. | import logging
__license__ = "MIT"
__project__ = "Flask-Restler"
__version__ = "1.6.2"
logger = logging.getLogger('flask-restler')
logger.addHandler(logging.NullHandler())
class APIError(Exception):
"""Store API exception's information."""
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['error'] = self.message
rv['code'] = rv.get('code', self.status_code)
return rv
def route(rule=None, endpoint=None, **options):
"""Custom routes in resources."""
def decorator(f):
endpoint_ = endpoint or f.__name__.lower()
f.route = (rule, endpoint_, options)
return f
if callable(rule):
rule, f = rule.__name__.lower(), rule
return decorator(f)
return decorator
from .api import Api, Resource # noqa
| import logging
__license__ = "MIT"
__project__ = "Flask-Restler"
__version__ = "1.6.2"
logger = logging.getLogger('flask-restler')
logger.addHandler(logging.NullHandler())
class APIError(Exception):
"""Store API exception's information."""
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['error'] = self.message
rv['code'] = rv.get('code', self.status_code)
return rv
def route(rule=None, endpoint=None, **options):
"""Custom routes in resources."""
def decorator(f):
endpoint_ = f.__name__.lower()
f.route = (rule, endpoint_, options)
return f
if callable(rule):
rule, f = rule.__name__.lower(), rule
return decorator(f)
return decorator
from .api import Api, Resource # noqa
|
Use Component instances in options | import startCase from 'lodash/startCase'
import PropTypes from 'prop-types'
import React from 'react'
import Panel from 'react-bootstrap/lib/Panel'
import Tab from 'react-bootstrap/lib/Tab'
import Tabs from 'react-bootstrap/lib/Tabs'
import Icon from 'react-fa'
import { connect } from 'react-redux'
import Custom from './Custom'
import Diceware from './Diceware'
import Generic from './Generic'
import { selector, setOptionsKey } from '../../reducers/optionsKey'
const options = {
generic: {
component: <Generic />,
icon: <Icon name="check-square" />
},
diceware: {
component: <Diceware />,
icon: <Icon name="book" />
},
custom: {
component: <Custom />,
icon: <Icon name="question-circle" />
}
}
export function Options({ optionsKey, setOptionsKey }) {
return (
<Tabs activeKey={optionsKey} onSelect={setOptionsKey} id="options">
{Object.entries(options).map(([name, { component, icon }]) => (
<Tab key={name} eventKey={name} title={<div>{icon} {startCase(name)}</div>}>
<Panel>{component}</Panel>
</Tab>
))}
</Tabs>
)
}
Options.propTypes = {
optionsKey: PropTypes.string.isRequired,
setOptionsKey: PropTypes.func.isRequired
}
export default connect(selector, { setOptionsKey })(Options)
| import startCase from 'lodash/startCase'
import PropTypes from 'prop-types'
import React from 'react'
import Panel from 'react-bootstrap/lib/Panel'
import Tab from 'react-bootstrap/lib/Tab'
import Tabs from 'react-bootstrap/lib/Tabs'
import Icon from 'react-fa'
import { connect } from 'react-redux'
import Custom from './Custom'
import Diceware from './Diceware'
import Generic from './Generic'
import { selector, setOptionsKey } from '../../reducers/optionsKey'
const options = {
generic: {
Component: Generic,
icon: 'check-square'
},
diceware: {
Component: Diceware,
icon: 'book'
},
custom: {
Component: Custom,
icon: 'question-circle'
}
}
export function Options({ optionsKey, setOptionsKey }) {
return (
<Tabs activeKey={optionsKey} onSelect={setOptionsKey} id="options">
{Object.entries(options).map(([name, { Component, icon }]) => (
<Tab key={name} eventKey={name} title={<div><Icon name={icon} /> {startCase(name)}</div>}>
<Panel><Component /></Panel>
</Tab>
))}
</Tabs>
)
}
Options.propTypes = {
optionsKey: PropTypes.string.isRequired,
setOptionsKey: PropTypes.func.isRequired
}
export default connect(selector, { setOptionsKey })(Options)
|
Add 'config' as argument to rules' constructors | /**
* The core of BEM hint
* ====================
*/
var vow = require('vow'),
_ = require('lodash'),
scan = require('./walk'),
loadRules = require('./load-rules'),
Configuration = require('./configuration'),
utils = require('./utils');
/**
* Loads the BEM entities and checks them
* @param {Object} [loadedConfig]
* @param {String} [loadedConfig.configPath]
* @param {Array} [loadedConfig.levels]
* @param {Array} [loadedCinfig.excludeFiles]
* @param {Array} targets
* @returns {Promise * Array} - the list of BEM errors
*/
module.exports = function (loadedConfig, targets) {
var config = new Configuration(loadedConfig);
return vow.all([scan(targets, config), loadRules()])
.spread(function (entities, rules) {
return vow.all(_.keys(rules).map(function (rule) {
var _rule = new rules[rule](config);
return _rule.check(entities);
}));
})
.then(function (res) {
var bemErros = [];
_(res).keys().forEach(function (item) {
bemErros = bemErros.concat(res[item]);
});
return utils.sortByFullpath(bemErros);
});
};
| /**
* The core of BEM hint
* ====================
*/
var vow = require('vow'),
_ = require('lodash'),
scan = require('./walk'),
loadRules = require('./load-rules'),
Configuration = require('./configuration'),
utils = require('./utils');
/**
* Loads the BEM entities and checks them
* @param {Object} [loadedConfig]
* @param {String} [loadedConfig.configPath]
* @param {Array} [loadedConfig.levels]
* @param {Array} [loadedCinfig.excludeFiles]
* @param {Array} targets
* @returns {Promise * Array} - the list of BEM errors
*/
module.exports = function (loadedConfig, targets) {
var config = new Configuration(loadedConfig);
return vow.all([scan(targets, config), loadRules()])
.spread(function (entities, rules) {
return vow.all(_.keys(rules).map(function (rule) {
var _rule = new rules[rule]();
return _rule.check(entities);
}));
})
.then(function (res) {
var bemErros = [];
_(res).keys().forEach(function (item) {
bemErros = bemErros.concat(res[item]);
});
return utils.sortByFullpath(bemErros);
});
};
|
Test blueprints for corner cases | # coding: utf-8
import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).build()
assert [('const2', {'str': 'hello'})] == m.create()
def test_model_with_multiple_entities():
m = model(
entity('first', {'name': lambda: 'elves'}),
entity('second', {'name': lambda: 'humans'})).build()
assert [('first', {'name': 'elves'}),
('second', {'name': 'humans'})] == m.create()
def test_model_with_multiple_params():
m = model(entity('human', {
'head': lambda: 1,
'hands': lambda: 2,
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
# error handling
def test_same_enitities_should_throw_error():
pass
def test_same_params_should_throw_error():
pass
| # coding: utf-8
import os, sys
sys.path.append(os.path.join(sys.path[0], '..'))
from carlo import model, entity, generate
def test_minimal_model():
m = model(entity('const', {'int': lambda: 42})).build()
assert [('const', {'int': 42})] == m.create()
m = model(entity('const2', {'str': lambda: 'hello'})).build()
assert [('const2', {'str': 'hello'})] == m.create()
def test_model_with_multiple_entities():
m = model(
entity('first', {'name': lambda: 'elves'}),
entity('second', {'name': lambda: 'humans'})).build()
assert [('first', {'name': 'elves'}),
('second', {'name': 'humans'})] == m.create()
def test_model_with_multiple_params():
m = model(entity('human', {
'head': lambda: 1,
'hands': lambda: 2,
'name': lambda: 'Hurin',
})).build()
assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
|
FIX - path of .cfg file corrected | """
Author: Ashish Gaikwad <ash.gkwd@gmail.com>
Copyright (c) 2015 Ashish Gaikwad
Description: This script will post a message on your slack channel
Please configure your `/etc/brainy-beats.cfg` file first.
Example brainy-beats.cfg
[slack]
url=https://hooks.slack.com/services/XxXxXxXxXx
channel=botwa
icon_emoji=ghost
username=beats-bot
"""
from subprocess import call
import sys
import json
import ConfigParser
def payload(text, conf):
toPost = {
"channel": "#" + conf.get("slack", "channel"),
"username": conf.get("slack", "username"),
"text": text,
"icon_emoji": ":" + conf.get("slack", "icon_emoji") + ":"
}
return "payload=" + json.dumps(toPost)
def main():
CONFIG_FILE = '/etc/brainy-beats.cfg'
# read configuration
conf = ConfigParser.ConfigParser()
conf.read(CONFIG_FILE)
call([
"curl",
"-X",
"POST",
"--data-urlencode",
payload(sys.argv[1], conf),
conf.get("slack", "url")
])
if __name__ == '__main__':
main() | """
Author: Ashish Gaikwad <ash.gkwd@gmail.com>
Copyright (c) 2015 Ashish Gaikwad
Description: This script will post a message on your slack channel
Please configure your `/etc/brainy-beats.cfg` file first.
Example brainy-beats.cfg
[slack]
url=https://hooks.slack.com/services/XxXxXxXxXx
channel=botwa
icon_emoji=ghost
username=beats-bot
"""
from subprocess import call
import sys
import json
import ConfigParser
def payload(text, conf):
toPost = {
"channel": "#" + conf.get("slack", "channel"),
"username": conf.get("slack", "username"),
"text": text,
"icon_emoji": ":" + conf.get("slack", "icon_emoji") + ":"
}
return "payload=" + json.dumps(toPost)
def main():
CONFIG_FILE = '/etc/slack_post.cfg'
# read configuration
conf = ConfigParser.ConfigParser()
conf.read(CONFIG_FILE)
call([
"curl",
"-X",
"POST",
"--data-urlencode",
payload(sys.argv[1], conf),
conf.get("slack", "url")
])
if __name__ == '__main__':
main() |
Make findOne reactive for ride owners subscription.
fix #9 | Router.configure({
layoutTemplate: 'layout'
});
Router.route('/', {
name: 'home',
waitOn: function () {
return Meteor.subscribe('verifiedUsersCount');
},
onBeforeAction: function () {
if (Meteor.user()) {
Router.go('ridesList');
} else {
this.next();
}
}
});
Router.route('/caronas', {
name: 'ridesList',
onBeforeAction: function () {
if (! Meteor.user() && ! Meteor.loggingIn()) {
Router.go('home');
} else {
this.next();
}
},
waitOn: function () {
var userIds = [];
var subscriptions = [];
subscriptions.push(Meteor.subscribe('rides'));
Tracker.autorun(function () {
userIds = _(Rides.find({}, { userId: 1 }).fetch()).pluck('userId');
subscriptions.push(Meteor.subscribe('users', userIds));
});
return [subscriptions];
},
data: function () {
return Rides.find({}, { sort: { departureTime: 1 } });
}
});
Router.route('/perfil', {
name: 'profile'
});
Router.route('/inviteEmails', {
name: 'inviteEmails'
});
| Router.configure({
layoutTemplate: 'layout'
});
Router.route('/', {
name: 'home',
waitOn: function () {
return Meteor.subscribe('verifiedUsersCount');
},
onBeforeAction: function () {
if (Meteor.user()) {
Router.go('ridesList');
} else {
this.next();
}
}
});
Router.route('/caronas', {
name: 'ridesList',
onBeforeAction: function () {
if (! Meteor.user() && ! Meteor.loggingIn()) {
Router.go('home');
} else {
this.next();
}
},
waitOn: function () {
var userIds = [];
Tracker.autorun(function () {
userIds = _(Rides.find({}, { userId: 1 }).fetch()).pluck('userId');
});
return [Meteor.subscribe('rides'), Meteor.subscribe('users', userIds)];
},
data: function () {
return Rides.find({}, { sort: { departureTime: 1 } });
}
});
Router.route('/perfil', {
name: 'profile'
});
Router.route('/inviteEmails', {
name: 'inviteEmails'
});
|
Refactor syntax language selector redirect url | const toArray = nodelist => Array.prototype.slice.call(nodelist);
const things = ['method', 'case', 'organization'];
const languageSelect = {
redirectUrl: null,
isThingDetailsPageWithLanguageParam: false,
init(tracking) {
this.tracking = tracking;
this.generateRedirectPath();
const selectEls = document.querySelectorAll(".js-language-select");
if (!selectEls) return;
toArray(selectEls).forEach(select => {
select.addEventListener("change", e => {
this.tracking.sendWithCallback("language", "language_dropdown", e.target.value, () => {
this.handleSelectChange(e);
});
});
});
},
handleSelectChange(e) {
let redirectUrl = this.isThingDetailsPageWithLanguageParam ? `${this.redirectUrl}/${e.target.value}` : this.redirectUrl;
location.href =
`/set-locale?locale=${e.target.value}` +
`&redirectTo=${redirectUrl}`;
},
generateRedirectPath() {
this.redirectUrl = window.location.pathname;
let urlPathMeta = window.location.pathname.split('/');
if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3] && (urlPathMeta[3] !== 'edit')) {
this.redirectUrl = `/${urlPathMeta[1]}/${urlPathMeta[2]}`;
this.isThingDetailsPageWithLanguageParam = true;
}
}
};
export default languageSelect;
| const toArray = nodelist => Array.prototype.slice.call(nodelist);
const things = ['method', 'case', 'organization'];
const languageSelect = {
redirectUrl: null,
isThingDetailsPageWithLanguageParam: false,
init(tracking) {
this.tracking = tracking;
this.generateRedirectPath();
const selectEls = document.querySelectorAll(".js-language-select");
if (!selectEls) return;
toArray(selectEls).forEach(select => {
select.addEventListener("change", e => {
this.tracking.sendWithCallback("language", "language_dropdown", e.target.value, () => {
this.handleSelectChange(e);
});
});
});
},
handleSelectChange(e) {
let redirectUrl = this.isThingDetailsPageWithLanguageParam ? `${this.redirectUrl}/${e.target.value}` : this.redirectUrl;
location.href =
`/set-locale?locale=${e.target.value}` +
`&redirectTo=${redirectUrl}`;
},
generateRedirectPath() {
this.redirectUrl = window.location.pathname;
let urlPathMeta = window.location.pathname.split('/');
if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3] && urlPathMeta[3] !== 'edit') {
this.redirectUrl = `/${urlPathMeta[1]}/${urlPathMeta[2]}`;
this.isThingDetailsPageWithLanguageParam = true;
}
}
};
export default languageSelect;
|
Fix dashboard bug when user is not in any teams. | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from actstream.models import Action
from teams.models import Team
@login_required
def index(request):
template_name = 'dashboard/index.html'
# Chain together queries to find all team activities.
q = None
team_ct = ContentType.objects.get(app_label='teams', model='team')
for team in request.user.team_set.all():
subq = Q(target_content_type=team_ct) & Q(target_object_id=team.id)
if q is None:
q = subq
else:
q |= subq
if q is not None:
team_actions = Action.objects.filter(q).order_by('-timestamp')
else:
team_actions = []
template_context = {
'team_actions': team_actions,
}
return render_to_response(
template_name,
template_context,
RequestContext(request),
)
| from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from actstream.models import Action
from teams.models import Team
@login_required
def index(request):
template_name = 'dashboard/index.html'
# Chain together queries to find all team activities.
q = None
team_ct = ContentType.objects.get(app_label='teams', model='team')
for team in request.user.team_set.all():
subq = Q(target_content_type=team_ct) & Q(target_object_id=team.id)
if q is None:
q = subq
else:
q |= subq
team_actions = Action.objects.filter(q).order_by('-timestamp')
template_context = {
'team_actions': team_actions,
}
return render_to_response(
template_name,
template_context,
RequestContext(request),
)
|
Add static builder taking port and path | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.component;
/**
* A {@link BindingPattern} which is implicitly constructed by the model, e.g for built-in handlers and filter chains.
*
* @author bjorncs
*/
public class SystemBindingPattern extends BindingPattern {
private SystemBindingPattern(String scheme, String host, String port, String path) { super(scheme, host, port, path); }
private SystemBindingPattern(String binding) { super(binding); }
public static SystemBindingPattern fromHttpPath(String path) { return new SystemBindingPattern("http", "*", null, path);}
public static SystemBindingPattern fromPattern(String binding) { return new SystemBindingPattern(binding);}
public static SystemBindingPattern fromPortAndPath(String port, String path) { return new SystemBindingPattern("http", "*", port, path); }
@Override
public String toString() {
return "SystemBindingPattern{" +
"scheme='" + scheme() + '\'' +
", host='" + host() + '\'' +
", port='" + port().orElse(null) + '\'' +
", path='" + path() + '\'' +
'}';
}
}
| // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.component;
/**
* A {@link BindingPattern} which is implicitly constructed by the model, e.g for built-in handlers and filter chains.
*
* @author bjorncs
*/
public class SystemBindingPattern extends BindingPattern {
private SystemBindingPattern(String scheme, String host, String port, String path) { super(scheme, host, port, path); }
private SystemBindingPattern(String binding) { super(binding); }
public static SystemBindingPattern fromHttpPath(String path) { return new SystemBindingPattern("http", "*", null, path);}
public static SystemBindingPattern fromPattern(String binding) { return new SystemBindingPattern(binding);}
@Override
public String toString() {
return "SystemBindingPattern{" +
"scheme='" + scheme() + '\'' +
", host='" + host() + '\'' +
", port='" + port().orElse(null) + '\'' +
", path='" + path() + '\'' +
'}';
}
}
|
Make exact_match non-required option (false by default) | <?php
namespace CodeTool\ArtifactDownloader\Scope\Config\Factory;
use CodeTool\ArtifactDownloader\DomainObject\DomainObjectInterface;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfig;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigChildNode;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigInterface;
class ScopeConfigFactory implements ScopeConfigFactoryInterface
{
/**
* @param DomainObjectInterface $do
*
* @return ScopeConfigChildNode
*/
private function createChildNode(DomainObjectInterface $do)
{
return new ScopeConfigChildNode($do->toArray());
}
/**
* @param string $scopeName
* @param DomainObjectInterface $do
*
* @return ScopeConfigInterface
*/
public function createFromDo($scopeName, DomainObjectInterface $do)
{
$scopeRules = [];
foreach ($do->get('rules') as $rule) {
$scopeRules[] = $this->createChildNode($rule);
}
return new ScopeConfig($scopeName, $do->getOrDefault('exact_match', false), $scopeRules);
}
}
| <?php
namespace CodeTool\ArtifactDownloader\Scope\Config\Factory;
use CodeTool\ArtifactDownloader\DomainObject\DomainObjectInterface;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfig;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigChildNode;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigInterface;
class ScopeConfigFactory implements ScopeConfigFactoryInterface
{
/**
* @param DomainObjectInterface $do
*
* @return ScopeConfigChildNode
*/
private function createChildNode(DomainObjectInterface $do)
{
return new ScopeConfigChildNode($do->toArray());
}
/**
* @param string $scopeName
* @param DomainObjectInterface $do
*
* @return ScopeConfigInterface
*/
public function createFromDo($scopeName, DomainObjectInterface $do)
{
$scopeRules = [];
foreach ($do->get('rules') as $rule) {
$scopeRules[] = $this->createChildNode($rule);
}
return new ScopeConfig($scopeName, $do->get('exact_match'), $scopeRules);
}
}
|
Allow singular route model bindings. | <?php
namespace Northstar\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'Northstar\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->singularResourceParameters();
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
}
}
| <?php
namespace Northstar\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'Northstar\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
}
}
|
Use `set` not `add` after the delete
We want the `add` action to be _synchronous_. That means that if the
action fails anywhere we consider it a failure.
Afterwards, we want to do an _asynchronous_ `set` action. It is okay if
some hosts do not recieve the set, they will consistently get the prior
delete. | <?php
namespace iFixit\Matryoshka;
use iFixit\Matryoshka;
/**
* Ensures that a delete is issued before trying to update an existing key.
*
* This layer is useful for working with mcrouter. mcrouter provides a reliable
* delete stream, but can't guarantee updates are recorded.
*/
class DeleteBeforeUpdate extends BackendWrap {
public function set($key, $value, $expiration = 0) {
if ($this->backend->add($key, $value) === false) {
$this->backend->delete($key);
$this->backend->set($key, $valaue);
}
}
public function setMultiple(array $values, $expiration = 0) {
foreach ($values as $key => $value) {
$this->set($key, $value, $expiration);
}
}
}
| <?php
namespace iFixit\Matryoshka;
use iFixit\Matryoshka;
/**
* Ensures that a delete is issued before trying to update an existing key.
*
* This layer is useful for working with mcrouter. mcrouter provides a reliable
* delete stream, but can't guarantee updates are recorded.
*/
class DeleteBeforeUpdate extends BackendWrap {
public function set($key, $value, $expiration = 0) {
if ($this->backend->add($key, $value) === false) {
$this->backend->delete($key);
$this->backend->add($key, $valaue);
}
}
public function setMultiple(array $values, $expiration = 0) {
foreach ($values as $key => $value) {
$this->set($key, $value, $expiration);
}
}
}
|
Use prepare instead of dispatched | import { compose } from 'redux';
import { connect } from 'react-redux';
import prepare from 'app/utils/prepare';
import { fetch } from 'app/actions/FrontpageActions';
import { login, logout } from 'app/actions/UserActions';
import Overview from './components/Overview';
import { selectFrontpage } from 'app/reducers/frontpage';
import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn';
import PublicFrontpage from './components/PublicFrontpage';
import { fetchPersonalFeed } from 'app/actions/FeedActions';
import {
selectFeedById,
selectFeedActivitesByFeedId
} from 'app/reducers/feeds';
const mapStateToProps = state => ({
loadingFrontpage: state.frontpage.fetching,
frontpage: selectFrontpage(state),
feed: selectFeedById(state, { feedId: 'personal' }),
feedItems: selectFeedActivitesByFeedId(state, {
feedId: 'personal'
})
});
const mapDispatchToProps = { login, logout };
export default compose(
prepare(({ loggedIn }, dispatch) =>
dispatch(fetch()).then(
() => (loggedIn ? dispatch(fetchPersonalFeed()) : Promise.resolve())
)
),
connect(mapStateToProps, mapDispatchToProps),
replaceUnlessLoggedIn(PublicFrontpage)
)(Overview);
| import { compose } from 'redux';
import { connect } from 'react-redux';
import { dispatched } from '@webkom/react-prepare';
import { fetch } from 'app/actions/FrontpageActions';
import { login, logout } from 'app/actions/UserActions';
import Overview from './components/Overview';
import { selectFrontpage } from 'app/reducers/frontpage';
import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn';
import PublicFrontpage from './components/PublicFrontpage';
import { fetchPersonalFeed } from 'app/actions/FeedActions';
import {
selectFeedById,
selectFeedActivitesByFeedId
} from 'app/reducers/feeds';
const mapStateToProps = state => ({
loadingFrontpage: state.frontpage.fetching,
frontpage: selectFrontpage(state),
feed: selectFeedById(state, { feedId: 'personal' }),
feedItems: selectFeedActivitesByFeedId(state, {
feedId: 'personal'
})
});
const mapDispatchToProps = { login, logout };
export default compose(
replaceUnlessLoggedIn(PublicFrontpage),
dispatched(
({ loggedIn }, dispatch) =>
dispatch(fetch()).then(
() => (loggedIn ? dispatch(fetchPersonalFeed()) : Promise.resolve())
),
{
componentWillReceiveProps: false
}
),
connect(mapStateToProps, mapDispatchToProps)
)(Overview);
|
Fix incorrect paths in postcss debugger | // https://github.com/andywer/postcss-debug#js-code
/* eslint-disable strict, no-console */
'use strict';
const fs = require('fs');
const postcss = require('postcss');
const postcssrc = require('postcss-load-config');
const { createDebugger } = require('postcss-debug');
const debug = createDebugger();
const ctx = {
map: { inline: false },
from: './packages/css/src/index.css',
to: './packages/css/dist/index.css',
};
const css = fs.readFileSync(ctx.from, 'utf8');
postcssrc(ctx).then(({ plugins, options }) => {
postcss(debug(plugins))
.process(css, options)
.then((result) => {
result.warnings().forEach((warn) => {
process.stderr.write(`${warn.toString()}\n`);
});
if (result.map) {
fs.writeFile(`${result.opts.to}.map`, result.map.toString());
}
debug.inspect();
console.info('\n-----------------------------------------\n');
console.info(plugins);
console.info('\n-----------------------------------------\n');
console.info(result);
})
.catch((error) => {
if (error.name === 'CssSyntaxError') {
process.stderr.write(error.message + error.showSourceCode());
} else {
throw error;
}
});
});
| // https://github.com/andywer/postcss-debug#js-code
/* eslint-disable strict, no-console */
'use strict';
const fs = require('fs');
const postcss = require('postcss');
const postcssrc = require('postcss-load-config');
const { createDebugger } = require('postcss-debug');
const debug = createDebugger();
const ctx = {
map: { inline: false },
from: './src/css/main.css',
to: './lib/index.css',
};
const css = fs.readFileSync(ctx.from, 'utf8');
postcssrc(ctx).then(({ plugins, options }) => {
postcss(debug(plugins))
.process(css, options)
.then((result) => {
result.warnings().forEach((warn) => {
process.stderr.write(`${warn.toString()}\n`);
});
if (result.map) {
fs.writeFile(`${result.opts.to}.map`, result.map.toString());
}
debug.inspect();
console.info('\n-----------------------------------------\n');
console.info(plugins);
console.info('\n-----------------------------------------\n');
console.info(result);
})
.catch((error) => {
if (error.name === 'CssSyntaxError') {
process.stderr.write(error.message + error.showSourceCode());
} else {
throw error;
}
});
});
|
Raise error specific to address checksum failure
Because is_address() also checks for a valid checksum, the old code showed a generic "not an address" error if the checksum failed. | from eth_utils import (
is_address,
is_checksum_address,
is_checksum_formatted_address,
is_dict,
is_list_like,
)
def validate_abi(abi):
"""
Helper function for validating an ABI
"""
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
for e in abi:
if not is_dict(e):
raise ValueError("The elements of 'abi' are not all dictionaries")
def validate_address(value):
"""
Helper function for validating an address
"""
validate_address_checksum(value)
if not is_address(value):
raise ValueError("'{0}' is not an address".format(value))
def validate_address_checksum(value):
"""
Helper function for validating an address EIP55 checksum
"""
if is_checksum_formatted_address(value):
if not is_checksum_address(value):
raise ValueError("'{0}' has an invalid EIP55 checksum".format(value))
| from eth_utils import (
is_address,
is_checksum_address,
is_checksum_formatted_address,
is_dict,
is_list_like,
)
def validate_abi(abi):
"""
Helper function for validating an ABI
"""
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
for e in abi:
if not is_dict(e):
raise ValueError("The elements of 'abi' are not all dictionaries")
def validate_address(value):
"""
Helper function for validating an address
"""
if not is_address(value):
raise ValueError("'{0}' is not an address".format(value))
validate_address_checksum(value)
def validate_address_checksum(value):
"""
Helper function for validating an address EIP55 checksum
"""
if is_checksum_formatted_address(value):
if not is_checksum_address(value):
raise ValueError("'{0}' has an invalid EIP55 checksum".format(value))
|
[Closure] Convert `goog.promise.Resolver` to `goog.module` and to ES6.
RELNOTES: n/a
PiperOrigin-RevId: 412903963
Change-Id: Ib71d583308c6154c111c9e78f2c3c0aa97b0d25a | /**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
goog.module('goog.promise.Resolver');
goog.module.declareLegacyNamespace();
const GoogPromise = goog.requireType('goog.Promise');
const Thenable = goog.requireType('goog.Thenable');
/**
* Resolver interface for promises. The resolver is a convenience interface that
* bundles the promise and its associated resolve and reject functions together,
* for cases where the resolver needs to be persisted internally.
* @template TYPE
* @interface
*/
class Resolver {
constructor() {
/**
* The promise that created this resolver.
* @type {!GoogPromise<TYPE>}
*/
this.promise;
/**
* Resolves this resolver with the specified value.
* @type {function((TYPE|GoogPromise<TYPE>|Promise<TYPE>|IThenable|Thenable)=)}
*/
this.resolve;
/**
* Rejects this resolver with the specified reason.
* @type {function(*=): void}
*/
this.reject;
}
}
exports = Resolver;
| /**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('goog.promise.Resolver');
goog.requireType('goog.Promise');
/**
* Resolver interface for promises. The resolver is a convenience interface that
* bundles the promise and its associated resolve and reject functions together,
* for cases where the resolver needs to be persisted internally.
*
* @interface
* @template TYPE
*/
goog.promise.Resolver = function() {};
/**
* The promise that created this resolver.
* @type {!goog.Promise<TYPE>}
*/
goog.promise.Resolver.prototype.promise;
/**
* Resolves this resolver with the specified value.
* @type {function((TYPE|goog.Promise<TYPE>|Thenable)=)}
*/
goog.promise.Resolver.prototype.resolve;
/**
* Rejects this resolver with the specified reason.
* @type {function(*=): void}
*/
goog.promise.Resolver.prototype.reject;
|
Fix bug in user pass code
The functions to query user and org passes return non-verified passes when
verified=None, which was not intended. | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time != None)
).all()
elif not verified and verified is not None:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.owner_id == user_id).all()
def query_org_passes(session, org_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time != None)
).all()
elif not verified and verified is not None:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.org_id == org_id).all()
| # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time != None)
).all()
elif not verified:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.owner_id == user_id).all()
def query_org_passes(session, org_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time != None)
).all()
elif not verified:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.org_id == org_id).all()
|
Add HTML Comment remover to normal template processing.
All of the other plugins are using the `lintTree` hook, which cannot
modify the resulting generated template. This commit adds the
RemoveConfigurationHtmlComments plugin as part of the normal
ember-cli-htmlbars preprocessing (which does modify the "real" generated
templates). | /* jshint node: true */
/*eslint-env node*/
'use strict';
var TemplateLinter = require('./broccoli-template-linter');
module.exports = {
name: 'ember-cli-template-lint',
lintTree: function(type, tree) {
if (type === 'templates') {
var ui = this.ui;
var mockConsole = {
log: function(data) {
ui.writeLine(data);
},
error: function(data) {
ui.writeLine(data, 'ERROR');
}
};
return new TemplateLinter(tree, {
annotation: 'TemplateLinter',
templatercPath: this.project.root + '/.template-lintrc',
generateTestFile: this.project.generateTestFile,
_console: mockConsole
});
}
},
setupPreprocessorRegistry: function(type, registry) {
var RemoveConfigurationHtmlComments = require('./ext/plugins/internal/remove-configuration-html-comments');
registry.add('htmlbars-ast-plugin', {
name: 'remove-configuration-html-comments',
plugin: RemoveConfigurationHtmlComments()
});
}
};
| /* jshint node: true */
/*eslint-env node*/
'use strict';
var TemplateLinter = require('./broccoli-template-linter');
module.exports = {
name: 'ember-cli-template-lint',
lintTree: function(type, tree) {
if (type === 'templates') {
var ui = this.ui;
var mockConsole = {
log: function(data) {
ui.writeLine(data);
},
error: function(data) {
ui.writeLine(data, 'ERROR');
}
};
return new TemplateLinter(tree, {
annotation: 'TemplateLinter',
templatercPath: this.project.root + '/.template-lintrc',
generateTestFile: this.project.generateTestFile,
_console: mockConsole
});
}
}
};
|
Put the script loading in test in a try/catch because it was causing an error in certain cases with Opera. | var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
try {
testOk = js_files[index].test();
} catch (e) {
// with certain browsers like opera the above test can fail
// because of undefined variables...
testOk = true;
}
if (testOk) {
var s = document.createElement('script');
s.src = js_files[index].src;
s.type = 'text/javascript';
head.appendChild(s);
s.onload = function(){
loadScript(index+1);
}
} else {
loadScript(index+1);
}
}
loadScript(0);
}
| var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
if (js_files[index].test()){
// console.log('Loading ' + js_files[index].src);
var s = document.createElement('script');
s.src = js_files[index].src;
s.type = 'text/javascript';
head.appendChild(s);
s.onload = function(){
loadScript(index+1);
}
}
else{
loadScript(index+1);
}
}
loadScript(0);
}
|
Add support for a setup phase which is not recorded. | package net.openhft.chronicle.wire;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
* Created by peter on 17/05/2017.
*/
public class TextMethodTesterTest {
@Test
public void run() throws IOException {
TextMethodTester test = new TextMethodTester<>(
"methods-in.yaml",
MockMethodsImpl::new,
MockMethods.class,
"methods-in.yaml")
.setup("methods-in.yaml") // calls made here are ignored.
.run();
assertEquals(test.expected(), test.actual());
}
}
class MockMethodsImpl implements MockMethods {
private final MockMethods out;
public MockMethodsImpl(MockMethods out) {
this.out = out;
}
@Override
public void method1(MockDto dto) {
out.method1(dto);
}
@Override
public void method2(MockDto dto) {
out.method2(dto);
}
} | package net.openhft.chronicle.wire;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
* Created by peter on 17/05/2017.
*/
public class TextMethodTesterTest {
@Test
public void run() throws IOException {
TextMethodTester test = new TextMethodTester<>(
"methods-in.yaml",
MockMethodsImpl::new,
MockMethods.class,
"methods-in.yaml").run();
assertEquals(test.expected(), test.actual());
}
}
class MockMethodsImpl implements MockMethods {
private final MockMethods out;
public MockMethodsImpl(MockMethods out) {
this.out = out;
}
@Override
public void method1(MockDto dto) {
out.method1(dto);
}
@Override
public void method2(MockDto dto) {
out.method2(dto);
}
} |
Set up the call to fetch | /**
RemoteCall
@description function that makes the remote call using the fetch polyfill,
running a series of provided lifecycle hooks
@exports @default {function} callRemoteResource
**/
/* eslint no-unused-vars:0 */
// TODO: should probably use a global fetch instance if we can
import fetch from 'isomorphic-fetch';
/**
@private
@name callRemoteResource
@desc makes a call using the fetch API w/ the given request data & hooks
@param {object} request
@param {string} request.uri
@param {string} request.method
@param {object} request.headers
@param {string} request.body
@param {object} request.requestOps arbitrary options passed to fetch
@param {array} statusActions an array of objects w/ code & callback keys
@param {object} hooks the lifecycle hooks evaluated at various times
@param {function} hooks.onBeforeCall
@param {function} hooks.onCallSuccess(data, response)
@param {function} hooks.onCallFailure(statusCode, data, response)
@returns {Promise<Response|Error>}
**/
export default function callRemoteResource(request, statusActions, hooks) {
const { uri, method, headers, body, requestOpts } = request;
const fetchReq = Object.assign({ method, headers, body }, requestOpts);
hooks.onBeforeCall();
// NOTE: this expects to be caught in the surrounding block
return fetch(uri, fetchReq);
}
| /**
RemoteCall
@description function that makes the remote call using the fetch polyfill,
running a series of provided lifecycle hooks
@exports @default {function} callRemoteResource
**/
/* eslint no-unused-vars:0 */
// TODO: should probably use a global fetch instance if we can
import fetch from 'isomorphic-fetch';
/**
@private
@name callRemoteResource
@desc makes a call using the fetch API w/ the given request data & hooks
@param {object} request
@param {string} request.uri
@param {string} request.method
@param {object} request.headers
@param {string} request.body
@param {object} request.requestOps arbitrary options passed to fetch
@param {array} statusActions an array of objects w/ code & callback keys
@param {object} hooks the lifecycle hooks evaluated at various times
@param {function} hooks.onBeforeCall
@param {function} hooks.onCallSuccess(data, response)
@param {function} hooks.onCallFailure(statusCode, data, response)
**/
export default function callRemoteResource(request, statusActions, hooks) {
return null;
}
|
Simplify the aws vpcs settings for testing | # -*- coding: utf-8 -*-
AWS_VPCS = [
{
'CidrBlock': '15.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
],
'create_internet_gateway': True,
'subnets': [
{
'CidrBlock': '15.0.0.0/24',
},
{
'CidrBlock': '15.0.1.0/24',
}
]
}
]
| # -*- coding: utf-8 -*-
AWS_VPCS = [
{
'CidrBlock': '15.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
],
'create_internet_gateway': True
},
{
'CidrBlock': '16.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
]
}
] |
Add default values for params | import gravity from "lib/loaders/legacy/gravity"
import OrderedSet from "./ordered_set"
import { GraphQLString, GraphQLNonNull, GraphQLList, GraphQLBoolean, GraphQLInt } from "graphql"
const OrderedSets = {
type: new GraphQLList(OrderedSet.type),
description: "A collection of OrderedSets",
args: {
key: {
type: new GraphQLNonNull(GraphQLString),
description: "Key to the OrderedSet or group of OrderedSets",
},
public: {
type: GraphQLBoolean,
defaultValue: true,
},
page: {
type: GraphQLInt,
defaultValue: 1,
},
size: {
type: GraphQLInt,
defaultValue: 10,
},
},
resolve: (root, options) => gravity("sets", options),
}
export default OrderedSets
| import gravity from "lib/loaders/legacy/gravity"
import OrderedSet from "./ordered_set"
import { GraphQLString, GraphQLNonNull, GraphQLList, GraphQLBoolean, GraphQLInt } from "graphql"
const OrderedSets = {
type: new GraphQLList(OrderedSet.type),
description: "A collection of OrderedSets",
args: {
key: {
type: new GraphQLNonNull(GraphQLString),
description: "Key to the OrderedSet or group of OrderedSets",
},
public: {
type: GraphQLBoolean,
defaultValue: true,
},
page: {
type: GraphQLInt,
},
size: {
type: GraphQLInt,
},
},
resolve: (root, options) => gravity("sets", options),
}
export default OrderedSets
|
Change 'test' checkboxes to radio buttons. Rename form field from 'tests' to 'test'. | <?php if ($tests): ?>
<?=form_open($form_action); ?>
<ul class="addons_index">
<?php foreach ($tests AS $addon): ?>
<li class="expanded">
<div class="addon_title">
<a href="#addon_<?=strtolower($addon->name); ?>"><?=str_replace('%addon_name%', ucfirst($addon->name), lang('addon_anchor')); ?></a>
<label><?=ucfirst($addon->name); ?>
<span>(<?=count($addon->tests) .' ' .(count($addon->tests) === 1 ? lang('test') : lang('tests')); ?>)</span>
</label>
</div>
<ul class="addon_tests" id="addon_testee">
<?php foreach ($addon->tests AS $test): ?>
<li><label><?=form_radio('test', $test->file_path, FALSE); ?> <?=$test->file_name; ?></label></li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul><!-- /.addons_index -->
<div class="submit_wrapper"><?=form_submit(array('name' => 'submit', 'value' => lang('run_tests'), 'class' => 'submit')); ?></div>
<?=form_close(); ?>
<?php else: ?>
<p><?=lang('no_tests'); ?></p>
<?php endif; ?> | <?php if ($tests): ?>
<?=form_open($form_action); ?>
<ul class="addons_index">
<?php foreach ($tests AS $addon): ?>
<li class="expanded">
<div class="addon_title">
<a href="#addon_<?=strtolower($addon->name); ?>"><?=str_replace('%addon_name%', ucfirst($addon->name), lang('addon_anchor')); ?></a>
<label><input type="checkbox" /> <?=ucfirst($addon->name); ?>
<span>(<?=count($addon->tests) .' ' .(count($addon->tests) === 1 ? lang('test') : lang('tests')); ?>)</span>
</label>
</div>
<ul class="addon_tests" id="addon_testee">
<?php foreach ($addon->tests AS $test): ?>
<li><label><?=form_checkbox('tests[]', $test->file_path, FALSE); ?> <?=$test->file_name; ?></label></li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul><!-- /.addons_index -->
<div class="submit_wrapper"><?=form_submit(array('name' => 'submit', 'value' => lang('run_tests'), 'class' => 'submit')); ?></div>
<?=form_close(); ?>
<?php else: ?>
<p><?=lang('no_tests'); ?></p>
<?php endif; ?> |
Update launcher for new features | #!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( json_mission )
#with Timer('Sampling observable points'):
#mission.sample_objective()
#with Timer('Sampling positions'):
#mission.sample_all_positions()
#print "Solving..."
#with Timer('Solving'):
#mission.solve()
##mission.solve('Position-based TSP')
#print "Displaying..."
#for robot in mission.team:
#robot.display_weighted_map()
#mission.display_situation()
#print "Updating poses and map"
#mission.update_poses()
#mission.update_map()
print "Starting Loop !"
#mission.loop_once()
#mission.loop(5,True)
mission.loop(10)
mission.update()
#for robot in mission.team:
#robot.display_weighted_map()
mission.display_situation()
mission.print_metrics()
print "Done."
| #!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( json_mission )
#with Timer('Sampling observable points'):
#mission.sample_objective()
#with Timer('Sampling positions'):
#mission.sample_all_positions()
#print "Solving..."
#with Timer('Solving'):
#mission.solve()
##mission.solve('Position-based TSP')
#print "Displaying..."
#for robot in mission.team:
#robot.display_weighted_map()
#mission.display_situation()
#print "Updating poses and map"
#mission.update_poses()
#mission.update_map()
print "Starting Loop !"
#mission.loop_once()
mission.loop(10)
mission.update()
mission.display_situation()
print "Done."
|
Revert "Retry queries up to 10 times on SQLite"
This reverts commit 2a731dbb | /* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
storage: 'data/juiceshop.sqlite',
logging: false
})
sequelizeNoUpdateAttributes(sequelize)
const db = {}
fs.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(modelName => {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
| /* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
storage: 'data/juiceshop.sqlite',
logging: false,
retry: {
max: 10
}
})
sequelizeNoUpdateAttributes(sequelize)
const db = {}
fs.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(modelName => {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
|
Change default value of displayname setting
New default is: "Display name + username" | import * as FrontendPrefsOptions from './utils/frontend-preferences-options';
const config = {
api:{
host: 'http://localhost:3000',
sentinel: null // keep always last
},
auth: {
cookieDomain: 'localhost',
tokenPrefix: 'freefeed_',
userStorageKey: 'USER_KEY',
sentinel: null // keep always last
},
captcha: {
siteKey: '',
sentinel: null // keep always last
},
search: {
searchEngine: null,
sentinel: null // keep always last
},
siteDomains: [ // for transform links in the posts, comments, etc.
'freefeed.net',
'gamma.freefeed.net'
],
sentry: {
publicDSN: null,
sentinel: null // keep always last
},
frontendPreferences: {
clientId: 'net.freefeed',
defaultValues: {
displayNames: {
displayOption: FrontendPrefsOptions.DISPLAYNAMES_BOTH,
useYou: true
},
realtimeActive: false,
comments: {
omitRepeatedBubbles: true,
highlightComments: true,
hiddenTypes: []
},
allowLinksPreview: false,
readMoreStyle: 'modern',
homefeed: {
hideUsers: []
}
}
}
};
export default config;
| import * as FrontendPrefsOptions from './utils/frontend-preferences-options';
const config = {
api:{
host: 'http://localhost:3000',
sentinel: null // keep always last
},
auth: {
cookieDomain: 'localhost',
tokenPrefix: 'freefeed_',
userStorageKey: 'USER_KEY',
sentinel: null // keep always last
},
captcha: {
siteKey: '',
sentinel: null // keep always last
},
search: {
searchEngine: null,
sentinel: null // keep always last
},
siteDomains: [ // for transform links in the posts, comments, etc.
'freefeed.net',
'gamma.freefeed.net'
],
sentry: {
publicDSN: null,
sentinel: null // keep always last
},
frontendPreferences: {
clientId: 'net.freefeed',
defaultValues: {
displayNames: {
displayOption: FrontendPrefsOptions.DISPLAYNAMES_DISPLAYNAME,
useYou: true
},
realtimeActive: false,
comments: {
omitRepeatedBubbles: true,
highlightComments: true,
hiddenTypes: []
},
allowLinksPreview: false,
readMoreStyle: 'modern',
homefeed: {
hideUsers: []
}
}
}
};
export default config;
|
Add reminder to improve the code
See #12 | package storage
import (
"github.com/rafaeljusto/toglacier/internal/archive"
"github.com/rafaeljusto/toglacier/internal/cloud"
)
// Backup stores the cloud location of the backup and some extra information
// about the files of the backup.
type Backup struct {
Backup cloud.Backup // TODO: rename this attribute?
Info archive.Info
}
// Backups represents a sorted list of backups that are ordered by creation
// date. It has the necessary methods so you could use the sort package of the
// standard library.
type Backups []Backup
// Len returns the number of backups.
func (b Backups) Len() int { return len(b) }
// Less compares two positions of the slice and verifies the preference. They
// are ordered from the newest backup to the oldest.
func (b Backups) Less(i, j int) bool { return b[i].Backup.CreatedAt.After(b[j].Backup.CreatedAt) }
// Swap change the backups position inside the slice.
func (b Backups) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
// Storage represents all commands to manage backups information locally. After
// the backup is uploaded we must keep track of them locally to speed up
// recovery and cloud cleanup (remove old ones).
type Storage interface {
// Save a backup information.
Save(Backup) error
// List all backup informations in the storage.
List() (Backups, error)
// Remove a specific backup information from the storage.
Remove(id string) error
}
| package storage
import (
"github.com/rafaeljusto/toglacier/internal/archive"
"github.com/rafaeljusto/toglacier/internal/cloud"
)
// Backup stores the cloud location of the backup and some extra information
// about the files of the backup.
type Backup struct {
Backup cloud.Backup
Info archive.Info
}
// Backups represents a sorted list of backups that are ordered by creation
// date. It has the necessary methods so you could use the sort package of the
// standard library.
type Backups []Backup
// Len returns the number of backups.
func (b Backups) Len() int { return len(b) }
// Less compares two positions of the slice and verifies the preference. They
// are ordered from the newest backup to the oldest.
func (b Backups) Less(i, j int) bool { return b[i].Backup.CreatedAt.After(b[j].Backup.CreatedAt) }
// Swap change the backups position inside the slice.
func (b Backups) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
// Storage represents all commands to manage backups information locally. After
// the backup is uploaded we must keep track of them locally to speed up
// recovery and cloud cleanup (remove old ones).
type Storage interface {
// Save a backup information.
Save(Backup) error
// List all backup informations in the storage.
List() (Backups, error)
// Remove a specific backup information from the storage.
Remove(id string) error
}
|
Bump version for v1.1.0 release | from setuptools import find_packages, setup
setup(
name="redshift_etl",
version="1.1.0",
author="Harry's Data Engineering and Contributors",
description="ETL code to ferry data from PostgreSQL databases or S3 files to Redshift clusters",
license="MIT",
keywords="redshift postgresql ETL ELT extract transform load",
url="https://github.com/harrystech/arthur-redshift-etl",
package_dir={"": "python"},
packages=find_packages("python"),
package_data={
"etl": [
"assets/*",
"config/*",
"render_template/templates/*"
]
},
scripts=[
"python/scripts/launch_ec2_instance.sh",
"python/scripts/launch_emr_cluster.sh",
"python/scripts/re_run_partial_pipeline.py",
"python/scripts/submit_arthur.sh"
],
entry_points={
"console_scripts": [
# NB The script must end in ".py" so that spark submit accepts it as a Python script.
"arthur.py = etl.commands:run_arg_as_command",
"run_tests.py = etl.selftest:run_tests"
]
}
)
| from setuptools import find_packages, setup
setup(
name="redshift_etl",
version="1.0.1",
author="Harry's Data Engineering and Contributors",
description="ETL code to ferry data from PostgreSQL databases (or S3 files) to Redshift cluster",
license="MIT",
keywords="redshift postgresql ETL ELT extract transform load",
url="https://github.com/harrystech/arthur-redshift-etl",
package_dir={"": "python"},
packages=find_packages("python"),
package_data={
"etl": [
"assets/*",
"config/*",
"render_template/templates/*"
]
},
scripts=[
"python/scripts/launch_ec2_instance.sh",
"python/scripts/launch_emr_cluster.sh",
"python/scripts/re_run_partial_pipeline.py",
"python/scripts/submit_arthur.sh"
],
entry_points={
"console_scripts": [
# NB The script must end in ".py" so that spark submit accepts it as a Python script.
"arthur.py = etl.commands:run_arg_as_command",
"run_tests.py = etl.selftest:run_tests"
]
}
)
|
Add require_relative to work with Rails 4.1.5 | //= require_relative ../vis/module/header
//= require moment
//= require hammer
//= require_relative ../component/emitter
//= require_relative ../vis/shim
//= require_relative ../vis/util
//= require_relative ../vis/DataSet
//= require_relative ../vis/DataView
//= require_relative ../vis/timeline/stack
//= require_relative ../vis/timeline/TimeStep
//= require_relative ../vis/timeline/component/Component
//= require_relative ../vis/timeline/Range
//= require_relative ../vis/timeline/component/TimeAxis
//= require_relative ../vis/timeline/component/CurrentTime
//= require_relative ../vis/timeline/component/CustomTime
//= require_tree ../vis/timeline/component/item
//= require_relative ../vis/timeline/component/ItemSet
//= require_relative ../vis/timeline/component/Group
//= require_relative ../vis/timeline/Timeline
//= require_relative ../vis/graph/dotparser
//= require_relative ../vis/graph/shapes
//= require_relative ../vis/graph/Node
//= require_relative ../vis/graph/Edge
//= require_relative ../vis/graph/Popup
//= require_relative ../vis/graph/Groups
//= require_relative ../vis/graph/Images
//= require_tree ../vis/graph/graphMixins
//= require_relative ../vis/graph/Graph
//= require_relative ../vis/graph3d/Graph3d
//= require_relative ../vis/module/exports
| //= require ../vis/module/header
//= require moment
//= require hammer
//= require ../component/emitter
//= require ../vis/shim
//= require ../vis/util
//= require ../vis/DataSet
//= require ../vis/DataView
//= require ../vis/timeline/stack
//= require ../vis/timeline/TimeStep
//= require ../vis/timeline/component/Component
//= require ../vis/timeline/Range
//= require ../vis/timeline/component/TimeAxis
//= require ../vis/timeline/component/CurrentTime
//= require ../vis/timeline/component/CustomTime
//= require_tree ../vis/timeline/component/item
//= require ../vis/timeline/component/ItemSet
//= require ../vis/timeline/component/Group
//= require ../vis/timeline/Timeline
//= require ../vis/graph/dotparser
//= require ../vis/graph/shapes
//= require ../vis/graph/Node
//= require ../vis/graph/Edge
//= require ../vis/graph/Popup
//= require ../vis/graph/Groups
//= require ../vis/graph/Images
//= require_tree ../vis/graph/graphMixins
//= require ../vis/graph/Graph
//= require ../vis/graph3d/Graph3d
//= require ../vis/module/exports
|
Comment about a possible attack vector. | from django.conf import settings
from django.core.cache import cache
from django.template import Template
from django.template.context import RequestContext
from snapboard.utils import get_response_cache_key, get_prefix_cache_key
class CachedTemplateMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# TODO: In DEV don't try to grab media out of the cache.
if settings.DEBUG and "." in request.path:
return
# TODO: I can imagine a problem with this where a user writes {% in his post %} ... which would then be rendered on the second pass.
response = None
if request.method == "GET":
prefix_key = get_prefix_cache_key(request)
prefix = cache.get(prefix_key, "0")
response_key = get_response_cache_key(prefix, request)
response = cache.get(response_key)
if response is None:
response = view_func(request, *view_args, **view_kwargs)
if response['content-type'].startswith('text/html'):
t = Template(response.content)
response.content = t.render(RequestContext(request))
return response | from django.conf import settings
from django.core.cache import cache
from django.template import Template
from django.template.context import RequestContext
from snapboard.utils import get_response_cache_key, get_prefix_cache_key
class CachedTemplateMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# TODO: In DEV don't try to grab media out of the cache.
if settings.DEBUG and "." in request.path:
return
response = None
if request.method == "GET":
prefix_key = get_prefix_cache_key(request)
prefix = cache.get(prefix_key, "0")
response_key = get_response_cache_key(prefix, request)
response = cache.get(response_key)
if response is None:
response = view_func(request, *view_args, **view_kwargs)
if response['content-type'].startswith('text/html'):
t = Template(response.content)
response.content = t.render(RequestContext(request))
return response |
Fix CLI i18n (for real) | #!/usr/bin/env php
<?php
use Symfony\Component\Console\Application;
require_once __DIR__ . '/vendor/autoload.php';
date_default_timezone_set('Europe/Madrid');
$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
__DIR__ . '/src/SoftwarePackages',
'Ontic\Yaes\SoftwarePackages'
);
setlocale(LC_ALL, getenv('LANG'));
bindtextdomain("messages", "locale");
textdomain("messages");
$application = new Application();
foreach($softwarePackages as $package)
{
$application->addCommands($package->getCommands());
}
$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();
| #!/usr/bin/env php
<?php
use Symfony\Component\Console\Application;
require_once __DIR__ . '/vendor/autoload.php';
date_default_timezone_set('Europe/Madrid');
$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
__DIR__ . '/src/SoftwarePackages',
'Ontic\Yaes\SoftwarePackages'
);
putenv("LC_ALL=" . getenv('LANG'));
bindtextdomain("messages", "locale");
textdomain("messages");
$application = new Application();
foreach($softwarePackages as $package)
{
$application->addCommands($package->getCommands());
}
$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();
|
Allow empty message initialization for raw message | /*
* Copyright 2006-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.message;
/**
* @author Christoph Deppisch
* @since 2.0
*/
public class RawMessage extends DefaultMessage {
/**
* Empty constructor initializing with empty message payload.
*/
public RawMessage() {
super();
}
/**
* Default constructor initializing with message payload
* @param messageData
*/
public RawMessage(String messageData) {
super(messageData);
}
@Override
public String toString() {
return getPayload(String.class);
}
}
| /*
* Copyright 2006-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.message;
/**
* @author Christoph Deppisch
* @since 2.0
*/
public class RawMessage extends DefaultMessage {
public RawMessage(String messageData) {
super(messageData);
}
@Override
public String toString() {
return getPayload(String.class);
}
}
|
Fix server not being created properly. | """
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
| """
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444):
assert check_argument_types()
self.app = resolve_reference(app)
self.ip = ip
self.port = port
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol_factory = partial(KyokaiProtocol, self.app, ctx)
server = await asyncio.get_event_loop().create_server(protocol_factory)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
feat: Switch table settings button style based on user click | import Ember from 'ember';
export default Ember.Component.extend({
userSettings: Ember.inject.service('user-settings'),
sortAscending: false,
init () {
this._super();
this.set('currency', this.get('userSettings').currency());
},
actions: {
sortByProperty (property) {
this.sortValues(property);
},
tableViewSettings (settings) {
if (this.get('tableViewSettings') === settings) { return; }
$('.table-view-settings button').removeClass('mdl-button--raised');
$(`#btn-${settings}`).addClass('mdl-button--raised');
this.set('tableViewSettings', settings);
}
},
sortValues (property) {
if (this.get('sortAscending')) {
const dataSorted = this.get('data').sortBy(property);
this.set('data', dataSorted);
} else {
const dataSorted = this.get('data').sortBy(property).reverse();
this.set('data', dataSorted);
}
this.set('sortAscending', !this.get('sortAscending'));
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
userSettings: Ember.inject.service('user-settings'),
sortAscending: false,
init () {
this._super();
this.set('currency', this.get('userSettings').currency());
},
actions: {
sortByProperty (property) {
this.sortValues(property);
}
},
sortValues (property) {
if (this.get('sortAscending')) {
const dataSorted = this.get('data').sortBy(property);
this.set('data', dataSorted);
} else {
const dataSorted = this.get('data').sortBy(property).reverse();
this.set('data', dataSorted);
}
this.set('sortAscending', !this.get('sortAscending'));
}
});
|
Hide back button when hasEvent | // @flow
import React, { Component } from 'react';
import type { Children } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// ======================================================
// Actions
// ======================================================
import * as ApplicationActions from '../../../actions/applicationActions';
// ======================================================
// Selectors
// ======================================================
import * as OrderSelector from '../../../selectors/order';
const mapStateToProps = state => {
return {
isEventOrder: OrderSelector.verifyIsEventOrder(state.order)
};
};
const actions = {
...ApplicationActions,
};
const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
class App extends Component {
props: {
children: Children,
back: Function,
isEventOrder: boolean
};
render() {
const { isEventOrder, back } = this.props;
return (
<div className="action-back">
{
!isEventOrder &&
<a
className="button purple M"
onClick={back}
>
<i className="fa fa-chevron-left" />ย้อนกลับ
</a>
}
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
| // @flow
import React, { Component } from 'react';
import type { Children } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// ======================================================
// Actions
// ======================================================
import * as ApplicationActions from '../../../actions/applicationActions';
const mapStateToProps = state => ({});
const actions = {
...ApplicationActions,
};
const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
class App extends Component {
props: {
children: Children,
back: Function
};
render() {
const { back } = this.props;
return (
<div className="action-back">
<a
className="button purple M"
onClick={back}
>
<i className="fa fa-chevron-left" />ย้อนกลับ
</a>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
Add final and add salt as an UUID | package com.sudoku.data.model;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @author jonathan
*/
public class Comment {
/**
* Champs de la classe Comment
* *
*/
private final User author;
private final String pseudo;
private final String userSalt; // We use the salt as an UUID to identify the poster
private String comment;
private Integer grade;
/**
* Méthode de la classe Comment
* @param comment
* @param grade
* @param u
*/
public Comment(String comment, Integer grade, User u) {
this.comment = comment;
this.grade = grade;
this.author = u;
this.pseudo = u.getPseudo();
this.userSalt = u.getSalt();
}
public static Comment buildFromAvroComment(
com.sudoku.comm.generated.Comment comment) {
return new Comment(comment.getComment(), comment.getGrade(),
User.buildFromAvroUser(comment.getAuthor()));
}
public User getAuthor() {
return author;
}
public String getPseudo() {
return pseudo;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
}
| package com.sudoku.data.model;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @author jonathan
*/
public class Comment {
/**
* Champs de la classe Comment
* *
*/
private User author;
private String pseudo;
private String comment;
private Integer grade;
/**
* Méthode de la classe Comment
*/
public Comment(String comment, Integer grade, User u) {
this.comment = comment;
this.grade = grade;
this.author = u;
this.pseudo = u.getPseudo();
}
public static Comment buildFromAvroComment(
com.sudoku.comm.generated.Comment comment) {
return new Comment(comment.getComment(), comment.getGrade(),
User.buildFromAvroUser(comment.getAuthor()));
}
public User getAuthor() {
return author;
}
public String getPseudo() {
return pseudo;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
}
|
Make edge tests more interesting | /* eslint-env mocha */
const Vue = require('vue-test');
const assert = require('assert');
const progressBar = require('../src/views/progress-bar');
const ProgressBarComponent = Vue.extend(progressBar);
describe('progressBar Component', () => {
describe('`percent` computed property', () => {
let vm;
beforeEach(() => {
vm = new ProgressBarComponent({
propsData: {
progress: 0,
},
}).$mount();
});
it('should give 0 percent for progress of < 0', () => {
vm.progress = -0.0000000001;
assert.equal(vm.percent, 0);
});
it('should give 10 percent for progress of 0.1', () => {
vm.progress = 0.1;
assert.equal(vm.percent, 10);
});
it('should give 100 percent for progress of 1.0', () => {
vm.progress = 1.0;
assert.equal(vm.percent, 100);
});
it('should give 100 percent for progress of > 1.0', () => {
vm.progress = 1.0000000001;
assert.equal(vm.percent, 100);
});
});
});
| /* eslint-env mocha */
const Vue = require('vue-test');
const progressBar = require('../src/views/progress-bar');
const ProgressBarComponent = Vue.extend(progressBar);
const assert = require('assert');
describe('progressBar Component', () => {
describe('`percent` computed property', () => {
let vm;
beforeEach(() => {
vm = new ProgressBarComponent({
propsData: {
progress: 0,
},
}).$mount();
});
it('should give 0 percent for progress of < 0', () => {
vm.progress = -1.0;
assert.equal(vm.percent, 0);
});
it('should give 10 percent for progress of 0.1', () => {
vm.progress = 0.1;
assert.equal(vm.percent, 10);
});
it('should give 100 percent for progress of 1.0', () => {
vm.progress = 1.0;
assert.equal(vm.percent, 100);
});
it('should give 100 percent for progress of > 1.0', () => {
vm.progress = 70.0;
assert.equal(vm.percent, 100);
});
});
});
|
Make sure a user can only link to one contact | from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from login.tests.model_maker import make_user
class TestContactUser(TestCase):
def test_link_user_to_contact(self):
"""Create a contact and link it to a user"""
contact = make_contact(
'pkimber',
'Patrick Kimber',
)
make_user_contact(make_user('fred'), contact)
user = User.objects.get(username='fred')
user_contacts = user.usercontact_set.all()
self.assertIn('Kimber', user_contacts[0].contact.name)
def test_one_contact_per_user(self):
"""Make sure a user can only link to one contact"""
fred = make_user('fred')
jsmith = make_contact('jsmith', 'John Smith')
pkimber = make_contact('pkimber', 'Patrick Kimber')
make_user_contact(fred, pkimber)
self.assertRaises(
IntegrityError,
make_user_contact,
fred,
jsmith,
)
| from django.contrib.auth.models import User
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from login.tests.model_maker import make_user
class TestContactUser(TestCase):
def test_link_user_to_contact(self):
"""Create a contact and link it to a user"""
contact = make_contact(
'pkimber',
'Patrick Kimber',
)
make_user_contact(make_user('fred'), contact)
user = User.objects.get(username='fred')
user_contacts = user.usercontact_set.all()
self.assertIn('Kimber', user_contacts[0].contact.name)
|
Fix for the component lookup error in vocabulary | from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
fields = getUtility(IDexterityFTI, name='bda.plone.productshop.product').lookupSchema()
except:
fields = ['Datasheet', ]
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
| from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
from zope.component import ComponentLookupError
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
type = getUtility(IDexterityFTI, name='bda.plone.productshop.product')
fields = type.lookupSchema()
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
except KeyError:
pass
finally:
pass
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
|
eslint: Enable browser in env options | module.exports = {
extends: 'eslint:recommended',
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
env: {
es6: true,
browser: true,
node: true
},
globals: {
jasmine: false,
jest: false,
describe: false,
xdescribe: false,
before: false,
beforeEach: false,
it: false,
xit: false,
after: false,
afterEach: false,
expect: false,
},
rules: {
'no-console': ['warn'],
'semi': ['error', 'always'],
'no-var': ['error'],
'no-unused-vars': ['error', { 'vars': 'all', 'args': 'none', 'caughtErrors': 'none' }],
'object-curly-spacing': ['error', 'always'],
'comma-dangle': ['error', 'always-multiline'],
'arrow-parens': ['error', 'always'],
'prefer-arrow-callback': ['error', { 'allowNamedFunctions': true }],
'space-before-function-paren': ['error', 'never']
}
}
| module.exports = {
extends: 'eslint:recommended',
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
env: {
es6: true,
browser: false,
node: true
},
globals: {
jasmine: false,
jest: false,
describe: false,
xdescribe: false,
before: false,
beforeEach: false,
it: false,
xit: false,
after: false,
afterEach: false,
expect: false,
},
rules: {
'no-console': ['warn'],
'semi': ['error', 'always'],
'no-var': ['error'],
'no-unused-vars': ['error', { 'vars': 'all', 'args': 'none', 'caughtErrors': 'none' }],
'object-curly-spacing': ['error', 'always'],
'comma-dangle': ['error', 'always-multiline'],
'arrow-parens': ['error', 'always'],
'prefer-arrow-callback': ['error', { 'allowNamedFunctions': true }],
'space-before-function-paren': ['error', 'never']
}
}
|
Fix ordering of query params
3rd time's a charm | import hashlib
import urllib
# Adapted from https://github.com/zzzsochi/Flask-Gravatar/blob/master/flaskext/gravatar.py
def gravatar(user, use_ssl=False, d=None, r=None, size=None):
if use_ssl:
base_url = 'https://secure.gravatar.com/avatar/'
else:
base_url = 'http://www.gravatar.com/avatar/'
# user can be a User instance or a username string
username = user.username if hasattr(user, 'username') else user
hash_code = hashlib.md5(unicode(username).encode('utf-8')).hexdigest()
url = base_url + '?'
# Order of query params matters, due to a quirk with gravatar
params = [
('d', 'identicon'),
('s', size),
]
if r:
params.append(('r', r))
url = base_url + hash_code + '?' + urllib.urlencode(params)
return url
| import hashlib
import urllib
# Adapted from https://github.com/zzzsochi/Flask-Gravatar/blob/master/flaskext/gravatar.py
def gravatar(user, use_ssl=False, d=None, r=None, size=None):
if use_ssl:
base_url = 'https://secure.gravatar.com/avatar/'
else:
base_url = 'http://www.gravatar.com/avatar/'
# user can be a User instance or a username string
username = user.username if hasattr(user, 'username') else user
hash_code = hashlib.md5(unicode(username).encode('utf-8')).hexdigest()
url = base_url + '?'
# Order of query params matters, due to a quirk with gravatar
params = [
('s', size),
('d', 'identicon'),
]
if r:
params.append(('r', r))
url = base_url + hash_code + '?' + urllib.urlencode(params)
return url
|
Implement image proxy for external photo urls | var Article = require('./lib/wikipedia');
var Quote = require('./lib/wikiquote');
var Photo = require('./lib/flickr');
var express = require('express');
var app = express();
var http = require('http');
var url = require('url');
app.use(express.static(__dirname + '/public'));
var respondWithRandom = function(resource, res) {
resource.getRandom()
.then(function(result) {
res.json(result);
})
.catch(function() {
res.status(500).send("Error fetching " + resource.name);
});
};
app.get('/photo', function(req, res) {
respondWithRandom(Photo, res);
});
app.get('/quote', function(req, res) {
respondWithRandom(Quote, res);
});
app.get('/article', function(req, res) {
respondWithRandom(Article, res);
});
exports.startServer = function(cb) {
app.listen(process.env.PORT || 3333);
cb();
};
app.get('/proxy', function(req, res) {
var proxied = req.query.url;
var urlParts = url.parse(proxied, true);
var options = {
host: urlParts.host,
path: urlParts.path
};
var callback = function(response) {
if (response.statusCode === 200) {
res.writeHead(200, {
'Content-Type': response.headers['content-type']
});
response.pipe(res);
} else {
res.writeHead(response.statusCode);
res.end();
}
};
http.request(options, callback).end();
}); | var Article = require('./lib/wikipedia');
var Quote = require('./lib/wikiquote');
var Photo = require('./lib/flickr');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var respondWithRandom = function(resource, res) {
resource.getRandom()
.then(function(result) {
res.json(result);
})
.catch(function() {
res.status(500).send("Error fetching " + resource.name);
});
};
app.get('/photo', function(req, res) {
respondWithRandom(Photo, res);
});
app.get('/quote', function(req, res) {
respondWithRandom(Quote, res);
});
app.get('/article', function(req, res) {
respondWithRandom(Article, res);
});
exports.startServer = function(cb) {
app.listen(process.env.PORT || 3333);
cb();
}; |
Bump version 1.0.8 -- more car details | #!/usr/bin/env python
from setuptools import setup, find_packages
DESCRIPTION = "A python module which returns details about a Danish car from its license plate number"
LONG_DESCRIPTION = open('README.rst').read()
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
INSTALL_REQUIRES = ['requests', 'beautifulsoup4']
try:
import importlib
except ImportError:
INSTALL_REQUIRES.append('importlib')
tests_require = [
'requests>=1.2',
'beautifulsoup4'
]
setup(
name='dk-car-scraper',
version='1.0.8',
packages=find_packages(exclude=[]),
author='Joshua Karjala-Svenden',
author_email='joshua@fluxuries.com',
url='https://github.com/joshuakarjala/dk-car-scraper/',
license='MIT',
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
install_requires=INSTALL_REQUIRES,
# tests_require=tests_require,
# extras_require={'test': tests_require},
# test_suite='runtests.runtests',
#include_package_data=True,
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
DESCRIPTION = "A python module which returns details about a Danish car from its license plate number"
LONG_DESCRIPTION = open('README.rst').read()
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
INSTALL_REQUIRES = ['requests', 'beautifulsoup4']
try:
import importlib
except ImportError:
INSTALL_REQUIRES.append('importlib')
tests_require = [
'requests>=1.2',
'beautifulsoup4'
]
setup(
name='dk-car-scraper',
version='1.0.7',
packages=find_packages(exclude=[]),
author='Joshua Karjala-Svenden',
author_email='joshua@fluxuries.com',
url='https://github.com/joshuakarjala/dk-car-scraper/',
license='MIT',
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
install_requires=INSTALL_REQUIRES,
# tests_require=tests_require,
# extras_require={'test': tests_require},
# test_suite='runtests.runtests',
#include_package_data=True,
)
|
Fix a typo in the Commands module help text | from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from zope.interface import implements
class CommandsCommand(BotCommand):
implements(IPlugin, IBotModule)
name = "Commands"
def triggers(self):
return ["commands"]
def load(self):
self.help = "Commands: commands | Lists all bot commands from the modules that are enabled for this server."
self.commandHelp = {}
def execute(self, server, source, command, params, data):
commandsList = []
for moduleName, module in self.bot.moduleHandler.loadedModules.iteritems():
if self.bot.moduleHandler.useModuleOnServer(moduleName, server) and isinstance(module, BotCommand):
commandsList += module.triggers()
msg = "Available commands: {}".format(", ".join(sorted(commandsList)))
self.bot.servers[server].outputHandler.cmdPRIVMSG(source, msg)
commandsCommand = CommandsCommand()
| from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from zope.interface import implements
class CommandsCommand(BotCommand):
implements(IPlugin, IBotModule)
name = "Commands"
def triggers(self):
return ["commands"]
def load(self):
self.help = "Commands: commands | Lists all bot commands from the modules tht are enabled for this server."
self.commandHelp = {}
def execute(self, server, source, command, params, data):
commandsList = []
for moduleName, module in self.bot.moduleHandler.loadedModules.iteritems():
if self.bot.moduleHandler.useModuleOnServer(moduleName, server) and isinstance(module, BotCommand):
commandsList += module.triggers()
msg = "Available commands: {}".format(", ".join(sorted(commandsList)))
self.bot.servers[server].outputHandler.cmdPRIVMSG(source, msg)
commandsCommand = CommandsCommand()
|
Change test name and test SVR too | import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_gamma_value_svm():
n, sz, d = 5, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=2, size=n)
gamma = 10.
for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]:
gak_model = ModelClass(kernel="gak", gamma=gamma)
sklearn_X, _ = gak_model._preprocess_sklearn(time_series,
labels,
fit_time=True)
cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
np.testing.assert_allclose(sklearn_X, cdist_mat)
| import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_svm_gak():
n, sz, d = 15, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=2, size=n)
gamma = 10.
gak_km = TimeSeriesSVC(kernel="gak", gamma=gamma)
sklearn_X, _ = gak_km._preprocess_sklearn(time_series, labels,
fit_time=True)
cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.))
np.testing.assert_allclose(sklearn_X, cdist_mat)
|
Include static files specific to regform | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from MaKaC.webinterface.pages.base import WPJinjaMixin
from MaKaC.webinterface.pages.conferences import WPConferenceModifBase
class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase):
template_prefix = 'events/registration/'
sidemenu_option = 'registration'
def getJSFiles(self):
return (WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls() +
self._asset_env['indico_regform'].urls())
def getCSSFiles(self):
return WPConferenceModifBase.getCSSFiles(self) + self._asset_env['registrationform_sass'].urls()
| # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from MaKaC.webinterface.pages.base import WPJinjaMixin
from MaKaC.webinterface.pages.conferences import WPConferenceModifBase
class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase):
template_prefix = 'events/registration'
sidemenu_option = 'registration'
def getJSFiles(self):
return WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls()
|
Use the full option name for clarity and also search in the user's home directory | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ilya Akhmadullin
# Copyright (c) 2013 Ilya Akhmadullin
#
# License: MIT
#
"""This module exports the jscs plugin class."""
from SublimeLinter.lint import Linter
class Jscs(Linter):
"""Provides an interface to jscs."""
syntax = ('javascript', 'html', 'html 5')
cmd = 'jscs -r checkstyle'
regex = (
r'^\s+?<error line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
# jscs always reports with error severity; show as warning
r'severity="(?P<warning>error)" '
r'message="(?P<message>.+?)"'
)
multiline = True
selectors = {'html': 'source.js.embedded.html'}
tempfile_suffix = 'js'
config_file = ('--config', '.jscs.json', '~')
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ilya Akhmadullin
# Copyright (c) 2013 Ilya Akhmadullin
#
# License: MIT
#
"""This module exports the jscs plugin class."""
from SublimeLinter.lint import Linter
class Jscs(Linter):
"""Provides an interface to jscs."""
syntax = ('javascript', 'html', 'html 5')
cmd = 'jscs -r checkstyle'
config_file = ('-c', '.jscs.json')
regex = (
r'^\s+?<error line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
# jscs always reports with error severity; show as warning
r'severity="(?P<warning>error)" '
r'message="(?P<message>.+?)"'
)
multiline = True
selectors = {'html': 'source.js.embedded.html'}
tempfile_suffix = 'js'
|
Fix tests to match ember-test-helpers 0.3.0. | import { describeModule, it } from 'ember-mocha';
import { setResolverRegistry } from 'tests/test-support/resolver';
window.expect = chai.expect;
function setupRegistry() {
setResolverRegistry({
'component:x-foo': Ember.Component.extend()
});
}
var callbackOrder, setupContext, teardownContext, beforeSetupContext, afterTeardownContext;
describeModule('component:x-foo', 'TestModule callbacks', {
beforeSetup: function() {
beforeSetupContext = this;
callbackOrder = [ 'beforeSetup' ];
setupRegistry();
},
setup: function() {
setupContext = this;
callbackOrder.push('setup');
expect(setupContext).to.not.equal(beforeSetupContext);
},
teardown: function() {
teardownContext = this;
callbackOrder.push('teardown');
expect(callbackOrder).to.deep.equal([ 'beforeSetup', 'setup', 'teardown']);
expect(setupContext).to.equal(teardownContext);
},
afterTeardown: function() {
afterTeardownContext = this;
callbackOrder.push('afterTeardown');
expect(callbackOrder).to.deep.equal([ 'beforeSetup', 'setup', 'teardown', 'afterTeardown']);
expect(afterTeardownContext).to.equal(beforeSetupContext);
expect(afterTeardownContext).to.not.equal(teardownContext);
}
}, function() {
it("should call setup callbacks in the correct order", function() {
expect(callbackOrder).to.deep.equal([ 'beforeSetup', 'setup' ]);
});
});
| import { describeModule, it } from 'ember-mocha';
import { setResolverRegistry } from 'tests/test-support/resolver';
window.expect = chai.expect;
function setupRegistry() {
setResolverRegistry({
'component:x-foo': Ember.Component.extend()
});
}
var a = 0;
var b = 0;
var beforeSetupOk = false;
var beforeTeardownOk = false;
describeModule('component:x-foo', 'TestModule callbacks', {
beforeSetup: function() {
setupRegistry();
beforeSetupOk = (a === 0);
b += 1;
},
setup: function() {
a += 1;
},
beforeTeardown: function() {
beforeTeardownOk = (a === 1);
b -= 1;
},
teardown: function() {
a -= 1;
}
}, function() {
it("beforeSetup callback is called prior to any test setup", function() {
expect(beforeSetupOk).to.be.truthy;
expect(b).to.equal(1);
});
it("setup callback is called prior to test", function() {
expect(a).to.equal(1);
});
it("teardown callback is called after test", function() {
expect(a).to.equal(1);
});
it("beforeTeardown callback is called prior to any test teardown", function() {
expect(beforeTeardownOk).to.be.truthy;
expect(b).to.equal(1);
});
});
|
Change band name to all caps | import React, { Component } from 'react';
import './App.css';
import './index.css';
import Rowbox from './components/Rowbox';
import IconRow from './components/IconRow';
class App extends Component {
render() {
return (
<main className='container'>
<div className='row row1'>
<h1 className='nameHeader'>FAY RAY</h1>
<IconRow />
</div>
<div className='row row2'>
<Rowbox text='Is a band' number='1'/>
<Rowbox text='Has a new single' number='2'/>
</div>
<div className='row row3'>
<Rowbox text='Plays shows' number='3'/>
<Rowbox text='Takes photos' number='4'/>
<Rowbox text='Uses email' number='5'/>
</div>
</main>
);
}
}
export default App;
| import React, { Component } from 'react';
import './App.css';
import './index.css';
import Rowbox from './components/Rowbox';
import IconRow from './components/IconRow';
class App extends Component {
render() {
return (
<main className='container'>
<div className='row row1'>
<h1 className='nameHeader'>Fay Ray</h1>
<IconRow />
</div>
<div className='row row2'>
<Rowbox text='Is a band' number='1'/>
<Rowbox text='Has a new single' number='2'/>
</div>
<div className='row row3'>
<Rowbox text='Plays shows' number='3'/>
<Rowbox text='Takes photos' number='4'/>
<Rowbox text='Uses email' number='5'/>
</div>
</main>
);
}
}
export default App;
|
Use TestCase instead of WP_UnitTestCase | <?php
use PHPUnit\Framework\TestCase;
use TwinDigital\WPTools\PluginTools;
class PluginToolsTest extends TestCase {
/**
* Instance of the class.
*
* @var \TwinDigital\WPTools\PluginTools $class
*/
public $class;
/**
* Tests if the plugin_list is loaded.
*
* @covers PluginTools::loadPluginList()
* @return void
*/
public function testLoadPluginList() {
$this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
}
/**
* Tests if the plugin_list is loaded.
*
* @covers PluginTools::loadPluginList()
* @return void
*/
public function testLoadPluginListForced() {
$this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
}
public function testRefreshLoadedPlugins() {
PluginTools::$loadedPlugins = null;
PluginTools::refreshLoadedPlugins();
$this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
}
public function setUp() {
$this->class = PluginTools::class;
}
public function tearDown() {
parent::tearDown();
}
}
| <?php
use PHPUnit\Framework\TestCase;
use TwinDigital\WPTools\PluginTools;
class PluginToolsTest extends WP_UnitTestCase {
/**
* Instance of the class.
*
* @var \TwinDigital\WPTools\PluginTools $class
*/
public $class;
/**
* Tests if the plugin_list is loaded.
*
* @covers PluginTools::loadPluginList()
* @return void
*/
public function testLoadPluginList() {
$this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
}
/**
* Tests if the plugin_list is loaded.
*
* @covers PluginTools::loadPluginList()
* @return void
*/
public function testLoadPluginListForced() {
$this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
}
public function testRefreshLoadedPlugins() {
PluginTools::$loadedPlugins = null;
PluginTools::refreshLoadedPlugins();
$this->assertNotCount(0, PluginTools::$loadedPlugins, 'Pluginlist is empty, probably failed loading the list of plugins.');
}
protected function setUp() {
$this->class = PluginTools::class;
}
public function tearDown() {
parent::tearDown(); // TODO: Change the autogenerated stub
}
}
|
Fix test for go completor. | # -*- coding: utf-8 -*-
import mock
import completor
from completor.compat import to_unicode
from completers.go import Go # noqa
def test_format_cmd(vim_mod):
vim_mod.funcs['line2byte'] = mock.Mock(return_value=20)
vim_mod.funcs['completor#utils#tempname'] = mock.Mock(
return_value=b'/tmp/vJBio2A/2.vim')
vim_mod.current.buffer.name = '/home/vagrant/bench.vim'
vim_mod.current.window.cursor = (1, 5)
go = completor.get('go')
go.input_data = to_unicode('self.', 'utf-8')
assert go.format_cmd() == [
'gocode', '-f=csv', '--in=/tmp/vJBio2A/2.vim', 'autocomplete',
'/home/vagrant/bench.vim', 24]
def test_parse():
data = [
b'func,,Errorf,,func(format string, a ...interface{}) error',
b'func,,Fprint,,func(w io.Writer, a ...interface{}) (n int, err error)', # noqa
]
go = completor.get('go')
assert go.parse(data) == [{
'word': b'Errorf',
'menu': b'func(format string, a ...interface{}) error'
}, {
'word': b'Fprint',
'menu': b'func(w io.Writer, a ...interface{}) (n int, err error)'
}]
| # -*- coding: utf-8 -*-
import mock
import completor
from completor.compat import to_unicode
from completers.go import Go # noqa
def test_format_cmd(vim_mod):
vim_mod.funcs['line2byte'] = mock.Mock(return_value=20)
vim_mod.funcs['completor#utils#tempname'] = mock.Mock(
return_value=b'/tmp/vJBio2A/2.vim')
vim_mod.current.window.cursor = (1, 5)
go = completor.get('go')
go.input_data = to_unicode('self.', 'utf-8')
assert go.format_cmd() == [
'gocode', '-f=csv', '--in=/tmp/vJBio2A/2.vim', 'autocomplete', 24]
def test_parse():
data = [
b'func,,Errorf,,func(format string, a ...interface{}) error',
b'func,,Fprint,,func(w io.Writer, a ...interface{}) (n int, err error)', # noqa
]
go = completor.get('go')
assert go.parse(data) == [{
'word': b'Errorf',
'menu': b'func(format string, a ...interface{}) error'
}, {
'word': b'Fprint',
'menu': b'func(w io.Writer, a ...interface{}) (n int, err error)'
}]
|
Delete zombie code from socket testing | var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
//var models = require("./models");
var PORT = process.env.PORT || 3000;
//models.sequelize.sync().then(function () {
io.on('connection', function(client) {
console.log('Someone connected!');
client.on('join', function(data) {
if(data === 'This is your teacher speaking') {
client.emit('greeting', 'Hiya, Teach!');
} else{
client.emit('greeting', 'Hello, student. Please wait for your instructor to open a new poll.');
}
});
client.on('newPoll', function(data) {
io.sockets.emit('openPoll', data);
});
client.on('disconnect', function(client) {
console.log('Bye!\n');
});
});
require('./config/routes.js')(app, express);
server.listen(PORT, function (){
console.log('listening on port', PORT);
});
// }; | var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
//var models = require("./models");
var PORT = process.env.PORT || 3000;
// app.get('/', function (req, res) {
// res.sendFile(__dirname + '/socketTest.html');
// })
//models.sequelize.sync().then(function () {
io.on('connection', function(client) {
console.log('Someone connected!');
client.on('join', function(data) {
if(data === 'This is your teacher speaking') {
client.emit('greeting', 'Hiya, Teach!');
} else{
client.emit('greeting', 'Hello, student. Please wait for your instructor to open a new poll.');
}
//client.emit('openPoll', 'hello, its me');
});
client.on('newPoll', function(data) {
console.log('>>>>>>>>>',data);
io.sockets.emit('openPoll', data);
});
client.on('disconnect', function(client) {
console.log('Bye!\n');
});
});
require('./config/routes.js')(app, express);
server.listen(PORT, function (){
console.log('listening on port', PORT);
});
// }; |
Change some function type to static in BCBProcess
It is...
static initProcess()
static initPopover()
static initEvent() |
class BCBProcess extends CommonProcess {
constructor() {
super({
name: `${Project.NAME} Process`
});
BCBProcess.initProcess();
}
static initProcess() {
BCBProcess.initPopover();
BCBProcess.initEvent();
}
static initPopover() {
{
new PopoverController({
name: 'ID Popover',
selector: '#login-id-help',
help: 'ID を入力してください。'
});
new PopoverController({
name: 'Password Popover',
selector: '#login-password-help',
help: 'パスワード を入力してください。'
});
new PopoverController({
name: 'Login Check Popover',
selector: '#login-check-help',
help: '共有デバイスでは設定に注意してください。'
});
new PopoverController({
name: 'Logined ID Popover',
selector: '#logined-id-help',
help: 'ログインしている ID です。'
});
}
}
static initEvent() {
new LoginEvent();
}
}
|
class BCBProcess extends CommonProcess {
constructor() {
super({
name: `${Project.NAME} Process`
});
this.initProcess();
}
initProcess() {
this.initPopover();
this.initEvent();
}
initPopover() {
{
new PopoverController({
name: 'ID Popover',
selector: '#login-id-help',
help: 'ID を入力してください。'
});
new PopoverController({
name: 'Password Popover',
selector: '#login-password-help',
help: 'パスワード を入力してください。'
});
new PopoverController({
name: 'Login Check Popover',
selector: '#login-check-help',
help: '共有デバイスでは設定に注意してください。'
});
new PopoverController({
name: 'Logined ID Popover',
selector: '#logined-id-help',
help: 'ログインしている ID です。'
});
}
}
initEvent() {
new LoginEvent();
}
}
|
Add base logic to unmarshal a yaml | package main
import (
"flag"
"fmt"
"os"
"io/ioutil"
"github.com/fatih/color"
"github.com/oshalygin/k8s-config/models"
"gopkg.in/yaml.v2"
)
func main() {
configurationFile := models.Deployment{}
configurationType := flag.String("type", "deployment", "Kubernetes configuration type, eg: deployment, rc, secret")
image := flag.String("image", "", "Docker image name")
imageTag := flag.String("tag", "", "Docker image tag")
filePath := flag.String("file-path", "", "Configuration file location")
flag.Parse()
file, err := ioutil.ReadFile("./test-files/deployment.yaml")
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
}
err = yaml.Unmarshal(file, &configurationFile)
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
}
err = checkRequiredFlags(*configurationType, *image, *imageTag, *filePath)
if err != nil {
color.Red("Error: %v", err)
color.Black("--------------------")
flag.PrintDefaults()
os.Exit(1)
}
fmt.Printf("type: %s\n", *configurationType)
fmt.Printf("image: %s\n", *image)
fmt.Printf("tag: %s\n", *imageTag)
fmt.Printf("file-path: %s\n", *filePath)
}
| package main
import (
"flag"
"fmt"
"os"
"github.com/fatih/color"
)
func main() {
configurationType := flag.String("type", "deployment", "Kubernetes configuration type, eg: deployment, rc, secret")
image := flag.String("image", "", "Docker image name")
imageTag := flag.String("tag", "", "Docker image tag")
filePath := flag.String("file-path", "", "Configuration file location")
flag.Parse()
err := checkRequiredFlags(*configurationType, *image, *imageTag, *filePath)
if err != nil {
color.Red("Error: %v", err)
color.Black("--------------------")
flag.PrintDefaults()
os.Exit(1)
}
fmt.Printf("type: %s\n", *configurationType)
fmt.Printf("image: %s\n", *image)
fmt.Printf("tag: %s\n", *imageTag)
fmt.Printf("file-path: %s\n", *filePath)
}
|
Fix online expoentially weighted variance calculation
Transcription error from the original article.
Fixes #2 | package onlinestats
// From http://queue.acm.org/detail.cfm?id=2534976
import "math"
type ExpWeight struct {
n int
m1 float64
v float64
alpha float64
}
func NewExpWeight(alpha float64) *ExpWeight {
return &ExpWeight{alpha: alpha}
}
func (e *ExpWeight) Push(x float64) {
if e.n == 0 {
e.m1 = x
e.v = 1
} else {
e.m1 = (1-e.alpha)*x + e.alpha*e.m1
v := (x - e.m1)
e.v = (1-e.alpha)*(v*v) + e.alpha*e.v
}
e.n++
}
func (e *ExpWeight) Len() int {
return e.n
}
func (e *ExpWeight) Mean() float64 {
return e.m1
}
func (e *ExpWeight) Var() float64 {
return e.v
}
func (e *ExpWeight) Stddev() float64 {
return math.Sqrt(e.v)
}
| package onlinestats
// From http://queue.acm.org/detail.cfm?id=2534976
import "math"
type ExpWeight struct {
n int
m1 float64
v float64
alpha float64
}
func NewExpWeight(alpha float64) *ExpWeight {
return &ExpWeight{alpha: alpha}
}
func (e *ExpWeight) Push(x float64) {
if e.n == 0 {
e.m1 = x
e.v = 1
} else {
e.m1 = (1-e.alpha)*x + e.alpha*e.m1
e.v = (1-e.alpha)*(x-e.m1) + e.alpha*e.v
}
e.n++
}
func (e *ExpWeight) Len() int {
return e.n
}
func (e *ExpWeight) Mean() float64 {
return e.m1
}
func (e *ExpWeight) Var() float64 {
return e.v
}
func (e *ExpWeight) Stddev() float64 {
return math.Sqrt(e.v)
}
|
Change install directory - now /usr/local/bin | """
MassOpenCloud / Hardware Isolation Layer (HIL)
Slurm / HIL Control Settings
May 2017, Tim Donahue tpd001@gmail.com
"""
DEBUG = True
SLURM_INSTALL_DIR = '/usr/local/bin/'
HIL_SLURMCTLD_PROLOG_LOGFILE = '/var/log/slurm-llnl/hil_prolog.log'
HIL_MONITOR_LOGFILE = '/var/log/slurm-llnl/hil_monitor.log'
HIL_RESERVATIONS_FILE = '/var/local/slurm-llnl/hil_reservations.txt'
USER_HIL_SUBDIR = '.hil'
USER_HIL_LOGFILE = 'hil_reservations.log'
HIL_CMD_NAMES = ('hil_reserve', 'hil_release')
HIL_PARTITION_PREFIX = 'HIL_partition_'
HIL_PARTITION_PREFIX = 'debug'
HIL_RESERVATION_DEFAULT_DURATION = 24 * 60 * 60 # Seconds
HIL_RESERVATION_GRACE_PERIOD = 4 * 60 * 60 # Seconds
HIL_RESERVATION_PREFIX = 'flexalloc_MOC_'
# Partition validation controls
RES_CHECK_DEFAULT_PARTITION = False
RES_CHECK_EXCLUSIVE_PARTITION = False
RES_CHECK_SHARED_PARTITION = False
RES_CHECK_PARTITION_STATE = True
# EOF
| """
MassOpenCloud / Hardware Isolation Layer (HIL)
Slurm / HIL Control Settings
May 2017, Tim Donahue tpd001@gmail.com
"""
DEBUG = True
SLURM_INSTALL_DIR = '/usr/bin/'
HIL_SLURMCTLD_PROLOG_LOGFILE = '/var/log/slurm-llnl/hil_prolog.log'
HIL_MONITOR_LOGFILE = '/var/log/slurm-llnl/hil_monitor.log'
HIL_RESERVATIONS_FILE = '/var/local/slurm-llnl/hil_reservations.txt'
USER_HIL_SUBDIR = '.hil'
USER_HIL_LOGFILE = 'hil_reservations.log'
HIL_CMD_NAMES = ('hil_reserve', 'hil_release')
HIL_PARTITION_PREFIX = 'HIL_partition_'
HIL_PARTITION_PREFIX = 'debug'
HIL_RESERVATION_DEFAULT_DURATION = 24 * 60 * 60 # Seconds
HIL_RESERVATION_GRACE_PERIOD = 4 * 60 * 60 # Seconds
HIL_RESERVATION_PREFIX = 'flexalloc_MOC_'
# Partition validation controls
RES_CHECK_DEFAULT_PARTITION = False
RES_CHECK_EXCLUSIVE_PARTITION = False
RES_CHECK_SHARED_PARTITION = False
RES_CHECK_PARTITION_STATE = True
# EOF
|
Make some pages private routes | import React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import { AuthProvider } from '../Auth';
import PrivateRoute from '../PrivateRoute';
import LandingPage from '../Landing';
import SignInPage from '../SignIn'
import ViewActivitiesPage from '../ViewActivities';
import ViewTripsPage from '../ViewTrips';
import * as ROUTES from '../../constants/routes';
/**
* The main App component that is fed to the index.js entrypoint. Defines all
* pages that can be visited using React Router.
*/
class App extends React.Component {
render() {
return (
<AuthProvider>
<Router>
<div>
<Route exact path={ROUTES.LANDING} component={LandingPage} />
<Route path={ROUTES.SIGN_IN} component={SignInPage} />
<PrivateRoute path={ROUTES.VIEW_TRIPS} component={ViewTripsPage} />
<PrivateRoute path={ROUTES.VIEW_ACTIVITIES} component={ViewActivitiesPage} />
</div>
</Router>
</AuthProvider>
);
}
};
export default App;
| import React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import LandingPage from '../Landing';
import SignInPage from '../SignIn'
import ViewActivitiesPage from '../ViewActivities';
import ViewTripsPage from '../ViewTrips';
import * as ROUTES from '../../constants/routes';
/**
* The main App component that is fed to the index.js entrypoint. Defines all
* pages that can be visited using React Router.
*/
class App extends React.Component {
render() {
return (
<Router>
<div>
<Route exact path={ROUTES.LANDING} component={LandingPage} />
<Route path={ROUTES.SIGN_IN} component={SignInPage} />
<Route path={ROUTES.VIEW_TRIPS} component={ViewTripsPage} />
<Route path={ROUTES.VIEW_ACTIVITIES} component={ViewActivitiesPage} />
</div>
</Router>
);
}
};
export default App;
|
Add check for failed reminders so that it doesn't case an Exception | from __future__ import absolute_import
from celery import shared_task
from django.utils import timezone
from django.conf import settings
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.models import generate_reminder
from studygroups.models import send_reminder
from studygroups.models import send_weekly_update
from django.utils import translation
import datetime
@shared_task
def send_reminders():
now = timezone.now()
translation.activate(settings.LANGUAGE_CODE)
# TODO - should this be set here or closer to where the language matters?
for reminder in Reminder.objects.filter(sent_at__isnull=True):
if reminder.study_group_meeting and reminder.study_group_meeting.meeting_time - now < datetime.timedelta(days=2):
send_reminder(reminder)
@shared_task
def gen_reminders():
for study_group in StudyGroup.objects.all():
translation.activate(settings.LANGUAGE_CODE)
generate_reminder(study_group)
@shared_task
def weekly_update():
# Create a report for the previous week
send_weekly_update()
| from __future__ import absolute_import
from celery import shared_task
from django.utils import timezone
from django.conf import settings
from studygroups.models import StudyGroup
from studygroups.models import Reminder
from studygroups.models import generate_reminder
from studygroups.models import send_reminder
from studygroups.models import send_weekly_update
from django.utils import translation
import datetime
@shared_task
def send_reminders():
now = timezone.now()
translation.activate(settings.LANGUAGE_CODE)
# TODO - should this be set here or closer to where the language matters?
for reminder in Reminder.objects.filter(sent_at__isnull=True):
if reminder.study_group_meeting.meeting_time - now < datetime.timedelta(days=2):
send_reminder(reminder)
@shared_task
def gen_reminders():
for study_group in StudyGroup.objects.all():
translation.activate(settings.LANGUAGE_CODE)
generate_reminder(study_group)
@shared_task
def weekly_update():
# Create a report for the previous week
send_weekly_update()
|
Remove test no functions called test | describe("Moments", function() {
var NO_ALLIES = "Unselect all";
var ALL_ALLIES = "Select all";
beforeAll(function() {
var elements = [];
elements.push("<div id='test_body'></div>");
elements.push("<label id='viewers_label'></label>");
elements.push("<input type='checkbox' id='viewers'></input>");
for (var i = 0; i < elements.length; i++) {
$(document.body).append(elements[i]);
}
});
it("test onReadyMoments to be called", function() {
var newOrEdit = spyOn(window, "newOrEdit");
onReadyMoments();
expect(newOrEdit).toHaveBeenCalled();
expect($('#viewers_label').text()).toBe("");
});
it("test onReadyMoments and newOrEdit to be called", function() {
$("body").addClass("moments new");
onReadyMoments();
expect($('#viewers_label').text()).toBe(ALL_ALLIES);
onReadyMoments();
});
it("test newOeEdit in onReadyMoments to be called", function() {
var newOrEdit = spyOn(window, "newOrEdit");
onReadyMoments();
expect(newOrEdit).toHaveBeenCalled();
});
});
| describe("Moments", function() {
var NO_ALLIES = "Unselect all";
var ALL_ALLIES = "Select all";
beforeAll(function() {
var elements = [];
elements.push("<div id='test_body'></div>");
elements.push("<label id='viewers_label'></label>");
elements.push("<input type='checkbox' id='viewers'></input>");
for (var i = 0; i < elements.length; i++) {
$(document.body).append(elements[i]);
}
});
it("test no functions called", function() {
var newOrEdit = spyOn(window, "newOrEdit");
expect(newOrEdit).not.toHaveBeenCalled();
});
it("test onReadyMoments to be called", function() {
var newOrEdit = spyOn(window, "newOrEdit");
onReadyMoments();
expect(newOrEdit).toHaveBeenCalled();
expect($('#viewers_label').text()).toBe("");
});
it("test onReadyMoments and newOrEdit to be called", function() {
$("body").addClass("moments new");
onReadyMoments();
expect($('#viewers_label').text()).toBe(ALL_ALLIES);
onReadyMoments();
});
it("test newOeEdit in onReadyMoments to be called", function() {
var newOrEdit = spyOn(window, "newOrEdit");
onReadyMoments();
expect(newOrEdit).toHaveBeenCalled();
});
});
|
Mark link to points to displaying page
As .current-page | <?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/../../lib/utils.php';
class NavigatorSection extends RawDataContainer implements Component {
public function render(): Component {
$currentpage = $this->get('page');
$subpagetmpls = $this->get('subpages');
$subpageitems = array_map(
function ($tmpl) use($currentpage) {
$page = $tmpl['page'];
return HtmlElement::emmetDepth(
"li#to-$page>a",
[
[
'dataset' => $tmpl,
'classes' => $currentpage === $page ? ['current-page'] : [],
],
[
'href' => $tmpl['href'],
$tmpl['title'],
],
]
);
},
$subpagetmpls
);
return HtmlElement::emmetBottom('nav>ul', [
HtmlElement::emmetTop('li#subpage-navigator-title.subpage.title', []),
HtmlElement::emmetTop('ul#subpage-navigator.subpage', $subpageitems),
]);
}
}
?>
| <?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/../../lib/utils.php';
class NavigatorSection extends RawDataContainer implements Component {
public function render(): Component {
$subpagetmpls = $this->get('subpages');
$subpageitems = array_map(
function ($tmpl) {
return HtmlElement::emmetDepth(
"li#to-{$tmpl['page']}>a",
[
[
'dataset' => $tmpl,
],
[
'href' => $tmpl['href'],
$tmpl['title'],
],
]
);
},
$subpagetmpls
);
return HtmlElement::emmetBottom('nav>ul', [
HtmlElement::emmetTop('li#subpage-navigator-title.subpage.title', []),
HtmlElement::emmetTop('ul#subpage-navigator.subpage', $subpageitems),
]);
}
}
?>
|
Add method to query DNZ Metadata API | import os
import json
import random
import flask
import requests
import hashlib
DNZ_URL = 'http://api.digitalnz.org/v3/records/'
DNZ_KEY = os.environ.get('DNZ_KEY')
records = {}
# TODO This should be switched to records associated with days.
# Create a hash table of all records.
for record in json.loads(open('data/records-2015.json').read())['records']:
record_hash = hashlib.md5(str(record['id']).encode('utf-8')).hexdigest()
records[record_hash] = record
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('index.html')
@app.route('/hello')
def hello():
return 'hello'
@app.route('/random')
def random_record():
record_hash = random.choice(list(records.keys()))
return str(get_metadata(records[record_hash]['id']))
def get_metadata(id):
url = DNZ_URL + '{id}.json?api_key={key}'.format(id=id, key=DNZ_KEY)
return requests.get(url).json()
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| import os
import json
import random
import flask
from hashlib import md5
records = {}
# Create a hash table of all records.
for record in json.loads(open('data/records-2015.json').read())['records']:
records[md5(str(record['id']).encode('utf-8')).hexdigest()] = record
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('index.html')
@app.route('/hello')
def hello():
return 'hello'
@app.route('/random')
def random_record():
record_hash = random.choice(list(records.keys()))
return str(records[record_hash])
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)
|
Format code using black and remove comments | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import tensorflow as tf
def create_keras_model():
model = tf.keras.Sequential(
[
tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation="relu"),
tf.keras.layers.Dense(10, activation="softmax"),
]
)
model.compile(
loss="sparse_categorical_crossentropy",
optimizer=tf.keras.optimizers.Adam(),
metrics=["sparse_categorical_accuracy"],
)
return model
| # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import tensorflow as tf
# Create the model
def create_keras_model():
model = tf.keras.Sequential(
[
tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation="relu"),
tf.keras.layers.Dense(10, activation="softmax"),
]
)
model.compile(
loss="sparse_categorical_crossentropy",
optimizer=tf.keras.optimizers.Adam(),
metrics=["accuracy"],
)
return model
|
Fix user search with 0 results | <?php
namespace Scriptotek\Alma\Users;
use Scriptotek\Alma\ResourceList;
class Users extends ResourceList
{
protected $resourceName = User::class;
/**
* Iterates over all users matching the given query.
* Handles continuation.
*/
public function search($query, $full = false, $batchSize = 10)
{
$offset = 0;
while (true) {
$response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);
if ($response->total_record_count == 0) {
break;
}
foreach ($response->user as $data) {
$user = User::fromResponse($this->client, $data);
if ($full) {
$user->fetch();
}
yield $user;
$offset++;
}
if ($offset >= $response->total_record_count) {
break;
}
}
}
}
| <?php
namespace Scriptotek\Alma\Users;
use Scriptotek\Alma\ResourceList;
class Users extends ResourceList
{
protected $resourceName = User::class;
/**
* Iterates over all users matching the given query.
* Handles continuation.
*/
public function search($query, $full = false, $batchSize = 10)
{
$offset = 0;
while (true) {
$response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);
foreach ($response->user as $data) {
$user = User::fromResponse($this->client, $data);
if ($full) {
$user->fetch();
}
yield $user;
$offset++;
}
if ($offset >= $response->total_record_count) {
break;
}
}
}
}
|
fix(lint): Fix post install eslint fix triggering an error | const Base = require('yeoman-generator');
class LintGenerator extends Base {
initializing() {
this.composeWith('rn-toolbox:checkversion');
}
install() {
this.yarnInstall(['prettier', 'eslint', 'eslint-config-universe'], {
dev: true,
cwd: this.destinationRoot(),
}).then(() => {
this.spawnCommand('yarn', ['test:lint', '--', '--fix'], {
cwd: this.destinationPath(),
});
});
}
writing() {
this.fs.copyTpl(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copyTpl(
this.templatePath('eslintignore'),
this.destinationPath('.eslintignore')
);
this.fs.copyTpl(
this.templatePath('prettierrc'),
this.destinationPath('.prettierrc')
);
this.fs.extendJSON(
'package.json',
{
scripts: { 'test:lint': 'eslint . --quiet' },
},
null,
2
);
}
end() {
this.config.set('lint', true);
this.config.save();
}
}
module.exports = LintGenerator;
| const Base = require('yeoman-generator');
class LintGenerator extends Base {
initializing() {
this.composeWith('rn-toolbox:checkversion');
}
install() {
this.yarnInstall([
'prettier',
'eslint',
'eslint-config-universe',
], {
dev: true,
cwd: this.destinationRoot(),
});
this.spawnCommand('yarn', ['test:lint', '--', '--fix'], {
cwd: this.destinationPath(),
});
}
writing() {
this.fs.copyTpl(
this.templatePath('eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copyTpl(
this.templatePath('eslintignore'),
this.destinationPath('.eslintignore')
);
this.fs.copyTpl(
this.templatePath('prettierrc'),
this.destinationPath('.prettierrc')
);
this.fs.extendJSON('package.json', {
scripts: { 'test:lint': 'eslint . --quiet' },
}, null, 2);
}
end() {
this.config.set('lint', true);
this.config.save();
}
}
module.exports = LintGenerator;
|
Use tags or direct url | from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
if not tag.find('/') == -1:
tag = tag[::-1]
pos = tag.find('/')
tag = tag[:pos]
tag = tag[::-1]
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
description = soup.find_all('div', {'class':'description'})
content = soup.find_all('div', {'class':'content'})
stats = {}
for i in range(len(description)):
description_text = ((description[i].get_text()).replace(' ', '_')).lower()
content_text = content[i].get_text()
stats[description_text] = content_text
if stats['clan'] == 'No Clan':
stats['clan'] = None
return stats
stats = statsRoyale(tag='9890JJJV')
print stats
| from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
stats = {}
content = soup.find_all('div', {'class':'content'})
stats['clan'] = content[0].get_text()
if stats['clan'] == 'No Clan':
stats['clan'] = None
stats['highest_trophies'] = content[1].get_text()
stats['last_known_trophies'] = content[2].get_text()
stats['challenge_cards_won'] = content[3].get_text()
stats['tournament_cards_won'] = content[4].get_text()
stats['total_donations'] = content[5].get_text()
stats['best_session_rank'] = content[6].get_text()
stats['previous_session_rank'] = content[7].get_text()
stats['legendary_trophies'] = content[8].get_text()
stats['wins'] = content[9].get_text()
stats['losses'] = content[10].get_text()
stats['3_crown_wins'] = content[11].get_text()
return stats
stats = statsRoyale(tag='9890JJJV')
print stats
|
Remove unused imports from test_check_get_new | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('filling up the boring replacements',
r'http://rlee287.github.io/pyautoupdate/testing/')
launch._get_new()
with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code:
file_text=file_code.read()
assert "new version" in file_text
@needinternet
def test_check_get_invalid_archive(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('what file? hahahaha',
r'http://rlee287.github.io/pyautoupdate/testing2/',
newfiles="project.tar.gz")
launch._get_new()
assert os.path.isfile("project.tar.gz.dump")
os.remove("project.tar.gz.dump")
| from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
import sys
import pytest
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('filling up the boring replacements',
r'http://rlee287.github.io/pyautoupdate/testing/')
launch._get_new()
with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code:
file_text=file_code.read()
assert "new version" in file_text
@needinternet
def test_check_get_invalid_archive(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('what file? hahahaha',
r'http://rlee287.github.io/pyautoupdate/testing2/',
newfiles="project.tar.gz")
launch._get_new()
assert os.path.isfile("project.tar.gz.dump")
os.remove("project.tar.gz.dump")
|
Fix typo in Bing images. | from aiohttp import BasicAuth
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image"
api_key = config.create("bing", "key",
fallback="unset",
comment="An API key from Bing")
@commands.register("image", "images", "i", category="Search")
@rate_limit()
async def image(message):
"""
Search Bing for an image.
"""
q = message.content.strip()
if not q:
raise CommandError("Search term required!")
r = await http.get(SEARCH_URL, params=[
('$format', 'json'),
('$top', '10'),
('Query', "'{}'".format(q)),
], auth=BasicAuth("", password=api_key()))
data = r.json()['d']
if len(data['results']):
return Response(data['results'][0]['MediaUrl'])
else:
raise CommandError("no results found")
| from aiohttp import BasicAuth
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image"
api_key = config.create("bing", "key",
fallback="unset",
comment="An API key from Bing")
@commands.register("image", "images", ""i", category="Search")
@rate_limit()
async def image(message):
"""
Search Bing for an image.
"""
q = message.content.strip()
if not q:
raise CommandError("Search term required!")
r = await http.get(SEARCH_URL, params=[
('$format', 'json'),
('$top', '10'),
('Query', "'{}'".format(q)),
], auth=BasicAuth("", password=api_key()))
data = r.json()['d']
if len(data['results']):
return Response(data['results'][0]['MediaUrl'])
else:
raise CommandError("no results found")
|
Add test for calculating sum of ages
Signed-off-by: Dieter Scholz <2d66d24b3b7ab25e74eac42fe6f751014f0cf625@code2bytes.org> | package org.code2bytes.samples.lambda;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class PersonListTest {
private List<Person> persons;
@Before
public void setUp() throws Exception {
persons = new ArrayList<>();
persons.add(new Person("Test Person 1", 20));
persons.add(new Person("Test Person 2", 21));
persons.add(new Person("Test Person 3", 22));
persons.add(new Person("Test Person 4", 23));
}
@Test
public void testArraySize() {
assertThat("array contains 4 elements", 4, equalTo(4));
}
@Test
public void testSum() {
Integer total = persons.parallelStream().map(p -> p.getAgeInYears())
.reduce((sum, p) -> sum + p).get();
assertThat("sum should be 86", 86, equalTo(total));
}
}
| package org.code2bytes.samples.lambda;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class PersonListTest {
private List<Person> persons;
@Before
public void setUp() throws Exception {
persons = new ArrayList<>();
persons.add(new Person("Test Person 1", 20));
persons.add(new Person("Test Person 2", 21));
persons.add(new Person("Test Person 3", 22));
persons.add(new Person("Test Person 4", 23));
}
@Test
public void testArraySize() {
assertEquals("Array should contain 4 elements", 4, persons.size());
}
@Test
public void testForEach() {
persons.forEach(p -> System.out.println(p.getAgeInYears()));
}
}
|
Use ModuleNotFoundError instead of ImportError | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from server.tsuserver import TsuServer3
# Idiotproof setup
def check_pyyaml():
try:
import yaml
except ModuleNotFoundError:
print("Couldn't import PyYAML. Installing it for you...")
import pip
pip.main(["install", "--user", "pyyaml"])
def main():
server = TsuServer3()
server.start()
if __name__ == '__main__':
check_pyyaml()
main()
| #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from server.tsuserver import TsuServer3
# Idiotproof setup
def check_pyyaml():
try:
import yaml
except ImportError:
print("Couldn't import PyYAML. Installing it for you...")
import pip
pip.main(["install", "--user", "pyyaml"])
def main():
server = TsuServer3()
server.start()
if __name__ == '__main__':
check_pyyaml()
main()
|
Add support for fixed values in hidden form element | <?php
namespace Opf\Form\Elements;
use Opf\Form\ElementAbstract;
use Opf\Form\ElementInterface;
class Hidden extends ElementAbstract implements ElementInterface
{
public function __construct($name, $value)
{
$this->name = $name;
$this->value = $value;
}
public function __toString()
{
$error = '';
if (count($this->errors) > 0) {
$error = '<p class="help-block">' . implode('<br/>', $this->errors) . '</p>';
}
$html = '<input type="hidden" name="%s" value="%s">';
return sprintf(
$html,
$this->name,
$this->value
);
}
} | <?php
namespace Opf\Form\Elements;
use Opf\Form\ElementAbstract;
use Opf\Form\ElementInterface;
class Hidden extends ElementAbstract implements ElementInterface
{
public function __construct($name)
{
$this->name = $name;
}
public function __toString()
{
$error = '';
if (count($this->errors) > 0) {
$error = '<p class="help-block">' . implode('<br/>', $this->errors) . '</p>';
}
$html = '<input type="hidden" name="%s" value="%s">';
return sprintf(
$html,
$this->name,
$this->value
);
}
} |
fix: Update options key to match updated package | let banner = require('add-banner');
let fs = require('fs');
let path = require('path');
const buildFolder = './build/';
function appendBanner(directory) {
let files = fs.readdirSync(directory);
for (let i = 0; i < files.length; ++i) {
let stat = fs.statSync(directory + files[i]);
if (stat.isDirectory()) {
const subDirectory = directory + files[i] + '/';
appendBanner(subDirectory);
} else if (path.extname(files[i]) === '.js') {
const options = {
template: './tasks/banner.tmpl',
filename: files[i]
};
const newFile = banner(directory + files[i], options);
fs.writeFileSync(directory + files[i], newFile);
console.log('\t' + files[i]);
} else {
console.log('\tIgnoring ' + files[i]);
}
}
}
let files = fs.readdirSync(buildFolder);
console.log('Adding banners to files: ');
appendBanner(buildFolder, files);
| let banner = require('add-banner');
let fs = require('fs');
let path = require('path');
const buildFolder = './build/';
function appendBanner(directory) {
let files = fs.readdirSync(directory);
for (let i = 0; i < files.length; ++i) {
let stat = fs.statSync(directory + files[i]);
if (stat.isDirectory()) {
let subDirectory = directory + files[i] + '/';
appendBanner(subDirectory);
} else if (path.extname(files[i]) === '.js') {
let options = {
banner: './tasks/banner.tmpl',
filename: files[i]
};
let newFile = banner(directory + files[i], options);
fs.writeFileSync(directory + files[i], newFile);
console.log('\t' + files[i]);
} else {
console.log('\tIgnoring ' + files[i]);
}
}
}
let files = fs.readdirSync(buildFolder);
console.log('Adding banners to files: ');
appendBanner(buildFolder, files);
|
Fix char test to only run on test/none.
Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d
Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326
Tested-by: jenkins
Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com> | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
def setup_method(self, method):
self.__cleanup_char_tables()
self.__create_char_tables()
def teardown_method(self, method):
self.__cleanup_char_tables()
def __cleanup_char_tables(self):
self.client.execute('drop table if exists functional.test_char_tmp');
self.client.execute('drop table if exists functional.test_varchar_tmp');
def __create_char_tables(self):
self.client.execute(
'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
self.client.execute(
'create table if not exists functional.test_char_tmp (c char(5))')
@classmethod
def add_test_dimensions(cls):
super(TestStringQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
create_exec_option_dimension(disable_codegen_options=[True]))
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format in ['text'] and
v.get_value('table_format').compression_codec in ['none'])
def test_varchar(self, vector):
self.run_test_case('QueryTest/chars', vector)
| #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
def setup_method(self, method):
self.__cleanup_char_tables()
self.__create_char_tables()
def teardown_method(self, method):
self.__cleanup_char_tables()
def __cleanup_char_tables(self):
self.client.execute('drop table if exists functional.test_char_tmp');
self.client.execute('drop table if exists functional.test_varchar_tmp');
def __create_char_tables(self):
self.client.execute(
'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
self.client.execute(
'create table if not exists functional.test_char_tmp (c char(5))')
@classmethod
def add_test_dimensions(cls):
super(TestStringQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
create_exec_option_dimension(disable_codegen_options=[True]))
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format in ['text'])
def test_varchar(self, vector):
self.run_test_case('QueryTest/chars', vector)
|
Use []byte as 1st arg of NewRSASHASigner()
* Use []byte as first arg of NewRSASHASigner()
* Add NewRSASHASignerFromPEM() to new a signer from private PEM file | package jwthelper
import (
"github.com/dgrijalva/jwt-go"
)
type Signer struct {
Method jwt.SigningMethod
key interface{}
}
type SignerOption struct {
f func(s *Signer)
}
func SignerMethod(m jwt.SigningMethod) SignerOption {
return SignerOption{func(s *Signer) {
s.Method = m
}}
}
func NewRSASHASigner(signKey []byte, options ...SignerOption) *Signer {
s := &Signer{
// Default signing method: RSASHA-256.
Method: jwt.SigningMethodRS256,
}
// Override customized options.
for _, op := range options {
op.f(s)
}
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(signKey)
if err != nil {
return &Signer{}
}
s.key = privateKey
return s
}
func NewRSASHASignerFromPEM(privatePEM string, options ...SignerOption) *Signer {
buf, err := ReadKey(privatePEM)
if err != nil {
return &Signer{}
}
return NewRSASHASigner(buf, options...)
}
func (s *Signer) SignedString(claims jwt.Claims) (string, error) {
token := jwt.NewWithClaims(s.Method, claims)
return token.SignedString(s.key)
}
| package jwthelper
import (
"github.com/dgrijalva/jwt-go"
)
type Signer struct {
Method jwt.SigningMethod
key interface{}
}
type SignerOption struct {
f func(s *Signer)
}
func SignerMethod(m jwt.SigningMethod) SignerOption {
return SignerOption{func(s *Signer) {
s.Method = m
}}
}
func NewRSASHASigner(privatePEM string, options ...SignerOption) *Signer {
s := &Signer{
// Default signing method: RSASHA-256.
Method: jwt.SigningMethodRS256,
}
// Override customized options.
for _, op := range options {
op.f(s)
}
buf, err := ReadKey(privatePEM)
if err != nil {
return &Signer{}
}
if s.key, err = jwt.ParseRSAPrivateKeyFromPEM(buf); err != nil {
return &Signer{}
}
return s
}
func (s *Signer) SignedString(claims jwt.Claims) (string, error) {
token := jwt.NewWithClaims(s.Method, claims)
return token.SignedString(s.key)
}
|
Address review comment: Add link to upstream ticket. | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.test -*-
"""
Flocker is a hypervisor that provides ZFS-based replication and fail-over
functionality to a Linux-based user-space operating system.
"""
import sys
import os
def _logEliotMessage(data):
"""
Route a serialized Eliot log message to the Twisted log.
:param data: ``bytes``, a serialized message.
"""
from twisted.python.log import msg
from json import loads
msg("ELIOT: " + data)
if "eliot:traceback" in data:
# Don't bother decoding every single log message...
decoded = loads(data)
if decoded.get(u"message_type") == u"eliot:traceback":
msg("ELIOT Extracted Traceback:\n" + decoded["traceback"])
# Ugly but convenient. There should be some better way to do this...
# See https://twistedmatrix.com/trac/ticket/6939
if sys.argv and os.path.basename(sys.argv[0]) == 'trial':
from eliot import addDestination
addDestination(_logEliotMessage)
del addDestination
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.test -*-
"""
Flocker is a hypervisor that provides ZFS-based replication and fail-over
functionality to a Linux-based user-space operating system.
"""
import sys
import os
def _logEliotMessage(data):
"""
Route a serialized Eliot log message to the Twisted log.
:param data: ``bytes``, a serialized message.
"""
from twisted.python.log import msg
from json import loads
msg("ELIOT: " + data)
if "eliot:traceback" in data:
# Don't bother decoding every single log message...
decoded = loads(data)
if decoded.get(u"message_type") == u"eliot:traceback":
msg("ELIOT Extracted Traceback:\n" + decoded["traceback"])
# Ugly but convenient. There should be some better way to do this...
if sys.argv and os.path.basename(sys.argv[0]) == 'trial':
from eliot import addDestination
addDestination(_logEliotMessage)
del addDestination
|
Add another button in CrudFrame now adds below the current category
item. | package com.clementscode.mmi.swing;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JPanel;
public class ActionForCategoryItemGui extends AbstractAction {
private static final long serialVersionUID = 1L;
private String cmd;
private GuiForCategoryItem guiForCategoryItem;
public ActionForCategoryItemGui(String cmd,
GuiForCategoryItem guiForCategoryItem, String text) {
super(text);
this.cmd = cmd;
this.guiForCategoryItem = guiForCategoryItem;
}
public void actionPerformed(ActionEvent e) {
CrudFrame crudFrame = guiForCategoryItem.getCrudFrame();
JPanel diyTable = crudFrame.getDiyTable();
if (CrudFrame.ADD_CATEGORY_ITEM.equals(cmd)) {
GuiForCategoryItem g4ci = new GuiForCategoryItem(crudFrame);
crudFrame.getLstGuiForCategoryItems().add(g4ci);
int oneBellow = 0;
int numComponents = diyTable.getComponentCount();
for (int n = 0; n < numComponents; ++n) {
Component comp = diyTable.getComponent(n);
if (comp.equals(guiForCategoryItem)) {
oneBellow = n + 1;
break;
}
}
crudFrame.getDiyTable().add(g4ci, oneBellow);
} else if (CrudFrame.DELETE_CATEGORY_ITEM.equals(cmd)) {
diyTable.remove(guiForCategoryItem);
}
crudFrame.refreshGui();
}
}
| package com.clementscode.mmi.swing;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JPanel;
public class ActionForCategoryItemGui extends AbstractAction {
private static final long serialVersionUID = 1L;
private String cmd;
private GuiForCategoryItem guiForCategoryItem;
public ActionForCategoryItemGui(String cmd,
GuiForCategoryItem guiForCategoryItem, String text) {
super(text);
this.cmd = cmd;
this.guiForCategoryItem = guiForCategoryItem;
}
public void actionPerformed(ActionEvent e) {
CrudFrame crudFrame = guiForCategoryItem.getCrudFrame();
if (CrudFrame.ADD_CATEGORY_ITEM.equals(cmd)) {
GuiForCategoryItem g4ci = new GuiForCategoryItem(crudFrame);
crudFrame.getLstGuiForCategoryItems().add(g4ci);
crudFrame.getDiyTable().add(g4ci);
} else if (CrudFrame.DELETE_CATEGORY_ITEM.equals(cmd)) {
JPanel diyTable = crudFrame.getDiyTable();
diyTable.remove(guiForCategoryItem);
}
crudFrame.refreshGui();
}
}
|
:new: Set process title to ucompiler | #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
const UCompiler = require('..')
const knownCommands = ['go', 'watch']
const parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
console.error(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1])
}
| #!/usr/bin/env node
'use strict'
require('debug').enable('UCompiler:*')
const UCompiler = require('..')
const knownCommands = ['go', 'watch']
const parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
console.error(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1])
}
|
Check if fullscreen is already enabled on mount | var screenfull = require('screenfull');
var FullscreenMixin = {
getInitialState: function() {
return {
hasFullscreen: false
};
},
componentDidMount: function () {
var enabled = screenfull.enabled;
if (enabled) {
document.addEventListener(screenfull.raw.fullscreenchange, this.onChangeFullscreen);
this.setState({
hasFullscreen: enabled,
isFullscreen: screenfull.isFullscreen,
fullScreenElement: screenfull.element
});
}
},
requestFullscreen: function (ref) {
if (ref && ref.getDOMNode) {
var elem = ref.getDOMNode();
screenfull.request(elem);
} else {
screenfull.request();
}
},
exitFullscreen: function () {
screenfull.exit();
},
onChangeFullscreen: function (e) {
var isFullscreen = screenfull.isFullscreen;
this.setState({
isFullscreen: isFullscreen,
fullScreenElement: screenfull.element
});
if (isFullscreen) {
typeof this.onEnterFullscreen === 'function' && this.onEnterFullscreen(e);
} else {
typeof this.onExitFullscreen === 'function' && this.onExitFullscreen(e);
}
}
};
module.exports = FullscreenMixin;
| var screenfull = require('screenfull');
var FullscreenMixin = {
getInitialState: function() {
return {
hasFullscreen: false
};
},
componentDidMount: function () {
var enabled = screenfull.enabled;
if (enabled) {
document.addEventListener(screenfull.raw.fullscreenchange, this.onChangeFullscreen);
this.setState({
hasFullscreen: enabled
});
}
},
requestFullscreen: function (ref) {
if (ref && ref.getDOMNode) {
var elem = ref.getDOMNode();
screenfull.request(elem);
} else {
screenfull.request();
}
},
exitFullscreen: function () {
screenfull.exit();
},
onChangeFullscreen: function (e) {
var isFullscreen = screenfull.isFullscreen;
this.setState({
isFullscreen: isFullscreen,
fullScreenElement: screenfull.element
});
if (isFullscreen) {
typeof this.onEnterFullscreen === 'function' && this.onEnterFullscreen(e);
} else {
typeof this.onExitFullscreen === 'function' && this.onExitFullscreen(e);
}
}
};
module.exports = FullscreenMixin;
|
Update copy for toggle feature notification | import $ from 'jquery';
export default class ToggleFeatureNotifier {
constructor({chromeWrapper}) {
this._chromeWrapper = chromeWrapper;
this.notify = this.notify.bind(this);
}
notify() {
const optionsUrl = this._chromeWrapper.getURL('src/options/index.html');
prependElementAsChildOf('#tracker', `
<div class="ui message">
<i class="close icon"></i>
<div class="header">
WWLTW Extension Update
</div>
<p>The WWLTW chrome extension is now disabled by default for all backlogs. You can enable it for any of your backlogs from
the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p>
</div>
`);
$('.message .close').on('click', function () {
$(this)
.closest('.message')
.transition('fade')
;
});
}
}
const prependElementAsChildOf = function (parent, html) {
let elementContainer = document.createElement('div');
elementContainer.innerHTML = html;
$(parent).prepend(elementContainer);
}; | import $ from 'jquery';
export default class ToggleFeatureNotifier {
constructor({chromeWrapper}) {
this._chromeWrapper = chromeWrapper;
this.notify = this.notify.bind(this);
}
notify() {
const optionsUrl = this._chromeWrapper.getURL('src/options/index.html');
prependElementAsChildOf('#tracker', `
<div class="ui message">
<i class="close icon"></i>
<div class="header">
WWLTW Extension Update
</div>
<p>You can enable and disable the WWLTW chrome extension for individual backlogs from
the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p>
</div>
`);
$('.message .close').on('click', function () {
$(this)
.closest('.message')
.transition('fade')
;
});
}
}
const prependElementAsChildOf = function (parent, html) {
let elementContainer = document.createElement('div');
elementContainer.innerHTML = html;
$(parent).prepend(elementContainer);
}; |
Add transforming function to pref_encodings | from math import floor
from collections import Counter
def floored_percentage(val, digits):
"""
Return string of floored value with given digits after period
:param val:
:param digits:
:return:
"""
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
def pref_encoding(data, encoding_transform=None):
"""
Return string with unique words in list with percentage of they frequency
:param data:
:param encoding_transform:
:return str:
"""
encoding_counted = Counter(data)
total = sum(encoding_counted.values())
sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)
return ' / '.join(
["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])
def make_total_row(source, agg):
"""
Execute agg column based function for source columns. For example if you need `total` in table data:
Examples:
src = [[1,1],[1,2],[1,3]]
print(make_total_row(src, [sum, min]))
>>> [3, 1]
:param source:
:param agg:
:return:
"""
return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
| from math import floor
from collections import Counter
def floored_percentage(val, digits):
"""
Return string of floored value with given digits after period
:param val:
:param digits:
:return:
"""
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
def pref_encoding(data):
"""
Return string with unique words in list with percentage of they frequency
:param data:
:return str:
"""
encoding_counted = Counter(data)
total = sum(encoding_counted.values())
sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)
return ' / '.join(
["{:<1} [{:<4}]".format(k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])
def make_total_row(source, agg):
"""
Execute agg column based function for source columns. For example if you need `total` in table data:
Examples:
src = [[1,1],[1,2],[1,3]]
print(make_total_row(src, [sum, min]))
>>> [3, 1]
:param source:
:param agg:
:return:
"""
return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
|
Fix GitHub strategy missing email
Fixes an issue with an empty/missing/null Email coming from GitHub's
OAuth call response. | 'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
GithubStrategy = require('passport-github').Strategy,
users = require('../../controllers/users.server.controller');
module.exports = function(config) {
// Use github strategy
passport.use(new GithubStrategy({
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.github.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
// Set the provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
var providerUserProfile = {
displayName: profile.displayName || profile.username,
email: (profile.emails && profile.emails.length) ? profile.emails[0].value : undefined,
username: profile.username,
provider: 'github',
providerIdentifierField: 'id',
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}));
};
| 'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
GithubStrategy = require('passport-github').Strategy,
users = require('../../controllers/users.server.controller');
module.exports = function(config) {
// Use github strategy
passport.use(new GithubStrategy({
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.github.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
// Set the provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
var providerUserProfile = {
displayName: profile.displayName || profile.username,
email: profile.emails[0].value,
username: profile.username,
provider: 'github',
providerIdentifierField: 'id',
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}));
};
|
Use variable instead of static 3000 port | var theme = require('./lib/theme');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var minify = require('express-minify');
var compress = require('compression');
var port = 3000;
app.disable('x-powered-by');
app.use(compress());
app.use(minify(
{
cache: __dirname + '/cache'
}));
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*')
next();
});
app.use(bodyParser.json())
app.use(cors());
app.use("/themes.json", express.static('themes.json'));
app.get('/:theme', theme);
app.post('/:theme', theme);
app.get('/theme/:theme', theme);
app.post('/theme/:theme', theme);
app.listen(port);
console.log("Starting theme-manager..");
console.log('Server is now running at http://localhost:' + port + '/');
| var theme = require('./lib/theme');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var minify = require('express-minify');
var compress = require('compression');
app.disable('x-powered-by');
app.use(compress());
app.use(minify(
{
cache: __dirname + '/cache'
}));
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*')
next();
});
app.use(bodyParser.json())
app.use(cors());
app.use("/themes.json", express.static('themes.json'));
app.get('/:theme', theme);
app.post('/:theme', theme);
app.get('/theme/:theme', theme);
app.post('/theme/:theme', theme);
app.listen(3000);
console.log("Starting theme-manager..");
console.log('Server is now running at http://localhost:3000/');
|
Add shebang for Python to sample script | #!/usr/bin/env python
import subprocess
import urllib
def main():
api_url = 'https://uw-alert.herokuapp.com/check_availability'
courses = [{'level': 'under',
'session': 1151,
'subject': 'CS',
'number': 341,
'email': 'youremail@example.com'}]
for course in courses:
encoded_query = urllib.urlencode(course)
subprocess.call(['curl', '-X', 'POST', '-H', 'Cache-Control: no-cache', '-H', 'Content-Type: application/x-www-form-urlencoded', '-d', encoded_query, api_url])
if __name__ == '__main__':
main()
| import subprocess
import urllib
def main():
api_url = 'https://uw-alert.herokuapp.com/check_availability'
courses = [{'level': 'under',
'session': 1151,
'subject': 'CS',
'number': 341,
'email': 'youremail@example.com'}]
for course in courses:
encoded_query = urllib.urlencode(course)
subprocess.call(['curl', '-X', 'POST', '-H', 'Cache-Control: no-cache', '-H', 'Content-Type: application/x-www-form-urlencoded', '-d', encoded_query, api_url])
if __name__ == '__main__':
main()
|
BAP-12009: Create command oro:debug:condition
- remove not used import | <?php
namespace Oro\Bundle\ActionBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
class DebugConditionCommand extends AbstractDebugCommand
{
const ARGUMENT_NAME = 'condition-name';
const COMMAND_NAME = 'oro:debug:condition';
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName(self::COMMAND_NAME)
->setDescription('Displays current "conditions" for an application')
->addArgument(self::ARGUMENT_NAME, InputArgument::OPTIONAL, 'A condition name')
->setHelp(<<<EOF
The <info>%command.name%</info> displays list of all conditions with full description:
<info>php %command.full_name%</info>
EOF
);
}
/**
* {@inheritdoc}
*/
protected function getFactoryServiceId()
{
return 'oro_action.expression.factory';
}
/**
* {@inheritdoc}
*/
protected function getArgumentName()
{
return self::ARGUMENT_NAME;
}
}
| <?php
namespace Oro\Bundle\ActionBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Oro\Component\ConfigExpression\ExpressionFactory;
class DebugConditionCommand extends AbstractDebugCommand
{
const ARGUMENT_NAME = 'condition-name';
const COMMAND_NAME = 'oro:debug:condition';
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName(self::COMMAND_NAME)
->setDescription('Displays current "conditions" for an application')
->addArgument(self::ARGUMENT_NAME, InputArgument::OPTIONAL, 'A condition name')
->setHelp(<<<EOF
The <info>%command.name%</info> displays list of all conditions with full description:
<info>php %command.full_name%</info>
EOF
);
}
/**
* {@inheritdoc}
*/
protected function getFactoryServiceId()
{
return 'oro_action.expression.factory';
}
/**
* {@inheritdoc}
*/
protected function getArgumentName()
{
return self::ARGUMENT_NAME;
}
}
|
Delete a private method from interface | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import abc
import six
from .acceptor import LoaderAcceptor
from .error import InvalidDataError
@six.add_metaclass(abc.ABCMeta)
class TableFormatterInterface(object):
"""
Abstract class of table data validator.
"""
@abc.abstractmethod
def to_table_data(self): # pragma: no cover
pass
class TableFormatter(LoaderAcceptor, TableFormatterInterface):
"""
Abstract class of |TableData| formatter.
"""
def _validate_source_data(self):
if len(self._source_data) == 0:
raise InvalidDataError("souce data is empty")
def __init__(self, source_data):
self._source_data = source_data
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import abc
import six
from .acceptor import LoaderAcceptor
from .error import InvalidDataError
@six.add_metaclass(abc.ABCMeta)
class TableFormatterInterface(object):
"""
Abstract class of table data validator.
"""
@abc.abstractmethod
def to_table_data(self): # pragma: no cover
pass
@abc.abstractmethod
def _validate_source_data(self): # pragma: no cover
pass
class TableFormatter(LoaderAcceptor, TableFormatterInterface):
"""
Abstract class of |TableData| formatter.
"""
def _validate_source_data(self):
if len(self._source_data) == 0:
raise InvalidDataError("souce data is empty")
def __init__(self, source_data):
self._source_data = source_data
|
Break build on Sass error | const sass = require('gulp-sass');
const gulpif = require('gulp-if');
const autoprefixer = require('gulp-autoprefixer');
const preprocess = require('gulp-preprocess');
const sourcemaps = require('gulp-sourcemaps');
const config = require('../../../config/config');
const paths = require('../../paths');
const isProduction = config.env === 'production';
// add extra sass paths
const SASS_PATHS = [
`${paths.nodeModules}`,
];
function handleError(error) {
sass.logError.call(this, error);
process.exit(1);
}
module.exports = (gulp) => {
return gulp.src(`${paths.sourceStyles}/**/*.scss`)
.pipe(gulpif(!isProduction, sourcemaps.init()))
.pipe(sass({
includePaths: SASS_PATHS,
outputStyle: isProduction ? 'compressed' : 'expanded',
}).on('error', handleError))
.pipe(autoprefixer({
browsers: ['> 0%', 'IE 8'],
}))
.pipe(preprocess({
context: {
FONT_CDN_PATH: config.fontCdn,
},
}))
.pipe(gulpif(!isProduction, sourcemaps.write('.')))
.pipe(gulp.dest(`${paths.outputStyles}`));
};
| const sass = require('gulp-sass');
const gulpif = require('gulp-if');
const autoprefixer = require('gulp-autoprefixer');
const preprocess = require('gulp-preprocess');
const sourcemaps = require('gulp-sourcemaps');
const config = require('../../../config/config');
const paths = require('../../paths');
const isProduction = config.env === 'production';
// add extra sass paths
const SASS_PATHS = [
`${paths.nodeModules}`,
];
module.exports = (gulp) => {
return gulp.src(`${paths.sourceStyles}/**/*.scss`)
.pipe(gulpif(!isProduction, sourcemaps.init()))
.pipe(sass({
includePaths: SASS_PATHS,
outputStyle: isProduction ? 'compressed' : 'expanded',
}).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['> 0%', 'IE 8'],
}))
.pipe(preprocess({
context: {
FONT_CDN_PATH: config.fontCdn,
},
}))
.pipe(gulpif(!isProduction, sourcemaps.write('.')))
.pipe(gulp.dest(`${paths.outputStyles}`));
};
|
Use UTF-8 while write testcases json | package ru.yandex.qatools.allure.data.utils;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import ru.yandex.qatools.allure.data.ReportGenerationException;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* @author Dmitry Baev charlie@yandex-team.ru
* Date: 31.10.13
*/
public final class AllureReportUtils {
private AllureReportUtils() {
}
public static void serialize(final File directory, String name, Object obj) {
try {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector annotatoinInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
mapper.getSerializationConfig().with(annotatoinInspector);
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(new File(directory, name)), StandardCharsets.UTF_8);
mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj);
} catch (IOException e) {
throw new ReportGenerationException(e);
}
}
}
| package ru.yandex.qatools.allure.data.utils;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import ru.yandex.qatools.allure.data.ReportGenerationException;
import java.io.*;
/**
* @author Dmitry Baev charlie@yandex-team.ru
* Date: 31.10.13
*/
public final class AllureReportUtils {
private AllureReportUtils() {
}
public static void serialize(final File directory, String name, Object obj) {
try {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector ai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
mapper.getSerializationConfig().with(ai);
mapper.writerWithDefaultPrettyPrinter().writeValue(new File(directory, name), obj);
} catch (IOException e) {
throw new ReportGenerationException(e);
}
}
}
|
Fix unicode fail in search indexing. | import datetime
import os
import codecs
from haystack.indexes import *
from haystack import site
from projects.models import File, ImportedFile
from projects import constants
class FileIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='project__user')
project = CharField(model_attr='project__name')
title = CharField(model_attr='heading')
def get_queryset(self):
return File.objects.filter(project__status=constants.LIVE_STATUS)
class ImportedFileIndex(SearchIndex):
text = CharField(document=True)
author = CharField(model_attr='project__user')
project = CharField(model_attr='project__name')
title = CharField(model_attr='name')
def prepare_text(self, obj):
full_path = obj.project.full_html_path
to_read = os.path.join(full_path, obj.path.lstrip('/'))
content = codecs.open(to_read, encoding="utf-8", mode='r').read()
return content
site.register(File, FileIndex)
site.register(ImportedFile, ImportedFileIndex)
| import datetime
import os
from haystack.indexes import *
from haystack import site
from projects.models import File, ImportedFile
from projects import constants
class FileIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='project__user')
project = CharField(model_attr='project__name')
title = CharField(model_attr='heading')
def get_queryset(self):
return File.objects.filter(project__status=constants.LIVE_STATUS)
class ImportedFileIndex(SearchIndex):
text = CharField(document=True)
author = CharField(model_attr='project__user')
project = CharField(model_attr='project__name')
title = CharField(model_attr='name')
def prepare_text(self, obj):
full_path = obj.project.full_html_path
to_read = os.path.join(full_path, obj.path.lstrip('/'))
content = open(to_read, 'r').read()
return content
site.register(File, FileIndex)
site.register(ImportedFile, ImportedFileIndex)
|
Make the spacebar usable for inline edit | /*!
* Copyright 2012 Sakai Foundation (SF) Licensed under the
* Educational Community 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.osedu.org/licenses/ECL-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.
*/
define(['jquery'], function (jQuery) {
(function() {
/**
* Catch the keypress event for `enter` and `space` when an editable field has focus
*/
$(document).on('focus', '.jeditable-field', function(ev) {
$(this).keypress(function(ev) {
if (ev.which == 13 || ev.which == 32){
ev.preventDefault();
$(this).trigger('click.editable');
}
});
});
})();
});
| /*!
* Copyright 2012 Sakai Foundation (SF) Licensed under the
* Educational Community 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.osedu.org/licenses/ECL-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.
*/
define(['jquery'], function (jQuery) {
(function() {
/**
* Catch the keypress event for `enter` when an editable field has focus
*/
$(document).on('focus', '.jeditable-field', function(ev) {
$(this).keypress(function(ev) {
if (ev.which == 13){
$(this).trigger('click.editable');
}
});
});
})();
});
|
Increase timeout for timeout job | package jobs
import (
"fmt"
"time"
)
// WorkersList is a map associating a worker type with its acutal
// configuration.
type WorkersList map[string]*WorkerConfig
// WorkersList is the list of available workers with their associated Do
// function.
var workersList WorkersList
func init() {
workersList = WorkersList{
"print": {
Concurrency: 4,
WorkerFunc: func(m *Message, _ <-chan time.Time) error {
var msg string
if err := m.Unmarshal(&msg); err != nil {
return err
}
_, err := fmt.Println(msg)
return err
},
},
"timeout": {
Concurrency: 4,
Timeout: 10 * time.Second,
WorkerFunc: func(_ *Message, timeout <-chan time.Time) error {
<-timeout
return ErrTimedOut
},
},
}
}
// GetWorkersList returns a globally defined worker config list
func GetWorkersList() WorkersList {
return workersList
}
| package jobs
import (
"fmt"
"time"
)
// WorkersList is a map associating a worker type with its acutal
// configuration.
type WorkersList map[string]*WorkerConfig
// WorkersList is the list of available workers with their associated Do
// function.
var workersList WorkersList
func init() {
workersList = WorkersList{
"print": {
Concurrency: 4,
WorkerFunc: func(m *Message, _ <-chan time.Time) error {
var msg string
if err := m.Unmarshal(&msg); err != nil {
return err
}
_, err := fmt.Println(msg)
return err
},
},
"timeout": {
Concurrency: 4,
Timeout: 1 * time.Second,
WorkerFunc: func(_ *Message, timeout <-chan time.Time) error {
<-timeout
return ErrTimedOut
},
},
}
}
// GetWorkersList returns a globally defined worker config list
func GetWorkersList() WorkersList {
return workersList
}
|
Use Java 8 constructs for unwrap | /*
* Copyright Terracotta, 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 org.ehcache.jsr107;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
/**
* @author teck
*/
final class Unwrap {
static <T> T unwrap(Class<T> clazz, Object... obj) {
requireNonNull(clazz);
return stream(obj).filter(clazz::isInstance).map(clazz::cast).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Cannot unwrap to " + clazz));
}
private Unwrap() {
//
}
}
| /*
* Copyright Terracotta, 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 org.ehcache.jsr107;
/**
* @author teck
*/
final class Unwrap {
static <T> T unwrap(Class<T> clazz, Object... obj) {
if (clazz == null || obj == null) {
throw new NullPointerException();
}
for (Object o : obj) {
if (o != null && clazz.isAssignableFrom(o.getClass())) {
return clazz.cast(o);
}
}
throw new IllegalArgumentException("Cannot unwrap to " + clazz);
}
private Unwrap() {
//
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.