text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Remove a console log statement, so tests run without extraneous logging | define (["lib/lodash", "lib/Handlebars", "src/skinner/core/keypath"], function (_, Handlebars, keyPath) {
"use strict";
function resolveData(data, subject, additionalDimensionData, context) {
var allContext = keyPath(subject, "condition", {});
if (!_.isUndefined(additionalDimensionData)) {
allContext = _.extend({}, allContext, additionalDimensionData);
}
Handlebars.registerHelper("indexed", function (key) {
return key[context];
});
function mapper(value) {
if (_.isArray(value) || _.isObject(value)) {
return resolveData(value, subject, additionalDimensionData, context);
}
else if (_.isString(value)) {
var template = Handlebars.compile(value);
return template(allContext);
}
else {
return value;
}
}
if (_.isArray(data)) {
return _.map(data, mapper);
}
else {
return _.mapValues(data, mapper);
}
}
return {
"resolveData": resolveData
};
});
| define (["lib/lodash", "lib/Handlebars", "src/skinner/core/keypath"], function (_, Handlebars, keyPath) {
"use strict";
function resolveData(data, subject, additionalDimensionData, context) {
var allContext = keyPath(subject, "condition", {});
if (!_.isUndefined(additionalDimensionData)) {
allContext = _.extend({}, allContext, additionalDimensionData);
}
Handlebars.registerHelper("indexed", function (key) {
return key[context];
});
function mapper(value) {
console.log(value);
if (_.isArray(value) || _.isObject(value)) {
return resolveData(value, subject, additionalDimensionData, context);
}
else if (_.isString(value)) {
var template = Handlebars.compile(value);
return template(allContext);
}
else {
return value;
}
}
if (_.isArray(data)) {
return _.map(data, mapper);
}
else {
return _.mapValues(data, mapper);
}
}
return {
"resolveData": resolveData
};
});
|
Add keyup to event list to fix IE so it updates height properly when deleting text. | (function($){
$.fn.textareaAutoExpand = function(){
return this.each(function(){
var textarea = $(this);
var height = textarea.height();
var diff = parseInt(textarea.css('borderBottomWidth')) + parseInt(textarea.css('borderTopWidth')) +
parseInt(textarea.css('paddingBottom')) + parseInt(textarea.css('paddingTop'));
var hasInitialValue = (this.value.replace(/\s/g, '').length > 0);
if (textarea.css('box-sizing') === 'border-box' ||
textarea.css('-moz-box-sizing') === 'border-box' ||
textarea.css('-webkit-box-sizing') === 'border-box') {
height = textarea.outerHeight();
if (this.scrollHeight + diff == height) // special case for Firefox where scrollHeight isn't full height on border-box
diff = 0;
} else {
diff = 0;
}
if (hasInitialValue) {
textarea.height(this.scrollHeight);
}
textarea.on('scroll input keyup', function(event){ // keyup isn't necessary but when deleting text IE needs it to reset height properly
if (event.keyCode == 13 && !event.shiftKey) {
// just allow default behavior to enter new line
if (this.value.replace(/\s/g, '').length == 0) {
event.stopImmediatePropagation();
event.stopPropagation();
}
}
textarea.height(0);
//textarea.height(Math.max(height - diff, this.scrollHeight - diff));
textarea.height(this.scrollHeight - diff);
});
});
}
})(jQuery);
| (function($){
$.fn.textareaAutoExpand = function(){
return this.each(function(){
var textarea = $(this);
var height = textarea.height();
var diff = parseInt(textarea.css('borderBottomWidth')) + parseInt(textarea.css('borderTopWidth')) +
parseInt(textarea.css('paddingBottom')) + parseInt(textarea.css('paddingTop'));
var hasInitialValue = (this.value.replace(/\s/g, '').length > 0);
if (textarea.css('box-sizing') === 'border-box' ||
textarea.css('-moz-box-sizing') === 'border-box' ||
textarea.css('-webkit-box-sizing') === 'border-box') {
height = textarea.outerHeight();
if (this.scrollHeight + diff == height) // special case for Firefox where scrollHeight isn't full height on border-box
diff = 0;
} else {
diff = 0;
}
if (hasInitialValue) {
textarea.height(this.scrollHeight);
}
textarea.on('scroll input', function(event){
if (event.keyCode == 13 && !event.shiftKey) {
// just allow default behavior to enter new line
if (this.value.replace(/\s/g, '').length == 0) {
event.stopImmediatePropagation();
event.stopPropagation();
}
}
textarea.height(0);
//textarea.height(Math.max(height - diff, this.scrollHeight - diff));
textarea.height(this.scrollHeight - diff);
});
});
}
})(jQuery);
|
Add pytz as a test requirement | from distutils.core import setup
import skyfield # safe, because __init__.py contains no import statements
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst', 'rb').read().decode('utf-8'),
license='MIT',
author='Brandon Rhodes',
author_email='[email protected]',
url='http://github.com/brandon-rhodes/python-skyfield/',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Astronomy',
],
packages=[
'skyfield',
'skyfield.data',
'skyfield.tests',
],
package_data = {
'skyfield': ['documentation/*.rst'],
'skyfield.data': ['*.npy', '*.txt'],
},
install_requires=[
'jplephem>=2.3',
'numpy',
'sgp4>=1.4',
],
test_requires=[
'pytz',
],
)
| from distutils.core import setup
import skyfield # safe, because __init__.py contains no import statements
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst', 'rb').read().decode('utf-8'),
license='MIT',
author='Brandon Rhodes',
author_email='[email protected]',
url='http://github.com/brandon-rhodes/python-skyfield/',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Astronomy',
],
packages=[
'skyfield',
'skyfield.data',
'skyfield.tests',
],
package_data = {
'skyfield': ['documentation/*.rst'],
'skyfield.data': ['*.npy', '*.txt'],
},
install_requires=[
'jplephem>=2.3',
'numpy',
'sgp4>=1.4',
])
|
Fix typo documention -> documentation | # -*- coding: utf-8 -*-
'''
The acl module handles client_acl operations
Additional information on client_acl can be
found by reading the salt documentation:
http://docs.saltstack.com/en/latest/ref/clientacl.html
'''
# Import python libraries
from __future__ import absolute_import
import re
class ClientACL(object):
'''
Represents the client ACL and provides methods
to query the ACL for given operations
'''
def __init__(self, blacklist):
self.blacklist = blacklist
def user_is_blacklisted(self, user):
'''
Takes a username as a string and returns a boolean. True indicates that
the provided user has been blacklisted
'''
for blacklisted_user in self.blacklist.get('users', []):
if re.match(blacklisted_user, user):
return True
return False
def cmd_is_blacklisted(self, cmd):
for blacklisted_module in self.blacklist.get('modules', []):
# If this is a regular command, it is a single function
if isinstance(cmd, str):
funs_to_check = [cmd]
# If this is a compound function
else:
funs_to_check = cmd
for fun in funs_to_check:
if re.match(blacklisted_module, fun):
return True
return False
| # -*- coding: utf-8 -*-
'''
The acl module handles client_acl operations
Additional information on client_acl can be
found by reading the salt documention:
http://docs.saltstack.com/en/latest/ref/clientacl.html
'''
# Import python libraries
from __future__ import absolute_import
import re
class ClientACL(object):
'''
Represents the client ACL and provides methods
to query the ACL for given operations
'''
def __init__(self, blacklist):
self.blacklist = blacklist
def user_is_blacklisted(self, user):
'''
Takes a username as a string and returns a boolean. True indicates that
the provided user has been blacklisted
'''
for blacklisted_user in self.blacklist.get('users', []):
if re.match(blacklisted_user, user):
return True
return False
def cmd_is_blacklisted(self, cmd):
for blacklisted_module in self.blacklist.get('modules', []):
# If this is a regular command, it is a single function
if isinstance(cmd, str):
funs_to_check = [cmd]
# If this is a compound function
else:
funs_to_check = cmd
for fun in funs_to_check:
if re.match(blacklisted_module, fun):
return True
return False
|
Support for new sf api | <?php
namespace Dami\Cli\Command;
use Symfony\Component\Console\Input\InputArgument,
Symfony\Component\Console\Input\InputOption,
Symfony\Component\Console,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface;
class StatusCommand extends ContainerAwareCommand
{
protected function configure()
{
parent::configure();
$this
->setDescription('Migrations status.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$migrationFiles = $this->getContainer()->get('dami.migration_files');
$migrationFiles->statusIntention();
$rows = array();
foreach ($migrationFiles->get() as $migrationFile) {
$status = $migrationFile->isMigrated() ? 'Migrated' : 'Not migrated';
$rows[] = array($status, $migrationFile->getVersion(), $migrationFile->getName());
}
if (count($rows) > 0) {
(new Console\Helper\Table($output))
->setHeaders(['Status', 'Version', 'Name'])
->setRows($rows)
->render($output);
} else {
$output->writeln(sprintf('<comment>There are no migrations.</comment>'));
}
}
}
| <?php
namespace Dami\Cli\Command;
use Symfony\Component\Console\Input\InputArgument,
Symfony\Component\Console\Input\InputOption,
Symfony\Component\Console,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface;
use Dami\Migration\MigrationFiles;
class StatusCommand extends ContainerAwareCommand
{
protected function configure()
{
parent::configure();
$this
->setDescription('Migrations status.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$migrationFiles = $this->getContainer()->get('dami.migration_files');
$migrationFiles->statusIntention();
$rows = array();
foreach ($migrationFiles->get() as $migrationFile) {
$status = $migrationFile->isMigrated() ? 'Migrated' : 'Not migrated';
$rows[] = array($status, $migrationFile->getVersion(), $migrationFile->getName());
}
if (count($rows) > 0) {
$table = $this->getHelperSet()->get('table');
$table
->setHeaders(array('Status', 'Version', 'Name'))
->setRows($rows)
->render($output);
} else {
$output->writeln(sprintf('<comment>There are no migrations.</comment>'));
}
}
}
|
Add event on selected element | ( function( window, define, require, requirejs, undefined ) {
'use strict';
define( [
'jquery',
'lodash',
'utils/event'
], function( $, _, Event ) {
/**
* Global Breakpoint system
*/
var EVENT_BREAKPOINT_CHANGE = 'Breakpoint/change';
return {
isGlobal: true,
currentBreakpoint: '',
defaults: function() {
return {
selector: 'body',
defaultBreakpoint: 'default'
};
},
ready: function( element, options ) {
this.settings = _.extend( this.defaults(), options );
this.currentBreakpoint = this.get();
},
events: function( element, options ) {
this.settings = _.extend( this.defaults(), options );
$( window ).on( 'resize', _.bind( function() {
var breakpoint = this.get();
if ( this.currentBreakpoint !== breakpoint ) {
this.currentBreakpoint = breakpoint;
Event.trigger( EVENT_BREAKPOINT_CHANGE, [ breakpoint ] );
$( this.settings.selector ).trigger( EVENT_BREAKPOINT_CHANGE, [ breakpoint ] );
}
}, this ) );
},
get: function() {
var breakpoint = this.settings.defaultBreakpoint;
if ( 'getComputedStyle' in window ) {
breakpoint = window.getComputedStyle(
document.querySelector( this.settings.selector ),
':after'
).getPropertyValue( 'content' );
breakpoint = breakpoint.replace( /"/g, '' );
}
return breakpoint;
}
};
} );
} )( this, this.define, this.require, this.requirejs );
| ( function( window, define, require, requirejs, undefined ) {
'use strict';
define( [
'jquery',
'lodash',
'utils/event'
], function( $, _, Event ) {
/**
* Global Breakpoint system
*/
return {
isGlobal: true,
currentBreakpoint: '',
defaults: function() {
return {
selector: 'body',
defaultBreakpoint: 'default'
};
},
ready: function( element, options ) {
this.settings = _.extend( this.defaults(), options );
this.currentBreakpoint = this.get();
},
events: function( element, options ) {
this.settings = _.extend( this.defaults(), options );
$( window ).on( 'resize', _.bind( function() {
var breakpoint = this.get();
if ( this.currentBreakpoint !== breakpoint ) {
this.currentBreakpoint = breakpoint;
Event.trigger( 'Breakpoint/change', [ breakpoint ] );
}
}, this ) );
},
get: function() {
var breakpoint = this.settings.defaultBreakpoint;
if ( 'getComputedStyle' in window ) {
breakpoint = window.getComputedStyle(
document.querySelector( this.settings.selector ),
':after'
).getPropertyValue( 'content' );
breakpoint = breakpoint.replace( /"/g, '' );
}
return breakpoint;
}
};
} );
} )( this, this.define, this.require, this.requirejs );
|
Clean up how we enable the extension after loading options | (function() {
var Handler = function() {
var options = {
urlPatterns: [],
shortcutKey: null,
linkSelector: null
};
var window;
var enabled = false;
this.init = function(obj) {
window = obj;
var keys = Object.keys(options);
chrome.storage.sync.get(keys, function(saved) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (saved[key]) {
options[key] = saved[key];
}
}
optionsLoaded();
});
};
this.enabled = function() {
return enabled;
}
var optionsLoaded = function() {
if (options.urlPatterns.length > 0) {
var r = new RegExp("^(" + options.urlPatterns.join("|") + ")", "i");
if (r.test(window.location.href)) {
enabled = true;
}
}
if (enabled) {
window.addEventListener("keypress", handleKeypress, false);
}
};
var handleKeypress = function(e) {
var tag = e.target.tagName.toLowerCase();
if (tag === 'input' || tag === 'textarea') {
return;
}
if (e.altKey || e.ctrlKey) {
return;
}
if (e.keyCode === options.shortcutKey) {
var a = document.querySelector(options.linkSelector);
if (a) {
chrome.extension.sendMessage({ url: a.href });
}
}
};
}
if (window === top) {
var handler = new Handler();
handler.init(window);
}
})();
| (function() {
var Handler = function() {
var options = {
urlPatterns: [],
shortcutKey: null,
linkSelector: null
};
this.init = function() {
var keys = Object.keys(options);
chrome.storage.sync.get(keys, function(saved) {
for (var key in keys) {
if (saved[key]) {
options[key] = saved[key];
}
}
});
console.log("options", options);
};
this.enabled = function() {
var enabled = false;
if (options.urlPatterns.length > 0) {
var r = new RegExp("^(" + options.urlPatterns.join("|") + ")", "i");
if (r.test(window.location.href)) {
enabled = true;
}
}
return enabled;
}
this.handleKeypress = function(e) {
var tag = e.target.tagName.toLowerCase();
if (tag === 'input' || tag === 'textarea') {
return;
}
if (e.altKey || e.ctrlKey) {
return;
}
if (e.keyCode === options.shortcutKey) {
var a = document.querySelector(options.linkSelector);
if (a) {
chrome.extension.sendMessage({ url: a.href });
}
}
};
}
if (window === top) {
var handler = new Handler();
handler.init();
if (handler.enabled()) {
window.addEventListener("keypress", handler.handleKeypress, false);
}
}
})();
|
Connect to the "elasticsearch" host by default | #!/usr/bin/env python
# encoding: utf-8
import socket
from os import environ as env
from tornado.netutil import Resolver
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
class UnixResolver(Resolver):
def initialize(self, resolver):
self.resolver = resolver
def close(self):
self.resolver.close()
@gen.coroutine
def resolve(self, host, port, *args, **kwargs):
scheme, path = Storage.DOCKER.split('://')
if host == 'docker':
if scheme == 'unix':
raise gen.Return([(socket.AF_UNIX, path)])
elif scheme == 'tcp' or scheme == 'http':
t = path.split(":")
if len(t) > 1:
host, port = t
port = int(port)
else:
host, port = t[0], 80
result = yield self.resolver.resolve(host, port, *args, **kwargs)
raise gen.Return(result)
AsyncHTTPClient.configure(
None,
resolver=UnixResolver(resolver=Resolver()),
max_clients=20000
)
class Storage(object):
CONTAINERS = set([])
DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock')
ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://elasticsearch:9200')
http = AsyncHTTPClient()
| #!/usr/bin/env python
# encoding: utf-8
import socket
from os import environ as env
from tornado.netutil import Resolver
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
class UnixResolver(Resolver):
def initialize(self, resolver):
self.resolver = resolver
def close(self):
self.resolver.close()
@gen.coroutine
def resolve(self, host, port, *args, **kwargs):
scheme, path = Storage.DOCKER.split('://')
if host == 'docker':
if scheme == 'unix':
raise gen.Return([(socket.AF_UNIX, path)])
elif scheme == 'tcp' or scheme == 'http':
t = path.split(":")
if len(t) > 1:
host, port = t
port = int(port)
else:
host, port = t[0], 80
result = yield self.resolver.resolve(host, port, *args, **kwargs)
raise gen.Return(result)
AsyncHTTPClient.configure(
None,
resolver=UnixResolver(resolver=Resolver()),
max_clients=20000
)
class Storage(object):
CONTAINERS = set([])
DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock')
ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://127.0.0.1:9200')
http = AsyncHTTPClient()
|
Remove deleted & child reservation types | define(['app', 'text!./schedule.html', 'lodash'], function(app, template, _) {
app.directive("cctvFrameSchedule", ['$http', function($http) {
return {
restrict: 'E',
template: template,
replace: true,
scope: {
content: '='
},
link: function($scope) {
$scope.selectedTypes = {};
$scope.updateTypes = updateReservationTypes;
if($scope.content && $scope.content.reservationTypes) {
$scope.content.reservationTypes.forEach(function(id){
$scope.selectedTypes[id]=true;
});
}
$http.get('/api/v2016/reservation-types', { params : { q: { "meta.status": { $ne: "deleted" } } } }).then(function(res) {
$scope.reservationTypes = _.filter(res.data, function(t){
return !t.parent;
});
});
//========================================
//
//========================================
function updateReservationTypes() {
$scope.content.reservationTypes = [];
_.forEach($scope.selectedTypes, function(selected, key) {
if (selected)
$scope.content.reservationTypes.push(key);
});
}
}
};
}]);
});
| define(['app', 'text!./schedule.html', 'lodash'], function(app, template, _) {
app.directive("cctvFrameSchedule", ['$http', function($http) {
return {
restrict: 'E',
template: template,
replace: true,
scope: {
content: '='
},
link: function($scope) {
$scope.selectedTypes = {};
$scope.updateTypes = updateReservationTypes;
if($scope.content && $scope.content.reservationTypes) {
$scope.content.reservationTypes.forEach(function(id){
$scope.selectedTypes[id]=true;
});
}
$http.get('/api/v2016/reservation-types').then(function(res) {
$scope.reservationTypes = res.data;
});
//========================================
//
//========================================
function updateReservationTypes() {
$scope.content.reservationTypes = [];
_.forEach($scope.selectedTypes, function(selected, key) {
if (selected)
$scope.content.reservationTypes.push(key);
});
}
}
};
}]);
});
|
Add default value for owner_details. | /*@ngInject*/
function ProjectModelService(projectsAPI) {
class Project {
constructor(id, name, owner) {
this.id = id;
this.name = name;
this.owner = owner;
this.samples_count = 0;
this.processes_count = 0;
this.experiments_count = 0;
this.files_count = 0;
this.description = "";
this.birthtime = 0;
this.owner_details = {};
this.mtime = 0;
}
static fromJSON(data) {
let p = new Project(data.id, data.name, data.owner);
p.samples_count = data.samples;
p.processes_count = data.processes;
p.experiments_count = data.experiments;
p.files_counts = data.files;
p.description = data.description;
p.birthtime = new Date(data.birthtime * 1000);
p.mtime = new Date(data.mtime * 1000);
p.users = data.users;
p.owner_details = data.owner_details;
return p;
}
static get(id) {
}
static getProjectsForCurrentUser() {
return projectsAPI.getAllProjects().then(
(projects) => projects.map(p => Project.fromJSON(p))
);
}
save() {
}
update() {
}
}
return Project;
}
angular.module('materialscommons').factory('ProjectModel', ProjectModelService);
| /*@ngInject*/
function ProjectModelService(projectsAPI) {
class Project {
constructor(id, name, owner) {
this.id = id;
this.name = name;
this.owner = owner;
this.samples_count = 0;
this.processes_count = 0;
this.experiments_count = 0;
this.files_count = 0;
this.description = "";
this.birthtime = 0;
this.mtime = 0;
}
static fromJSON(data) {
let p = new Project(data.id, data.name, data.owner);
p.samples_count = data.samples;
p.processes_count = data.processes;
p.experiments_count = data.experiments;
p.files_counts = data.files;
p.description = data.description;
p.birthtime = new Date(data.birthtime * 1000);
p.mtime = new Date(data.mtime * 1000);
p.users = data.users;
p.owner_details = data.owner_details;
return p;
}
static get(id) {
}
static getProjectsForCurrentUser() {
return projectsAPI.getAllProjects().then(
(projects) => projects.map(p => Project.fromJSON(p))
);
}
save() {
}
update() {
}
}
return Project;
}
angular.module('materialscommons').factory('ProjectModel', ProjectModelService);
|
Convert JSON blob to relational db structure. | #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2015 ghostwords.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from time import sleep
from .utils import DATABASE_URL
import dataset
def collect(crawl_id, result_queue, log):
db = dataset.connect(DATABASE_URL)
while True:
if result_queue.empty():
sleep(0.01)
continue
result = result_queue.get()
if result is None:
break
crawl_url, result = result
if not result:
with db:
db['result'].insert(dict(
crawl_id=crawl_id,
crawl_url=crawl_url
))
continue
for page_url, page_data in result.items():
for domain, ddata in page_data['domains'].items():
for script_url, sdata in ddata['scripts'].items():
with db:
result_id = db['result'].insert(dict(
crawl_id=crawl_id,
crawl_url=crawl_url,
page_url=page_url,
domain=domain,
script_url=script_url,
canvas=sdata['canvas']['fingerprinting'],
font_enum=sdata['fontEnumeration'],
navigator_enum=sdata['navigatorEnumeration']
))
# property access counts get saved in `property_count`
rows = []
for property, count in sdata['counts'].items():
rows.append(dict(
result_id=result_id,
property=property,
count=count
))
with db:
db['property_count'].insert_many(rows)
log("Collecting finished.")
| #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2015 ghostwords.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from time import sleep
from .utils import DATABASE_URL
import dataset
import json
def collect(crawl_id, result_queue, log):
with dataset.connect(DATABASE_URL) as db:
while True:
if result_queue.empty():
sleep(0.01)
continue
result = result_queue.get()
if result is None:
break
crawl_url, result = result
page_url, data = None, None
if result:
[(page_url, data)] = result.items()
data = json.dumps(data)
db['result'].insert(dict(
crawl_id=crawl_id,
crawl_url=crawl_url,
page_url=page_url,
data=data
))
log("Collecting finished.")
|
Add Pykka as a dependency | from __future__ import unicode_literals
import re
from setuptools import setup
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Mopidy-Scrobbler',
version=get_version('mopidy_scrobbler/__init__.py'),
url='https://github.com/mopidy/mopidy-scrobbler',
license='Apache License, Version 2.0',
author='Stein Magnus Jodal',
author_email='[email protected]',
description='Mopidy extension for scrobbling played tracks to Last.fm',
long_description=open('README.rst').read(),
packages=['mopidy_scrobbler'],
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'Mopidy',
'Pykka >= 1.1',
'pylast >= 0.5.7',
],
entry_points={
'mopidy.ext': [
'scrobbler = mopidy_scrobbler:Extension',
],
},
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Multimedia :: Sound/Audio :: Players',
],
)
| from __future__ import unicode_literals
import re
from setuptools import setup
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Mopidy-Scrobbler',
version=get_version('mopidy_scrobbler/__init__.py'),
url='https://github.com/mopidy/mopidy-scrobbler',
license='Apache License, Version 2.0',
author='Stein Magnus Jodal',
author_email='[email protected]',
description='Mopidy extension for scrobbling played tracks to Last.fm',
long_description=open('README.rst').read(),
packages=['mopidy_scrobbler'],
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'Mopidy',
'pylast >= 0.5.7',
],
entry_points={
'mopidy.ext': [
'scrobbler = mopidy_scrobbler:Extension',
],
},
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Multimedia :: Sound/Audio :: Players',
],
)
|
Allow pieces to take one another | import React from "react";
import classNames from "classnames";
import { movePiece, selectPiece } from "store/actions";
class ChessBoardSquare extends React.Component {
constructor(props) {
super(props);
this.selectSquare = this.selectSquare.bind(this);
}
squareCoords() {
return { rank: this.props.rank, file: this.props.file };
}
selectSquare() {
var { store } = this.props;
if (store.getState().selectedSquare != null) {
store.dispatch(movePiece(store.getState().selectedSquare, this.squareCoords()));
}
else if (this.props.piece != undefined) {
store.dispatch(selectPiece(this.squareCoords()));
}
};
isSelectedSquare() {
var { store } = this.props;
if (store.getState().selectedSquare == null) {
return false;
}
else {
return this.squareCoords().rank == store.getState().selectedSquare.rank
&& this.squareCoords().file == store.getState().selectedSquare.file;
}
}
render() {
if (this.props.piece == undefined) {
var squareClass = "board-square";
}
else {
var squareClass = classNames(
"board-square",
this.props.piece.type,
this.props.piece.colour,
{ "selected": this.isSelectedSquare() }
)
}
return <div className={squareClass} onClick={this.selectSquare} />
}
}
export default ChessBoardSquare;
| import React from "react";
import classNames from "classnames";
import { movePiece, selectPiece } from "store/actions";
class ChessBoardSquare extends React.Component {
constructor(props) {
super(props);
this.selectSquare = this.selectSquare.bind(this);
}
squareCoords() {
return { rank: this.props.rank, file: this.props.file };
}
selectSquare() {
var { store } = this.props;
console.log(`Clicked: ${this.props.file}${this.props.rank}`);
if (this.props.piece != undefined) {
store.dispatch(selectPiece(this.squareCoords()));
}
else {
console.log("About to move!");
store.dispatch(movePiece(store.getState().selectedSquare, this.squareCoords()));
console.log("Moved!");
}
console.log(store.getState().selectedSquare);
};
isSelectedSquare() {
var { store } = this.props;
if (store.getState().selectedSquare == null) {
return false;
}
else {
return this.squareCoords().rank == store.getState().selectedSquare.rank
&& this.squareCoords().file == store.getState().selectedSquare.file;
}
}
render() {
if (this.props.piece == undefined) {
var squareClass = "board-square";
}
else {
var squareClass = classNames(
"board-square",
this.props.piece.type,
this.props.piece.colour,
{ "selected": this.isSelectedSquare() }
)
}
return <div className={squareClass} onClick={this.selectSquare} />
}
}
export default ChessBoardSquare;
|
Make mocks added in test-check timeout tests PHPUnit 4.5-compatible | <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector');
$informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);
$output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
$output->method('write');
$context = Context::getInstance();
$context->setService('information-collector', $informationCollector);
$context->setService('output', $output);
}
/** @test */
public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
{
$check = new TestsCheck(['command' => 'echo OK']);
$check->execute();
}
/** @test */
public function succeeds_when_command_finished_within_configured_timeout()
{
$check = new TestsCheck(['command' => 'echo OK', 'timeout' => 0.100]);
$check->execute();
}
/** @test */
public function fails_when_the_command_exceeds_the_timeout()
{
$this->setExpectedException('Exception', 'exceeded the timeout');
$check = new TestsCheck(['command' => 'sleep 1', 'timeout' => 0.100]);
$check->execute();
}
}
| <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->createMock('Liip\RMT\Information\InformationCollector');
$informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);
$output = $this->createMock('Symfony\Component\Console\Output\OutputInterface');
$output->method('write');
$context = Context::getInstance();
$context->setService('information-collector', $informationCollector);
$context->setService('output', $output);
}
/** @test */
public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
{
$check = new TestsCheck(['command' => 'echo OK']);
$check->execute();
}
/** @test */
public function succeeds_when_command_finished_within_configured_timeout()
{
$check = new TestsCheck(['command' => 'echo OK', 'timeout' => 0.100]);
$check->execute();
}
/** @test */
public function fails_when_the_command_exceeds_the_timeout()
{
$this->setExpectedException('Exception', 'exceeded the timeout');
$check = new TestsCheck(['command' => 'sleep 1', 'timeout' => 0.100]);
$check->execute();
}
}
|
Remove dead error check from user agent.
Remove an error test from an earlier verion of the user agent that used
a different library. Axios will raise an exception on error.
Closes #485. | const stream = require('stream')
const url = require('url')
const logger = require('prolific.logger').create('compassion.colleague')
const axios = require('axios')
const httpAdapter = require('axios/lib/adapters/http')
module.exports = {
json: async (location, path, body) => {
const resolved = url.resolve(location, path)
try {
if (body == null) {
return (await axios.get(resolved)).data
} else {
return (await axios.post(resolved, body)).data
}
} catch (error) {
logger.error('ua', { url: resolved, stack: error.stack })
return null
}
},
// See: // https://github.com/andrewstart/axios-streaming/blob/master/axios.js
stream: async (location, path, body) => {
const resolved = url.resolve(location, path)
try {
return (await axios.post(resolved, body, {
responseType: 'stream',
adapter: httpAdapter
})).data
} catch (error) {
logger.error('ua', { url: resolved, stack: error.stack })
}
const empty = new stream.PassThrough
empty.end()
return empty
}
}
| const stream = require('stream')
const url = require('url')
const logger = require('prolific.logger').create('compassion.colleague')
const axios = require('axios')
const httpAdapter = require('axios/lib/adapters/http')
module.exports = {
json: async (location, path, body) => {
const resolved = url.resolve(location, path)
try {
if (body == null) {
return (await axios.get(resolved)).data
} else {
return (await axios.post(resolved, body)).data
}
} catch (error) {
logger.error('ua', { url: resolved, stack: error.stack })
return null
}
},
// See: // https://github.com/andrewstart/axios-streaming/blob/master/axios.js
stream: async (location, path, body) => {
const resolved = url.resolve(location, path)
try {
const response = await axios.post(resolved, body, {
responseType: 'stream',
adapter: httpAdapter
})
if (Math.floor(response.status / 100) == 2) {
return response.data
}
} catch (error) {
logger.error('ua', { url: resolved, stack: error.stack })
}
const empty = new stream.PassThrough
empty.end()
return empty
}
}
|
Fix passing GCC compiler options on Windows | #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"]
extra_link_args = [] if os.name == 'nt' else ["-g"]
mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
sources=['src/thinning.cpp',
'src/distance.cpp',
'src/grassfire.cpp',
'src/popcount.cpp',
'src/neighbours.cpp'],
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args)
setup(
name='cv_algorithms',
license='Apache license 2.0',
packages=find_packages(exclude=['tests*']),
install_requires=['cffi>=0.7'],
ext_modules=[mod_cv_algorithms],
test_suite='nose.collector',
tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'],
setup_requires=['nose>=1.0'],
platforms="any",
zip_safe=False,
version='1.0.0',
long_description=io.open("README.rst", encoding="utf-8").read(),
description='Optimized OpenCV extra algorithms for Python',
url="https://github.com/ulikoehler/"
)
| #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
sources=['src/thinning.cpp',
'src/distance.cpp',
'src/grassfire.cpp',
'src/popcount.cpp',
'src/neighbours.cpp'],
extra_compile_args=["-g", "-O2", "-march=native"],
extra_link_args=["-g"])
setup(
name='cv_algorithms',
license='Apache license 2.0',
packages=find_packages(exclude=['tests*']),
install_requires=['cffi>=0.7'],
ext_modules=[mod_cv_algorithms],
test_suite='nose.collector',
tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'],
setup_requires=['nose>=1.0'],
platforms="any",
zip_safe=False,
version='1.0.0',
long_description=io.open("README.rst", encoding="utf-8").read(),
description='Optimized OpenCV extra algorithms for Python',
url="https://github.com/ulikoehler/"
)
|
Use laravel application instance when running suitey | <?php
namespace TheCrypticAce\Suitey;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Foundation\Application;
class Suitey
{
/**
* The laravel application instance
* A container used to resolve dependencies
*
* @var \Illuminate\Contracts\Foundation\Application
*/
private $app;
/**
* A list of all executable steps
*
* @var \Illuminate\Support\Collection
*/
private $steps;
public function __construct(Application $app)
{
$this->app = $app;
$this->steps = new Collection;
}
public function add($steps)
{
$this->steps = $this->steps->merge(array_wrap($steps));
}
public function fresh()
{
return tap(clone $this, function ($instance) {
$instance->steps = new Collection;
});
}
public function run(IO $io)
{
return Process::usingOutput($io->output(), function () use ($io) {
return $this->pipeline()->send($io)->then(function ($io) {
return 0;
});
});
}
private function pipeline()
{
$pipeline = new Pipeline($this->app);
return $pipeline->through($this->pending()->all());
}
private function pending()
{
return $this->steps->map(function ($step, $index) {
return new PendingStep($step, 1 + $index, $this->steps->count());
});
}
}
| <?php
namespace TheCrypticAce\Suitey;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Container\Container;
class Suitey
{
/**
* A list of all executable steps
*
* @var \Illuminate\Support\Collection
*/
private $steps;
/**
* A container used to resolve dependencies
*
* @var \Illuminate\Contracts\Container\Container
*/
private $container;
public function __construct(Container $container)
{
$this->steps = new Collection;
$this->container = $container;
}
public function add($steps)
{
$this->steps = $this->steps->merge(array_wrap($steps));
}
public function fresh()
{
return tap(clone $this, function ($instance) {
$instance->steps = new Collection;
});
}
public function run(IO $io)
{
return Process::usingOutput($io->output(), function () use ($io) {
return $this->pipeline()->send($io)->then(function ($io) {
return 0;
});
});
}
private function pipeline()
{
$pipeline = new Pipeline($this->container);
return $pipeline->through($this->pending()->all());
}
private function pending()
{
return $this->steps->map(function ($step, $index) {
return new PendingStep($step, 1 + $index, $this->steps->count());
});
}
}
|
Remove annoying logging in Router | from threading import Thread
import zmq
from logbook import Logger
class Router(Thread):
"""Thread waiting for a request by another Driver and responding to
it with the chunked asked.
"""
def __init__(self, name, redis, get_chunk):
super(Router, self).__init__()
self.name = name
self.redis = redis
self.get_chunk = get_chunk
self.router = None
self.logger = Logger("{} - Router".format(self.name))
self.context = zmq.Context.instance()
def run(self):
self.router = self.context.socket(zmq.ROUTER)
port = self.router.bind_to_random_port('tcp://*')
self.redis.set('drivers:{}:router'.format(self.name), port)
while True:
msg = self.router.recv_multipart()
self._respond_to(*msg)
def _respond_to(self, identity, filename, offset, size):
"""Calls the `get_chunk` handler defined by the Driver to get
the chunk and send it to the addressee.
"""
self.logger.debug("Getting chunk of size {} from offset {} in {}"
.format(size, offset, filename))
chunk = self.get_chunk(filename, int(offset), int(size))
self.router.send_multipart((identity, chunk))
| from threading import Thread
import zmq
from logbook import Logger
class Router(Thread):
"""Thread waiting for a request by another Driver and responding to
it with the chunked asked.
"""
def __init__(self, name, redis, get_chunk):
super(Router, self).__init__()
self.name = name
self.redis = redis
self.get_chunk = get_chunk
self.router = None
self.logger = Logger("{} - Router".format(self.name))
self.context = zmq.Context.instance()
def run(self):
self.router = self.context.socket(zmq.ROUTER)
port = self.router.bind_to_random_port('tcp://*')
self.redis.set('drivers:{}:router'.format(self.name), port)
while True:
self.logger.info("Listening...")
msg = self.router.recv_multipart()
self._respond_to(*msg)
def _respond_to(self, identity, filename, offset, size):
"""Calls the `get_chunk` handler defined by the Driver to get
the chunk and send it to the addressee.
"""
self.logger.debug("Getting chunk of size {} from offset {} in {}"
.format(size, offset, filename))
chunk = self.get_chunk(filename, int(offset), int(size))
self.router.send_multipart((identity, chunk))
self.logger.debug("Chunk sended")
|
Switch to list equality check | from tests.base_case import ChatBotTestCase
from chatterbot.trainers import ChatterBotCorpusTrainer
class ChatterBotCorpusTrainingTestCase(ChatBotTestCase):
"""
Test case for training with data from the ChatterBot Corpus.
"""
def setUp(self):
super(ChatterBotCorpusTrainingTestCase, self).setUp()
self.chatbot.set_trainer(ChatterBotCorpusTrainer)
def test_train_with_english_greeting_corpus(self):
self.chatbot.train('chatterbot.corpus.english.greetings')
statement = self.chatbot.storage.find('Hello')
self.assertIsNotNone(statement)
def test_train_with_english_greeting_corpus_tags(self):
self.chatbot.train('chatterbot.corpus.english.greetings')
statement = self.chatbot.storage.find('Hello')
self.assertEqual(['greetings'], statement.get_tags())
def test_train_with_multiple_corpora(self):
self.chatbot.train(
'chatterbot.corpus.english.greetings',
'chatterbot.corpus.english.conversations',
)
statement = self.chatbot.storage.find('Hello')
self.assertIsNotNone(statement)
def test_train_with_english_corpus(self):
self.chatbot.train('chatterbot.corpus.english')
statement = self.chatbot.storage.find('Hello')
self.assertIsNotNone(statement)
| from tests.base_case import ChatBotTestCase
from chatterbot.trainers import ChatterBotCorpusTrainer
class ChatterBotCorpusTrainingTestCase(ChatBotTestCase):
"""
Test case for training with data from the ChatterBot Corpus.
"""
def setUp(self):
super(ChatterBotCorpusTrainingTestCase, self).setUp()
self.chatbot.set_trainer(ChatterBotCorpusTrainer)
def test_train_with_english_greeting_corpus(self):
self.chatbot.train('chatterbot.corpus.english.greetings')
statement = self.chatbot.storage.find('Hello')
self.assertIsNotNone(statement)
def test_train_with_english_greeting_corpus_tags(self):
self.chatbot.train('chatterbot.corpus.english.greetings')
statement = self.chatbot.storage.find('Hello')
self.assertIn('greetings', statement.get_tags())
def test_train_with_multiple_corpora(self):
self.chatbot.train(
'chatterbot.corpus.english.greetings',
'chatterbot.corpus.english.conversations',
)
statement = self.chatbot.storage.find('Hello')
self.assertIsNotNone(statement)
def test_train_with_english_corpus(self):
self.chatbot.train('chatterbot.corpus.english')
statement = self.chatbot.storage.find('Hello')
self.assertIsNotNone(statement)
|
Update SampleDateUtil to include isCompleted during Task creation | package utask.model.util;
import utask.commons.exceptions.IllegalValueException;
import utask.model.ReadOnlyUTask;
import utask.model.UTask;
import utask.model.tag.UniqueTagList;
import utask.model.task.Deadline;
import utask.model.task.EventTask;
import utask.model.task.Frequency;
import utask.model.task.IsCompleted;
import utask.model.task.Name;
import utask.model.task.Task;
import utask.model.task.Timestamp;
import utask.model.task.UniqueTaskList.DuplicateTaskException;
public class SampleDataUtil {
public static Task[] getSamplePersons() {
try {
return new Task[] {
new EventTask(new Name("My first task"), new Deadline("010117"), new Timestamp("0900 to 1000"),
new Frequency("-"),
new UniqueTagList("important"),
new IsCompleted("no"))
};
} catch (IllegalValueException e) {
throw new AssertionError("sample data cannot be invalid", e);
}
}
public static ReadOnlyUTask getSampleAddressBook() {
try {
UTask sampleAB = new UTask();
for (Task sampleTask : getSamplePersons()) {
sampleAB.addTask(sampleTask);
}
return sampleAB;
} catch (DuplicateTaskException e) {
throw new AssertionError("sample data cannot contain duplicate persons", e);
}
}
}
| package utask.model.util;
import utask.commons.exceptions.IllegalValueException;
import utask.model.ReadOnlyUTask;
import utask.model.UTask;
import utask.model.tag.UniqueTagList;
import utask.model.task.Deadline;
import utask.model.task.EventTask;
import utask.model.task.Frequency;
import utask.model.task.Name;
import utask.model.task.Task;
import utask.model.task.Timestamp;
import utask.model.task.UniqueTaskList.DuplicateTaskException;
public class SampleDataUtil {
public static Task[] getSamplePersons() {
try {
return new Task[] {
new EventTask(new Name("My first task"), new Deadline("010117"), new Timestamp("0900 to 1000"),
new Frequency("-"),
new UniqueTagList("important"))
};
} catch (IllegalValueException e) {
throw new AssertionError("sample data cannot be invalid", e);
}
}
public static ReadOnlyUTask getSampleAddressBook() {
try {
UTask sampleAB = new UTask();
for (Task sampleTask : getSamplePersons()) {
sampleAB.addTask(sampleTask);
}
return sampleAB;
} catch (DuplicateTaskException e) {
throw new AssertionError("sample data cannot contain duplicate persons", e);
}
}
}
|
Revert "Always use registrationCount when calculating numbers"
This reverts commit 726f87eae7b5609e75ee4d94d376f230317c9b32. | // @flow
import React from 'react';
import styles from './AttendanceStatus.css';
import withModal from './withModal';
import type { EventPool } from 'app/models';
type AttendanceElementProps = {
pool: EventPool,
index: number,
toggleModal: number => void
};
const AttendanceElement = ({
pool: { name, registrations, registrationCount, capacity },
index,
toggleModal
}: AttendanceElementProps) => {
const totalCount = registrations ? registrations.length : registrationCount;
const Status = () => (
<strong>{`${totalCount}/${capacity ? capacity : '∞'}`}</strong>
);
return (
<div className={styles.poolBox}>
<strong>{name}</strong>
{registrations ? (
<a onClick={() => toggleModal(index)}>
<Status />
</a>
) : (
<Status />
)}
</div>
);
};
export type AttendanceStatusProps = {
pools: Array<EventPool>,
toggleModal: number => void
};
const AttendanceStatus = ({ pools, toggleModal }: AttendanceStatusProps) => {
const toggleKey = key => (pools.length > 1 ? key + 1 : key);
return (
<div className={styles.attendanceBox}>
{(pools || []).map((pool, index) => (
<AttendanceElement
key={index}
pool={pool}
index={index}
toggleModal={key => toggleModal(toggleKey(key))}
/>
))}
</div>
);
};
AttendanceStatus.Modal = withModal(AttendanceStatus);
export default AttendanceStatus;
| // @flow
import React from 'react';
import styles from './AttendanceStatus.css';
import withModal from './withModal';
import type { EventPool } from 'app/models';
type AttendanceElementProps = {
pool: EventPool,
index: number,
toggleModal: number => void
};
const AttendanceElement = ({
pool: { name, registrations, registrationCount, capacity },
index,
toggleModal
}: AttendanceElementProps) => {
const Status = () => (
<strong>{`${registrationCount}/${capacity ? capacity : '∞'}`}</strong>
);
return (
<div className={styles.poolBox}>
<strong>{name}</strong>
{registrations ? (
<a onClick={() => toggleModal(index)}>
<Status />
</a>
) : (
<Status />
)}
</div>
);
};
export type AttendanceStatusProps = {
pools: Array<EventPool>,
toggleModal: number => void
};
const AttendanceStatus = ({ pools, toggleModal }: AttendanceStatusProps) => {
const toggleKey = key => (pools.length > 1 ? key + 1 : key);
return (
<div className={styles.attendanceBox}>
{(pools || []).map((pool, index) => (
<AttendanceElement
key={index}
pool={pool}
index={index}
toggleModal={key => toggleModal(toggleKey(key))}
/>
))}
</div>
);
};
AttendanceStatus.Modal = withModal(AttendanceStatus);
export default AttendanceStatus;
|
Add numpy array as a possibility for setting external magnetic field. | import numpy as np
class FixedZeeman(object):
def __init__(self, H, multiplier=1, name='fixedzeeman'):
if not isinstance(H, (list, tuple, np.ndarray)) or len(H) != 3:
raise ValueError('H must be a 3-element tuple or list.')
else:
self.H = H
if not isinstance(multiplier, (float, int)):
raise ValueError('Multiplier must be a positive float or int.')
else:
self.multiplier = multiplier
if not isinstance(name, str):
raise ValueError('name must be a string.')
else:
self.name = name
def get_mif(self):
# Create mif string.
mif = '# FixedZeeman\n'
mif += 'Specify Oxs_FixedZeeman:{} '.format(self.name)
mif += '{\n'
mif += '\tfield {\n'
mif += '\t\tOxs_UniformVectorField {\n'
mif += '\t\t\tvector {'
mif += ' {} {} {} '.format(self.H[0], self.H[1], self.H[2])
mif += '}\n'
mif += '\t\t}\n'
mif += '\t}\n'
mif += '\tmultiplier {}\n'.format(self.multiplier)
mif += '}\n\n'
return mif
| class FixedZeeman(object):
def __init__(self, H, multiplier=1, name='fixedzeeman'):
if not isinstance(H, (list, tuple)) or len(H) != 3:
raise ValueError('H must be a 3-element tuple or list.')
else:
self.H = H
if not isinstance(multiplier, (float, int)):
raise ValueError('Multiplier must be a positive float or int.')
else:
self.multiplier = multiplier
if not isinstance(name, str):
raise ValueError('name must be a string.')
else:
self.name = name
def get_mif(self):
# Create mif string.
mif = '# FixedZeeman\n'
mif += 'Specify Oxs_FixedZeeman:{} '.format(self.name)
mif += '{\n'
mif += '\tfield {\n'
mif += '\t\tOxs_UniformVectorField {\n'
mif += '\t\t\tvector {'
mif += ' {} {} {} '.format(self.H[0], self.H[1], self.H[2])
mif += '}\n'
mif += '\t\t}\n'
mif += '\t}\n'
mif += '\tmultiplier {}\n'.format(self.multiplier)
mif += '}\n\n'
return mif
|
Use the site that has scheme also input. | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
| try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("http://{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
|
Bump version: 0.0.12 -> 0.0.13
[ci skip] | # /setup.py
#
# Installation and setup script for parse-shebang
#
# See /LICENCE.md for Copyright information
"""Installation and setup script for parse-shebang."""
from setuptools import find_packages, setup
setup(name="parse-shebang",
version="0.0.13",
description="""Parse shebangs and return their components.""",
long_description_markdown_filename="README.md",
author="Sam Spilsbury",
author_email="[email protected]",
classifiers=["Development Status :: 3 - Alpha",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Intended Audience :: Developers",
"Topic :: System :: Shells",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License"],
url="http://github.com/polysquare/parse-shebang",
license="MIT",
keywords="development",
packages=find_packages(exclude=["test"]),
install_requires=["setuptools"],
extras_require={
"upload": ["setuptools-markdown"]
},
test_suite="nose.collector",
zip_safe=True,
include_package_data=True)
| # /setup.py
#
# Installation and setup script for parse-shebang
#
# See /LICENCE.md for Copyright information
"""Installation and setup script for parse-shebang."""
from setuptools import find_packages, setup
setup(name="parse-shebang",
version="0.0.12",
description="""Parse shebangs and return their components.""",
long_description_markdown_filename="README.md",
author="Sam Spilsbury",
author_email="[email protected]",
classifiers=["Development Status :: 3 - Alpha",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Intended Audience :: Developers",
"Topic :: System :: Shells",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License"],
url="http://github.com/polysquare/parse-shebang",
license="MIT",
keywords="development",
packages=find_packages(exclude=["test"]),
install_requires=["setuptools"],
extras_require={
"upload": ["setuptools-markdown"]
},
test_suite="nose.collector",
zip_safe=True,
include_package_data=True)
|
Fix print for python 3
Fix print statement in copy_from_theme management command. | import errno
import glob
import os
import shutil
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand
def copy(src, dest):
if not os.path.exists(os.path.dirname(dest)):
os.makedirs(os.path.dirname(dest))
try:
shutil.copytree(src, dest)
except OSError as e:
# If the error was caused because the source wasn't a directory
if e.errno == errno.ENOTDIR:
shutil.copy(src, dest)
else:
print('Directory not copied. Error: %s' % e)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"--path",
type="string",
dest="path",
help="a glob wildcard to copy templates from"
),
)
def handle(self, *args, **options):
path = options["path"]
base = os.path.join(os.path.dirname(__file__), "../../templates")
dest = os.path.join(settings.PACKAGE_ROOT, "templates")
for f in glob.glob(os.path.join(base, path)):
print(f.replace(base, dest))
copy(f, f.replace(base, dest))
| import errno
import glob
import os
import shutil
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand
def copy(src, dest):
if not os.path.exists(os.path.dirname(dest)):
os.makedirs(os.path.dirname(dest))
try:
shutil.copytree(src, dest)
except OSError as e:
# If the error was caused because the source wasn't a directory
if e.errno == errno.ENOTDIR:
shutil.copy(src, dest)
else:
print('Directory not copied. Error: %s' % e)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"--path",
type="string",
dest="path",
help="a glob wildcard to copy templates from"
),
)
def handle(self, *args, **options):
path = options["path"]
base = os.path.join(os.path.dirname(__file__), "../../templates")
dest = os.path.join(settings.PACKAGE_ROOT, "templates")
for f in glob.glob(os.path.join(base, path)):
print f.replace(base, dest)
copy(f, f.replace(base, dest))
|
Remove reliance on function prototype extension. | import Ember from "ember";
import Snippets from "../snippets";
/* global require */
var Highlight = require('highlight.js');
export default Ember.Component.extend({
tagName: 'pre',
classNameBindings: ['language'],
unindent: true,
_unindent: function(src) {
if (!this.get('unindent')) {
return src;
}
var match, min, lines = src.split("\n");
for (var i = 0; i < lines.length; i++) {
match = /^\s*/.exec(lines[i]);
if (match && (typeof min === 'undefined' || min > match[0].length)) {
min = match[0].length;
}
}
if (typeof min !== 'undefined' && min > 0) {
src = src.replace(new RegExp("(\\n|^)\\s{" + min + "}", 'g'), "$1");
}
return src;
},
source: Ember.computed('name', function(){
return this._unindent(
(Snippets[this.get('name')] || "")
.replace(/^(\s*\n)*/, '')
.replace(/\s*$/, '')
);
}),
didInsertElement: function(){
Highlight.highlightBlock(this.get('element'));
},
language: Ember.computed('name', function(){
var m = /\.(\w+)$/i.exec(this.get('name'));
if (m) {
switch (m[1].toLowerCase()) {
case 'js':
return 'javascript';
case 'hbs':
return 'handlebars';
}
}
})
});
| import Ember from "ember";
import Snippets from "../snippets";
/* global require */
var Highlight = require('highlight.js');
export default Ember.Component.extend({
tagName: 'pre',
classNameBindings: ['language'],
unindent: true,
_unindent: function(src) {
if (!this.get('unindent')) {
return src;
}
var match, min, lines = src.split("\n");
for (var i = 0; i < lines.length; i++) {
match = /^\s*/.exec(lines[i]);
if (match && (typeof min === 'undefined' || min > match[0].length)) {
min = match[0].length;
}
}
if (typeof min !== 'undefined' && min > 0) {
src = src.replace(new RegExp("(\\n|^)\\s{" + min + "}", 'g'), "$1");
}
return src;
},
source: function(){
return this._unindent(
(Snippets[this.get('name')] || "")
.replace(/^(\s*\n)*/, '')
.replace(/\s*$/, '')
);
}.property('name'),
didInsertElement: function(){
Highlight.highlightBlock(this.get('element'));
},
language: function(){
var m = /\.(\w+)$/i.exec(this.get('name'));
if (m) {
switch (m[1].toLowerCase()) {
case 'js':
return 'javascript';
case 'hbs':
return 'handlebars';
}
}
}.property('name')
});
|
Fix duplicate simultaneous build initiation. | const fs = require('fs-extra')
const { exec } = require('child_process')
const path = require('path')
module.exports = function getCurrentCommit (directory, callback) {
// If not a git repository, return null.
if (!fs.existsSync(path.join(directory, '.git'))) {
callback(null)
return
}
// http://stackoverflow.com/questions/2657935/checking-for-a-dirty-index-or-untracked-files-with-git
exec(
'git diff-index HEAD && git ls-files --exclude-standard --others',
{ cwd: directory },
(err, stdout, stderr) => {
if (err) {
throw err
} else {
const is_dirty = stdout.trim().length !== 0
exec(
'git rev-parse --short=N HEAD',
{ cwd: directory },
(err, stdout, stderr) => {
if (err) {
throw err
} else {
const sha = stdout.split('\n').join('')
const commit = `${ sha }${ is_dirty ? '-dirty' : '' }`
callback({ commit, is_dirty })
}
}
)
}
}
)
} | const fs = require('fs-extra')
const { exec } = require('child_process')
const path = require('path')
module.exports = function getCurrentCommit (directory, callback) {
// If not a git repository, return null.
if (!fs.existsSync(path.join(directory, '.git'))) {
callback(null)
}
// http://stackoverflow.com/questions/2657935/checking-for-a-dirty-index-or-untracked-files-with-git
exec(
'git diff-index HEAD && git ls-files --exclude-standard --others',
{ cwd: directory },
(err, stdout, stderr) => {
if (err) {
throw err
} else {
const is_dirty = stdout.trim().length !== 0
exec(
'git rev-parse --short=N HEAD',
{ cwd: directory },
(err, stdout, stderr) => {
if (err) {
throw err
} else {
const sha = stdout.split('\n').join('')
const commit = `${ sha }${ is_dirty ? '-dirty' : '' }`
callback({ commit, is_dirty })
}
}
)
}
}
)
} |
Fix data erasure API test to use POST method
(was previously done via GET request) | const frisby = require('frisby')
const jsonHeader = { 'content-type': 'application/json' }
const REST_URL = 'http://localhost:3000/rest'
describe('/rest/user/erasure-request', () => {
it('Erasure request does not actually delete the user', () => {
return frisby.post(REST_URL + '/user/login', {
headers: jsonHeader,
body: {
email: '[email protected]',
password: 'bW9jLmxpYW1lbGdvb2dAaGNpbmltbWlrLm5yZW9qYg=='
}
})
.expect('status', 200)
.then(({ json: jsonLogin }) => {
return frisby.post(REST_URL + '/user/erasure-request', {
headers: { 'Authorization': 'Bearer ' + jsonLogin.authentication.token }
})
.expect('status', 202)
.then(() => {
return frisby.post(REST_URL + '/user/login', {
headers: jsonHeader,
body: {
email: '[email protected]',
password: 'bW9jLmxpYW1lbGdvb2dAaGNpbmltbWlrLm5yZW9qYg=='
}
})
.expect('status', 200)
})
})
})
})
| const frisby = require('frisby')
const jsonHeader = { 'content-type': 'application/json' }
const REST_URL = 'http://localhost:3000/rest'
describe('/rest/user/erasure-request', () => {
it('Erasure request does not actually delete the user', () => {
return frisby.post(REST_URL + '/user/login', {
headers: jsonHeader,
body: {
email: '[email protected]',
password: 'bW9jLmxpYW1lbGdvb2dAaGNpbmltbWlrLm5yZW9qYg=='
}
})
.expect('status', 200)
.then(({ json: jsonLogin }) => {
return frisby.get(REST_URL + '/user/erasure-request', {
headers: { 'Authorization': 'Bearer ' + jsonLogin.authentication.token }
})
.expect('status', 202)
.then(() => {
return frisby.post(REST_URL + '/user/login', {
headers: jsonHeader,
body: {
email: '[email protected]',
password: 'bW9jLmxpYW1lbGdvb2dAaGNpbmltbWlrLm5yZW9qYg=='
}
})
.expect('status', 200)
})
})
})
})
|
Replace phpdoc blocks by language type hints | <?php
namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook;
use Symfony\Component\Process\Process;
class HookCopier
{
private $hookDir = '.git/hooks/';
public function copyPreCommitHook(): void
{
$this->copyHookFile('pre-commit');
}
public function copyCommitMsgHook(): void
{
$this->copyHookFile('commit-msg');
}
public function copyPrePushHook(): void
{
$this->copyHookFile('pre-push');
}
private function hookExists(string $hookFile): bool
{
return file_exists(sprintf('%s%s', $this->hookDir, $hookFile));
}
private function copyFile(string $hookFile): void
{
$copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir));
$copy->run();
}
private function setPermissions(string $hookFile): void
{
$permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile));
$permissions->run();
}
private function copyHookFile(string $file): void
{
if (false === $this->hookExists($file)) {
$this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file));
$this->setPermissions($file);
}
}
}
| <?php
namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook;
use Symfony\Component\Process\Process;
class HookCopier
{
private $hookDir = '.git/hooks/';
public function copyPreCommitHook()
{
$this->copyHookFile('pre-commit');
}
public function copyCommitMsgHook()
{
$this->copyHookFile('commit-msg');
}
public function copyPrePushHook()
{
$this->copyHookFile('pre-push');
}
/**
* @param string $hookFile
*
* @return bool
*/
private function hookExists($hookFile)
{
return file_exists(sprintf('%s%s', $this->hookDir, $hookFile));
}
/**
* @param string $hookFile
*/
private function copyFile($hookFile)
{
$copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir));
$copy->run();
}
/**
* @param $hookFile
*/
private function setPermissions($hookFile)
{
$permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile));
$permissions->run();
}
/**
* @param string $file
*/
private function copyHookFile($file)
{
if (false === $this->hookExists($file)) {
$this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file));
$this->setPermissions($file);
}
}
}
|
Add new-line at EOF, when dumping userdb | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self[event.target][nick]
except KeyError:
for i in self[event.target].values():
if i['host'] == event.source.host:
del self[event.target][i['hostmask'].split("!")[0]]
break
def add_entry(self, channel, nick, hostmask, account):
temp = {
'hostmask': hostmask,
'host': hostmask.split("@")[1],
'account': account,
'seen': [__import__("time").time(), ""]
}
failed = False
try:
user = self[channel][nick]
except KeyError:
failed = True
self[channel][nick] = temp
if not failed:
del temp['seen']
user.update(temp)
def get_user_host(self, channel, nick):
try:
host = "*!*@" + self[channel][nick]['host']
except KeyError:
self.irc.send("WHO {0} nuhs%nhuac".format(channel))
host = "*!*@" + self[channel][nick]['host']
return host
def flush(self):
with open('userdb.json', 'w') as f:
json.dump(self, f, indent=2, separators=(',', ': '))
f.write("\n")
| import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self[event.target][nick]
except KeyError:
for i in self[event.target].values():
if i['host'] == event.source.host:
del self[event.target][i['hostmask'].split("!")[0]]
break
def add_entry(self, channel, nick, hostmask, account):
temp = {
'hostmask': hostmask,
'host': hostmask.split("@")[1],
'account': account,
'seen': [__import__("time").time(), ""]
}
failed = False
try:
user = self[channel][nick]
except KeyError:
failed = True
self[channel][nick] = temp
if not failed:
del temp['seen']
user.update(temp)
def get_user_host(self, channel, nick):
try:
host = "*!*@" + self[channel][nick]['host']
except KeyError:
self.irc.send("WHO {0} nuhs%nhuac".format(channel))
host = "*!*@" + self[channel][nick]['host']
return host
def flush(self):
with open('userdb.json', 'w') as f:
json.dump(self, f, indent=2, separators=(',', ': '))
|
Use most_fields as search type | var module = angular.module('JGivenApp',['ngSanitize']);
var elasticSearchHost = 'localhost'
module.controller(
'ApplicationController',
['$scope', '$http',
function( $scope, $http ) {
$scope.getScenarios = function() {
console.log("Searching for "+$scope.search);
data = {
query: {
multi_match: {
query: $scope.search,
type: 'most_fields',
fields: ['description', '_all']
}
},
size: 20,
highlight : {
fields : {
"description" : {}
}
}
};
$http({
method: 'POST',
url: 'http://' + elasticSearchHost + ':9200/r14.9/scenario/_search?pretty=true',
data: data
}).success( function(data) {
console.log( JSON.stringify( data.hits.hits ) );
$scope.searchResult = data;
$scope.scenarios = data.hits.hits;
});
};
$scope.trustHtml = function( html ) {
return $sce.trustAsHtml( html );
};
}
]);
| var module = angular.module('JGivenApp',['ngSanitize']);
var elasticSearchHost = 'localhost'
module.controller(
'ApplicationController',
['$scope', '$http',
function( $scope, $http ) {
$scope.getScenarios = function() {
console.log("Searching for "+$scope.search);
data = {
query: {
multi_match: {
query: $scope.search,
fields: ['description', '_all']
}
},
size: 20,
highlight : {
fields : {
"description" : {}
}
}
};
$http({
method: 'POST',
url: 'http://' + elasticSearchHost + ':9200/r14.9/scenario/_search?pretty=true',
data: data
}).success( function(data) {
console.log( JSON.stringify( data.hits.hits ) );
$scope.searchResult = data;
$scope.scenarios = data.hits.hits;
});
};
$scope.trustHtml = function( html ) {
return $sce.trustAsHtml( html );
};
}
]);
|
Check email before user email validator | <?php
namespace Gitonomy\Bundle\FrontendBundle\Validation\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Bundle\DoctrineBundle\Registry;
class UserEmailValidator extends ConstraintValidator
{
/**
* @var Symfony\Bundle\DoctrineBundle\Registry
*/
protected $doctrineRegistry;
function __construct(Registry $doctrineRegistry)
{
$this->doctrineRegistry = $doctrineRegistry;
}
public function isValid($value, Constraint $constraint)
{
if (null === $value) {
return true;
}
if (false === filter_var($value, FILTER_VALIDATE_EMAIL)) {
return true;
}
$count = $this->doctrineRegistry
->getRepository('GitonomyCoreBundle:Email')
->createQueryBuilder('e')
->select('COUNT(e)')
->where('e.email = :email')
->setParameters(array(
'email' => $value
))
->getQuery()
->getSingleScalarResult()
;
if ($count == 0) {
$this->setMessage($constraint->message);
return false;
}
return true;
}
}
| <?php
namespace Gitonomy\Bundle\FrontendBundle\Validation\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Bundle\DoctrineBundle\Registry;
class UserEmailValidator extends ConstraintValidator
{
/**
* @var Symfony\Bundle\DoctrineBundle\Registry
*/
protected $doctrineRegistry;
function __construct(Registry $doctrineRegistry)
{
$this->doctrineRegistry = $doctrineRegistry;
}
public function isValid($value, Constraint $constraint)
{
if (null === $value) {
return true;
}
$count = $this->doctrineRegistry
->getRepository('GitonomyCoreBundle:Email')
->createQueryBuilder('e')
->select('COUNT(e)')
->where('e.email = :email')
->setParameters(array(
'email' => $value
))
->getQuery()
->getSingleScalarResult()
;
if ($count == 0) {
$this->setMessage($constraint->message);
return false;
}
return true;
}
}
|
Add new scope for every film element, to avoid rewriting genre massive. | app.directive('film', function() {
return{
restrict: 'E',
scope: {},
controller: function($scope){
$scope.genres = [];
this.addGenres = function(genres){
$scope.genres = $scope.genres.concat(genres);
};
},
link: function(scope, element){
element.addClass('info');
element.bind('mouseenter', function(){
console.log(scope.genres);
});
}
};
});
app.directive('genre', function(){
return {
require: "film",
link: function(scope, element, attrs, filmCtrl){
var genres = attrs.genre.split(" ");
filmCtrl.addGenres(genres);
}
};
});
app.directive('mouseenter', function(){
return function(scope, element){
element.bind('mouseenter', function(){
element.addClass('active');
});
}
});
app.directive('mouseleave', function(){
return function(scope, element){
element.bind('mouseleave', function(){
element.removeClass('active');
});
}
});
app.directive('load', function(){
return function(scope, element, attrs){
element.bind("click", function(){
scope.$apply(attrs.load);
});
};
}); | app.directive('film', function() {
return{
restrict: 'E',
controller: function($scope){
$scope.genres = [];
this.addGenres = function(genres){
$scope.genres = $scope.genres.concat(genres);
};
},
link: function(scope, element){
element.addClass('info');
element.bind('mouseenter', function(){
console.log(scope.genres);
});
}
};
});
app.directive('genre', function(){
return {
require: "film",
link: function(scope, element, attrs, filmCtrl){
var genres = attrs.genre.split(" ");
filmCtrl.addGenres(genres);
}
};
});
app.directive('mouseenter', function(){
return function(scope, element){
element.bind('mouseenter', function(){
element.addClass('active');
});
}
});
app.directive('mouseleave', function(){
return function(scope, element){
element.bind('mouseleave', function(){
element.removeClass('active');
});
}
});
app.directive('load', function(){
return function(scope, element, attrs){
element.bind("click", function(){
scope.$apply(attrs.load);
});
};
}); |
Add some error handling around releasing wake locks | package com.markupartist.sthlmtraveling.service;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
abstract public class WakefulIntentService extends IntentService {
private static String TAG = "WakefulIntentService";
public static final String LOCK_NAME =
"com.markupartist.sthlmtraveling.service.WakefulIntentService.Static";
private static PowerManager.WakeLock lockStatic = null;
public WakefulIntentService(String name) {
super(name);
}
synchronized private static PowerManager.WakeLock getLock(Context context) {
if (lockStatic == null) {
PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME);
lockStatic.setReferenceCounted(true);
}
return (lockStatic);
}
abstract void doWakefulWork(Intent intent);
public static void acquireStaticLock(Context context) {
Log.d(TAG, "About acquire static lock");
getLock(context).acquire();
}
@Override
final protected void onHandleIntent(Intent intent) {
try {
doWakefulWork(intent);
} finally {
PowerManager.WakeLock lock = getLock(getApplicationContext());
if (lock.isHeld()) {
try {
lock.release();
} catch (Exception e) {
Log.e(TAG, "Exception when releasing wakelock");
}
}
}
}
}
| package com.markupartist.sthlmtraveling.service;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
abstract public class WakefulIntentService extends IntentService {
private static String TAG = "WakefulIntentService";
public static final String LOCK_NAME_STATIC =
"com.markupartist.sthlmtraveling.service.WakefulIntentService.Static";
private static PowerManager.WakeLock lockStatic = null;
public WakefulIntentService(String name) {
super(name);
}
synchronized private static PowerManager.WakeLock getLock(Context context) {
Log.d(TAG, "About to get lock");
if (lockStatic == null) {
PowerManager mgr =
(PowerManager)context.getSystemService(Context.POWER_SERVICE);
lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
LOCK_NAME_STATIC);
lockStatic.setReferenceCounted(true);
}
return lockStatic;
}
abstract void doWakefulWork(Intent intent);
public static void acquireStaticLock(Context context) {
Log.d(TAG, "About acquire static lock");
getLock(context).acquire();
}
@Override
final protected void onHandleIntent(Intent intent) {
doWakefulWork(intent);
getLock(this).release();
}
}
|
Add fix to ace worker loading error | hqDefine('app_manager/js/download_index_main',[
'jquery',
'underscore',
'ace-builds/src-min-noconflict/ace',
'app_manager/js/download_async_modal',
'app_manager/js/source_files',
],function ($, _, ace) {
// work around with ace issue https://github.com/ajaxorg/ace/issues/732 also see the linked open issue.
ace.require("ace/edit_session").EditSession.prototype.$startWorker = function () {};
$(function () {
var elements = $('.prettyprint');
_.each(elements, function (elem) {
var editor = ace.edit(
elem,
{
showPrintMargin: false,
maxLines: 40,
minLines: 3,
fontSize: 14,
wrap: true,
useWorker: false, // enable the worker to show syntax errors
}
);
var fileName = $(elem).data('filename');
if (fileName.endsWith('json')) {
editor.session.setMode('ace/mode/json');
} else {
editor.session.setMode('ace/mode/xml');
}
editor.setReadOnly(true);
});
});
}); | hqDefine('app_manager/js/download_index_main',[
'jquery',
'underscore',
'ace-builds/src-min-noconflict/ace',
'app_manager/js/download_async_modal',
'app_manager/js/source_files',
],function ($, _, ace) {
ace.require("ace/config").set("packaged", false);
$(function () {
var elements = $('.prettyprint');
_.each(elements, function (elem) {
var editor = ace.edit(
elem,
{
showPrintMargin: false,
maxLines: 40,
minLines: 3,
fontSize: 14,
wrap: true,
useWorker: false, // enable the worker to show syntax errors
}
);
var fileName = $(elem).data('filename');
if (fileName.endsWith('json')) {
editor.session.setMode('ace/mode/json');
} else {
editor.session.setMode('ace/mode/xml');
}
editor.setReadOnly(true);
});
});
}); |
Add optional event_cmd bash file into the docs | from i3pystatus import IntervalModule
class Pianobar(IntervalModule):
"""
Shows the title and artist name of the current music
In pianobar config file must be setted the fifo and event_command options
(see man pianobar for more information)
For the event_cmd use:
https://github.com/jlucchese/pianobar/blob/master/contrib/pianobar-song-i3.sh
Mouse events:
- Left click play/pauses
- Right click plays next song
- Scroll up/down changes volume
"""
settings = (
("format"),
("songfile", "File generated by pianobar eventcmd"),
("ctlfile", "Pianobar fifo file"),
("color", "The color of the text"),
)
format = "{songtitle} -- {songartist}"
required = ("format", "songfile", "ctlfile")
color = "#FFFFFF"
def run(self):
with open(self.songfile, "r") as f:
contents = f.readlines()
sn = contents[0].strip()
sa = contents[1].strip()
self.output = {
"full_text": self.format.format(songtitle=sn, songartist=sa),
"color": self.color
}
def on_leftclick(self):
open(self.ctlfile, "w").write("p")
def on_rightclick(self):
open(self.ctlfile, "w").write("n")
def on_upscroll(self):
open(self.ctlfile, "w").write(")")
def on_downscroll(self):
open(self.ctlfile, "w").write("(")
| from i3pystatus import IntervalModule
class Pianobar(IntervalModule):
"""
Shows the title and artist name of the current music
In pianobar config file must be setted the fifo and event_command options
(see man pianobar for more information)
Mouse events:
- Left click play/pauses
- Right click plays next song
- Scroll up/down changes volume
"""
settings = (
("format"),
("songfile", "File generated by pianobar eventcmd"),
("ctlfile", "Pianobar fifo file"),
("color", "The color of the text"),
)
format = "{songtitle} -- {songartist}"
required = ("format", "songfile", "ctlfile")
color = "#FFFFFF"
def run(self):
with open(self.songfile, "r") as f:
contents = f.readlines()
sn = contents[0].strip()
sa = contents[1].strip()
self.output = {
"full_text": self.format.format(songtitle=sn, songartist=sa),
"color": self.color
}
def on_leftclick(self):
open(self.ctlfile, "w").write("p")
def on_rightclick(self):
open(self.ctlfile, "w").write("n")
def on_upscroll(self):
open(self.ctlfile, "w").write(")")
def on_downscroll(self):
open(self.ctlfile, "w").write("(")
|
Fix buffering issue in udp bridge | #!/usr/bin/env python
import select
import serial
import socket
def run_lux_udp(host, port, dev):
with serial.Serial(dev, baudrate=3000000, xonxoff=False) as ser:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
last_addr = None
serial_buffer = ""
while True:
inputs, outputs, errors = select.select([sock.fileno(), ser.fileno()], [], [])
while sock.fileno() in inputs:
try:
packet, last_addr = sock.recvfrom(1100, socket.MSG_DONTWAIT)
except socket.error:
break
#print ">", repr(packet)
if len(packet) == 0: # Ping, respond back
sock.sendto("", 0, last_addr)
else:
ser.write(packet)
if ser.fileno() in inputs:
serial_buffer += ser.read()
while "\0" in serial_buffer:
packet, null, serial_buffer = serial_buffer.partition("\0")
sock.sendto(packet + null, 0, last_addr)
#print "<", repr(packet)
if __name__ == "__main__":
while True:
try:
run_lux_udp(host="0.0.0.0", port=1365, dev="/dev/ttyACM0")
except Exception as e:
print e
select.select([], [], [], 5)
| #!/usr/bin/env python
import select
import serial
import socket
def run_lux_udp(host, port, dev):
with serial.Serial(dev, baudrate=3000000, xonxoff=False) as ser:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
last_addr = None
serial_buffer = ""
while True:
inputs, outputs, errors = select.select([sock.fileno(), ser.fileno()], [], [])
if sock.fileno() in inputs:
packet, last_addr = sock.recvfrom(1100)
#print ">", repr(packet)
if len(packet) == 0: # Ping, respond back
sock.sendto("", 0, last_addr)
else:
ser.write(packet)
if ser.fileno() in inputs:
serial_buffer += ser.read()
while "\0" in serial_buffer:
packet, null, serial_buffer = serial_buffer.partition("\0")
sock.sendto(packet + null, 0, last_addr)
#print "<", repr(packet)
if __name__ == "__main__":
while True:
try:
run_lux_udp(host="0.0.0.0", port=1365, dev="/dev/ttyACM0")
except Exception as e:
print e
select.select([], [], [], 5)
|
Fix model config to alter on every change | /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
connection: 'someMongodbServer',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
migrate: 'alter'
};
| /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
connection: 'someMongodbServer',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
//migrate: 'alter'
};
|
Enable mirage on production for now | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
i18n: {
defaultLocale: 'en',
},
emblemOptions: {
blueprints: false
},
modulePrefix: 'irene',
environment: environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
'ember-simple-auth': {
loginEndPoint: '/login',
checkEndPoint: '/check',
logoutEndPoint: '/logout'
}
};
if (environment === 'production') {
ENV['ember-cli-mirage'] = {
enabled: true
};
}
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
i18n: {
defaultLocale: 'en',
},
emblemOptions: {
blueprints: false
},
modulePrefix: 'irene',
environment: environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
'ember-simple-auth': {
loginEndPoint: '/login',
checkEndPoint: '/check',
logoutEndPoint: '/logout'
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Rename directory for Toki Pona recordings
See parent commit. | <?php
use Cake\Core\Configure;
use Migrations\AbstractMigration;
class TokiPonaCodeRename extends AbstractMigration
{
private $langColumns = [
'contributions' => ['sentence_lang', 'translation_lang'],
'contributions_stats' => ['lang'],
'languages' => ['code'],
'last_contributions' => ['sentence_lang', 'translation_lang'],
'reindex_flags' => ['lang'],
'sentence_comments' => ['lang'],
'sentences' => ['lang'],
'sentences_translations' => ['sentence_lang', 'translation_lang'],
'users_languages' => ['language_code'],
'vocabulary' => ['lang'],
];
private $oldCode = 'toki';
private $newCode = 'tok';
private function updateCode($from, $to) {
foreach ($this->langColumns as $table => $columns) {
foreach ($columns as $column) {
$this->getQueryBuilder()
->update($table)
->set($column, $to)
->where([$column => $from])
->execute();
}
}
$audioBasePath = Configure::read('Recordings.path');
if (is_dir($audioBasePath.DS.$from)) {
rename($audioBasePath.DS.$from, $audioBasePath.DS.$to);
}
}
public function up() {
$this->updateCode($this->oldCode, $this->newCode);
}
public function down() {
$this->updateCode($this->newCode, $this->oldCode);
}
}
| <?php
use Migrations\AbstractMigration;
class TokiPonaCodeRename extends AbstractMigration
{
private $langColumns = [
'contributions' => ['sentence_lang', 'translation_lang'],
'contributions_stats' => ['lang'],
'languages' => ['code'],
'last_contributions' => ['sentence_lang', 'translation_lang'],
'reindex_flags' => ['lang'],
'sentence_comments' => ['lang'],
'sentences' => ['lang'],
'sentences_translations' => ['sentence_lang', 'translation_lang'],
'users_languages' => ['language_code'],
'vocabulary' => ['lang'],
];
private $oldCode = 'toki';
private $newCode = 'tok';
private function updateCode($from, $to) {
foreach ($this->langColumns as $table => $columns) {
foreach ($columns as $column) {
$this->getQueryBuilder()
->update($table)
->set($column, $to)
->where([$column => $from])
->execute();
}
}
}
public function up() {
$this->updateCode($this->oldCode, $this->newCode);
}
public function down() {
$this->updateCode($this->newCode, $this->oldCode);
}
}
|
Add a css loader to import global style from external components | var rucksack = require('rucksack-css')
var webpack = require('webpack')
var path = require('path')
module.exports = {
context: path.join(__dirname, './client'),
entry: {
jsx: './index.js',
html: './index.html',
vendor: ['react']
},
output: {
path: path.join(__dirname, './static'),
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.html$/,
loader: 'file?name=[name].[ext]'
},
{
test: /\.css$/,
include: /client/,
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'postcss-loader'
]
},
{
test: /\.css$/,
exclude: /client/,
loader: 'style!css'
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loaders: [
'react-hot',
'babel-loader'
]
},
],
},
resolve: {
extensions: ['', '.js', '.jsx']
},
postcss: [
rucksack({
autoprefixer: true
})
],
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
})
],
devServer: {
contentBase: './client',
hot: true
}
}
| var rucksack = require('rucksack-css')
var webpack = require('webpack')
var path = require('path')
module.exports = {
context: path.join(__dirname, './client'),
entry: {
jsx: './index.js',
html: './index.html',
vendor: ['react']
},
output: {
path: path.join(__dirname, './static'),
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.html$/,
loader: 'file?name=[name].[ext]'
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'postcss-loader'
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loaders: [
'react-hot',
'babel-loader'
]
},
],
},
resolve: {
extensions: ['', '.js', '.jsx']
},
postcss: [
rucksack({
autoprefixer: true
})
],
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
})
],
devServer: {
contentBase: './client',
hot: true
}
}
|
Remove a for loop in favour of a dict comprehension |
from contextlib import contextmanager
from functools import wraps
from fastats.core.ast_transforms.convert_to_jit import convert_to_jit
from fastats.core.ast_transforms.processor import AstProcessor
@contextmanager
def code_transform(func, replaced):
try:
yield func
finally:
for k, v in replaced.items():
func.__globals__[k] = v
replaced.clear()
def fs(func):
# The initial function *must* be jittable,
# else we can't do anything.
_func = func
replaced = {}
@wraps(func)
def fs_wrapper(*args, **kwargs):
return_callable = kwargs.pop('return_callable', None)
if not kwargs:
return _func(*args)
with code_transform(_func, replaced) as _f:
# TODO : remove fastats keywords such as 'debug'
# before passing into AstProcessor
new_funcs = {v.__name__: convert_to_jit(v) for v in kwargs.values()
if v.__name__ not in kwargs}
kwargs = {k: convert_to_jit(v) for k, v in kwargs.items()}
processor = AstProcessor(_f, kwargs, replaced, new_funcs)
proc = processor.process()
if return_callable:
return convert_to_jit(proc)
return convert_to_jit(proc)(*args)
return fs_wrapper
|
from contextlib import contextmanager
from functools import wraps
from fastats.core.ast_transforms.convert_to_jit import convert_to_jit
from fastats.core.ast_transforms.processor import AstProcessor
@contextmanager
def code_transform(func, replaced):
try:
yield func
finally:
for k, v in replaced.items():
func.__globals__[k] = v
replaced.clear()
def fs(func):
# The initial function *must* be jittable,
# else we can't do anything.
_func = func
replaced = {}
@wraps(func)
def fs_wrapper(*args, **kwargs):
return_callable = kwargs.pop('return_callable', None)
if not kwargs:
return _func(*args)
with code_transform(_func, replaced) as _f:
# TODO : remove fastats keywords such as 'debug'
# before passing into AstProcessor
new_funcs = {}
for v in kwargs.values():
if v.__name__ in kwargs:
continue
new_funcs[v.__name__] = convert_to_jit(v)
kwargs = {k: convert_to_jit(v) for k, v in kwargs.items()}
processor = AstProcessor(_f, kwargs, replaced, new_funcs)
proc = processor.process()
if return_callable:
return convert_to_jit(proc)
return convert_to_jit(proc)(*args)
return fs_wrapper
|
Add fast-math back to compiler options, now that anaconda can handle it
Closes #13
See https://github.com/ContinuumIO/anaconda-issues/issues/182 | #!/usr/bin/env python
# Copyright (c) 2014, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from auto_version import calculate_version, build_py_copy_version
def configuration(parent_package='', top_path=None):
import numpy
from distutils.errors import DistutilsError
if numpy.__dict__.get('quaternion') is not None:
raise DistutilsError('The target NumPy already has a quaternion type')
from numpy.distutils.misc_util import Configuration
# if(os.environ.get('THIS_IS_TRAVIS') is not None):
# print("This appears to be Travis!")
# compile_args = ['-O3']
# else:
# compile_args = ['-ffast-math', '-O3']
compile_args = ['-ffast-math', '-O3']
config = Configuration('quaternion', parent_package, top_path)
config.add_extension('numpy_quaternion',
['quaternion.c', 'numpy_quaternion.c'],
depends=['quaternion.c', 'quaternion.h', 'numpy_quaternion.c'],
extra_compile_args=compile_args, )
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(configuration=configuration,
version=calculate_version(),
cmdclass={'build_py': build_py_copy_version},)
| #!/usr/bin/env python
# Copyright (c) 2014, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from auto_version import calculate_version, build_py_copy_version
def configuration(parent_package='', top_path=None):
import numpy
from distutils.errors import DistutilsError
if numpy.__dict__.get('quaternion') is not None:
raise DistutilsError('The target NumPy already has a quaternion type')
from numpy.distutils.misc_util import Configuration
# if(os.environ.get('THIS_IS_TRAVIS') is not None):
# print("This appears to be Travis!")
# compile_args = ['-O3']
# else:
# compile_args = ['-ffast-math', '-O3']
compile_args = ['-O3']
config = Configuration('quaternion', parent_package, top_path)
config.add_extension('numpy_quaternion',
['quaternion.c', 'numpy_quaternion.c'],
depends=['quaternion.c', 'quaternion.h', 'numpy_quaternion.c'],
extra_compile_args=compile_args, )
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(configuration=configuration,
version=calculate_version(),
cmdclass={'build_py': build_py_copy_version},)
|
Implement input API as spec'd in oonib.md | import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config, log
class InputDescHandler(OONIBHandler):
def get(self, inputID):
bn = os.path.basename(inputID) + ".desc"
try:
f = open(os.path.join(config.main.input_dir, bn))
a = {}
inputDesc = yaml.safe_load(f)
for k in ['name', 'description', 'version', 'author', 'date']:
a[k] = inputDesc[k]
self.write(json.dumps(a))
except IOError:
log.err("No Input Descriptor found for id %s" % inputID)
except Exception, e:
log.err("Invalid Input Descriptor found for id %s" % inputID)
class InputListHandler(OONIBHandler):
def get(self):
path = os.path.abspath(config.main.input_dir) + "/*.desc"
inputnames = map(os.path.basename, glob.iglob(path))
inputList = []
for inputname in inputnames:
f = open(os.path.join(config.main.input_dir, inputname))
d = yaml.safe_load(f)
inputList.append({
'id': inputname,
'name': d['name'],
'description': d['description']
})
f.close()
self.write(json.dumps(inputList))
| import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config
class InputDescHandler(OONIBHandler):
def get(self, inputID):
#XXX return the input descriptor
# see oonib.md in ooni-spec
bn = os.path.basename(inputID) + ".desc"
try:
f = open(os.path.join(config.main.input_dir, bn))
a = {}
inputDesc = yaml.safe_load(f)
a['id'] = inputID
a['name'] = inputDesc['name']
a['description'] = inputDesc['description']
self.write(json.dumps(a))
except Exception:
log.err("No Input Descriptor found for id %s" % inputID)
class InputListHandler(OONIBHandler):
def get(self):
path = os.path.abspath(config.main.input_dir) + "/*.desc"
inputnames = map(os.path.basename, glob.iglob(path))
inputList = []
for inputname in inputnames:
f = open(os.path.join(config.main.input_dir, inputname))
d = yaml.safe_load(f)
inputList.append({
'id': inputname,
'name': d['name'],
'description': d['description']
})
f.close()
self.write(json.dumps(inputList))
|
Use - instead of _ when converting filename in file upload | Ext2.ns('Kwc.Basic.DownloadTag');
Kwc.Basic.DownloadTag.Panel = Ext2.extend(Ext2.Panel, {
initComponent: function() {
Kwc.Basic.DownloadTag.Panel.superclass.initComponent.call(this);
this.findByType('kwf.file')[0].on('uploaded', function(field, value) {
if (value) {
this.ownerCt.find('autoFillWithFilename', 'filename').forEach(function (f) {
var v = value.uploaded_filename || value.filename;
v = v.toLowerCase().replace(/ä/g, 'ae').replace(/ö/g, 'oe')
.replace(/ü/g, 'ue').replace(/ß/g, 'ss')
.replace(/[^a-z0-9]/g, '-').replace(/--+/g, '-');
f.setValue(v);
}, this);
this.ownerCt.find('autoFillWithFilename', 'filenameWithExt').forEach(function (f) {
if (f.getValue() == '') {
f.setValue(value.filename+'.'+value.extension);
}
}, this);
}
}, this);
}
});
Ext2.reg('Kwc.Basic.DownloadTag', Kwc.Basic.DownloadTag.Panel);
| Ext2.ns('Kwc.Basic.DownloadTag');
Kwc.Basic.DownloadTag.Panel = Ext2.extend(Ext2.Panel, {
initComponent: function() {
Kwc.Basic.DownloadTag.Panel.superclass.initComponent.call(this);
this.findByType('kwf.file')[0].on('uploaded', function(field, value) {
if (value) {
this.ownerCt.find('autoFillWithFilename', 'filename').forEach(function (f) {
var v = value.uploaded_filename || value.filename;
v = v.toLowerCase().replace(/ä/g, 'ae').replace(/ö/g, 'oe')
.replace(/ü/g, 'ue').replace(/ß/g, 'ss')
.replace(/[^a-z0-9]/g, '_').replace(/__+/g, '_');
f.setValue(v);
}, this);
this.ownerCt.find('autoFillWithFilename', 'filenameWithExt').forEach(function (f) {
if (f.getValue() == '') {
f.setValue(value.filename+'.'+value.extension);
}
}, this);
}
}, this);
}
});
Ext2.reg('Kwc.Basic.DownloadTag', Kwc.Basic.DownloadTag.Panel);
|
Fix getting registrations error if no project id | <?php
namespace MapasCulturais\Repositories;
use MapasCulturais\Traits;
class Registration extends \MapasCulturais\Repository{
/**
*
* @param \MapasCulturais\Entities\Project $project
* @param \MapasCulturais\Entities\User $user
* @return \MapasCulturais\Entities\Registration[]
*/
function findByProjectAndUser(\MapasCulturais\Entities\Project $project, $user){
if($user->is('guest') || !$project->id){
return array();
}
$dql = "
SELECT
r
FROM
MapasCulturais\Entities\Registration r
LEFT JOIN MapasCulturais\Entities\RegistrationAgentRelation rar WITH rar.owner = r
WHERE
r.project = :project AND
(
r.owner IN (:agents) OR
rar.agent IN (:agents)
)";
$q = $this->_em->createQuery($dql);
$q->setParameters(array(
'project' => $project,
'agents' => $user->agents ? $user->agents->toArray() : array(-1)
));
return $q->getResult();
}
} | <?php
namespace MapasCulturais\Repositories;
use MapasCulturais\Traits;
class Registration extends \MapasCulturais\Repository{
/**
*
* @param \MapasCulturais\Entities\Project $project
* @param \MapasCulturais\Entities\User $user
* @return \MapasCulturais\Entities\Registration[]
*/
function findByProjectAndUser(\MapasCulturais\Entities\Project $project, $user){
if($user->is('guest')){
return array();
}
$dql = "
SELECT
r
FROM
MapasCulturais\Entities\Registration r
LEFT JOIN MapasCulturais\Entities\RegistrationAgentRelation rar WITH rar.owner = r
WHERE
r.project = :project AND
(
r.owner IN (:agents) OR
rar.agent IN (:agents)
)";
$q = $this->_em->createQuery($dql);
$q->setParameters(array(
'project' => $project,
'agents' => $user->agents ? $user->agents->toArray() : array(-1)
));
return $q->getResult();
}
} |
Return from exit condition sooner
Since an array doesn't need to be converted to itself, there's
no reason to go any further in this method. | <?php
namespace Haystack\Functional;
use Haystack\Container\ContainerInterface;
use Haystack\HArray;
use Haystack\Helpers\Helper;
use Haystack\HString;
class HaystackMap
{
/** @var array */
private $arr;
/**
* @param HArray $array
*/
public function __construct(HArray $array)
{
$this->arr = $array->toArray();
}
/**
* @param callable $func
* @param array $variadicList Variadic list of arrays to invoke array_map with
* @return array
*/
public function map(callable $func, array $variadicList = [])
{
$sourceHaystack = [$this->arr];
$arrayOfVariadics = array_map(function ($item) {
return $this->convertToArray($item);
}, $variadicList);
return call_user_func_array('array_map', array_merge([$func], $sourceHaystack, $arrayOfVariadics));
}
private function convertToArray($item)
{
if (is_array($item)) {
return $item;
}
if (is_string($item)) {
return (new HString($item))->toArray();
}
if ($item instanceof ContainerInterface) {
return $item->toArray();
}
throw new \InvalidArgumentException(Helper::getType($item) . " cannot be mapped");
}
}
| <?php
namespace Haystack\Functional;
use Haystack\Container\ContainerInterface;
use Haystack\HArray;
use Haystack\Helpers\Helper;
use Haystack\HString;
class HaystackMap
{
/** @var array */
private $arr;
/**
* @param HArray $array
*/
public function __construct(HArray $array)
{
$this->arr = $array->toArray();
}
/**
* @param callable $func
* @param array $variadicList Variadic list of arrays to invoke array_map with
* @return array
*/
public function map(callable $func, array $variadicList = [])
{
$sourceHaystack = [$this->arr];
$arrayOfVariadics = array_map(function ($item) {
return $this->convertToArray($item);
}, $variadicList);
return call_user_func_array('array_map', array_merge([$func], $sourceHaystack, $arrayOfVariadics));
}
private function convertToArray($item)
{
if (is_string($item)) {
return (new HString($item))->toArray();
}
if ($item instanceof ContainerInterface) {
return $item->toArray();
}
if (is_array($item)) {
return $item;
}
throw new \InvalidArgumentException(Helper::getType($item) . " cannot be mapped");
}
}
|
Remove Time component's dependency on utils | /*
* Semantic time element
*/
define(['react', 'moment'], function(React, Moment) {
var Time = React.createClass({
propTypes: {
date: React.PropTypes.instanceOf(Date),
showAbsolute: React.PropTypes.bool,
showRelative: React.PropTypes.bool
},
getDefaultProps: function() {
return {
showAbsolute: true,
showRelative: true
};
},
render: function() {
var text = "";
var moment = Moment(this.props.date);
var absoluteText = moment.format("MMM D, YYYY");
var relativeText = moment.fromNow();
if (this.props.showAbsolute) {
text += absoluteText;
if (this.props.showRelative)
text += " (" + relativeText + ")";
} else if (this.props.showRelative) {
text += relativeText;
}
return React.DOM.time({
title: Moment(this.props.date).format(),
dateTime: Moment(this.props.date).utc().format()
}, text);
}
});
return Time;
});
| /*
* Semantic time element
*/
define(['react', 'utils', 'moment'], function(React, Utils, Moment) {
var Time = React.createClass({
propTypes: {
date: React.PropTypes.instanceOf(Date),
showAbsolute: React.PropTypes.bool,
showRelative: React.PropTypes.bool
},
getDefaultProps: function() {
return {
showAbsolute: true,
showRelative: true
};
},
render: function() {
var text = "";
var absoluteText = Moment(this.props.date).format("MMM D, YYYY");
var relativeText = Utils.relative_time(this.props.date);
if (this.props.showAbsolute) {
text += absoluteText;
if (this.props.showRelative)
text += " (" + relativeText + ")";
} else if (this.props.showRelative) {
text += relativeText;
}
return React.DOM.time({
title: Moment(this.props.date).format(),
dateTime: Moment(this.props.date).utc().format()
}, text);
}
});
return Time;
});
|
Adjust for renamed CSV class |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import Writer
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
if label:
self.short_description = label
def __call__(self, admin, request, queryset):
if self.serialiser is None:
ser_class = modelserialiser_factory(
'%sSerialiser' % admin.__class__.__name__,
admin.model,
**self.opts
)
else:
ser_class = self.serialiser
def inner(ser):
csv = Writer(fields=ser._fields.keys())
yield csv.write_headers()
for obj in queryset:
data = {
key: force_text(val)
for key, val in ser.object_deflate(obj).items()
}
yield csv.write_dict(data)
response = StreamingHttpResponse(inner(ser_class()), content_type='text/csv')
filename = self.opts.get('filename', 'export_{classname}.csv')
if callable(filename):
filename = filename(admin)
else:
filename = filename.format(
classname=admin.__class__.__name__,
model=admin.model._meta.module_name,
app_label=admin.model._meta.app_label,
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
|
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
if label:
self.short_description = label
def __call__(self, admin, request, queryset):
if self.serialiser is None:
ser_class = modelserialiser_factory(
'%sSerialiser' % admin.__class__.__name__,
admin.model,
**self.opts
)
else:
ser_class = self.serialiser
def inner(ser):
csv = CSV(fields=ser._fields.keys())
yield csv.write_headers()
for obj in queryset:
data = {
key: force_text(val)
for key, val in ser.object_deflate(obj).items()
}
yield csv.write_dict(data)
response = StreamingHttpResponse(inner(ser_class()), content_type='text/csv')
filename = self.opts.get('filename', 'export_{classname}.csv')
if callable(filename):
filename = filename(admin)
else:
filename = filename.format(
classname=admin.__class__.__name__,
model=admin.model._meta.module_name,
app_label=admin.model._meta.app_label,
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
|
Use fat arrows instead of that=this. Some foratting fixes | "use strict";
const medium = require('medium-sdk');
class CamayakMedium {
constructor(api_key) {
this.api_key = api_key;
// Since we use an Integration Token instead
// of oAuth login, we just enter dummy values
// for the oAuth client options.
this.client = new medium.MediumClient({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET'
});
// Then set the access token directly.
this.client.setAccessToken(this.api_key);
}
// Publish an assignment
publish(content, cb) {
this.client.getUser( (error, user) => {
if (error) {
return cb(error);
};
this.client.createPost(
{ userId: user.id,
title: content.heading,
contentFormat: medium.PostContentFormat.HTML,
content: content.content,
publishStatus: medium.PostPublishStatus.PUBLIC
},
(error, post) => {
if (error) {
return cb(error);
}
return cb(null, {published_id: post.id, published_url: post.url});
}
);
});
}
// Medium has no update capability
update(content, cb) {
// Just publish the edit as a new post on Medium
return this.publish(content, cb);
}
// Medium has no update capability
retract(content, cb) {
return cb(null, {published_id: content.published_id, published_url: content.published_url});
}
}
module.exports = CamayakMedium; | "use strict";
const medium = require('medium-sdk');
class CamayakMedium {
constructor(api_key) {
this.api_key = api_key;
// Since we use an Integration Token instead
// of oAuth login, we just enter dummy values
// for the oAuth client options.
this.client = new medium.MediumClient({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET'
});
// Then set the access token directly.
this.client.setAccessToken(this.api_key);
}
// Publish an assignment
publish(content, cb) {
var client = this.client;
client.getUser(function (error, user) {
if (error) {
return cb(error);
}
client.createPost({
userId: user.id,
title: content.heading,
contentFormat: medium.PostContentFormat.HTML,
content: content.content,
publishStatus: medium.PostPublishStatus.PUBLIC
}, function (error, post) {
if (error) {
return cb(error);
}
return cb(null, {published_id: post.id, published_url: post.url});
})
})
}
// Medium has no update capability
update(content, cb) {
// Just publish the edit as a new post on Medium
return this.publish(content, cb);
}
// Medium has no update capability
retract(content, cb) {
return cb(null, {published_id: content.published_id, published_url: content.published_url});
}
}
module.exports = CamayakMedium; |
Revert "Force boolean as not all set to true/false some are 1/0"
This reverts commit b80e83192363f6f77f70bc7a663cae9ff6ef40cd. | <?php
namespace DBAL\Tests\Caching;
use PHPUnit\Framework\TestCase;
abstract class CacheTest extends TestCase{
protected $host = '127.0.0.1';
protected $port = false;
protected $cache;
public function setUp() {
$this->cache->connect($this->host, $this->port);
if(!$this->cache->save('servicetest', 'isactive', 60)){
$this->markTestSkipped(
'No connection is available to the caching server'
);
}
}
public function tearDown() {
unset($this->cache);
}
public function testConnect(){
$this->assertObjectHasAttribute('cache', $this->cache->connect($this->host, $this->port));
}
public function testCacheAdd(){
$this->assertTrue($this->cache->save('key1', 'testvalue', 60));
}
public function testCacheRetrieve(){
$this->assertEquals('testvalue', $this->cache->fetch('key1'));
}
public function testCacheOverride(){
$this->cache->replace('key1', 'newvalue', 60);
$this->assertEquals('newvalue', $this->cache->fetch('key1'));
}
public function testCacheDelete(){
$this->assertTrue($this->cache->delete('key1'));
$this->assertFalse($this->cache->delete('key1'));
}
public function testCacheClear(){
$this->cache->save('key1', 'testvalue', 60);
$this->assertTrue($this->cache->deleteAll());
}
}
| <?php
namespace DBAL\Tests\Caching;
use PHPUnit\Framework\TestCase;
abstract class CacheTest extends TestCase{
protected $host = '127.0.0.1';
protected $port = false;
protected $cache;
public function setUp() {
$this->cache->connect($this->host, $this->port);
if(!$this->cache->save('servicetest', 'isactive', 60)){
$this->markTestSkipped(
'No connection is available to the caching server'
);
}
}
public function tearDown() {
unset($this->cache);
}
public function testConnect(){
$this->assertObjectHasAttribute('cache', $this->cache->connect($this->host, $this->port));
}
public function testCacheAdd(){
$this->assertTrue($this->cache->save('key1', 'testvalue', 60));
}
public function testCacheRetrieve(){
$this->assertEquals('testvalue', $this->cache->fetch('key1'));
}
public function testCacheOverride(){
$this->cache->replace('key1', 'newvalue', 60);
$this->assertEquals('newvalue', $this->cache->fetch('key1'));
}
public function testCacheDelete(){
$this->assertTrue($this->cache->delete('key1'));
$this->assertFalse($this->cache->delete('key1'));
}
public function testCacheClear(){
$this->cache->save('key1', 'testvalue', 60);
$this->assertTrue((bool)$this->cache->deleteAll());
}
}
|
Fix unsupported `headers` and `status` of undefined |
/**
* OAuth interceptor.
*/
function oauthInterceptor($q, $rootScope, OAuthToken) {
return {
request: function(config) {
config.headers = config.headers || {};
// Inject `Authorization` header.
if (!config.headers.hasOwnProperty('Authorization') && OAuthToken.getAuthorizationHeader()) {
config.headers.Authorization = OAuthToken.getAuthorizationHeader();
}
return config;
},
responseError: function(rejection) {
if (!rejection) {
return $q.reject(rejection);
}
// Catch `invalid_request` and `invalid_grant` errors and ensure that the `token` is removed.
if (400 === rejection.status && rejection.data &&
('invalid_request' === rejection.data.error || 'invalid_grant' === rejection.data.error)
) {
OAuthToken.removeToken();
$rootScope.$emit('oauth:error', rejection);
}
// Catch `invalid_token` and `unauthorized` errors.
// The token isn't removed here so it can be refreshed when the `invalid_token` error occurs.
if (401 === rejection.status &&
(rejection.data && 'invalid_token' === rejection.data.error) ||
(rejection.headers && rejection.headers('www-authenticate') && 0 === rejection.headers('www-authenticate').indexOf('Bearer'))
) {
$rootScope.$emit('oauth:error', rejection);
}
return $q.reject(rejection);
}
};
}
oauthInterceptor.$inject = ['$q', '$rootScope', 'OAuthToken'];
/**
* Export `oauthInterceptor`.
*/
export default oauthInterceptor;
|
/**
* OAuth interceptor.
*/
function oauthInterceptor($q, $rootScope, OAuthToken) {
return {
request: function(config) {
config.headers = config.headers || {};
// Inject `Authorization` header.
if (!config.headers.hasOwnProperty('Authorization') && OAuthToken.getAuthorizationHeader()) {
config.headers.Authorization = OAuthToken.getAuthorizationHeader();
}
return config;
},
responseError: function(rejection) {
// Catch `invalid_request` and `invalid_grant` errors and ensure that the `token` is removed.
if (400 === rejection.status && rejection.data &&
('invalid_request' === rejection.data.error || 'invalid_grant' === rejection.data.error)
) {
OAuthToken.removeToken();
$rootScope.$emit('oauth:error', rejection);
}
// Catch `invalid_token` and `unauthorized` errors.
// The token isn't removed here so it can be refreshed when the `invalid_token` error occurs.
if (401 === rejection.status &&
(rejection.data && 'invalid_token' === rejection.data.error) ||
(rejection.headers('www-authenticate') && 0 === rejection.headers('www-authenticate').indexOf('Bearer'))
) {
$rootScope.$emit('oauth:error', rejection);
}
return $q.reject(rejection);
}
};
}
oauthInterceptor.$inject = ['$q', '$rootScope', 'OAuthToken'];
/**
* Export `oauthInterceptor`.
*/
export default oauthInterceptor;
|
Remove debug and use warngins | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import warnings
class CsvConverter:
def __init__(self, csv_file_path):
self.csv_file_path = csv_file_path
self.rows = []
self.source_product_code = "product_code"
self.source_quantity = "quantity"
self.debug = False
def clear(self):
self.rows = []
def addRow(self, row):
self.rows.append(row)
def getRow(self, index):
return self.rows[index]
def setSourceColumns(self, source_product_code, source_quantity):
self.source_product_code = source_product_code
self.source_quantity = source_quantity
def convertRow(self, row):
if not row[self.source_product_code]:
raise ValueError
return {
'product_code': row[self.source_product_code],
'quantity': int(row[self.source_quantity])
}
def read_csv(self, file_object):
reader = csv.DictReader(file_object)
for row in reader:
try:
self.addRow(self.convertRow(row))
except ValueError as e:
warnings.warn("Row parsing: {} Warning: {}".format(row, e.strerror), UserWarning)
def read_file(self):
with open(self.csv_file_path, 'rb') as csvfile:
self.read_csv(csvfile)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
class CsvConverter:
def __init__(self, csv_file_path):
self.csv_file_path = csv_file_path
self.rows = []
self.source_product_code = "product_code"
self.source_quantity = "quantity"
self.debug = False
def set_debug(self, debug):
self.debug = debug
def clear(self):
self.rows = []
def addRow(self, row):
self.rows.append(row)
def getRow(self, index):
return self.rows[index]
def setSourceColumns(self, source_product_code, source_quantity):
self.source_product_code = source_product_code
self.source_quantity = source_quantity
def convertRow(self, row):
if not row[self.source_product_code]:
raise ValueError
if self.debug:
print row
return {
'product_code': row[self.source_product_code],
'quantity': int(row[self.source_quantity])
}
def read_csv(self, file_object):
reader = csv.DictReader(file_object)
for row in reader:
self.addRow(self.convertRow(row))
def read_file(self):
with open(self.csv_file_path, 'rb') as csvfile:
self.read_csv(csvfile)
|
Add method to return book in component | import React from 'react';
import { Link } from 'react-router-dom';
const BorrowedBooks = (props) => {
const {
books, returnBook, user, isSendingRequest, returnRequests,
} = props;
console.log(props);
if (!books.length) {
return (
<div className="row center">
<p className="grey-text">You have no borrowed books </p>
</div>
);
}
return (
<div className="row">
<table className="striped responsive-table">
<thead>
<tr>
<th>Book</th>
<th>Date Borrowed</th>
<th>Status</th>
<th>Date Returned</th>
</tr>
</thead>
<tbody>
{ books.map((book, index) =>
<tr key={ index }>
<td><Link to= {`/books/${book.bookId}`}> { book.borrowedBooks.title } </Link></td>
<td> { book.createdAt.split('T')[0] } </td>
<td> { book.status } </td>
<td> { book.status === 'Returned' ? book.updatedAt.split('T')[0] : '' } </td>
{ book.status !== 'Returned' &&
!returnRequests.find(request =>
request.bookId === book.bookId) &&
<td><button onClick = { returnBook.bind(null, user.id, book.bookId) }
className = "btn btn-small btn-wave waves-effect red"
disabled = { isSendingRequest } >Return</button></td>
}
</tr>)}
</tbody>
</table>
</div>
);
};
export default BorrowedBooks;
| import React from 'react';
import { Link } from 'react-router-dom';
const BorrowedBooks = (props) => {
const { books } = props;
if (!books.length) {
return (
<div className="row center">
<p className="grey-text">You have no borrowed books </p>
</div>
);
}
return (
<div className="row">
<table className="striped responsive-table">
<thead>
<tr>
<th>Book</th>
<th>Date Borrowed</th>
<th>Status</th>
<th>Date Returned</th>
</tr>
</thead>
<tbody>
{ books.map((book, index) =>
<tr key={ index }>
<td><Link to= {`/books/${book.bookId}`}> { book.borrowedBooks.title } </Link></td>
<td> { book.createdAt.split('T')[0] } </td>
<td> { book.status } </td>
<td> { book.status === 'Returned' ? book.updatedAt.split('T')[0] : '' } </td>
{ book.status !== 'Returned' &&
<td><button>Return</button></td>
}
</tr>)}
</tbody>
</table>
</div>
);
};
export default BorrowedBooks;
|
Prepare for making it a kata. | // 1: assertThat
// To do: make all tests pass, leave the assert lines unchanged!
import {
assertThat, equalTo,
containsString, throws, returns,
} from 'hamjest';
describe('The core function, `assertThat()`', () => {
it('is a function', () => {
const typeOfAssertThat = typeof assertThat;
assertThat(typeOfAssertThat, equalTo('function'));
});
describe('requires at least two params', () => {
it('1st: the actual value', () => {
const actual = 'actual';
const expected = equalTo('actual');
assertThat(actual, expected);
});
it('2nd: a matcher for the expected value', () => {
const matcher = equalTo('expected');
assertThat('expected', matcher);
});
describe('the optional 3rd param', () => {
it('goes first(!), and is the assertion reason', () => {
let caughtError;
const reason = 'This is the reason, the first `assertThat()` throws as part of its message.';
try {
assertThat(reason, true, equalTo(false));
} catch (e) {
caughtError = e;
}
assertThat(caughtError.message, containsString(reason));
});
});
});
describe('under the hood, it does', () => {
it('nothing, WHEN actual and expected match (using the given matcher)', () => {
const passingTest = () => assertThat(true, equalTo(true));
assertThat(passingTest, returns());
});
it('throw an assertion, WHEN actual and expected don`t match', () => {
const failingTest = () => assertThat(false, equalTo(true));
assertThat(failingTest, throws());
});
});
});
| // 1: assertThat
// To do: make all tests pass, leave the assert lines unchanged!
import {
assertThat, equalTo,
containsString, throws, returns,
} from 'hamjest';
describe('The core function, `assertThat()`', () => {
it('is a function', () => {
const typeOfAssertThat = typeof assertThat;
assertThat(typeOfAssertThat, equalTo('function'));
});
describe('requires at least two params', () => {
it('1st: the actual value', () => {
const expected = equalTo('actual');
assertThat('actual', expected);
});
it('2nd: a matcher for the expected value', () => {
const matcher = equalTo('expected');
assertThat('expected', matcher);
});
describe('the optional 3rd param', () => {
it('goes first(!), and is the assertion reason', () => {
const reason = 'This is the reason, the first `assertThat()` throws as part of its message.';
try {
assertThat(reason, true, equalTo(false));
} catch (e) {
assertThat(e.message, containsString(reason));
}
});
});
});
describe('under the hood, it does', () => {
it('nothing, WHEN actual and expected match (using the given matcher)', () => {
const passingTest = () => assertThat(true, equalTo(true));
assertThat(passingTest, returns());
});
it('throw an assertion, WHEN actual and expected don`t match', () => {
const failingTest = () => assertThat(false, equalTo(true));
assertThat(failingTest, throws());
});
});
});
|
Fix broken build due to missing config file | const fs = require('fs');
const restify = require('restify');
const builder = require('botbuilder');
const config = fs.existsSync('./config/index.js') ? require('./config') : {};
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
const connector = new builder.ChatConnector({
appId : process.env.MICROSOFT_BOT_APP_ID || config.MICROSOFT_BOT_APP_ID,
appPassword : process.env.MICROSOFT_BOT_APP_PASSWORD || config.MICROSOFT_BOT_APP_PASSWORD
});
const bot = new builder.UniversalBot(connector);
// Serve a static web page
server.get(/.*/, restify.serveStatic({
'directory': './landing',
'default': 'index.html'
}));
server.post('/api/messages', connector.listen());
//=========================================================
// Bots Dialogs
//=========================================================
bot.dialog('/', [
function (session) {
builder.Prompts.choice(session, "What would you like to do today?", [
"Look at nearby issues",
"Report an issue",
"Track my issues"
]);
},
function (session, results) {
if (results.response) {
session.send('not ok');
} else {
session.send("ok");
}
}
]);
| const restify = require('restify');
const builder = require('botbuilder');
const config = require('./config');
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
const connector = new builder.ChatConnector({
appId : process.env.MICROSOFT_BOT_APP_ID || config.MICROSOFT_BOT_APP_ID,
appPassword : process.env.MICROSOFT_BOT_APP_PASSWORD || config.MICROSOFT_BOT_APP_PASSWORD
});
const bot = new builder.UniversalBot(connector);
// Serve a static web page
server.get(/.*/, restify.serveStatic({
'directory': './landing',
'default': 'index.html'
}));
server.post('/api/messages', connector.listen());
//=========================================================
// Bots Dialogs
//=========================================================
bot.dialog('/', [
function (session) {
builder.Prompts.choice(session, "What would you like to do today?", [
"Look at nearby issues",
"Report an issue",
"Track my issues"
]);
},
function (session, results) {
if (results.response) {
session.send('not ok');
} else {
session.send("ok");
}
}
]);
|
Add id to json content types
Tests will probably fail! | from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {
'content_type': 'rich-text',
'html': self.text,
'id': self.pk,
}
def mediafile_data(mediafile):
"""Return json serializable data for the mediafile."""
if mediafile is None:
return None
return {
'url': mediafile.file.url,
'type': mediafile.type,
'created': mediafile.created,
'copyright': mediafile.copyright,
'file_size': mediafile.file_size,
}
class JsonSectionContent(SectionContent):
class Meta(SectionContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {
'id': self.pk,
'content_type': 'section',
'title': self.title,
'html': self.richtext,
'mediafile': mediafile_data(self.mediafile),
}
class JsonMediaFileContent(MediaFileContent):
class Meta(MediaFileContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
data = mediafile_data(self.mediafile)
data['content_type'] = 'media-file'
data['id'] = self.pk
return data
| from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {'content_type': 'rich-text', 'html': self.text}
def mediafile_data(mediafile):
"""Return json serializable data for the mediafile."""
if mediafile is None:
return None
return {
'url': mediafile.file.url,
'type': mediafile.type,
'created': mediafile.created,
'copyright': mediafile.copyright,
'file_size': mediafile.file_size,
}
class JsonSectionContent(SectionContent):
class Meta(SectionContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {
'content_type': 'section',
'title': self.title,
'html': self.richtext,
'mediafile': mediafile_data(self.mediafile),
}
class JsonMediaFileContent(MediaFileContent):
class Meta(MediaFileContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
data = mediafile_data(self.mediafile)
data['content_type'] = 'media-file'
return data
|
Hide password reset instruction alert after 3 seconds | import Ember from 'ember';
import ajax from 'ic-ajax';
export default Ember.Controller.extend({
needs: 'application',
auth_token: Ember.computed.alias('controllers.application.auth_token'),
currentUser: Ember.computed.alias('controllers.application.currentUser'),
email: null,
password: null,
response: null,
hidden: true,
actions: {
authenticate: function() {
var self = this;
ajax('/api/sign_in', {
type: 'POST',
data: this.getProperties('email', 'password')
}).then(function(response) {
self.set('response', response);
self.set('auth_token', response.auth_token);
var currentUser = response.user;
currentUser.id = 'current';
self.store.createRecord('user', currentUser);
self.set('currentUser', self.store.find('user', 'current'));
self.set('role', currentUser.role);
self.set('email', null);
self.set('password', null);
self.transitionToRoute('dashboard');
});
},
recover_password: function() {
var self = this;
ajax('/api/password_reset', {
type: 'POST',
data: {user: {email: this.get('email')}}
}).then(function(response) {
self.set('email', null);
self.set('hidden', false);
Ember.run.later(function() {
self.set('hidden', true);
}, 3000);
});
},
toggle_recovery: function() {
Ember.$('.password-recovery').toggle();
Ember.$('.login-modal').toggle();
}
}
});
| import Ember from 'ember';
import ajax from 'ic-ajax';
export default Ember.Controller.extend({
needs: 'application',
auth_token: Ember.computed.alias('controllers.application.auth_token'),
currentUser: Ember.computed.alias('controllers.application.currentUser'),
email: null,
password: null,
response: null,
hidden: true,
actions: {
authenticate: function() {
var self = this;
ajax('/api/sign_in', {
type: 'POST',
data: this.getProperties('email', 'password')
}).then(function(response) {
self.set('response', response);
self.set('auth_token', response.auth_token);
var currentUser = response.user;
currentUser.id = 'current';
self.store.createRecord('user', currentUser);
self.set('currentUser', self.store.find('user', 'current'));
self.set('role', currentUser.role);
self.set('email', null);
self.set('password', null);
self.transitionToRoute('dashboard');
});
},
recover_password: function() {
var self = this;
ajax('/api/password_reset', {
type: 'POST',
data: {user: {email: this.get('email')}}
}).then(function(response) {
self.set('email', null);
self.set('hidden', false);
});
},
toggle_recovery: function() {
Ember.$('.password-recovery').toggle();
Ember.$('.login-modal').toggle();
}
}
});
|
Remove all moderator made comments before 2021/01/01 | import random
import string
from datetime import datetime
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
jan_01_2021 = timezone.make_aware(datetime(2021, 1, 1))
Comment.objects.filter(
content_type_id__in=ct_pks,
submit_date__lte=jan_01_2021
).exclude(
user_name="System"
).delete()
| import random
import string
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
for badword in ['mark', 'cheat', 'alt', 'tos violation']:
Comment.objects.filter(
content_type_id__in=ct_pks,
comment__icontains=badword,
).delete()
|
Refactor BasicAuth to extend the abstract client | <?php
namespace Intercom;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
class IntercomBasicAuthClient extends IntercomAbstractClient
{
/** @var array The required config variables for this type of client */
private static $required = ['app_id', 'api_key', 'headers', 'service_description'];
/**
* Creates a Basic Auth Client with the supplied configuration options
*
* @param array $config
* @return Client|IntercomBasicAuthClient
*/
public static function factory($config = [])
{
$default = [
'service_description' => __DIR__ . '/Service/config/intercom.json',
'headers' => [
'Content-Type' => self::DEFAULT_CONTENT_TYPE,
'Accept' => self::DEFAULT_ACCEPT_HEADER
]
];
$config = Collection::fromConfig($config, $default, static::$required);
$client = new self();
$client->setDefaultOption('headers', $config->get('headers'));
$client->setDefaultOption('auth', [
$config->get('app_id'),
$config->get('api_key'),
'Basic'
]);
$client->setDescription(static::getServiceDescriptionFromFile($config->get('service_description')));
return $client;
}
}
| <?php
namespace Intercom;
use InvalidArgumentException;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
class IntercomBasicAuthClient extends Client
{
/**
* Creates a Basic Auth Client with the supplied configuration options
*
* @param array $config
* @return Client|IntercomBasicAuthClient
*/
public static function factory($config = [])
{
$default = [
'service_description' => __DIR__ . '/Service/config/intercom.json',
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/vnd.intercom.3+json'
]
];
$required = [
'app_id',
'api_key',
'headers',
'service_description'
];
$config = Collection::fromConfig($config, $default, $required);
$client = new self();
$client->setDefaultOption('headers', $config->get('headers'));
$client->setDefaultOption('auth', [
$config->get('app_id'),
$config->get('api_key'),
'Basic'
]);
$client->setDescription(static::getServiceDescriptionFromFile($config->get('service_description')));
return $client;
}
/**
* Loads the service description from the service description file
*
* @param string $description_file The service description file
* @return ServiceDescription
* @throws InvalidArgumentException If the description file doesn't exist or cannot be read
*/
public function getServiceDescriptionFromFile($description_file) {
if (!file_exists($description_file) || !is_readable($description_file)) {
throw new InvalidArgumentException('Unable to read API definition schema');
}
return ServiceDescription::factory($description_file);
}
}
|
MAINT: Use the new version of traitlets. | from setuptools import setup
from sys import version_info
def install_requires():
requires = [
'traitlets>=4.1',
'six>=1.9.0',
'pyyaml>=3.11',
]
if (version_info.major, version_info.minor) < (3, 4):
requires.append('singledispatch>=3.4.0')
return requires
def extras_require():
return {
'test': [
'tox',
'pytest>=2.8.5',
'pytest-cov>=1.8.1',
'pytest-pep8>=1.0.6',
],
}
def main():
setup(
name='straitlets',
version='0.0.1',
description="Serializable IPython Traitlets",
author="Scott Sanderson",
author_email="[email protected]",
packages=[
'straitlets',
],
include_package_data=True,
zip_safe=True,
url="https://github.com/quantopian/serializable-traitlets",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: IPython',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python',
],
install_requires=install_requires(),
extras_require=extras_require()
)
if __name__ == '__main__':
main()
| from setuptools import setup
from sys import version_info
def install_requires():
requires = [
'traitlets>=4.0',
'six>=1.9.0',
'pyyaml>=3.11',
]
if (version_info.major, version_info.minor) < (3, 4):
requires.append('singledispatch>=3.4.0')
return requires
def extras_require():
return {
'test': [
'tox',
'pytest>=2.8.5',
'pytest-cov>=1.8.1',
'pytest-pep8>=1.0.6',
],
}
def main():
setup(
name='straitlets',
version='0.0.1',
description="Serializable IPython Traitlets",
author="Scott Sanderson",
author_email="[email protected]",
packages=[
'straitlets',
],
include_package_data=True,
zip_safe=True,
url="https://github.com/quantopian/serializable-traitlets",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: IPython',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python',
],
install_requires=install_requires(),
extras_require=extras_require()
)
if __name__ == '__main__':
main()
|
Fix token to place request parsing: allow hierarchy depths > 2 | package org.jboss.as.console.client.util;
import com.allen_sauer.gwt.log.client.Log;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import java.util.ArrayList;
import java.util.List;
/**
* @author Heiko Braun
* @date 2/17/11
*/
public class Places {
public static List<PlaceRequest> fromString(String urlString)
{
List<PlaceRequest> places = null;
try {
places = new ArrayList<PlaceRequest>();
StringTokenizer tokenizer = new StringTokenizer(urlString, "/");
while(tokenizer.hasMoreTokens())
{
parseSingleToken(places, tokenizer.nextToken());
}
} catch (Throwable e) {
Log.error("Error parsing token: " + urlString);
}
return places;
}
private static void parseSingleToken(List<PlaceRequest> places, String token) {
if(token.contains(";")) // parametrized?
{
StringTokenizer params = new StringTokenizer(token, ";");
PlaceRequest request = null;
while(params.hasMoreTokens())
{
String tok = params.nextToken();
if(tok.contains("="))
{
if(null==request) break;
// parameter
String[] parameter = tok.split("=");
request = request.with(parameter[0], parameter[1]);
}
else
{
// address
request = new PlaceRequest(tok);
}
}
// exit, either wrong token or different formatter
if(null==request)
throw new IllegalArgumentException("Illegal token: "+token);
places.add(request);
}
else
{
places.add(new PlaceRequest(token));
}
}
}
| package org.jboss.as.console.client.util;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import java.util.ArrayList;
import java.util.List;
/**
* @author Heiko Braun
* @date 2/17/11
*/
public class Places {
public static List<PlaceRequest> fromString(String urlString)
{
List<PlaceRequest> places = new ArrayList<PlaceRequest>();
// TODO: Tis is currently limited to a a parent/child hierarchy with depth 1
if(urlString.contains("/"))
{
String[] parentChild = urlString.split("/");
String parent = parentChild[0];
places.add(new PlaceRequest(parent));
String child = parentChild[1];
if(child.contains(";"))
{
String[] split = child.split(";");
String childPlace = split[0];
String params[] = split[1].split("=");
places.add(new PlaceRequest(childPlace).with(params[0], params[1]));
}
else
{
places.add(new PlaceRequest(child));
}
}
return places;
}
}
|
Test against ember 2.0.x and 2.1.x in CI | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-1.10',
dependencies: {
ember: '~1.10.0'
}
},
{
name: 'ember-1.11',
dependencies: {
ember: '~1.11.0'
}
},
{
name: 'ember-1.12',
dependencies: {
ember: '~1.12.0'
}
},
{
name: 'ember-1.13',
dependencies: {
ember: '~1.13.0'
}
},
{
name: 'ember-2.0',
dependencies: {
ember: '~2.0.0'
}
},
{
name: 'ember-2.1',
dependencies: {
ember: '~2.1.0'
}
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
| module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-1.10',
dependencies: {
ember: '~1.10.0'
}
},
{
name: 'ember-1.11',
dependencies: {
ember: '~1.11.0'
}
},
{
name: 'ember-1.12',
dependencies: {
ember: '~1.12.0'
}
},
{
name: 'ember-1.13',
dependencies: {
ember: '~1.13.0'
}
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
|
Implement a method to convert udesrscore case to camelCase | <?php
namespace Air\BookishBundle\Lib;
class NytApiHandler
{
private $nytApiKey;
private $guzzleClient;
public function __construct($nytApiKey, $guzzleClient)
{
$this->nytApiKey = $nytApiKey;
$this->guzzleClient = $guzzleClient;
}
public function getNytApiKey()
{
return $this->nytApiKey;
}
public function getBestSellersOverview($date = '2014-01-01')
{
$request = $this->guzzleClient->get('/svc/books/v2/lists/overview.json?published_date=' . $date . '&api-key=' . $this->getNytApiKey());
$response = $request->send();
$responseArray = $response->json();
return $this->convertKeysToCamelCase($responseArray);
}
private function convertKeysToCamelCase($apiResponseArray)
{
$arr = [];
foreach ($apiResponseArray as $key => $value) {
if (preg_match('/_/', $key)) {
$key = preg_replace_callback('/_([^_]*)/', function($matches) {
return ucfirst($matches[1]);
}, $key);
}
if (is_array($value))
$value = $this->convertKeysToCamelCase($value);
$arr[$key] = $value;
}
return $arr;
}
} | <?php
namespace Air\BookishBundle\Lib;
class NytApiHandler
{
private $nytApiKey;
private $guzzleClient;
public function __construct($nytApiKey, $guzzleClient)
{
$this->nytApiKey = $nytApiKey;
$this->guzzleClient = $guzzleClient;
}
public function getNytApiKey()
{
return $this->nytApiKey;
}
public function getBestSellersOverview($date = '2014-01-01')
{
$request = $this->guzzleClient->get('/svc/books/v2/lists/overview.json?published_date=' . $date . '&api-key=' . $this->getNytApiKey());
$response = $request->send();
$responseArray = $response->json();
$responseArray = $this->convertKeysToCamelCase($responseArray);
var_dump($responseArray);
return $responseArray;
}
private function convertKeysToCamelCase($apiResponseArray)
{
array_walk_recursive($apiResponseArray, 'self::convertKeys');
}
private static function convertKeys(&$item, &$key)
{
if (preg_match('/_/', $key)) {
echo $key;
$key = str_replace('_', '', $key);
$key = lcfirst($key);
}
}
} |
Remove skip in type juggling. | <?php
class TypeJugglingTest extends PHPUnit_Framework_TestCase
{
public function testFromFalseOrNullToArray()
{
foreach (array(false, null) as $testValue) {
$var = $testValue;
$var['foo'] = 10;
$this->assertEquals('array', gettype($var));
}
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
* @expectedExceptionMessage Creating default object from empty value
*/
public function testFromFalseToObject()
{
$var = false;
$var->name = 'bob';
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
* @expectedExceptionMessage Cannot use a scalar value as an array
*/
public function testFromTrueToArray()
{
$var = true;
$var['foo'] = 10;
$this->assertEquals('array', gettype($var));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testFromStringToArray()
{
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$this->markTestSkipped('This crash my PHP cli');
return;
}
$var = '2.5';
$var['foo'] = 10;
}
}
| <?php
class TypeJugglingTest extends PHPUnit_Framework_TestCase
{
public function testFromFalseOrNullToArray()
{
foreach (array(false, null) as $testValue) {
$var = $testValue;
$var['foo'] = 10;
$this->assertEquals('array', gettype($var));
}
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
* @expectedExceptionMessage Creating default object from empty value
*/
public function testFromFalseToObject()
{
$var = false;
$var->name = 'bob';
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
* @expectedExceptionMessage Cannot use a scalar value as an array
*/
public function testFromTrueToArray()
{
$var = true;
$var['foo'] = 10;
$this->assertEquals('array', gettype($var));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testFromStringToArray()
{
$this->markTestSkipped('This crash my PHP cli');
$var = '2.5';
$var['foo'] = 10;
}
}
|
Use assertEqual instead of assertEquals | import unittest
from anser import Anser, Client
class BasicAnserTest(unittest.TestCase):
def test_creation(self):
server = Anser(__file__)
self.assertEqual(server.name, __file__)
def test_creation_explicit_no_debug(self):
server = Anser(__file__, debug=False)
self.assertFalse(server.debug)
def test_creation_implicit_no_debug(self):
server = Anser(__file__)
self.assertFalse(server.debug)
def test_creation_explicit_debug(self):
server = Anser(__file__, debug=True)
self.assertTrue(server.debug)
def test_add_action(self):
server = Anser(__file__)
@server.action('default')
def dummy_action(message, address):
pass
self.assertTrue(dummy_action in server.actions)
class BasicClientTest(unittest.TestCase):
def test_creation(self):
client = Client('10.0.0.1', 4000)
self.assertEqual(client.address, '10.0.0.1')
self.assertEqual(client.port, 4000)
def test_creation_implicit_no_debug(self):
client = Client('10.0.0.1', 4000)
self.assertFalse(client.debug)
def test_creation_explicit_debug(self):
client = Client('10.0.0.1', 4000, debug=True)
self.assertTrue(client.debug)
if __name__ == '__main__':
unittest.main()
| import unittest
from anser import Anser, Client
class BasicAnserTest(unittest.TestCase):
def test_creation(self):
server = Anser(__file__)
self.assertEquals(server.name, __file__)
def test_creation_explicit_no_debug(self):
server = Anser(__file__, debug=False)
self.assertFalse(server.debug)
def test_creation_implicit_no_debug(self):
server = Anser(__file__)
self.assertFalse(server.debug)
def test_creation_explicit_debug(self):
server = Anser(__file__, debug=True)
self.assertTrue(server.debug)
def test_add_action(self):
server = Anser(__file__)
@server.action('default')
def dummy_action(message, address):
pass
self.assertTrue(dummy_action in server.actions)
class BasicClientTest(unittest.TestCase):
def test_creation(self):
client = Client('10.0.0.1', 4000)
self.assertEquals(client.address, '10.0.0.1')
self.assertEquals(client.port, 4000)
def test_creation_implicit_no_debug(self):
client = Client('10.0.0.1', 4000)
self.assertFalse(client.debug)
def test_creation_explicit_debug(self):
client = Client('10.0.0.1', 4000, debug=True)
self.assertTrue(client.debug)
if __name__ == '__main__':
unittest.main() |
Mark locale negotiation acceptance in progress | package examples.locale;
import com.vtence.molecule.WebServer;
import com.vtence.molecule.testing.http.HttpRequest;
import com.vtence.molecule.testing.http.HttpResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
import java.util.Locale;
import static com.vtence.molecule.testing.http.HttpResponseAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
public class LocaleNegotiationTest {
LocaleNegotiationExample example = new LocaleNegotiationExample("en", "en_US", "fr");
WebServer server = WebServer.create(9999);
HttpRequest request = new HttpRequest(9999);
HttpResponse response;
Locale originalDefault = Locale.getDefault();
@Before
public void startServer() throws IOException {
Locale.setDefault(Locale.US);
example.run(server);
}
@After
public void stopServer() throws IOException {
server.stop();
Locale.setDefault(originalDefault);
}
@Test @Ignore("wip")
public void selectingTheBestSupportedLanguage() throws IOException {
response = request.header("Accept-Language", "en; q=0.8, fr").send();
assertThat(response).hasBodyText(containsString("The best match is: fr"));
}
@Test
public void fallingBackToTheDefaultLanguage() throws IOException {
response = request.header("Accept-Language", "es-ES").send();
assertThat(response).hasBodyText(containsString("The best match is: en_US"));
}
} | package examples.locale;
import com.vtence.molecule.WebServer;
import com.vtence.molecule.testing.http.HttpRequest;
import com.vtence.molecule.testing.http.HttpResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Locale;
import static com.vtence.molecule.testing.http.HttpResponseAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
public class LocaleNegotiationTest {
LocaleNegotiationExample example = new LocaleNegotiationExample("en", "en_US", "fr");
WebServer server = WebServer.create(9999);
HttpRequest request = new HttpRequest(9999);
HttpResponse response;
Locale originalDefault = Locale.getDefault();
@Before
public void startServer() throws IOException {
Locale.setDefault(Locale.US);
example.run(server);
}
@After
public void stopServer() throws IOException {
server.stop();
Locale.setDefault(originalDefault);
}
@Test
public void selectingTheBestSupportedLanguage() throws IOException {
response = request.header("Accept-Language", "en; q=0.8, fr").send();
assertThat(response).hasBodyText(containsString("The best match is: fr"));
}
@Test
public void fallingBackToTheDefaultLanguage() throws IOException {
response = request.header("Accept-Language", "es-ES").send();
assertThat(response).hasBodyText(containsString("The best match is: en_US"));
}
} |
Add check to ensure launcher components begin with 'stockflux-' | import React, { useEffect, useState } from "react";
import { OpenfinApiHelpers } from "stockflux-core";
import Components from "stockflux-components";
import "./AppShortcuts.css";
export default () => {
const [apps, setApps] = useState([]);
useEffect(() => {
const options = {
method: "GET"
};
OpenfinApiHelpers.getCurrentWindow()
.then(window => window.getOptions())
.then(options => options.customData.apiBaseUrl)
.then(baseUrl => fetch(`${baseUrl}/apps/v1`, options))
.then(response => response.json())
.then(results => setApps(results))
.catch(console.error);
}, []);
return (
<div className="app-shortcuts">
{apps
.filter(
app =>
app.customConfig !== undefined &&
app.customConfig.showInLauncher &&
app.appId.indexOf("stockflux-") === 0
)
.map(app => {
/* Get the appropriate shortcut button by taking a part of stocklux appId
(e.g. "news", "watchlist", "chart"), capitalizing the first letter and
appending "Shortcut" at the end
*/
const AppShortcut =
Components[
app.appId
.split("stockflux-")[1]
.charAt(0)
.toUpperCase() +
app.appId.slice(11) +
"Shortcut"
];
return <AppShortcut key={app.appId} app={app} />;
})}
</div>
);
};
| import React, { useEffect, useState } from 'react';
import { OpenfinApiHelpers } from 'stockflux-core';
import Components from 'stockflux-components';
import './AppShortcuts.css';
export default () => {
const [apps, setApps] = useState([]);
useEffect(() => {
const options = {
method: 'GET'
};
OpenfinApiHelpers.getCurrentWindow()
.then(window => window.getOptions())
.then(options => options.customData.apiBaseUrl)
.then(baseUrl => fetch(`${baseUrl}/apps/v1`, options))
.then(response => response.json())
.then(results => setApps(results))
.catch(console.error);
}, []);
return (
<div className="app-shortcuts">
{apps
.filter(
app =>
app.customConfig !== undefined && app.customConfig.showInLauncher
)
.map(app => {
/* Get the appropriate shortcut button by taking a part of stocklux appId
(e.g. "news", "watchlist", "chart"), capitalizing the first letter and
appending "Shortcut" at the end
*/
const AppShortcut =
Components[
app.appId
.split('stockflux-')[1]
.charAt(0)
.toUpperCase() +
app.appId.slice(11) +
'Shortcut'
];
return <AppShortcut key={app.appId} app={app} />;
})}
</div>
);
};
|
Throw exception if action method does not exist | <?php
namespace watoki\cqurator;
use watoki\factory\Factory;
use watoki\smokey\Dispatcher;
use watoki\smokey\EventDispatcher;
class ActionDispatcher implements Dispatcher {
/** @var Dispatcher */
private $dispatcher;
/** @var \watoki\factory\Factory */
private $factory;
public function __construct(Factory $factory) {
$this->factory = $factory;
$this->dispatcher = new EventDispatcher();
}
/**
* @param string $class
* @param object|callable|string $handler
*/
public function addActionHandler($class, $handler) {
if (!is_callable($handler)) {
$classReflection = new \ReflectionClass($class);
$methodName = lcfirst($classReflection->getShortName());
$handler = function ($action) use ($handler, $methodName) {
$handler = is_object($handler) ? $handler : $this->factory->getInstance($handler);
if (!method_exists($handler, $methodName)) {
$class = get_class($handler);
throw new \InvalidArgumentException("Method [$class::$methodName] does not exist.");
}
return call_user_func(array($handler, $methodName), $action);
};
}
$this->dispatcher->addListener($class, $handler);
}
/**
* @param mixed $event
* @return \watoki\smokey\Result
*/
public function fire($event) {
return $this->dispatcher->fire($event);
}
} | <?php
namespace watoki\cqurator;
use watoki\factory\Factory;
use watoki\smokey\Dispatcher;
use watoki\smokey\EventDispatcher;
class ActionDispatcher implements Dispatcher {
/** @var Dispatcher */
private $dispatcher;
/** @var \watoki\factory\Factory */
private $factory;
public function __construct(Factory $factory) {
$this->factory = $factory;
$this->dispatcher = new EventDispatcher();
}
/**
* @param string $class
* @param object|callable|string $handler
*/
public function addActionHandler($class, $handler) {
if (!is_callable($handler)) {
$classReflection = new \ReflectionClass($class);
$methodName = lcfirst($classReflection->getShortName());
$handler = function ($action) use ($handler, $methodName) {
$handler = is_object($handler) ? $handler : $this->factory->getInstance($handler);
return call_user_func(array($handler, $methodName), $action);
};
}
$this->dispatcher->addListener($class, $handler);
}
/**
* @param mixed $event
* @return \watoki\smokey\Result
*/
public function fire($event) {
return $this->dispatcher->fire($event);
}
} |
Set default locale in test to avoid test failures when different default is used than expected. | # -*- coding: utf-8 -*-
"""
Unit Test: orchard.extensions.babel
"""
import unittest
import orchard
import orchard.extensions.flask_babel
class BabelUnitTest(unittest.TestCase):
def setUp(self):
self.app = orchard.create_app('Testing')
self.app.config['BABEL_DEFAULT_LOCALE'] = 'en'
self.app.config['LANGUAGES'] = {
'de': 'Deutsch',
'en': 'English'
}
def test_get_locale(self):
# The preferred language is available.
headers = {
'Accept-Language': 'de,en;q=0.3'
}
with self.app.test_request_context('/', headers = headers):
locale = orchard.extensions.flask_babel._get_locale()
self.assertEqual(locale, 'de')
# The preferred language is not available.
headers = {
'Accept-Language': 'fr,en;q=0.3'
}
with self.app.test_request_context('/', headers = headers):
locale = orchard.extensions.flask_babel._get_locale()
self.assertEqual(locale, 'en')
# None of the accepted languages is available.
headers = {
'Accept-Language': 'fr,es;q=0.3'
}
with self.app.test_request_context('/', headers = headers):
locale = orchard.extensions.flask_babel._get_locale()
self.assertEqual(locale, 'en')
| # -*- coding: utf-8 -*-
"""
Unit Test: orchard.extensions.babel
"""
import unittest
import orchard
import orchard.extensions.flask_babel
class BabelUnitTest(unittest.TestCase):
def setUp(self):
self.app = orchard.create_app('Testing')
self.app.config['LANGUAGES'] = {
'de': 'Deutsch',
'en': 'English'
}
def test_get_locale(self):
# The preferred language is available.
headers = {
'Accept-Language': 'de,en;q=0.3'
}
with self.app.test_request_context('/', headers = headers):
locale = orchard.extensions.flask_babel._get_locale()
self.assertEqual(locale, 'de')
# The preferred language is not available.
headers = {
'Accept-Language': 'fr,en;q=0.3'
}
with self.app.test_request_context('/', headers = headers):
locale = orchard.extensions.flask_babel._get_locale()
self.assertEqual(locale, 'en')
# None of the accepted languages is available.
headers = {
'Accept-Language': 'fr,es;q=0.3'
}
with self.app.test_request_context('/', headers = headers):
locale = orchard.extensions.flask_babel._get_locale()
self.assertEqual(locale, 'en')
|
Swap query/refresh button spots on list screen | import React from "react";
import {Box} from "adminlte";
import LinkedListGroup from "app/components/LinkedListGroup";
import Pagination from "app/components/Pagination";
import RefreshButton from "app/components/RefreshButton";
import SearchBox from "app/components/SearchBox";
class MasterBox extends React.Component {
render() {
const {collection, CreateForm, QueryForm} = this.props;
return (
<Box.Wrapper>
<Box.Header>
<Box.Title>{collection.title}</Box.Title>
<Box.Tools>
<SearchBox {...this.props}/>
</Box.Tools>
</Box.Header>
<Box.Body>
<LinkedListGroup {...this.props}/>
<div className="text-center">
<CreateForm {...this.props}/>
<RefreshButton {...this.props}/>
<QueryForm {...this.props}/>
</div>
<Pagination {...this.props}/>
</Box.Body>
</Box.Wrapper>
);
}
}
export default MasterBox;
| import React from "react";
import {Box} from "adminlte";
import LinkedListGroup from "app/components/LinkedListGroup";
import Pagination from "app/components/Pagination";
import RefreshButton from "app/components/RefreshButton";
import SearchBox from "app/components/SearchBox";
class MasterBox extends React.Component {
render() {
const {collection, CreateForm, QueryForm} = this.props;
return (
<Box.Wrapper>
<Box.Header>
<Box.Title>{collection.title}</Box.Title>
<Box.Tools>
<SearchBox {...this.props}/>
</Box.Tools>
</Box.Header>
<Box.Body>
<LinkedListGroup {...this.props}/>
<div className="text-center">
<CreateForm {...this.props}/>
<QueryForm {...this.props}/>
<RefreshButton {...this.props}/>
</div>
<Pagination {...this.props}/>
</Box.Body>
</Box.Wrapper>
);
}
}
export default MasterBox;
|
Fix the gift certificate module so that an invalid code won't throw an exception. | """
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
valid_gc = False
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
valid_gc = gc.valid
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not valid_gc:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
| """
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not gc.valid:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
Fix typo: it is $this->storage, not just any local $storage | <?php
namespace Ob_Ivan\Cache\Driver;
use DateTime;
use Ob_Ivan\Cache\StorageInterface;
class MemoryDriver implements StorageInterface
{
const KEY_EXPIRE = __LINE__;
const KEY_VALUE = __LINE__;
/**
* @var [
* <string key> => [
* KEY_EXPIRE => <DateTime Expiration date>,
* KEY_VALUE => <mixed Stored value>,
* ],
* ...
* ]
**/
protected $storage = [];
public function delete($key)
{
unset($this->storage[$key]);
return true;
}
public function get($key)
{
if (isset($this->storage[$key])) {
if ($this->storage[$key][static::KEY_EXPIRE] < (new DateTime)) {
unset($this->storage[$key]);
} else {
return $this->storage[$key][static::KEY_VALUE];
}
}
return null;
}
public function set($key, $value, $duration = null)
{
if ($duration < 0) {
return false;
}
$this->storage[$key] = [
static::KEY_EXPIRE => new DateTime(
$duration > 0
? '+' . intval($duration) . 'sec'
: '+10000years'
),
static::KEY_VALUE => $value,
];
return true;
}
}
| <?php
namespace Ob_Ivan\Cache\Driver;
use DateTime;
use Ob_Ivan\Cache\StorageInterface;
class MemoryDriver implements StorageInterface
{
const KEY_EXPIRE = __LINE__;
const KEY_VALUE = __LINE__;
/**
* @var [
* <string key> => [
* KEY_EXPIRE => <DateTime Expiration date>,
* KEY_VALUE => <mixed Stored value>,
* ],
* ...
* ]
**/
protected $storage = [];
public function delete($key)
{
unset($storage[$key]);
return true;
}
public function get($key)
{
if (isset($storage[$key])) {
if ($storage[$key][static::KEY_EXPIRE] < (new DateTime)) {
unset($storage[$key]);
} else {
return $storage[$key][static::KEY_VALUE];
}
}
return null;
}
public function set($key, $value, $duration = null)
{
if ($duration < 0) {
return false;
}
$storage[$key] = [
static::KEY_EXPIRE => new DateTime(
$duration > 0
? '+' . intval($duration) . 'sec'
: '+10000years'
),
static::KEY_VALUE => $value,
];
return true;
}
}
|
Add integration test via docker | 'use strict';
/*jslint nomen: true, stupid: true*/
module.exports = function (grunt) {
grunt.registerTask('integration-test', 'Run integration tests', [
'docker-integration-test'
]);
grunt.registerMultiTask('docker-integration-test', function runTask() {
/*eslint-disable no-invalid-this*/
if (String(global.build.options.BuildConfig.nodeMajorVersion) === process.env.DOCKER_INTEGRATION_TEST_NODE_VERSION) {
grunt.log.writeln('Integration test requested.');
var childProcess = require('child_process');
var path = require('path');
var fs = require('fs');
var directory = path.join(__dirname, 'integration');
var file = path.join(directory, 'build.sh');
grunt.log.writeln('Running integration test script.');
/*eslint-disable no-sync*/
var output = childProcess.execFileSync(file, {
cwd: directory,
encoding: 'utf8'
});
/*eslint-enable no-sync*/
grunt.log.writeln(output);
} else {
grunt.log.writeln('Skipping integration test.');
}
/*eslint-enable no-invalid-this*/
});
return {
tasks: {
'docker-integration-test': {
full: {}
}
}
};
};
| 'use strict';
/*jslint nomen: true, stupid: true*/
module.exports = function (grunt) {
grunt.registerTask('integration-test', 'Run integration tests', [
'docker-integration-test'
]);
grunt.registerMultiTask('docker-integration-test', function runTask() {
/*eslint-disable no-invalid-this*/
if (String(global.build.options.BuildConfig.nodeMajorVersion) === process.env.DOCKER_INTEGRATION_TEST_NODE_VERSION) {
grunt.log.writeln('Integration test requested.');
var childProcess = require('child_process');
var path = require('path');
var fs = require('fs');
var directory = path.join(__dirname, 'integration');
var file = path.join(directory, 'build.sh');
grunt.log.writeln('Running integration test script.');
/*eslint-disable no-sync*/
childProcess.execFileSync(file, {
cwd: directory,
encoding: 'utf8'
});
/*eslint-enable no-sync*/
} else {
grunt.log.writeln('Skipping integration test.');
}
/*eslint-enable no-invalid-this*/
});
return {
tasks: {
'docker-integration-test': {
full: {}
}
}
};
};
|
Add a 5 second pause | """
The django clearsessions commend internally calls:
cls.get_model_class().objects.filter(
expire_date__lt=timezone.now()).delete()
which could lock the DB table for a long time when
having a large number of records to delete.
To prevent the job running forever, we only delete a limit number of
expired django sessions in a single run
"""
import logging
from datetime import timedelta
import time
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sessions.models import Session
from django.utils import timezone
from myuw.logger.timer import Timer
logger = logging.getLogger(__name__)
begin_delta = 1920
log_format = "Deleted django sessions expired before {}, Time={} seconds"
class Command(BaseCommand):
def handle(self, *args, **options):
now = timezone.now()
for ddelta in range(begin_delta, 0, -1):
timer = Timer()
cut_off_dt = now - timedelta(days=ddelta)
try:
qset = Session.objects.filter(expire_date__lt=cut_off_dt)
if qset.exists():
qset.delete()
logger.info(log_format.format(cut_off_dt.date(),
timer.get_elapsed()))
time.sleep(5)
except Exception as ex:
logger.error(str(ex))
| """
The django clearsessions commend internally calls:
cls.get_model_class().objects.filter(
expire_date__lt=timezone.now()).delete()
which could lock the DB table for a long time when
having a large number of records to delete.
To prevent the job running forever, we only delete a limit number of
expired django sessions in a single run
"""
import logging
from datetime import timedelta
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sessions.models import Session
from django.utils import timezone
from myuw.logger.timer import Timer
logger = logging.getLogger(__name__)
begin_delta = 1920
log_format = "Deleted django sessions expired before {}, Time={} seconds"
class Command(BaseCommand):
def handle(self, *args, **options):
now = timezone.now()
for ddelta in range(begin_delta, 0, -1):
timer = Timer()
cut_off_dt = now - timedelta(days=ddelta)
try:
qset = Session.objects.filter(expire_date__lt=cut_off_dt)
if qset.exists():
qset.delete()
logger.info(log_format.format(cut_off_dt.date(),
timer.get_elapsed()))
except Exception as ex:
logger.error(str(ex))
|
Disable PXF in ORCA CI | import os
import subprocess
import sys
from GpdbBuildBase import GpdbBuildBase
class GpBuild(GpdbBuildBase):
def __init__(self, mode):
self.mode = 'on' if mode == 'orca' else 'off'
def configure(self):
return subprocess.call(["./configure",
"--enable-mapreduce",
"--with-perl",
"--with-libxml",
"--with-python",
"--disable-gpcloud",
"--disable-pxf",
"--prefix=/usr/local/gpdb"], cwd="gpdb_src")
def icg(self):
status = subprocess.call(
"printf '\nLD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib\nexport \
LD_LIBRARY_PATH' >> /usr/local/gpdb/greenplum_path.sh", shell=True)
if status:
return status
status = subprocess.call([
"runuser gpadmin -c \"source /usr/local/gpdb/greenplum_path.sh \
&& make create-demo-cluster DEFAULT_QD_MAX_CONNECT=150\""], cwd="gpdb_src/gpAux/gpdemo", shell=True)
if status:
return status
return subprocess.call([
"runuser gpadmin -c \"source /usr/local/gpdb/greenplum_path.sh \
&& source gpAux/gpdemo/gpdemo-env.sh && PGOPTIONS='-c optimizer={0}' \
make -C src/test installcheck-good\"".format(self.mode)], cwd="gpdb_src", shell=True)
| import os
import subprocess
import sys
from GpdbBuildBase import GpdbBuildBase
class GpBuild(GpdbBuildBase):
def __init__(self, mode):
self.mode = 'on' if mode == 'orca' else 'off'
def configure(self):
return subprocess.call(["./configure",
"--enable-mapreduce",
"--with-perl",
"--with-libxml",
"--with-python",
"--disable-gpcloud",
"--prefix=/usr/local/gpdb"], cwd="gpdb_src")
def icg(self):
status = subprocess.call(
"printf '\nLD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib\nexport \
LD_LIBRARY_PATH' >> /usr/local/gpdb/greenplum_path.sh", shell=True)
if status:
return status
status = subprocess.call([
"runuser gpadmin -c \"source /usr/local/gpdb/greenplum_path.sh \
&& make create-demo-cluster DEFAULT_QD_MAX_CONNECT=150\""], cwd="gpdb_src/gpAux/gpdemo", shell=True)
if status:
return status
return subprocess.call([
"runuser gpadmin -c \"source /usr/local/gpdb/greenplum_path.sh \
&& source gpAux/gpdemo/gpdemo-env.sh && PGOPTIONS='-c optimizer={0}' \
make -C src/test installcheck-good\"".format(self.mode)], cwd="gpdb_src", shell=True)
|
Improve efficiency by merging two loops accessing the same data into one loop | package com.google.sps.data;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import org.apache.commons.collections4.keyvalue.MultiKey;
/*
* Class representing one row/entry in the aggregation response. A NULL field value
* means the field was not being aggregated by, and will be omitted from the JSON response
*/
public final class AggregationResponseEntry {
private String annotatedAssetId;
private String annotatedLocation;
private String annotatedUser;
private final int count;
private List<String> deviceIds;
private List<String> serialNumbers;
public AggregationResponseEntry(
MultiKey key,
List<ChromeOSDevice> devices,
LinkedHashSet<AnnotatedField> fields) {
String keys[] = (String[]) key.getKeys();
int currKey = 0;
Iterator<AnnotatedField> it = fields.iterator();
while (it.hasNext()) {
switch(it.next()) {
case ASSET_ID:
this.annotatedAssetId = keys[currKey++];
break;
case LOCATION:
this.annotatedLocation = keys[currKey++];
break;
case USER:
this.annotatedUser = keys[currKey++];
break;
}
}
this.count = devices.size();
this.deviceIds = new ArrayList<String>();
this.serialNumbers = new ArrayList<String>();
for (ChromeOSDevice device : devices) {
this.deviceIds.add(device.getDeviceId());
this.serialNumbers.add(device.getSerialNumber());
}
}
}
| package com.google.sps.data;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections4.keyvalue.MultiKey;
/*
* Class representing one row/entry in the aggregation response. A NULL field value
* means the field was not being aggregated by, and will be omitted from the JSON response
*/
public final class AggregationResponseEntry {
private String annotatedAssetId;
private String annotatedLocation;
private String annotatedUser;
private final int count;
private List<String> deviceIds;
private List<String> serialNumbers;
public AggregationResponseEntry(
MultiKey key,
List<ChromeOSDevice> devices,
LinkedHashSet<AnnotatedField> fields) {
String keys[] = (String[]) key.getKeys();
int currKey = 0;
Iterator<AnnotatedField> it = fields.iterator();
while (it.hasNext()) {
switch(it.next()) {
case ASSET_ID:
this.annotatedAssetId = keys[currKey++];
break;
case LOCATION:
this.annotatedLocation = keys[currKey++];
break;
case USER:
this.annotatedUser = keys[currKey++];
break;
}
}
this.count = devices.size();
this.deviceIds = devices.stream()
.map(device -> device.getDeviceId())
.collect(Collectors.toList());
this.serialNumbers = devices.stream()
.map(device -> device.getSerialNumber())
.collect(Collectors.toList());
}
}
|
Rollback to supporting older versions of cffi | #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"]
extra_link_args = [] if os.name == 'nt' else ["-g"]
mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
sources=['src/thinning.cpp',
'src/distance.cpp',
'src/grassfire.cpp',
'src/popcount.cpp',
'src/neighbours.cpp'],
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args)
setup(
name='cv_algorithms',
license='Apache license 2.0',
packages=find_packages(exclude=['tests*']),
install_requires=['cffi>=0.7'],
ext_modules=[mod_cv_algorithms],
test_suite='nose.collector',
tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'],
setup_requires=['nose>=1.0'],
platforms="any",
zip_safe=False,
version='1.0.0',
long_description=io.open("README.rst", encoding="utf-8").read(),
description='Optimized OpenCV extra algorithms for Python',
url="https://github.com/ulikoehler/"
)
| #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"]
extra_link_args = [] if os.name == 'nt' else ["-g"]
mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
sources=['src/thinning.cpp',
'src/distance.cpp',
'src/grassfire.cpp',
'src/popcount.cpp',
'src/neighbours.cpp'],
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args)
setup(
name='cv_algorithms',
license='Apache license 2.0',
packages=find_packages(exclude=['tests*']),
install_requires=['cffi>=1.10'],
ext_modules=[mod_cv_algorithms],
test_suite='nose.collector',
tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'],
setup_requires=['nose>=1.0'],
platforms="any",
zip_safe=False,
version='1.0.0',
long_description=io.open("README.rst", encoding="utf-8").read(),
description='Optimized OpenCV extra algorithms for Python',
url="https://github.com/ulikoehler/"
)
|
Fix the test to disassemble as if at address zero, not at an invalid address. The default SBAddress constructor sets the offset to 0xffffffffffffffff and the section to NULL.
This was causing problems on clang 602 branches that use MemoryObjects to as the container for opcode bytes instead of a plain array of bytes. So we were asking for 3 bytes to be disassembled at address 0xffffffffffffffff which would cause an unsigned overflow and cause the MemoryObject to refuse to read anymore bytes.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@227153 91177308-0d34-0410-b5e6-96231b3b80d8 | """
Use lldb Python API to disassemble raw machine code bytes
"""
import os, time
import re
import unittest2
import lldb, lldbutil
from lldbtest import *
class DisassembleRawDataTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@python_api_test
def test_disassemble_raw_data(self):
"""Test disassembling raw bytes with the API."""
self.disassemble_raw_data()
def disassemble_raw_data(self):
"""Test disassembling raw bytes with the API."""
# Create a target from the debugger.
target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "x86_64")
self.assertTrue(target, VALID_TARGET)
raw_bytes = bytearray([0x48, 0x89, 0xe5])
insts = target.GetInstructions(lldb.SBAddress(0, target), raw_bytes)
inst = insts.GetInstructionAtIndex(0)
if self.TraceOn():
print
print "Raw bytes: ", [hex(x) for x in raw_bytes]
print "Disassembled%s" % str(inst)
self.assertTrue (inst.GetMnemonic(target) == "movq")
self.assertTrue (inst.GetOperands(target) == '%' + "rsp, " + '%' + "rbp")
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| """
Use lldb Python API to disassemble raw machine code bytes
"""
import os, time
import re
import unittest2
import lldb, lldbutil
from lldbtest import *
class DisassembleRawDataTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@python_api_test
def test_disassemble_raw_data(self):
"""Test disassembling raw bytes with the API."""
self.disassemble_raw_data()
def disassemble_raw_data(self):
"""Test disassembling raw bytes with the API."""
# Create a target from the debugger.
target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "x86_64")
self.assertTrue(target, VALID_TARGET)
raw_bytes = bytearray([0x48, 0x89, 0xe5])
insts = target.GetInstructions(lldb.SBAddress(), raw_bytes)
inst = insts.GetInstructionAtIndex(0)
if self.TraceOn():
print
print "Raw bytes: ", [hex(x) for x in raw_bytes]
print "Disassembled%s" % str(inst)
self.assertTrue (inst.GetMnemonic(target) == "movq")
self.assertTrue (inst.GetOperands(target) == '%' + "rsp, " + '%' + "rbp")
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
|
Add Email Address for Contact | import React, { PropTypes, Component } from "react";
import { LOGO_BACKGROUND_PATH } from "../constants/image_paths";
const BetterSelfAddress = () => (
<p className="address small">
BetterHealth, Inc.
<br />
99 St Marks, 3D
<br />
New York, NY, 10009
<br />
[email protected]
</p>
);
export default class Footer extends Component {
render() {
return (
<section className="content-block-nopad bg-deepocean footer-wrap-1-3">
<div className="container footer-1-3">
<div className="col-md-4 pull-left">
<img
src={LOGO_BACKGROUND_PATH}
className="brand-img img-responsive"
/>
</div>
<div className="col-md-3 pull-right">
<p className="address-bold-line">
We <i className="fa fa-heart pomegranate" /> analytics
</p>
<BetterSelfAddress />
</div>
<div className="col-xs-12 footer-text">
<p>
Please take a few minutes to read our
{" "}
<a href="#">Terms & Conditions</a>
{" "}
and
{" "}
<a href="#">Privacy Policy</a>
</p>
</div>
</div>
</section>
);
}
}
| import React, { PropTypes, Component } from "react";
import { LOGO_BACKGROUND_PATH } from "../constants/image_paths";
const BetterSelfAddress = () => (
<p className="address small">
BetterHealth, Inc.<br />99 St Marks, 3D<br />New York, NY, 10009
</p>
);
export default class Footer extends Component {
render() {
return (
<section className="content-block-nopad bg-deepocean footer-wrap-1-3">
<div className="container footer-1-3">
<div className="col-md-4 pull-left">
<img
src={LOGO_BACKGROUND_PATH}
className="brand-img img-responsive"
/>
</div>
<div className="col-md-3 pull-right">
<p className="address-bold-line">
We <i className="fa fa-heart pomegranate" /> analytics
</p>
<BetterSelfAddress />
</div>
<div className="col-xs-12 footer-text">
<p>
Please take a few minutes to read our
{" "}
<a href="#">Terms & Conditions</a>
{" "}
and
{" "}
<a href="#">Privacy Policy</a>
</p>
</div>
</div>
</section>
);
}
}
|
Fix mistake in last commit | import sys
from datetime import datetime
from courtutils.databases.postgres import PostgresDatabase
from courtreader import readers
from courtutils.logger import get_logger
log = get_logger()
reader = readers.DistrictCourtReader()
reader.connect()
db = PostgresDatabase('district')
def update_case(fips):
cases_to_fix = db.get_cases_with_no_past_due(fips, 'criminal')
for case_to_fix in cases_to_fix:
case = {
'fips': fips,
'case_number': case_to_fix[0],
'details_fetched_for_hearing_date': case_to_fix[1],
'collected': datetime.now()
}
case['details'] = reader.get_case_details_by_number(
fips, 'criminal', case_to_fix[0],
case['details_url'] if 'details_url' in case else None)
if 'error' in case['details']:
log.warn('Could not collect case details for %s in %s',
case_to_fix[0], case['fips'])
else:
log.info('%s %s', fips, case['details']['CaseNumber'])
db.replace_case_details(case, 'criminal')
if len(sys.argv) > 1:
update_case(sys.argv[1])
else:
courts = list(db.get_courts())
for court in courts:
update_case(court['fips'])
| import sys
from datetime import datetime
from courtutils.databases.postgres import PostgresDatabase
from courtreader import readers
from courtutils.logger import get_logger
log = get_logger()
reader = readers.DistrictCourtReader()
reader.connect()
db = PostgresDatabase('district')
def update_case(fips):
cases_to_fix = db.get_cases_with_no_past_due(fips, 'criminal')
for case_to_fix in cases_to_fix:
case = {
'fips': fips,
'case_number': case_to_fix[0],
'details_fetched_for_hearing_date': case_to_fix[1],
'collected': datetime.now()
}
case['details'] = reader.get_case_details_by_number(
fips, 'criminal', case_to_fix[0],
case['details_url'] if 'details_url' in case else None)
if 'error' in case['details']:
log.warn('Could not collect case details for %s in %s',
case_to_fix[0], case['fips'])
else:
log.info('%s %s', fips, case['details']['CaseNumber'])
db.replace_case_details(case, 'criminal')
if len(sys.argv) > 2:
update_case(sys.argv[2])
else:
courts = list(db.get_courts())
for court in courts:
update_case(court['fips'])
|
Add missing mechanism-too-weak SASL Error | /**
*
* Copyright 2014 Florian Schmaus
*
* 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.jivesoftware.smack.sasl;
import java.util.logging.Level;
import java.util.logging.Logger;
public enum SASLError {
aborted,
account_disabled,
credentials_expired,
encryption_required,
incorrect_encoding,
invalid_authzid,
invalid_mechanism,
malformed_request,
mechanism_too_weak,
not_authorized,
temporary_auth_failure;
private static final Logger LOGGER = Logger.getLogger(SASLError.class.getName());
@Override
public String toString() {
return this.name().replace('_', '-');
}
public static SASLError fromString(String string) {
string = string.replace('-', '_');
SASLError saslError = null;
try {
saslError = SASLError.valueOf(string);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Could not transform string '" + string + "' to SASLError", e);
}
return saslError;
}
}
| /**
*
* Copyright 2014 Florian Schmaus
*
* 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.jivesoftware.smack.sasl;
import java.util.logging.Level;
import java.util.logging.Logger;
public enum SASLError {
aborted,
account_disabled,
credentials_expired,
encryption_required,
incorrect_encoding,
invalid_authzid,
invalid_mechanism,
malformed_request,
not_authorized,
temporary_auth_failure;
private static final Logger LOGGER = Logger.getLogger(SASLError.class.getName());
@Override
public String toString() {
return this.name().replace('_', '-');
}
public static SASLError fromString(String string) {
string = string.replace('-', '_');
SASLError saslError = null;
try {
saslError = SASLError.valueOf(string);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Could not transform string '" + string + "' to SASLError", e);
}
return saslError;
}
}
|
Change type comparisions with isinstance | from django import forms
def parsleyfy(klass):
class ParsleyClass(klass):
def __init__(self, *args, **kwargs):
super(ParsleyClass, self).__init__(*args, **kwargs)
for key, val in self.fields.items():
if val.required:
val.widget.attrs.update({"data-required": "true"})
if isinstance(val, forms.URLField):
val.widget.attrs.update({"data-type": "url"})
if isinstance(val, forms.EmailField):
val.widget.attrs.update({"data-type": "email"})
if isinstance(val, forms.IntegerField):
val.widget.attrs.update({"data-type": "digits"})
if isinstance(val, forms.DecimalField):
val.widget.attrs.update({"data-type": "number"})
if isinstance(val, forms.RegexField):
val.widget.attrs.update({"data-regexp": val.regex.pattern})
if hasattr(val, "max_length") and val.max_length:
val.widget.attrs.update({"data-maxlength": val.max_length})
if hasattr(val, "min_length") and val.min_length:
val.widget.attrs.update({"data-minlength": val.min_length})
return ParsleyClass
| from django import forms
def parsleyfy(klass):
class ParsleyClass(klass):
def __init__(self, *args, **kwargs):
super(ParsleyClass, self).__init__(*args, **kwargs)
for key, val in self.fields.items():
if val.required:
val.widget.attrs.update({"data-required": "true"})
if type(val) == forms.URLField:
val.widget.attrs.update({"data-type": "url"})
if type(val) == forms.EmailField:
val.widget.attrs.update({"data-type": "email"})
if type(val) == forms.IntegerField:
val.widget.attrs.update({"data-type": "digits"})
if type(val) == forms.DecimalField:
val.widget.attrs.update({"data-type": "number"})
if type(val) == forms.RegexField:
val.widget.attrs.update({"data-regexp": val.regex.pattern})
if hasattr(val, "max_length") and val.max_length:
val.widget.attrs.update({"data-maxlength": val.max_length})
if hasattr(val, "min_length") and val.min_length:
val.widget.attrs.update({"data-minlength": val.min_length})
return ParsleyClass
|
Replace assertGreaterEqual with assertTrue(a >= b) | from unittest import TestCase
from itertools import repeat, imap, izip, cycle
from spicedham.bayes import Bayes
from spicedham import Spicedham
class TestBayes(TestCase):
def test_classify(self):
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._training(b)
alphabet = map(chr, range(97, 123))
for letter in alphabet:
p = b.classify(letter)
self.assertEqual(p, 0.5)
def _training(self, bayes):
alphabet = map(chr, range(97, 123))
reversed_alphabet = reversed(alphabet)
messagePairs = izip(alphabet, reversed_alphabet)
for message, is_spam in izip(messagePairs, cycle((True, False))):
bayes.train(message, is_spam)
def test_train(self):
alphabet = map(chr, range(97, 123))
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._training(b)
for letter in alphabet:
result = sh.backend.get_key(b.__class__.__name__, letter)
self.assertEqual(result, {'numTotal': 2, 'numSpam': 1})
self.assertTrue(result['numTotal'] >= result['numSpam'])
| from unittest import TestCase
from itertools import repeat, imap, izip, cycle
from spicedham.bayes import Bayes
from spicedham import Spicedham
class TestBayes(TestCase):
def test_classify(self):
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._training(b)
alphabet = map(chr, range(97, 123))
for letter in alphabet:
p = b.classify(letter)
self.assertEqual(p, 0.5)
def _training(self, bayes):
alphabet = map(chr, range(97, 123))
reversed_alphabet = reversed(alphabet)
messagePairs = izip(alphabet, reversed_alphabet)
for message, is_spam in izip(messagePairs, cycle((True, False))):
bayes.train(message, is_spam)
def test_train(self):
alphabet = map(chr, range(97, 123))
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._training(b)
for letter in alphabet:
result = sh.backend.get_key(b.__class__.__name__, letter)
self.assertEqual(result, {'numTotal': 2, 'numSpam': 1})
self.assertGreaterEqual(result['numTotal'], result['numSpam'])
|
Raise AttributeError instead of None | import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
print self.json_path
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
| import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
print self.json_path
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
|
Update grunt to use bower_components | module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
options: {
sourceMap: true
},
dist: {
files: {
'public/css/calendar.css': 'public/sass/calendar.scss'
}
}
},
concat: {
// 2. Configuration for concatinating files goes here.
dist: {
src: [
'bower_components/jquery/dist/jquery.min.js',
'bower_components/moment/min/moment.min.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.min.js',
'bower_components/datetimepicker/jquery.datetimepicker.js'
],
dest: 'public/js/build/production.js'
}
},
uglify: {
build: {
src: 'public/js/build/production.js',
dest: 'public/js/build/production.min.js'
}
}
});
// 3. Where we tell Grunt we plan to use this plug-in.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-sass');
// 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask('default', ['concat', 'uglify', 'sass']);
};
| module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
options: {
sourceMap: true
},
dist: {
files: {
'public/css/calendar.css': 'public/sass/calendar.scss'
}
}
},
concat: {
// 2. Configuration for concatinating files goes here.
dist: {
src: [
'public/js/jquery-1.11.1.min.js',
'public/js/moment.js',
'public/js/bootstrap.min.js',
'public/js/jquery.datetimepicker.js'
],
dest: 'public/js/build/production.js'
}
},
uglify: {
build: {
src: 'public/js/build/production.js',
dest: 'public/js/build/production.min.js'
}
}
});
// 3. Where we tell Grunt we plan to use this plug-in.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-sass');
// 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask('default', ['concat', 'uglify', 'sass']);
};
|
Add cast so code compiles properly under source 1.4 | package org.bouncycastle.cms;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.interfaces.PBEKey;
import javax.crypto.spec.PBEParameterSpec;
public abstract class CMSPBEKey
implements PBEKey
{
private char[] password;
private byte[] salt;
private int iterationCount;
protected static PBEParameterSpec getParamSpec(AlgorithmParameters algParams)
throws InvalidAlgorithmParameterException
{
try
{
return (PBEParameterSpec)algParams.getParameterSpec(PBEParameterSpec.class);
}
catch (InvalidParameterSpecException e)
{
throw new InvalidAlgorithmParameterException("cannot process PBE spec: " + e.getMessage());
}
}
public CMSPBEKey(char[] password, byte[] salt, int iterationCount)
{
this.password = password;
this.salt = salt;
this.iterationCount = iterationCount;
}
public CMSPBEKey(char[] password, PBEParameterSpec pbeSpec)
{
this(password, pbeSpec.getSalt(), pbeSpec.getIterationCount());
}
public char[] getPassword()
{
return password;
}
public byte[] getSalt()
{
return salt;
}
public int getIterationCount()
{
return iterationCount;
}
public String getAlgorithm()
{
return "PKCS5S2";
}
public String getFormat()
{
return "RAW";
}
public byte[] getEncoded()
{
return null;
}
abstract byte[] getEncoded(String algorithmOid);
}
| package org.bouncycastle.cms;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.interfaces.PBEKey;
import javax.crypto.spec.PBEParameterSpec;
public abstract class CMSPBEKey
implements PBEKey
{
private char[] password;
private byte[] salt;
private int iterationCount;
protected static PBEParameterSpec getParamSpec(AlgorithmParameters algParams)
throws InvalidAlgorithmParameterException
{
try
{
return algParams.getParameterSpec(PBEParameterSpec.class);
}
catch (InvalidParameterSpecException e)
{
throw new InvalidAlgorithmParameterException("cannot process PBE spec: " + e.getMessage());
}
}
public CMSPBEKey(char[] password, byte[] salt, int iterationCount)
{
this.password = password;
this.salt = salt;
this.iterationCount = iterationCount;
}
public CMSPBEKey(char[] password, PBEParameterSpec pbeSpec)
{
this(password, pbeSpec.getSalt(), pbeSpec.getIterationCount());
}
public char[] getPassword()
{
return password;
}
public byte[] getSalt()
{
return salt;
}
public int getIterationCount()
{
return iterationCount;
}
public String getAlgorithm()
{
return "PKCS5S2";
}
public String getFormat()
{
return "RAW";
}
public byte[] getEncoded()
{
return null;
}
abstract byte[] getEncoded(String algorithmOid);
}
|
Add support for django 1.8 by using test runner | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django_pandas',
'django_pandas.tests',
),
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
"USER": "",
"PASSWORD": "",
"HOST": "",
"PORT": "",
}
},
MIDDLEWARE_CLASSES = ()
)
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
def runtests(*test_args):
if not test_args:
test_args = ['django_pandas']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
if django.VERSION < (1, 8):
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(['tests'])
sys.exit(failures)
else:
from django.test.runner import DiscoverRunner
failures = DiscoverRunner(
verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests()
| #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django_pandas',
'django_pandas.tests',
),
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
"USER": "",
"PASSWORD": "",
"HOST": "",
"PORT": "",
}
},
MIDDLEWARE_CLASSES = ()
)
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
Fix PEP8 E713 - test for membership should be "not in" | # -*- coding: utf-8 -*-
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warn("Bad syntax in grains file! Skipping.")
return {}
return {}
| # -*- coding: utf-8 -*-
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if not 'conf_file' in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warn("Bad syntax in grains file! Skipping.")
return {}
return {}
|
Fix added for faster animation. Conflict with modals not showing up resolved. | var apiFactoryApp = angular.module("APIFactoryWeb", ["ngRoute", "Shared", "Main", "Entities"]);
apiFactoryApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/entities', {
templateUrl: 'partials/entities.partial.html',
controller: 'EntityController'
}).
otherwise({
redirectTo: '/entities'
});
}
]);
apiFactoryApp.directive('materialDropdown', ['$rootScope', function($rootScope) {
return {
restrict: 'EA',
link: function(scope, iElement, attrs) {
var element = $(iElement);
element.dropdown({
constrain_width: false, // Does not change width of dropdown to that of the activator
hover: false // Activate on click
}
);
element.click(function() {
var dropdown = element.next();
dropdown.show();
var height = dropdown.css('height');
dropdown.css('height', '0');
dropdown.animate({
'opacity': '1',
'height': height
}, 'fast');
dropdown.attr('visible', 'visible');
});
}
};
}]); | var apiFactoryApp = angular.module("APIFactoryWeb", ["ngRoute", "Shared", "Main", "Entities"]);
apiFactoryApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/entities', {
templateUrl: 'partials/entities.partial.html',
controller: 'EntityController'
}).
otherwise({
redirectTo: '/entities'
});
}
]);
apiFactoryApp.directive('materialDropdown', ['$rootScope', function($rootScope) {
return {
restrict: 'EA',
link: function(scope, iElement, attrs) {
var element = $(iElement);
element.dropdown({
constrain_width: false, // Does not change width of dropdown to that of the activator
hover: false // Activate on click
}
);
element.click(function() {
console.log("Clicked!");
var dropdown = element.next();
dropdown.show();
var height = dropdown.css('height');
dropdown.css('height', '0');
dropdown.animate({
'opacity': '1',
'height': height
});
})
console.log("Applied");
}
};
}]); |
Fix command message if the account wasn't found on deleting. | package com.github.games647.flexiblelogin.tasks;
import com.github.games647.flexiblelogin.FlexibleLogin;
import java.util.UUID;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.command.CommandSource;
public class UnregisterTask implements Runnable {
private final FlexibleLogin plugin;
private final CommandSource src;
private final Object accountIndentifer;
public UnregisterTask(FlexibleLogin plugin, CommandSource src, UUID uuid) {
this.plugin = plugin;
this.src = src;
this.accountIndentifer = uuid;
}
public UnregisterTask(FlexibleLogin plugin, CommandSource src, String playerName) {
this.plugin = plugin;
this.src = src;
this.accountIndentifer = playerName;
}
@Override
public void run() {
boolean accountFound;
if (accountIndentifer instanceof String) {
accountFound = plugin.getDatabase().deleteAccount((String) accountIndentifer);
} else {
accountFound = plugin.getDatabase().deleteAccount((UUID) accountIndentifer);
}
if (accountFound) {
src.sendMessage(Texts.of(TextColors.DARK_GREEN, "Deleted account of: " + accountIndentifer));
} else {
src.sendMessage(Texts.of(TextColors.DARK_RED, "User account not found"));
}
}
}
| package com.github.games647.flexiblelogin.tasks;
import com.github.games647.flexiblelogin.FlexibleLogin;
import java.util.UUID;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.command.CommandSource;
public class UnregisterTask implements Runnable {
private final FlexibleLogin plugin;
private final CommandSource src;
private final Object accountIndentifer;
public UnregisterTask(FlexibleLogin plugin, CommandSource src, UUID uuid) {
this.plugin = plugin;
this.src = src;
this.accountIndentifer = uuid;
}
public UnregisterTask(FlexibleLogin plugin, CommandSource src, String playerName) {
this.plugin = plugin;
this.src = src;
this.accountIndentifer = playerName;
}
@Override
public void run() {
boolean accountFound;
if (accountIndentifer instanceof String) {
accountFound = plugin.getDatabase().deleteAccount((String) accountIndentifer);
} else {
accountFound = plugin.getDatabase().deleteAccount((UUID) accountIndentifer);
}
if (accountFound) {
src.sendMessage(Texts.of(TextColors.DARK_GREEN, "Deleted account of: " + accountIndentifer));
} else {
src.sendMessage(Texts.of(TextColors.DARK_RED, "Error executing command. See console"));
}
}
}
|
Fix typing conflict on Python 3.7
When using bazel on Python3.7, I got error message below
```
Traceback (most recent call last):
File "/private/var/tmp/_bazel_yujo/abf0a3d83a4b1d722a32424a453d5c05/sandbox/darwin-sandbox/39/execroot/__main__/bazel-out/darwin-fastbuild/bin/tests/unit/unit_tests.runfiles/__main__/tests/unit/runner.py", line 2, in <module>
from typing import Any
File "/private/var/tmp/_bazel_yujo/abf0a3d83a4b1d722a32424a453d5c05/sandbox/darwin-sandbox/39/execroot/__main__/bazel-out/darwin-fastbuild/bin/tests/unit/unit_tests.runfiles/pip_deps_pypi__typing_3_7_4_1/typing.py", line 1357, in <module>
class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
File "/private/var/tmp/_bazel_yujo/abf0a3d83a4b1d722a32424a453d5c05/sandbox/darwin-sandbox/39/execroot/__main__/bazel-out/darwin-fastbuild/bin/tests/unit/unit_tests.runfiles/pip_deps_pypi__typing_3_7_4_1/typing.py", line 1005, in __new__
self._abc_registry = extra._abc_registry
AttributeError: type object 'Callable' has no attribute '_abc_registry'
```
After some research, I found this is because expiringdict requires 'typing' regardless of Python version.
From [typing doc](https://docs.python.org/3/library/typing.html), it becomes part of standard library in python 3.5. | from setuptools import setup, find_packages
try:
import md5 # fix for "No module named _md5" error
except ImportError:
# python 3 moved md5
from hashlib import md5
tests_require = [
"dill",
"coverage",
"coveralls",
"mock",
"nose",
]
setup(name="expiringdict",
version="1.2.0",
description="Dictionary with auto-expiring values for caching purposes",
long_description=open("README.rst").read(),
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Topic :: Software Development :: Libraries",
],
keywords="",
author="Mailgun Technologies Inc.",
author_email="[email protected]",
url="https://www.mailgun.com/",
license="Apache 2",
packages=find_packages(exclude=["tests"]),
include_package_data=True,
zip_safe=True,
tests_require=tests_require,
install_requires=[
'typing;python_version<"3.5"',
],
extras_require={
"tests": tests_require,
})
| from setuptools import setup, find_packages
try:
import md5 # fix for "No module named _md5" error
except ImportError:
# python 3 moved md5
from hashlib import md5
tests_require = [
"dill",
"coverage",
"coveralls",
"mock",
"nose",
]
setup(name="expiringdict",
version="1.2.0",
description="Dictionary with auto-expiring values for caching purposes",
long_description=open("README.rst").read(),
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Topic :: Software Development :: Libraries",
],
keywords="",
author="Mailgun Technologies Inc.",
author_email="[email protected]",
url="https://www.mailgun.com/",
license="Apache 2",
packages=find_packages(exclude=["tests"]),
include_package_data=True,
zip_safe=True,
tests_require=tests_require,
install_requires=[
"typing",
],
extras_require={
"tests": tests_require,
})
|
Include poll info field in JSON response | <?php
namespace app\modules\rest\versions\v1\controllers;
use Yii;
use app\models\Poll;
use app\models\Code;
use app\modules\rest\controllers\VotingRestController;
use yii\helpers\ArrayHelper;
use app\components\filters\TokenFilter;
use yii\base\UserException;
class PollController extends VotingRestController
{
public $modelClass = 'app\models\Poll';
public function actionGet()
{
$token = Yii::$app->request->get('token'); // Better way to get this?
$code = Code::findCodeByToken($token);
if (!$code || !$code->isValid()) {
throw new UserException(Yii::t('app', 'Invalid voting code'));
} elseif ($code->isUsed()) {
throw new UserException(Yii::t('app', 'This voting code has already been used'));
}
$poll = $code->getPoll()->with(['options', 'organizer'])->one();
$options = $poll->getOptions()->all();
$organizer = $poll->getOrganizer()->one();
$pollFields = ['title', 'question', 'info', 'select_min', 'select_max', 'start_time', 'end_time'];
$data = ArrayHelper::merge($poll->toArray($pollFields), ['options' => ArrayHelper::getColumn($options, function($option) {
$optionFields = ['id', 'text'];
return $option->toArray($optionFields);
}), 'organizer' => $organizer->toArray(['name', 'email'])]);
return $data;
}
}
| <?php
namespace app\modules\rest\versions\v1\controllers;
use Yii;
use app\models\Poll;
use app\models\Code;
use app\modules\rest\controllers\VotingRestController;
use yii\helpers\ArrayHelper;
use app\components\filters\TokenFilter;
use yii\base\UserException;
class PollController extends VotingRestController
{
public $modelClass = 'app\models\Poll';
public function actionGet()
{
$token = Yii::$app->request->get('token'); // Better way to get this?
$code = Code::findCodeByToken($token);
if (!$code || !$code->isValid()) {
throw new UserException(Yii::t('app', 'Invalid voting code'));
} elseif ($code->isUsed()) {
throw new UserException(Yii::t('app', 'This voting code has already been used'));
}
$poll = $code->getPoll()->with(['options', 'organizer'])->one();
$options = $poll->getOptions()->all();
$organizer = $poll->getOrganizer()->one();
$pollFields = ['title', 'question', 'select_min', 'select_max', 'start_time', 'end_time'];
$data = ArrayHelper::merge($poll->toArray($pollFields), ['options' => ArrayHelper::getColumn($options, function($option) {
$optionFields = ['id', 'text'];
return $option->toArray($optionFields);
}), 'organizer' => $organizer->toArray(['name', 'email'])]);
return $data;
}
}
|
BAP-6772: Remove organization calendar type from community edition | <?php
namespace Oro\Bundle\PlatformBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Oro\Component\Config\Loader\CumulativeConfigLoader;
use Oro\Component\Config\Loader\YamlCumulativeFileLoader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class OroPlatformExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container)
{
$configLoader = new CumulativeConfigLoader(
'oro_app_config',
new YamlCumulativeFileLoader('Resources/config/oro/app.yml')
);
$resources = $configLoader->load();
$extensions = $container->getExtensions();
foreach ($resources as $resource) {
foreach ($resource->data as $name => $config) {
if (!empty($extensions[$name])) {
$container->prependExtensionConfig($name, $config);
}
}
}
}
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
}
}
| <?php
namespace Oro\Bundle\PlatformBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Oro\Component\Config\Loader\CumulativeConfigLoader;
use Oro\Component\Config\Loader\YamlCumulativeFileLoader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class OroPlatformExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container)
{
$configLoader = new CumulativeConfigLoader(
'oro_app_config',
new YamlCumulativeFileLoader('Resources/config/oro/app.yml')
);
$resources = $configLoader->load();
$extensions = $container->getExtensions();
foreach ($resources as $resource) {
foreach ($resource->data as $name => $config) {
var_dump($name);
if (!empty($extensions[$name])) {
$container->prependExtensionConfig($name, $config);
}
}
}
}
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
}
}
|
Handle failed geocoder requests correct | anol.geocoder.Base = function(_options) {
if(_options === undefined) {
return;
}
this.url = _options.url;
this.options = _options;
};
anol.geocoder.Base.prototype = {
CLASS_NAME: 'anol.geocoder.Base',
handleResponse: function(response) {
var self = this;
var results = [];
$.each(response, function(idx, result) {
results.push({
displayText: self.extractDisplayText(result),
coordinate: self.extractCoordinate(result),
projectionCode: self.RESULT_PROJECTION
});
});
return results;
},
request: function(searchString) {
var self = this;
var deferred = $.Deferred();
if(this.options.method === 'post') {
$.post(self.url, self.getData(searchString))
.success(function(response) {
var results = self.handleResponse(response);
deferred.resolve(results);
})
.fail(function() {
deferred.resolve([]);
});
} else {
$.get(self.getUrl(searchString))
.success(function(response) {
var results = self.handleResponse(response);
deferred.resolve(results);
})
.fail(function() {
deferred.resolve([]);
});
}
return deferred.promise();
},
extractDisplayText: function() {
throw 'Not implemented';
},
extractCoordinate: function() {
throw 'Not implemented';
},
getUrl: function() {
throw 'Not implemented';
},
getData: function(searchString) {
return {
search: searchString
};
}
};
| anol.geocoder.Base = function(_options) {
if(_options === undefined) {
return;
}
this.url = _options.url;
this.options = _options;
};
anol.geocoder.Base.prototype = {
CLASS_NAME: 'anol.geocoder.Base',
handleResponse: function(response) {
var self = this;
var results = [];
$.each(response, function(idx, result) {
results.push({
displayText: self.extractDisplayText(result),
coordinate: self.extractCoordinate(result),
projectionCode: self.RESULT_PROJECTION
});
});
return results;
},
request: function(searchString) {
var self = this;
var deferred = $.Deferred();
if(this.options.method === 'post') {
$.post(self.url, self.getData(searchString))
.success(function(response) {
var results = self.handleResponse(response);
deferred.resolve(results);
});
} else {
$.get(self.getUrl(searchString))
.success(function(response) {
var results = self.handleResponse(response);
deferred.resolve(results);
});
}
return deferred.promise();
},
extractDisplayText: function() {
throw 'Not implemented';
},
extractCoordinate: function() {
throw 'Not implemented';
},
getUrl: function() {
throw 'Not implemented';
},
getData: function(searchString) {
return {
search: searchString
};
}
};
|
Use Objects::requireNonNull instead of if-throw | /*
* Copyright (c) 2013-2015 Falko Schumann <www.muspellheim.de>
* Released under the terms of the MIT License.
*/
package de.muspellheim.signalslot;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A signal act as source of data and can connect to any compatible slot.
*
* @param <T> value type
* @author Falko Schumann <www.muspellheim.de>
*/
public class Signal<T> implements Slot<T> {
private List<Slot<T>> slots = new CopyOnWriteArrayList<>();
private boolean blocked;
public final void connect(final Slot<T> slot) {
Objects.requireNonNull(receiver, "slot");
slots.add(slot);
}
public final void disconnect(final Slot<T> slot) {
Objects.requireNonNull(receiver, "slot");
slots.remove(slot);
}
public final void disconnectAll() {
slots.clear();
}
public final void emit(final T value) {
if (isBlocked()) {
return;
}
for (Slot<T> e : slots) {
e.receive(value);
}
}
public final boolean isBlocked() {
return blocked;
}
public final void setBlocked(final boolean blocked) {
this.blocked = blocked;
}
@Override
public final void receive(final T value) {
emit(value);
}
}
| /*
* Copyright (c) 2013-2015 Falko Schumann <www.muspellheim.de>
* Released under the terms of the MIT License.
*/
package de.muspellheim.signalslot;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A signal act as source of data and can connect to any compatible slot.
*
* @param <T> value type
* @author Falko Schumann <www.muspellheim.de>
*/
public class Signal<T> implements Slot<T> {
private List<Slot<T>> slots = new CopyOnWriteArrayList<>();
private boolean blocked;
public final void connect(final Slot<T> slot) {
if (slot == null) {
throw new NullPointerException("slot");
}
slots.add(slot);
}
public final void disconnect(final Slot<T> slot) {
if (slot == null) {
throw new NullPointerException("slot");
}
slots.remove(slot);
}
public final void disconnectAll() {
slots.clear();
}
public final void emit(final T value) {
if (isBlocked()) {
return;
}
for (Slot<T> e : slots) {
e.receive(value);
}
}
public final boolean isBlocked() {
return blocked;
}
public final void setBlocked(final boolean blocked) {
this.blocked = blocked;
}
@Override
public final void receive(final T value) {
emit(value);
}
}
|
Add source map to uglifyjs | const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './src/index.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, 'dist'),
filename: 'sync-client.min.js',
libraryTarget: 'commonjs2',
library: 'sync-client.min.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: ['transform-runtime'],
presets: [
['es2015', { modules: false }],
],
},
},
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
},
output: {
comments: false,
},
sourceMap: true,
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') },
}),
],
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js'],
modules: [
path.resolve(__dirname, 'node_modules'),
],
},
};
| const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './src/index.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, 'dist'),
filename: 'sync-client.min.js',
libraryTarget: 'commonjs2',
library: 'sync-client.min.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: ['transform-runtime'],
presets: [
['es2015', { modules: false }],
],
},
},
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
},
output: {
comments: false,
},
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') },
}),
],
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js'],
modules: [
path.resolve(__dirname, 'node_modules'),
],
},
};
|
Remove route ignore adding if not enabled | <?php
namespace Gregoriohc\Preview;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
class PreviewServiceProvider extends LaravelServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->handleConfigs();
if (!$this->app->routesAreCached()) {
$middleware = [];
if (request()->has('_middleware')) {
$middleware = array_merge(config('preview.middleware'), explode(',', request('_middleware')));
}
Route::group(['middleware' => $middleware], function () {
$route = trim(config('preview.route'), '\\');
Route::get($route.'/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
});
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [];
}
private function handleConfigs()
{
$configPath = __DIR__.'/../config/preview.php';
$this->publishes([$configPath => config_path('preview.php')]);
$this->mergeConfigFrom($configPath, 'preview');
}
public static function isEnabled()
{
return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
}
}
| <?php
namespace Gregoriohc\Preview;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
class PreviewServiceProvider extends LaravelServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->handleConfigs();
if (!$this->app->routesAreCached() && $this->isEnabled()) {
$middleware = [];
if (request()->has('_middleware')) {
$middleware = array_merge(config('preview.middleware'), explode(',', request('_middleware')));
}
Route::group(['middleware' => $middleware], function () {
$route = trim(config('preview.route'), '\\');
Route::get($route.'/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
});
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [];
}
private function handleConfigs()
{
$configPath = __DIR__.'/../config/preview.php';
$this->publishes([$configPath => config_path('preview.php')]);
$this->mergeConfigFrom($configPath, 'preview');
}
public static function isEnabled()
{
return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
}
}
|
Correct default handling of collection key | import stableStringify from 'json-stable-stringify';
function defaultGetId(item) {
return item.id;
}
function defaultCollectionKey(options = {}) {
return stableStringify(options);
}
function defaultItemKey(id) {
return id;
}
export default function generateStore({
getId = defaultGetId,
collectionKey = defaultCollectionKey,
itemKey = defaultItemKey
}) {
const {methodNames} = this;
return {
getInitialState() {
return {
collections: {},
items: {}
};
},
getId,
collectionKey,
itemKey,
[methodNames.getMany](options) {
const collection =
this.state.collections[this.collectionKey(options)];
if (!collection) {
return collection;
}
return collection.map(
id => this.state.items[this.itemKey(id, options)]
);
},
[methodNames.getSingle](id, options) {
return this.state.items[this.itemKey(id, options)];
},
receiveMany({options, result}) {
const resultIds = [];
result.forEach(item => {
const id = this.getId(item);
resultIds.push(id);
this.receiveSingle({id, options, result: item});
});
this.state.collections[this.collectionKey(options)] = resultIds;
},
receiveSingle({id, options, result}) {
if (id === undefined) {
id = this.getId(result);
}
this.state.items[this.itemKey(id, options)] = result;
}
};
}
| import stableStringify from 'json-stable-stringify';
function defaultGetId(item) {
return item.id;
}
function defaultCollectionKey(options) {
if (!options) {
return '';
}
return stableStringify(options);
}
function defaultItemKey(id) {
return id;
}
export default function generateStore({
getId = defaultGetId,
collectionKey = defaultCollectionKey,
itemKey = defaultItemKey
}) {
const {methodNames} = this;
return {
getInitialState() {
return {
collections: {},
items: {}
};
},
getId,
collectionKey,
itemKey,
[methodNames.getMany](options) {
const collection =
this.state.collections[this.collectionKey(options)];
if (!collection) {
return collection;
}
return collection.map(
id => this.state.items[this.itemKey(id, options)]
);
},
[methodNames.getSingle](id, options) {
return this.state.items[this.itemKey(id, options)];
},
receiveMany({options, result}) {
const resultIds = [];
result.forEach(item => {
const id = this.getId(item);
resultIds.push(id);
this.receiveSingle({id, options, result: item});
});
this.state.collections[this.collectionKey(options)] = resultIds;
},
receiveSingle({id, options, result}) {
if (id === undefined) {
id = this.getId(result);
}
this.state.items[this.itemKey(id, options)] = result;
}
};
}
|
Improve handling of non standard errors returned | (function () {
"use strict";
var Fiber = require('fibers'),
extend = require('util')._extend;
module.exports = Future;
function Future () {
this.fiber = Fiber.current;
this.resolved = false;
this.yielded = false;
}
Future.prototype.resolve = function (err, res) {
var self = this;
if (this.resolved) return;
this.resolved = true;
if (err && ! (err instanceof Error)) {
if (typeof err === 'string')
err = new Error(err);
else if (typeof err === 'object')
err = extend(new Error, err);
if (! err.message) err.message = '[syncho] Unknown error captured';
}
if (this.yielded) {
process.nextTick(function () {
if (err) {
self.fiber.run(err);
} else {
self.fiber.run(res);
}
self.fiber = null;
});
} else {
this.error = err;
this.result = res;
this.fiber = null;
}
};
Future.prototype.wait = function () {
if (! this.resolved) {
try {
this.result = this.produce();
}
catch (err) {
this.error = err;
}
}
this.fiber = null;
var result = this.result, error = this.error;
this.result = null;
this.error = null;
if (error)
throw error;
else
return result;
};
Future.prototype.produce = function () {
this.yielded = true;
var res = Fiber.yield();
if (res instanceof Error) throw res;
else return res;
};
})(); | (function () {
"use strict";
var Fiber = require('fibers');
module.exports = Future;
function Future () {
this.fiber = Fiber.current;
this.resolved = false;
this.yielded = false;
}
Future.prototype.resolve = function (err, res) {
var self = this;
if (this.resolved) return;
this.resolved = true;
if (err && ! (err instanceof Error)) err = new Error(err);
if (this.yielded) {
process.nextTick(function () {
if (err) {
self.fiber.run(err);
} else {
self.fiber.run(res);
}
self.fiber = null;
});
} else {
this.error = err;
this.result = res;
this.fiber = null;
}
};
Future.prototype.wait = function () {
if (! this.resolved) {
try {
this.result = this.produce();
}
catch (err) {
this.error = err;
}
}
this.fiber = null;
var result = this.result, error = this.error;
this.result = null;
this.error = null;
if (error)
throw error;
else
return result;
};
Future.prototype.produce = function () {
this.yielded = true;
var res = Fiber.yield();
if (res instanceof Error) throw res;
else return res;
};
})(); |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.