text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix Memcachestat. Using wrong classname
git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@902 44740490-163a-0410-bde0-09ae8108e29a
|
<?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_Memcache::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?>
|
<?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_MemcacheStore::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?>
|
Set base URL for production in demo
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
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
}
};
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.baseURL = '/';
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') {
ENV.baseURL = '/ember-inplace-edit';
}
return ENV;
};
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
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
}
};
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.baseURL = '/';
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;
};
|
Update up to changes in es5-ext
|
'use strict';
var aFrom = require('es5-ext/array/from')
, partial = require('es5-ext/function/#/partial')
, mixin = require('es5-ext/object/mixin')
, ee = require('event-emitter')
, o;
o = ee(exports = {
init: function () {
this.msg = [];
this.passed = [];
this.errored = [];
this.failed = [];
this.started = new Date();
return this;
},
in: function (msg) {
this.msg.push(msg);
},
out: function () {
this.msg.pop();
},
log: function (type, data) {
var o = { type: type, time: new Date(), data: data, msg: aFrom(this.msg) };
this.push(o);
this[type + 'ed'].push(o);
this.emit('data', o);
},
end: function () {
this.emit('end');
}
});
o.log.partial = partial;
o.error = o.log.partial('error');
o.pass = o.log.partial('pass');
o.fail = o.log.partial('fail');
module.exports = function () {
return mixin([], o).init();
};
|
'use strict';
var aFrom = require('es5-ext/array/from')
, partial = require('es5-ext/function/#/partial')
, extend = require('es5-ext/object/extend-properties')
, ee = require('event-emitter')
, o;
o = ee(exports = {
init: function () {
this.msg = [];
this.passed = [];
this.errored = [];
this.failed = [];
this.started = new Date();
return this;
},
in: function (msg) {
this.msg.push(msg);
},
out: function () {
this.msg.pop();
},
log: function (type, data) {
var o = { type: type, time: new Date(), data: data, msg: aFrom(this.msg) };
this.push(o);
this[type + 'ed'].push(o);
this.emit('data', o);
},
end: function () {
this.emit('end');
}
});
o.log.partial = partial;
o.error = o.log.partial('error');
o.pass = o.log.partial('pass');
o.fail = o.log.partial('fail');
module.exports = function () {
return extend([], o).init();
};
|
Remove fantastic from COB theme
Updates #10
|
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1})
return result['count']
class CobPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
# IConfigurer
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
def get_helpers(self):
# Register cob_theme_* helper functions
return {'cob_theme_groups': groups,
'cob_theme_dataset_count': dataset_count}
|
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1})
return result['count']
class CobPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
# IConfigurer
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
toolkit.add_resource('fanstatic', 'cob')
def get_helpers(self):
# Register cob_theme_* helper functions
return {'cob_theme_groups': groups,
'cob_theme_dataset_count': dataset_count}
|
Add 'places' library for the maps search box.
|
'use strict';
/**
* Google maps configuration.
*
* @param uiGmapGoogleMapApiProvider
*/
MapsConfiguration.$inject = ['uiGmapGoogleMapApiProvider'];
function MapsConfiguration(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
/**
* Google Maps API key.
*
* This key is specific to you/your application.
*
* An API key is recommended but maps will work, up to a point, without an API key.
*/
// key: 'Your API key',
/**
* Required version.
*
* Specifying e.g. "3" will always pick the latest version in that series.
*
* It is possible to specify a specific version, e.g. "3.19", or even the bleeding edge
* experimental version with "3.exp".
*
* If you specify a 'retired' version, then the oldest available version will be used.
*/
v: '3',
/**
* Include additional Google Maps libraries.
*
* The 'places' library is required for the map search box.
*/
libraries: 'places'
});
};
module.exports = MapsConfiguration;
|
'use strict';
/**
* Google maps configuration.
*
* @param uiGmapGoogleMapApiProvider
*/
MapsConfiguration.$inject = ['uiGmapGoogleMapApiProvider'];
function MapsConfiguration(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
/**
* Google Maps API key.
*
* This key is specific to you/your application.
*
* An API key is recommended but maps will work, up to a point, without an API key.
*/
// key: 'Your API key',
/**
* Required version.
*
* Specifying e.g. "3" will always pick the latest version in that series.
*
* It is possible to specify a specific version, e.g. "3.19", or even the bleeding edge
* experimental version with "3.exp".
*
* If you specify a 'retired' version, then the oldest available version will be used.
*/
v: '3'
});
};
module.exports = MapsConfiguration;
|
Set some fields as tranlate
|
# -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields
class CrmEmployeesRange(models.Model):
_name = 'crm.employees_range'
_order = "parent_left"
_parent_order = "name"
_parent_store = True
_description = "Employees range"
name = fields.Char(required=True, translate=True)
parent_id = fields.Many2one(comodel_name='crm.employees_range')
children = fields.One2many(comodel_name='crm.employees_range',
inverse_name='parent_id')
parent_left = fields.Integer('Parent Left', select=True)
parent_right = fields.Integer('Parent Right', select=True)
|
# -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields
class CrmEmployeesRange(models.Model):
_name = 'crm.employees_range'
_order = "parent_left"
_parent_order = "name"
_parent_store = True
_description = "Employees range"
name = fields.Char(required=True)
parent_id = fields.Many2one(comodel_name='crm.employees_range')
children = fields.One2many(comodel_name='crm.employees_range',
inverse_name='parent_id')
parent_left = fields.Integer('Parent Left', select=True)
parent_right = fields.Integer('Parent Right', select=True)
|
[IMP] Allow to override any config parameter via config file
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import api, models, tools
class IrConfigParameter(models.Model):
_inherit = 'ir.config_parameter'
@api.model
def get_param(self, key, default=False):
if key in tools.config.options:
return tools.config.get(key)
return super(IrConfigParameter, self).get_param(key, default)
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import api, models, tools
class IrConfigParameter(models.Model):
_inherit = 'ir.config_parameter'
@api.model
def get_param(self, key, default=False):
if key == 'server.environment':
return tools.config.get('server.environment') or default
if key == 'max_upload_size':
return tools.config.get('max_upload_size') or default
return super(IrConfigParameter, self).get_param(key, default)
|
Make FixtureDataItem private in related_to_domain
|
function(doc) {
var DOC_TYPES = { // use this object to look up case types
'ExceptionRecord': false,
'MessageLog': false,
'RegistrationRequest': false,
'SMSLog': false,
'XFormInstance': false,
'CommCareUser': false,
'CommCareCase': false,
'UserRole': true,
'Application': true,
'RemoteApp': true,
'CaseReminderHandler': true,
'FixtureDataType': true
};
if (doc.domain) {
// "public" if it's one of the public doctypes and it's the current version
var public = DOC_TYPES[doc.doc_type] &&
!((doc.doc_type === 'Application' || doc.doc_type === 'RemoteApp') && doc.copy_of);
emit([doc.domain, public], {doc_type: doc.doc_type, _id: doc._id});
}
}
|
function(doc) {
var DOC_TYPES = { // use this object to look up case types
'ExceptionRecord': false,
'MessageLog': false,
'RegistrationRequest': false,
'SMSLog': false,
'XFormInstance': false,
'CommCareUser': false,
'CommCareCase': false,
'UserRole': true,
'Application': true,
'RemoteApp': true,
'CaseReminderHandler': true,
'FixtureDataType': true,
'FixtureDataItem': true
};
if (doc.domain) {
// "public" if it's one of the public doctypes and it's the current version
var public = DOC_TYPES[doc.doc_type] &&
!((doc.doc_type === 'Application' || doc.doc_type === 'RemoteApp') && doc.copy_of);
emit([doc.domain, public], {doc_type: doc.doc_type, _id: doc._id});
}
}
|
Add correct edit counted quantity key value
|
/* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
export const ACTIONS = {
// tableAction constants
SORT_DATA: 'sortData',
FILTER_DATA: 'filterData',
REFRESH_DATA: 'refreshData',
ADD_ITEM: 'addItem',
ADD_RECORD: 'addRecord',
HIDE_OVER_STOCKED: 'hideOverStocked',
HIDE_STOCK_OUT: 'hideStockOut',
// pageAction constants
OPEN_MODAL: 'openModal',
CLOSE_MODAL: 'closeModal',
// rowAction constants
REFRESH_ROW: 'refreshRow',
EDIT_TOTAL_QUANTITY: 'editTotalQuantity',
EDIT_COUNTED_QUANTITY: 'editCountedQuantity',
EDIT_REQUIRED_QUANTITY: 'editRequiredQuantity',
EDIT_EXPIRY_DATE: 'editExpiryDate',
ENFORCE_REASON: 'enforceReasonChoice',
// cellAction constants
FOCUS_CELL: 'focusCell',
FOCUS_NEXT: 'focusNext',
SELECT_ROW: 'selectRow',
SELECT_ALL: 'selectAll',
SELECT_ITEMS: 'selectItems',
DESELECT_ROW: 'deselectRow',
DESELECT_ALL: 'deselectAll',
DELETE_RECORDS: 'deleteSelectedItems',
};
|
/* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
export const ACTIONS = {
// tableAction constants
SORT_DATA: 'sortData',
FILTER_DATA: 'filterData',
REFRESH_DATA: 'refreshData',
ADD_ITEM: 'addItem',
ADD_RECORD: 'addRecord',
HIDE_OVER_STOCKED: 'hideOverStocked',
HIDE_STOCK_OUT: 'hideStockOut',
// pageAction constants
OPEN_MODAL: 'openModal',
CLOSE_MODAL: 'closeModal',
// rowAction constants
REFRESH_ROW: 'refreshRow',
EDIT_TOTAL_QUANTITY: 'editTotalQuantity',
EDIT_COUNTED_QUANTITY: 'editCountedTotalQuantity',
EDIT_REQUIRED_QUANTITY: 'editRequiredQuantity',
EDIT_EXPIRY_DATE: 'editExpiryDate',
ENFORCE_REASON: 'enforceReasonChoice',
// cellAction constants
FOCUS_CELL: 'focusCell',
FOCUS_NEXT: 'focusNext',
SELECT_ROW: 'selectRow',
SELECT_ALL: 'selectAll',
SELECT_ITEMS: 'selectItems',
DESELECT_ROW: 'deselectRow',
DESELECT_ALL: 'deselectAll',
DELETE_RECORDS: 'deleteSelectedItems',
};
|
Change the parser library requirement to reference master
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='money-to-prisoners-transaction-uploader',
version='0.1',
packages=[
'mtp_transaction_uploader',
],
entry_points={
'console_scripts': ['upload-transactions = mtp_transaction_uploader.upload:main']
},
include_package_data=True,
license='BSD License',
description='Retrieve direct services file, process, and upload transactions',
long_description=README,
dependency_links=[
'https://github.com/ministryofjustice/bankline-direct-parser/tarball/master#egg=bankline-direct-parser'
],
install_requires=[
'requests-oauthlib==0.5.0',
'slumber==0.7.1',
'pysftp==0.2.8',
'bankline-direct-parser'
],
classifiers=[
'Intended Audience :: Python Developers',
],
test_suite='tests'
)
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='money-to-prisoners-transaction-uploader',
version='0.1',
packages=[
'mtp_transaction_uploader',
],
entry_points={
'console_scripts': ['upload-transactions = mtp_transaction_uploader.upload:main']
},
include_package_data=True,
license='BSD License',
description='Retrieve direct services file, process, and upload transactions',
long_description=README,
dependency_links=[
'https://github.com/ministryofjustice/bankline-direct-parser/tarball/data-services-parser#egg=bankline-direct-parser'
],
install_requires=[
'requests-oauthlib==0.5.0',
'slumber==0.7.1',
'pysftp==0.2.8',
'bankline-direct-parser'
],
classifiers=[
'Intended Audience :: Python Developers',
],
test_suite='tests'
)
|
Add reselect support for job limit values
|
import { createSelector } from "reselect";
import { endsWith, flatMap, keys, map, max, pick } from "lodash-es";
import { taskDisplayNames } from "../utils";
const getMaximumTaskLimit = (limits, type) => (
max(map(limits, (value, key) =>
endsWith(key, type) ? value : 0
))
);
const taskLimitKeys = flatMap(keys(taskDisplayNames), name => [`${name}_proc`, `${name}_mem`]);
const taskSpecificLimitSelector = state => pick(state.settings.data, taskLimitKeys);
const resourcesSelector = state => state.jobs.resources;
export const maxResourcesSelector = createSelector(
[resourcesSelector],
resources => {
if (resources === null) {
return {
maxProc: 1,
maxMem: 1
};
}
const maxProc = resources.proc.length;
const maxMem = Math.floor(resources.mem.total / Math.pow(1024, 3));
return { maxProc, maxMem };
}
);
export const minResourcesSelector = createSelector(
[taskSpecificLimitSelector],
(limits) => ({
minProc: getMaximumTaskLimit(limits, "proc"),
minMem: getMaximumTaskLimit(limits, "mem")
})
);
|
import { createSelector } from "reselect";
import { endsWith, flatMap, keys, map, max, pick } from "lodash-es";
import { taskDisplayNames } from "../utils";
const getMaximumTaskLimit = (limits, type) => (
max(map(limits, (value, key) =>
endsWith(key, type) ? value: 0
))
);
const taskLimitKeys = flatMap(keys(taskDisplayNames), name => [`${name}_proc`, `${name}_mem`]);
const taskSpecificLimitSelector = state => pick(state.settings.data, taskLimitKeys);
const resourcesSelector = state => state.jobs.resources;
export const maxResourcesSelector = createSelector(
[resourcesSelector],
resources => {
const procLimit = resources.proc.length;
const memLimit = parseFloat((resources.mem.total / Math.pow(1024, 3)).toFixed(1));
return { procLimit, memLimit };
}
);
export const minResourcesSelector = createSelector(
[taskSpecificLimitSelector],
(limits) => ({
proc: getMaximumTaskLimit(limits, "proc"),
mem: getMaximumTaskLimit(limits, "mem")
})
);
|
Fix error when the menu is horizontal.
FlexMenu created a unique menu with every item in a submenu.
|
$(function () {
var mainMenu = document.getElementById('header-nav');
$(mainMenu).bind('scroll', mainMenuDropShadow);
$(window).bind('resize', function() {
mainMenuDropShadow.apply(mainMenu);
mainMenuResponsiveCollapse();
});
mainMenuDropShadow.apply(mainMenu);
mainMenuResponsiveCollapse();
});
function mainMenuDropShadow() {
var headerFooter = $("#header-footer");
if (this.scrollHeight === this.clientHeight) {
headerFooter.removeClass('drop-shadow');
return;
}
var scrollPercent = 100 * this.scrollTop / this.scrollHeight / (1 - this.clientHeight / this.scrollHeight);
isNaN(scrollPercent) || scrollPercent >= 100 ? headerFooter.removeClass('drop-shadow') : headerFooter.addClass('drop-shadow');
}
function mainMenuResponsiveCollapse() {
var mainMenuItems = $('#header-menu');
if ($(window).width() > 768 && $(window).width() < 1024) {
mainMenuItems.flexMenu({'linkText': '...'});
} else {
mainMenuItems.flexMenu({ 'undo': true });
}
}
|
$(function () {
var mainMenu = document.getElementById('header-nav');
$(mainMenu).bind('scroll', mainMenuDropShadow);
$(window).bind('resize', function() {
mainMenuDropShadow.apply(mainMenu);
mainMenuResponsiveCollapse();
});
mainMenuDropShadow.apply(mainMenu);
mainMenuResponsiveCollapse();
});
function mainMenuDropShadow() {
var headerFooter = $("#header-footer");
if (this.scrollHeight === this.clientHeight) {
headerFooter.removeClass('drop-shadow');
return;
}
var scrollPercent = 100 * this.scrollTop / this.scrollHeight / (1 - this.clientHeight / this.scrollHeight);
isNaN(scrollPercent) || scrollPercent >= 100 ? headerFooter.removeClass('drop-shadow') : headerFooter.addClass('drop-shadow');
}
function mainMenuResponsiveCollapse() {
var mainMenuItems = $('#header-menu');
if ($(window).width() > 768 && $(window).width() < 1200) {
mainMenuItems.flexMenu({'linkText': '...'});
} else {
mainMenuItems.flexMenu({ 'undo': true });
}
}
|
Add loadApp to test cases
|
<?php
OC_App::loadApp('bookmarks');
class Test_LibBookmarks_Bookmarks extends UnitTestCase {
function testAddBM() {
$this->assertCount(0, OC_Bookmarks_Bookmarks::findBookmarks(0, 'id', array(), true, -1));
OC_Bookmarks_Bookmarks::addBookmark(
'http://owncloud.org', 'Owncloud project', array('oc', 'cloud'), 'An Awesome project');
$this->assertCount(1, OC_Bookmarks_Bookmarks::findBookmarks(0, 'id', array(), true, -1));
}
function testFindTags() {
// $uid=uniqid();
$this->assertEqual(OC_Bookmarks_Bookmarks::findTags(), array());
OC_Bookmarks_Bookmarks::addBookmark(
'http://owncloud.org', 'Owncloud project', array('oc', 'cloud'), 'An Awesome project');
$this->assertEqual(array(0=>array('tag' => 'cloud', 'nbr'=>1), 1=>array('tag' => 'oc', 'nbr'=>1)),
OC_Bookmarks_Bookmarks::findTags());
}
protected function tearDown() {
$query = OC_DB::prepare('DELETE FROM *PREFIX*bookmarks WHERE `user_id` = \'\' ');
$query->execute();
}
}
|
<?php
class Test_LibBookmarks_Bookmarks extends UnitTestCase {
function testAddBM() {
$this->assertCount(0, OC_Bookmarks_Bookmarks::findBookmarks(0, 'id', array(), true, -1));
OC_Bookmarks_Bookmarks::addBookmark(
'http://owncloud.org', 'Owncloud project', array('oc', 'cloud'), 'An Awesome project');
$this->assertCount(1, OC_Bookmarks_Bookmarks::findBookmarks(0, 'id', array(), true, -1));
}
function testFindTags() {
// $uid=uniqid();
$this->assertEqual(OC_Bookmarks_Bookmarks::findTags(), array());
OC_Bookmarks_Bookmarks::addBookmark(
'http://owncloud.org', 'Owncloud project', array('oc', 'cloud'), 'An Awesome project');
$this->assertEqual(array(0=>array('tag' => 'cloud', 'nbr'=>1), 1=>array('tag' => 'oc', 'nbr'=>1)),
OC_Bookmarks_Bookmarks::findTags());
}
protected function tearDown() {
$query = OC_DB::prepare('DELETE FROM *PREFIX*bookmarks WHERE `user_id` = \'\' ');
$query->execute();
}
}
|
Write the correct variable to disk
Maybe I should get more sleep
|
# -*- coding: utf-8 -*-
'''
Generate a unique uuid for this host, storing it on disk so it persists across
restarts
'''
import logging
import os
import uuid
log = logging.getLogger(__name__)
def host_uuid():
'''
Generate a unique uuid for this host, storing it on disk so it persists
across restarts
'''
cached_uuid = os.path.join(os.path.dirname(__opts__['configfile']), 'hubble_cached_uuid')
try:
if os.path.isfile(cached_uuid):
with open(cached_uuid, 'r') as f:
return {'host_uuid': f.read()}
except Exception as exc:
log.exception('Problem retrieving cached host uuid')
generated = uuid.uuid4()
with open(cached_uuid, 'w') as f:
f.write(generated)
return {'host_uuid': generated}
|
# -*- coding: utf-8 -*-
'''
Generate a unique uuid for this host, storing it on disk so it persists across
restarts
'''
import logging
import os
import uuid
log = logging.getLogger(__name__)
def host_uuid():
'''
Generate a unique uuid for this host, storing it on disk so it persists
across restarts
'''
cached_uuid = os.path.join(os.path.dirname(__opts__['configfile']), 'hubble_cached_uuid')
try:
if os.path.isfile(cached_uuid):
with open(cached_uuid, 'r') as f:
return {'host_uuid': f.read()}
except Exception as exc:
log.exception('Problem retrieving cached host uuid')
generated = uuid.uuid4()
with open(cached_uuid, 'w') as f:
f.write(cached_uuid)
return {'host_uuid': generated}
|
Fix zindex on bluedot overlay
|
import React from 'react';
import { View } from 'react-native';
import * as Animatable from 'react-native-animatable';
const BlueDot = ({ dotSize, dotStyle }) => {
const innerWhiteDotSize = dotSize * 0.6,
innerBlueDotSize = dotSize * 0.5;
return (
<View style={dotStyle}>
<Animatable.View
style={{ width: dotSize, height: dotSize, borderRadius: dotSize / 2, borderColor: '#B3E5FC', borderWidth: dotSize / 2, zIndex: 2 }}
ref={c => { this._view = c; }}
animation='zoomIn'
easing='ease'
iterationCount='infinite'
/>
<View style={{ position: 'absolute', top: ((dotSize - innerWhiteDotSize) / 2), left: ((dotSize - innerWhiteDotSize) / 2), width: innerWhiteDotSize, height: innerWhiteDotSize, borderRadius: innerWhiteDotSize / 2, borderColor: 'white', borderWidth: innerWhiteDotSize / 2, zIndex: 3 }} />
<View style={{ position: 'absolute', top: ((dotSize - innerBlueDotSize) / 2), left: ((dotSize - innerBlueDotSize) / 2), width: innerBlueDotSize, height: innerBlueDotSize, borderRadius: innerBlueDotSize / 2, borderColor: '#03A9F4', borderWidth: innerBlueDotSize / 2, zIndex: 4 }} />
</View>
);
};
export default BlueDot;
|
import React from 'react';
import { View } from 'react-native';
import * as Animatable from 'react-native-animatable';
const BlueDot = ({ dotSize, dotStyle }) => {
const innerWhiteDotSize = dotSize * 0.6,
innerBlueDotSize = dotSize * 0.5;
return (
<View style={dotStyle}>
<Animatable.View
style={{ width: dotSize, height: dotSize, borderRadius: dotSize / 2, borderColor: '#B3E5FC', borderWidth: dotSize / 2, zIndex: 2 }}
ref={c => { this._view = c; }}
animation='zoomIn'
easing='ease'
iterationCount='infinite'
/>
<View style={{ position: 'absolute', top: ((dotSize - innerWhiteDotSize) / 2), left: ((dotSize - innerWhiteDotSize) / 2), width: innerWhiteDotSize, height: innerWhiteDotSize, borderRadius: innerWhiteDotSize / 2, borderColor: 'white', borderWidth: innerWhiteDotSize / 2, zIndex: 3 }} />
<View style={{ position: 'absolute', top: ((dotSize - innerBlueDotSize) / 2), left: ((dotSize - innerBlueDotSize) / 2), width: innerBlueDotSize, height: innerBlueDotSize, borderRadius: innerBlueDotSize / 2, borderColor: '#03A9F4', borderWidth: innerBlueDotSize / 2, zIndex: 3 }} />
</View>
);
};
export default BlueDot;
|
Refactor to record and add docs.
|
package org.cryptomator.cryptofs.health.dirid;
import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;
import java.io.IOException;
import java.nio.file.Path;
/**
* The dir id backup file is missing.
*/
public record MissingDirIdBackup(String dirId, Path cipherDir) implements DiagnosticResult {
@Override
public Severity getSeverity() {
return Severity.WARN;
}
@Override
public String toString() {
return String.format("Directory ID backup for directory %s is missing.", cipherDir);
}
@Override
public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId, cipherDir));
}
}
|
package org.cryptomator.cryptofs.health.dirid;
import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;
import java.io.IOException;
import java.nio.file.Path;
/**
* TODO: adjust DirIdCheck
*/
public class MissingDirIdBackup implements DiagnosticResult {
private final Path cipherDir;
private final String dirId;
MissingDirIdBackup(String dirId, Path cipherDir) {
this.cipherDir = cipherDir;
this.dirId = dirId;
}
@Override
public Severity getSeverity() {
return Severity.WARN; //TODO: decide severity
}
@Override
public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId,cipherDir));
}
}
|
Handle missing projects properly in file-count script
GitOrigin-RevId: 5968fc3c6646a6e75b2b84440d59d9c0cbcead5e
|
const readline = require('readline')
const ProjectEntityHandler = require('../app/src/Features/Project/ProjectEntityHandler')
const ProjectGetter = require('../app/src/Features/Project/ProjectGetter')
const Errors = require('../app/src/Features/Errors/Errors')
async function countFiles() {
const rl = readline.createInterface({
input: process.stdin
})
for await (const projectId of rl) {
try {
const project = await ProjectGetter.promises.getProject(projectId)
if (!project) {
throw new Errors.NotFoundError('project not found')
}
const {
files,
docs
} = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
console.error(
projectId,
files.length,
(project.deletedFiles && project.deletedFiles.length) || 0,
docs.length,
(project.deletedDocs && project.deletedDocs.length) || 0
)
} catch (err) {
if (err instanceof Errors.NotFoundError) {
console.error(projectId, 'NOTFOUND')
} else {
throw err
}
}
}
}
countFiles().then(() => process.exit(0))
|
const readline = require('readline')
const ProjectEntityHandler = require('../app/src/Features/Project/ProjectEntityHandler')
const ProjectGetter = require('../app/src/Features/Project/ProjectGetter')
const Errors = require('../app/src/Features/Errors/Errors')
async function countFiles() {
const rl = readline.createInterface({
input: process.stdin
})
for await (const projectId of rl) {
try {
const project = await ProjectGetter.promises.getProject(projectId)
const {
files,
docs
} = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
console.error(
projectId,
files.length,
(project.deletedFiles && project.deletedFiles.length) || 0,
docs.length,
(project.deletedDocs && project.deletedDocs.length) || 0
)
} catch (err) {
if (err instanceof Errors.NotFoundError) {
console.error(projectId, 'NOTFOUND')
} else {
throw err
}
}
}
}
countFiles().then(() => process.exit(0))
|
Fix minor issue with the FS registry
|
<?php
namespace BlizzardGalaxy\ApiSupervisor\Registry;
use BlizzardGalaxy\ApiSupervisor\Exception\ApiSupervisorException;
/**
* Offers methods for easily reading in configuration values.
*
* @package BlizzardGalaxy\ApiSupervisor\Registry
* @author Petre Pătrașc <petre@dreamlabs.ro>
*/
class FileSystemRegistryManager extends AbstractRegistryManager
{
/**
* Return the filepath to the config folder.
*
* @return string
*/
private function getConfigFilePath()
{
return __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR;
}
/**
* Retrieve the API key used to make calls
* to Battle.NET endpoints.
*
* @return string
* @throws ApiSupervisorException
*/
public function getApiKey()
{
$apiKey = @file_get_contents($this->getConfigFilePath() . 'apikey.lock');
if (false === $apiKey) {
throw new ApiSupervisorException('Could not load API key.');
}
return trim($apiKey);
}
}
|
<?php
namespace BlizzardGalaxy\ApiSupervisor\Registry;
use BlizzardGalaxy\ApiSupervisor\Exception\ApiSupervisorException;
/**
* Offers methods for easily reading in configuration values.
*
* @package BlizzardGalaxy\ApiSupervisor\Registry
* @author Petre Pătrașc <petre@dreamlabs.ro>
*/
class FileSystemRegistryManager extends AbstractRegistryManager
{
const CONFIG_FILE_PATH = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR;
/**
* Retrieve the API key used to make calls
* to Battle.NET endpoints.
*
* @return string
* @throws ApiSupervisorException
*/
public function getApiKey()
{
$apiKey = @file_get_contents(self::CONFIG_FILE_PATH . 'apikey.lock');
if (false === $apiKey) {
throw new ApiSupervisorException('Could not load API key.');
}
return trim($apiKey);
}
}
|
Fix backwards compatibility for postgresql backend on Django 1.10 and earlier
|
import django
import psycopg2.extensions
from django_prometheus.db.common import DatabaseWrapperMixin, \
ExportingCursorWrapper
if django.VERSION >= (1, 9):
from django.db.backends.postgresql import base
else:
from django.db.backends.postgresql_psycopg2 import base
class DatabaseFeatures(base.DatabaseFeatures):
"""Our database has the exact same features as the base one."""
pass
class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
def get_connection_params(self):
conn_params = super(DatabaseWrapper, self).get_connection_params()
conn_params['cursor_factory'] = ExportingCursorWrapper(
psycopg2.extensions.cursor,
self.alias,
self.vendor,
)
return conn_params
def create_cursor(self, name=None):
# cursor_factory is a kwarg to connect() so restore create_cursor()'s
# default behavior
if django.VERSION >= (1, 11, 0):
return base.DatabaseWrapper.create_cursor(self, name=name)
else:
return base.DatabaseWrapper.create_cursor(self)
|
import django
import psycopg2.extensions
from django_prometheus.db.common import DatabaseWrapperMixin, \
ExportingCursorWrapper
if django.VERSION >= (1, 9):
from django.db.backends.postgresql import base
else:
from django.db.backends.postgresql_psycopg2 import base
class DatabaseFeatures(base.DatabaseFeatures):
"""Our database has the exact same features as the base one."""
pass
class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
def get_connection_params(self):
conn_params = super(DatabaseWrapper, self).get_connection_params()
conn_params['cursor_factory'] = ExportingCursorWrapper(
psycopg2.extensions.cursor,
self.alias,
self.vendor,
)
return conn_params
def create_cursor(self, name=None):
# cursor_factory is a kwarg to connect() so restore create_cursor()'s
# default behavior
return base.DatabaseWrapper.create_cursor(self, name=name)
|
Check for username existence in validation
|
<?php namespace Lossendae\PreviouslyOn\Services\Validators;
class User extends Validator
{
public static $rules = array(
'create' => array(
'email' => array('required', 'email', 'unique:users'),
'pwd' => array('required', 'min:6', 'max:18'),
'username' => array('required', 'min:3', 'max:16', 'unique:users'),
),
'update' => array(
'email' => array('required', 'email'),
'pwd' => array('min:6', 'max:18'),
'username' => array('required', 'min:3', 'max:16'),
),
'login' => array(
'username' => array('required', 'exists:users'),
'pwd' => array('required', 'min:6', 'max:18'),
),
);
}
|
<?php namespace Lossendae\PreviouslyOn\Services\Validators;
class User extends Validator
{
public static $rules = array(
'create' => array(
'email' => array('required', 'email', 'unique:users'),
'pwd' => array('required', 'min:6', 'max:18'),
'username' => array('required', 'min:3', 'max:16', 'unique:users'),
),
'update' => array(
'email' => array('required', 'email'),
'pwd' => array('min:6', 'max:18'),
'username' => array('required', 'min:3', 'max:16'),
),
'login' => array(
'username' => array('required'),
'pwd' => array('required', 'min:6', 'max:18'),
),
);
}
|
Fix DataDir to handle the case when the file doesn't exist
If the directory doesn't exist, EvalSymlinks returns an error and an
empty dir string, which will fail. This works around that by only
calling Abs in the success case.
|
// Package config provides configuration primitives for Overlord
package config
import (
"os"
"path/filepath"
)
// DataDir returns the path to the Overlord data directory
func DataDir() (string, error) {
data, valid := os.LookupEnv("OVERLORD_DATA")
if !valid {
homedir, err := os.UserHomeDir()
if err != nil {
return "", err
}
data = filepath.Join(homedir, ".overlord")
}
// Run realpath and normalize path
var dir string
var err error
dir, err = filepath.EvalSymlinks(data)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
dir = data
} else {
// Get absolute path
dir, err = filepath.Abs(dir)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
}
}
err = os.MkdirAll(dir, os.ModePerm)
if err != nil {
return "", err
}
return dir, nil
}
|
// Package config provides configuration primitives for Overlord
package config
import (
"os"
"path/filepath"
)
// DataDir returns the path to the Overlord data directory
func DataDir() (string, error) {
data, valid := os.LookupEnv("OVERLORD_DATA")
if !valid {
homedir, err := os.UserHomeDir()
if err != nil {
return "", err
}
data = filepath.Join(homedir, ".overlord")
}
// Run realpath and normalize path
var dir string
var err error
dir, err = filepath.EvalSymlinks(data)
if err != nil {
return "", err
}
// Get absolute path
dir, err = filepath.Abs(dir)
if err != nil {
return "", err
}
err = os.MkdirAll(dir, os.ModePerm)
if err != nil {
return "", err
}
return dir, nil
}
|
Remove the final attribute from the main events on the proxy
|
package com.hea3ven.tools.commonutils.mod;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraftforge.fml.common.network.IGuiHandler;
public class ProxyModBase {
private ModInitializerCommon modInitializer;
public ProxyModBase(ModInitializerCommon modInitializer) {
this.modInitializer = modInitializer;
}
public void onPreInitEvent() {
modInitializer.onPreInitEvent(this);
}
public void onInitEvent() {
modInitializer.onInitEvent(this);
}
public void onPostInitEvent() {
modInitializer.onPostInitEvent(this);
}
public void registerEnchantments() {
}
public List<Pair<String, IGuiHandler>> getGuiHandlers() {
return Lists.newArrayList();
}
public List<InfoBlock> getBlocks() {
return Lists.newArrayList();
}
public List<InfoBlockVariant> getVariantBlocks() {
return Lists.newArrayList();
}
public List<InfoTileEntity> getTileEntities() {
return Lists.newArrayList();
}
public List<InfoItem> getItems() {
return Lists.newArrayList();
}
}
|
package com.hea3ven.tools.commonutils.mod;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraftforge.fml.common.network.IGuiHandler;
public class ProxyModBase {
private ModInitializerCommon modInitializer;
public ProxyModBase(ModInitializerCommon modInitializer) {
this.modInitializer = modInitializer;
}
public final void onPreInitEvent() {
modInitializer.onPreInitEvent(this);
}
public final void onInitEvent() {
modInitializer.onInitEvent(this);
}
public final void onPostInitEvent() {
modInitializer.onPostInitEvent(this);
}
public void registerEnchantments() {
}
public List<Pair<String, IGuiHandler>> getGuiHandlers() {
return Lists.newArrayList();
}
public List<InfoBlock> getBlocks() {
return Lists.newArrayList();
}
public List<InfoBlockVariant> getVariantBlocks() {
return Lists.newArrayList();
}
public List<InfoTileEntity> getTileEntities() {
return Lists.newArrayList();
}
public List<InfoItem> getItems() {
return Lists.newArrayList();
}
}
|
Modify player teams upon clan add/remove
|
class Clan {
removePlayer(player) {
for (var i = 0; i < this.members.length; ++i) {
if (this.members[i].player.sid === player.player.sid) {
this.members[i].player.team = null;
this.members.splice(i, 1);
return true;
}
}
return false;
}
addPlayer(player) {
player.player.team = this.name;
this.members.push(player);
}
constructor(name) {
if (name) {
this.name = name;
} else {
this.name = null;
}
this.members = [];
}
}
module.exports = Clan;
|
class Clan {
removePlayer(player) {
for (var i = 0; i < this.members.length; ++i) {
if (this.members[i].player.sid === player.player.sid) {
this.members.splice(i, 1);
return true;
}
}
return false;
}
addPlayer(player) {
this.members.push(player);
}
constructor(name) {
if (name) {
this.name = name;
} else {
this.name = null;
}
this.members = [];
}
}
module.exports = Clan;
|
Update up to deferred v0.2
|
// Read all filenames from directory and it's subdirectories
'use strict';
var fs = require('fs')
, aritize = require('es5-ext/lib/Function/aritize').call
, curry = require('es5-ext/lib/Function/curry').call
, invoke = require('es5-ext/lib/Function/invoke')
, flatten = require('es5-ext/lib/List/flatten').call
, a2p = require('deferred/lib/async-to-promise').call
, all = require('deferred/lib/join/all')
, concat = aritize(String.prototype.concat, 1)
, trim = require('../path/trim');
module.exports = function readdir (path, callback) {
path = trim(path);
a2p(fs.readdir, path)
(function (files) {
return all(files.map(function (file) {
var npath = path + '/' + file;
return a2p(fs.stat, npath)
(function (stats) {
if (stats.isFile()) {
return file;
} else if (stats.isDirectory()) {
return a2p(readdir, npath)
(invoke('map', concat, file + '/'));
} else {
return null;
}
});
}))
(invoke('filter', Boolean))
(flatten)
(curry(callback, null));
}).end(callback);
};
|
// Read all filenames from directory and it's subdirectories
'use strict';
var fs = require('fs')
, aritize = require('es5-ext/lib/Function/aritize').call
, curry = require('es5-ext/lib/Function/curry').call
, invoke = require('es5-ext/lib/Function/invoke')
, flatten = require('es5-ext/lib/List/flatten').call
, a2p = require('deferred/lib/async-to-promise').call
, all = require('deferred/lib/join/all')
, concat = aritize(String.prototype.concat, 1)
, trim = require('../path/trim');
module.exports = function readdir (path, callback) {
path = trim(path);
a2p(fs.readdir, path).then(function (files) {
return all(files.map(function (file) {
var npath = path + '/' + file;
return a2p(fs.stat, npath).then(function (stats) {
if (stats.isFile()) {
return file;
} else if (stats.isDirectory()) {
return a2p(readdir, npath).then(invoke('map', concat, file + '/'));
} else {
return null;
}
});
}))
.then(invoke('filter', Boolean))
.then(flatten)
.then(curry(callback, null));
}).end(callback);
};
|
Add link to account page in banner.
|
import React, { Component } from 'react';
import { Navbar, Nav } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import SignOutButton from './SignOut';
import * as ROUTES from './constants/routes';
import 'bootstrap/dist/css/bootstrap.css';
import './Banner.css';
class Banner extends Component {
render() {
return (
<Navbar bg="light" variant="light" sticky="top">
<Navbar.Brand bsPrefix="banner-title">PICTOPHONE</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
<Nav.Link>
<Link to={ROUTES.ACCOUNT}>Account</Link>
</Nav.Link>
<Navbar.Text className="banner-log-out">
<SignOutButton />
</Navbar.Text>
</Navbar.Collapse>
</Navbar>
);
}
}
export default Banner;
|
import React, { Component } from 'react';
import { Navbar } from 'react-bootstrap';
import SignOutButton from './SignOut';
import 'bootstrap/dist/css/bootstrap.css';
import './Banner.css';
class Banner extends Component {
render() {
return (
<Navbar bg="light" variant="light" sticky="top">
<Navbar.Brand bsPrefix="banner-title">PICTOPHONE</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
<Navbar.Text className="banner-log-out">
<SignOutButton />
</Navbar.Text>
</Navbar.Collapse>
</Navbar>
);
}
}
export default Banner;
|
Use Objects.equals to simplify equals code
|
package org.realityforge.replicant.client;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class ChannelDescriptor
{
@Nonnull
private final Enum _graph;
@Nullable
private final Object _id;
public ChannelDescriptor( @Nonnull final Enum graph, @Nullable final Object id )
{
_graph = Objects.requireNonNull( graph );
_id = id;
}
@Nonnull
public Class getSystem()
{
return _graph.getDeclaringClass();
}
@Nonnull
public Enum getGraph()
{
return _graph;
}
@Nullable
public Object getID()
{
return _id;
}
@Override
public String toString()
{
return _graph.toString() + ( null != _id ? ":" + _id : "" );
}
@Override
public boolean equals( final Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
final ChannelDescriptor that = (ChannelDescriptor) o;
return Objects.equals( _graph, that._graph ) && Objects.equals( _id, that._id );
}
@Override
public int hashCode()
{
int result = _graph.hashCode();
result = 31 * result + ( _id != null ? _id.hashCode() : 0 );
return result;
}
}
|
package org.realityforge.replicant.client;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class ChannelDescriptor
{
@Nonnull
private final Enum _graph;
@Nullable
private final Object _id;
public ChannelDescriptor( @Nonnull final Enum graph, @Nullable final Object id )
{
_graph = Objects.requireNonNull( graph );
_id = id;
}
@Nonnull
public Class getSystem()
{
return _graph.getDeclaringClass();
}
@Nonnull
public Enum getGraph()
{
return _graph;
}
@Nullable
public Object getID()
{
return _id;
}
@Override
public String toString()
{
return _graph.toString() + ( null != _id ? ":" + _id : "" );
}
@Override
public boolean equals( final Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
final ChannelDescriptor that = (ChannelDescriptor) o;
return _graph.equals( that._graph ) && !( _id != null ? !_id.equals( that._id ) : that._id != null );
}
@Override
public int hashCode()
{
int result = _graph.hashCode();
result = 31 * result + ( _id != null ? _id.hashCode() : 0 );
return result;
}
}
|
Add headers to campaign level counts script
|
// Print out campaign level counts
// Usage:
// mongo <address>:<port>/<database> <script file> -u <username> -p <password>
print("free premium all campaign");
var cursor = db.campaigns.find({}, {slug: 1, levels: 1});
var allFree = 0;
var allPremium = 0;
while (cursor.hasNext()) {
var doc = cursor.next();
if (doc.slug === 'auditions') continue;
var free = 0;
var premium = 0;
for (var levelID in doc.levels) {
if (doc.levels[levelID].requiresSubscription) {
premium++;
}
else {
free++;
}
}
print(free + " " + premium + " " + (free + premium) + " " + doc.slug);
allFree += free;
allPremium += premium;
}
print(allFree + " " + allPremium + " " + (allFree + allPremium) + " overall");
|
// Print out campaign level counts
// Usage:
// mongo <address>:<port>/<database> <script file> -u <username> -p <password>
var cursor = db.campaigns.find({}, {slug: 1, levels: 1});
var allFree = 0;
var allPremium = 0;
while (cursor.hasNext()) {
var doc = cursor.next();
if (doc.slug === 'auditions') continue;
var free = 0;
var premium = 0;
for (var levelID in doc.levels) {
if (doc.levels[levelID].requiresSubscription) {
premium++;
}
else {
free++;
}
}
print(free + " " + premium + " " + (free + premium) + " " + doc.slug);
allFree += free;
allPremium += premium;
}
print(allFree + " " + allPremium + " " + (allFree + allPremium) + " overall");
|
Add test command (*It can be tested with `go install` to get local test cli)
|
package main
import (
"log"
"os"
"fmt"
"github.com/codegangsta/cli"
)
var Commands = []cli.Command{
commandAll,
commandBiz,
commandHack,
}
var commandAll = cli.Command{
Name: "all",
Usage: "",
Description: `
`,
Action: doAll,
}
var commandBiz = cli.Command{
Name: "biz",
Usage: "",
Description: `
`,
Action: doBiz,
}
var commandHack = cli.Command{
Name: "hack",
Usage: "",
Description: `
`,
Action: doHack,
}
func debug(v ...interface{}) {
if os.Getenv("DEBUG") != "" {
log.Println(v...)
}
}
func assert(err error) {
if err != nil {
log.Fatal(err)
}
}
func doAll(c *cli.Context) {
fmt.Printf("print all")
}
func doBiz(c *cli.Context) {
}
func doHack(c *cli.Context) {
}
|
package main
import (
"log"
"os"
"github.com/codegangsta/cli"
)
var Commands = []cli.Command{
commandAll,
commandBiz,
commandHack,
}
var commandAll = cli.Command{
Name: "all",
Usage: "",
Description: `
`,
Action: doAll,
}
var commandBiz = cli.Command{
Name: "biz",
Usage: "",
Description: `
`,
Action: doBiz,
}
var commandHack = cli.Command{
Name: "hack",
Usage: "",
Description: `
`,
Action: doHack,
}
func debug(v ...interface{}) {
if os.Getenv("DEBUG") != "" {
log.Println(v...)
}
}
func assert(err error) {
if err != nil {
log.Fatal(err)
}
}
func doAll(c *cli.Context) {
}
func doBiz(c *cli.Context) {
}
func doHack(c *cli.Context) {
}
|
Use a bool sensor for testing, and query the API instead of models
|
from django.test import TestCase
from spiff.api.tests import APITestMixin, withPermission
import models
class SensorTest(APITestMixin):
def setUp(self):
self.setupAPI()
self.sensor = models.Sensor.objects.create(
name = 'sensor',
description = 'Test sensor',
type = models.SENSOR_TYPE_BOOLEAN,
ttl = 255
)
@withPermission('sensors.read_sensor')
@withPermission('sensors.update_value_on_sensor')
def testSetSensorValue(self):
self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), {
'value': True,
})
sensor = self.getAPI('/v1/sensor/%s/'%(self.sensor.id))
self.assertEqual(sensor['value'], True)
self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), {
'value': False,
})
sensor = self.getAPI('/v1/sensor/%s/'%(self.sensor.id))
self.assertEqual(sensor['value'], False)
def testSensorTTL(self):
for i in range(0, self.sensor.ttl*2):
models.SensorValue.objects.create(
sensor=self.sensor,
value=True
)
self.assertEqual(len(self.sensor.values.all()), self.sensor.ttl)
|
from django.test import TestCase
from spiff.api.tests import APITestMixin, withPermission
import models
class SensorTest(APITestMixin):
def setUp(self):
self.setupAPI()
self.sensor = models.Sensor.objects.create(
name = 'sensor',
description = 'Test sensor',
type = 0,
ttl = 255
)
@withPermission('sensors.read_sensor')
@withPermission('sensors.update_value_on_sensor')
def testSetSensorValue(self):
self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), {
'value': True,
})
self.assertEqual(self.sensor.value(), 'True')
self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), {
'value': False,
})
self.assertEqual(self.sensor.value(), 'False')
def testSensorTTL(self):
for i in range(0, self.sensor.ttl*2):
models.SensorValue.objects.create(
sensor=self.sensor,
value=True
)
self.assertEqual(len(self.sensor.values.all()), self.sensor.ttl)
|
Switch from toggling visibility to switching on stored state in preparation for allow individual scenarios to toggle.
|
'use strict';
// Expand/collapse details.
$(function() {
var doExpand = 1
function expandCollapseDetails() {
var featureDetailsEls = window.document.getElementsByClassName('feature-details');
var scenarioDetailsEls = window.document.getElementsByClassName('scenario-details');
[].forEach.call(featureDetailsEls, function(el) {
if (doExpand) {
el.classList.remove('collapse');
} else {
el.classList.add('collapse');
}
});
[].forEach.call(scenarioDetailsEls, function(el) {
if (doExpand) {
el.classList.remove('collapse');
} else {
el.classList.add('collapse');
}
});
// Toggle expansion on alternative executions.
doExpand = doExpand ^ 1;
}
var expandCollapseDetailsEl = window.document.getElementById('expand-collapse-details');
expandCollapseDetailsEl.addEventListener('click', expandCollapseDetails);
});
// Expand/collapse tags.
$(function() {
function expandCollapseTags() {
var tagEls = window.document.getElementsByClassName('tags');
[].forEach.call(tagEls, function(el) {
el.classList.toggle('collapse');
});
}
var expandCollapseTagsEl = window.document.getElementById('expand-collapse-tags');
expandCollapseTagsEl.addEventListener('click', expandCollapseTags);
});
|
'use strict';
// Expand/collapse details.
$(function() {
function expandCollapseDetails() {
var featureDetailsEls = window.document.getElementsByClassName('feature-details');
var scenarioDetailsEls = window.document.getElementsByClassName('scenario-details');
[].forEach.call(featureDetailsEls, function(el) {
el.classList.toggle('collapse');
});
[].forEach.call(scenarioDetailsEls, function(el) {
el.classList.toggle('collapse');
});
}
var expandCollapseDetailsEl = window.document.getElementById('expand-collapse-details');
expandCollapseDetailsEl.addEventListener('click', expandCollapseDetails);
});
// Expand/collapse tags.
$(function() {
function expandCollapseTags() {
var tagEls = window.document.getElementsByClassName('tags');
[].forEach.call(tagEls, function(el) {
el.classList.toggle('collapse');
});
}
var expandCollapseTagsEl = window.document.getElementById('expand-collapse-tags');
expandCollapseTagsEl.addEventListener('click', expandCollapseTags);
});
|
Fix Resident Advisor regex to match new page design
|
#!/usr/bin/python
# Gets stuff from Resident Advisor's awesome 'RA Recommends' section
# Note: this is just regexing the HTML... so may stop working if page structure changes
# This is not written by, or affiliated with Resident Advisor at all
# 2013 oldhill // MIT license
import urllib2
import re
def getResidentData():
web_page = urllib2.urlopen('http://www.residentadvisor.net/reviews.aspx?format=recommend')
all_the_html = web_page.read()
relevant_block = re.findall('reviewArchive'+'(.*?)'+'</article>', all_the_html, re.DOTALL)[0]
# zeroing in...
relevant_string = re.findall('<h1>'+'(.*?)'+'</h1>', relevant_block, re.DOTALL)[0]
return relevant_string
def recommendedArtist():
relevant_set = getResidentData()
artist = relevant_set.split('-')[0].strip()
return artist
def recommendedWork():
relevant_set = getResidentData()
work = relevant_set.split('-')[1].strip()
return work
# Use this to test; it should print artist and album/track name on command line
def main():
test_artist = recommendedArtist()
test_work = recommendedWork()
print '\n>>>>>>>>>>>>>>>>>\n'
print test_artist
print test_work
print '\n>>>>>>>>>>>>>>>>>\n'
if __name__ == '__main__':
main()
|
#!/usr/bin/python
# Gets stuff from Resident Advisor's awesome 'RA Recommends' section
# Note: this is just regexing the HTML... so may stop working if page structure changes
# This is not written by, or affiliated with Resident Advisor at all
# 2013 oldhill // MIT license
import urllib2
import re
def getResidentData():
# grab all the data...
web_page = urllib2.urlopen('http://www.residentadvisor.net/reviews.aspx?format=recommend')
all_the_html = web_page.read()
demarcator = 'pb2' # surrounds records of recommended stuff
relevant_block = re.findall(demarcator+'(.*?)'+demarcator, all_the_html, re.DOTALL)[0]
# zeroing in...
relevant_string = re.findall('class=music>'+'(.*?)'+'</a', relevant_block, re.DOTALL)[0]
return relevant_string
def recommendedArtist():
relevant_set = getResidentData()
artist = relevant_set.split('-')[0].strip()
return artist
def recommendedWork():
relevant_set = getResidentData()
work = relevant_set.split('-')[1].strip()
return work
# Use this to test; it should print artist and album/track name on command line
def main():
test_artist = recommendedArtist()
test_work = recommendedWork()
print '\n>>>>>>>>>>>>>>>>>\n'
print test_artist
print test_work
print '\n>>>>>>>>>>>>>>>>>\n'
if __name__ == '__main__':
main()
|
Divide count by page size to determine if we should show the pager footer.
|
import { FooterController } from './FooterController';
export function FooterDirective(){
return {
restrict: 'E',
controller: FooterController,
controllerAs: 'footer',
scope: true,
bindToController: {
paging: '=',
onPage: '&'
},
template:
`<div class="dt-footer">
<div class="page-count">{{footer.paging.count}} total</div>
<dt-pager page="footer.page"
size="footer.paging.size"
count="footer.paging.count"
on-page="footer.onPaged(page)"
ng-show="footer.paging.count / footer.paging.size > 1">
</dt-pager>
</div>`,
replace: true
};
};
|
import { FooterController } from './FooterController';
export function FooterDirective(){
return {
restrict: 'E',
controller: FooterController,
controllerAs: 'footer',
scope: true,
bindToController: {
paging: '=',
onPage: '&'
},
template:
`<div class="dt-footer">
<div class="page-count">{{footer.paging.count}} total</div>
<dt-pager page="footer.page"
size="footer.paging.size"
count="footer.paging.count"
on-page="footer.onPaged(page)"
ng-show="footer.paging.count > 1">
</dt-pager>
</div>`,
replace: true
};
};
|
Add () to fixture definitions
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2018 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released under MIT licence; see LICENSE at the package root.
from os import path
from glob import glob
import pytest
import masterfile
# EXAMPLE_PATH =
# GOOD_PATH =
# GOOD_CSVS = glob(path.join(GOOD_PATH, '*csv'))
# PROBLEMS_PATH = path.join(EXAMPLE_PATH, 'problems')
@pytest.fixture()
def example_path():
return path.join(path.dirname(path.abspath(__file__)), 'examples')
@pytest.fixture()
def good_path():
return path.join(example_path(), 'good')
@pytest.fixture()
def good_csvs():
return glob(path.join(good_path(), '*csv'))
@pytest.fixture()
def problems_path():
return path.join(example_path(), 'problems')
@pytest.fixture()
def good_mf():
return masterfile.load(good_path())
@pytest.fixture()
def nosettings_mf():
return masterfile.load(example_path())
@pytest.fixture()
def problems_mf():
return masterfile.load(problems_path())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2018 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released under MIT licence; see LICENSE at the package root.
from os import path
from glob import glob
import pytest
import masterfile
# EXAMPLE_PATH =
# GOOD_PATH =
# GOOD_CSVS = glob(path.join(GOOD_PATH, '*csv'))
# PROBLEMS_PATH = path.join(EXAMPLE_PATH, 'problems')
@pytest.fixture
def example_path():
return path.join(path.dirname(path.abspath(__file__)), 'examples')
@pytest.fixture
def good_path():
return path.join(example_path(), 'good')
@pytest.fixture
def good_csvs():
return glob(path.join(good_path(), '*csv'))
@pytest.fixture
def problems_path():
return path.join(example_path(), 'problems')
@pytest.fixture
def good_mf():
return masterfile.load(good_path())
@pytest.fixture
def nosettings_mf():
return masterfile.load(example_path())
@pytest.fixture
def problems_mf():
return masterfile.load(problems_path())
|
Allow to pass multiple entities to the RemovalBlocked exception
|
<?php declare(strict_types=1);
namespace Becklyn\RadBundle\Exception;
/**
* Generic exception that marks, that the entity removal may be blocked by database (foreign keys, etc..) or
* semantic constraints (e.g. "can't remove main category").
*/
class EntityRemovalBlockedException extends \DomainException
{
/**
* @var object[]
*/
private $entities;
/**
* @inheritDoc
*
* @param object|object[] Entity
*/
public function __construct ($entities, string $message, \Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
$this->entities = \is_array($entities) ? $entities : [$entities];
}
/**
* @return object
*/
public function getEntities ()
{
return $this->entities;
}
}
|
<?php declare(strict_types=1);
namespace Becklyn\RadBundle\Exception;
/**
* Generic exception that marks, that the entity removal may be blocked by database (foreign keys, etc..) or
* semantic constraints (e.g. "can't remove main category").
*/
class EntityRemovalBlockedException extends \DomainException
{
/**
* @var object
*/
private $entity;
/**
* @inheritDoc
*
* @param object Entity
*/
public function __construct ($entity, string $message, \Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
$this->entity = $entity;
}
/**
* @return object
*/
public function getEntity ()
{
return $this->entity;
}
}
|
Fix relying on pyinfra generator unroll
|
# pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_copy=False,
present=True,
):
'''
Manage virtualenv.
+ python: python interpreter to use
+ site_packages: give access to the global site-packages
+ always_copy: always copy files rather than symlinking
+ present: whether the virtualenv should be installed
'''
if present is False and host.fact.directory(path):
# Ensure deletion of unwanted virtualenv
# no 'yield from' in python 2.7
yield files.directory(state, host, path, present=False)
elif present and not host.fact.directory(path):
# Create missing virtualenv
command = '/usr/bin/virtualenv'
if python:
command += ' -p {}'.format(python)
if site_packages:
command += ' --system-site-packages'
if always_copy:
command += ' --always-copy'
command += ' ' + path
yield command
|
# pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_copy=False,
present=True,
):
'''
Manage virtualenv.
+ python: python interpreter to use
+ site_packages: give access to the global site-packages
+ always_copy: always copy files rather than symlinking
+ present: whether the virtualenv should be installed
'''
if present is False and host.fact.directory(path):
# Ensure deletion of unwanted virtualenv
# no 'yield from' in python 2.7
for cmd in files.directory(state, host, path, present=False):
yield cmd
elif present and not host.fact.directory(path):
# Create missing virtualenv
command = '/usr/bin/virtualenv'
if python:
command += ' -p {}'.format(python)
if site_packages:
command += ' --system-site-packages'
if always_copy:
command += ' --always-copy'
command += ' ' + path
yield command
|
Make sure to check that the entry exists when returning the payload
|
'use strict'
class DocumentIndex {
constructor () {
this._index = {}
}
get (key, fullOp = false) {
return fullOp
? this._index[key]
: this._index[key] ? this._index[key].payload.value : null
}
updateIndex (oplog, onProgressCallback) {
const reducer = (handled, item, idx) => {
if (handled[item.payload.key] !== true) {
handled[item.payload.key] = true
if(item.payload.op === 'PUT') {
this._index[item.payload.key] = item
} else if (item.payload.op === 'DEL') {
delete this._index[item.payload.key]
}
}
if (onProgressCallback) onProgressCallback(item, idx)
return handled
}
oplog.values
.slice()
.reverse()
.reduce(reducer, {})
}
}
module.exports = DocumentIndex
|
'use strict'
class DocumentIndex {
constructor () {
this._index = {}
}
get (key, fullOp = false) {
return fullOp
? this._index[key]
: this._index[key].payload.value
}
updateIndex (oplog, onProgressCallback) {
const reducer = (handled, item, idx) => {
if (handled[item.payload.key] !== true) {
handled[item.payload.key] = true
if(item.payload.op === 'PUT') {
this._index[item.payload.key] = item
} else if (item.payload.op === 'DEL') {
delete this._index[item.payload.key]
}
}
if (onProgressCallback) onProgressCallback(item, idx)
return handled
}
oplog.values
.slice()
.reverse()
.reduce(reducer, {})
}
}
module.exports = DocumentIndex
|
Rename enum, fix docs, and make accessors package private
|
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gcloud;
/**
* Base class for all service exceptions.
*/
public class BaseServiceException extends RuntimeException {
private static final long serialVersionUID = 5028833760039966178L;
private final int code;
private final boolean retryable;
public BaseServiceException(int code, String message, boolean retryable) {
super(message);
this.code = code;
this.retryable = retryable;
}
public BaseServiceException(int code, String message, boolean retryable, Exception cause) {
super(message, cause);
this.code = code;
this.retryable = retryable;
}
/**
* Returns the code associated with this exception.
*/
public int code() {
return code;
}
/**
* Returns {@code true} when it is safe to retry the operation that caused this exception.
*/
public boolean retryable() {
return retryable;
}
}
|
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gcloud;
/**
* Base service exception.
*/
public class BaseServiceException extends RuntimeException {
private static final long serialVersionUID = 5028833760039966178L;
private final int code;
private final boolean retryable;
public BaseServiceException(int code, String message, boolean retryable) {
super(message);
this.code = code;
this.retryable = retryable;
}
public BaseServiceException(int code, String message, boolean retryable, Exception cause) {
super(message, cause);
this.code = code;
this.retryable = retryable;
}
/**
* Returns the code associated with this exception.
*/
public int code() {
return code;
}
public boolean retryable() {
return retryable;
}
}
|
Update gulp to add Draft in localhost
|
var del = require("del");
const gulp = require("gulp");
const plugins = require("gulp-load-plugins")();
const clean = () => {
return del[
'./public',
'./static/img/'
]
}
const css = () => {
gulp
.src("assets/css/**/*.css")
.pipe(plugins.plumber())
.pipe(plugins.csso({ comments: false }))
.pipe(gulp.dest("static/css/"));
};
const img = () => {
gulp
.src("assets/img/**/*")
.pipe(plugins.plumber())
.pipe(
plugins.imagemin([
plugins.imagemin.gifsicle({ interlaced: true }),
plugins.imagemin.jpegtran({ progressive: true }),
plugins.imagemin.optipng(),
plugins.imagemin.svgo()
])
)
.pipe(gulp.dest("static/img/"));
};
const hugoBuild = () => plugins.sh;
gulp.task("clean", clean);
gulp.task("css", css);
gulp.task("img", img);
gulp.task("build", plugins.sequence('clean', ["css", "img"]));
gulp.task("watchers", ["build"], () => {
gulp.watch("assets/css/**/*.css", ["css"]);
gulp.watch("assets/img/**/*", ["img"]);
});
gulp.task("hugo:dev", ["watchers"], plugins.shell.task(["hugo server -D"]));
gulp.task("hugo:build", ["build"], plugins.shell.task(["hugo"]));
gulp.task("default", ["hugo:dev"]);
|
var del = require("del");
const gulp = require("gulp");
const plugins = require("gulp-load-plugins")();
const clean = () => {
return del[
'./public',
'./static/img/'
]
}
const css = () => {
gulp
.src("assets/css/**/*.css")
.pipe(plugins.plumber())
.pipe(plugins.csso({ comments: false }))
.pipe(gulp.dest("static/css/"));
};
const img = () => {
gulp
.src("assets/img/**/*")
.pipe(plugins.plumber())
.pipe(
plugins.imagemin([
plugins.imagemin.gifsicle({ interlaced: true }),
plugins.imagemin.jpegtran({ progressive: true }),
plugins.imagemin.optipng(),
plugins.imagemin.svgo()
])
)
.pipe(gulp.dest("static/img/"));
};
const hugoBuild = () => plugins.sh;
gulp.task("clean", clean);
gulp.task("css", css);
gulp.task("img", img);
gulp.task("build", plugins.sequence('clean', ["css", "img"]));
gulp.task("watchers", ["build"], () => {
gulp.watch("assets/css/**/*.css", ["css"]);
gulp.watch("assets/img/**/*", ["img"]);
});
gulp.task("hugo:dev", ["watchers"], plugins.shell.task(["hugo server"]));
gulp.task("hugo:build", ["build"], plugins.shell.task(["hugo"]));
gulp.task("default", ["hugo:dev"]);
|
Set absolute path to public files
|
'use strict';
// Grab important stuff from the environment:
var ARDUINO = process.env.ARDUINO;
var PORT = process.env.PORT || 56267;
// Connect the controller to the device:
var FloppyController = require('./lib/floppyController');
var controller = new FloppyController(ARDUINO);
// Start the web interface and handle events:
var express = require('express'),
http = require('http'),
socket = require('socket.io');
var app = express(),
server = http.Server(app),
io = socket(server);
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/setFrequency', function(req, res) {
// controller.setFrequency(req.param.frequency);
res.send('Done: ' + req.param('freq'));
});
app.use(express.static(__dirname + '/public'));
server.listen(PORT, function() {
console.info('Server listening on port %d.', PORT);
});
|
'use strict';
// Grab important stuff from the environment:
var ARDUINO = process.env.ARDUINO;
var PORT = process.env.PORT || 56267;
// Connect the controller to the device:
var FloppyController = require('./lib/floppyController');
var controller = new FloppyController(ARDUINO);
// Start the web interface and handle events:
var express = require('express'),
http = require('http'),
socket = require('socket.io');
var app = express(),
server = http.Server(app),
io = socket(server);
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/setFrequency', function(req, res) {
// controller.setFrequency(req.param.frequency);
res.send('Done: ' + req.param('freq'));
});
app.use(express.static('public'));
server.listen(PORT, function() {
console.info('Server listening on port %d.', PORT);
});
|
Fix name of file in test for Clojure scripting
|
package com.semperos.screwdriver.scripting.js;
import com.semperos.screwdriver.TestUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import static org.junit.Assert.assertEquals;
public class CoffeeScriptEvalIntegrationTest {
@Before
public void setup() throws Exception {
TestUtil.deleteAssetDirectories();
}
@After
public void tearDown() throws Exception {
TestUtil.deleteAssetDirectories();
}
@Test
public void testEvalFile() throws Exception {
String expected = "THIS IS COFFEESCRIPT, outputDir is " + TestUtil.baseDirectoryPath();
File f = new File(TestUtil.baseDirectoryPath(), "screwdriver_build.coffee");
// Capture stdout and compare
ByteArrayOutputStream baos = TestUtil.captureStdout();
CoffeeScriptEval.evalFile(f);
assertEquals(expected, baos.toString());
TestUtil.restoreStdout();
}
}
|
package com.semperos.screwdriver.scripting.js;
import com.semperos.screwdriver.TestUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import static org.junit.Assert.assertEquals;
public class CoffeeScriptEvalIntegrationTest {
@Before
public void setup() throws Exception {
TestUtil.deleteAssetDirectories();
}
@After
public void tearDown() throws Exception {
TestUtil.deleteAssetDirectories();
}
@Test
public void testEvalFile() throws Exception {
String expected = "THIS IS COFFEESCRIPT, outputDir is " + TestUtil.baseDirectoryPath();
File f = new File(TestUtil.baseDirectoryPath(), "screwdriver_config.coffee");
// Capture stdout and compare
ByteArrayOutputStream baos = TestUtil.captureStdout();
CoffeeScriptEval.evalFile(f);
assertEquals(expected, baos.toString());
TestUtil.restoreStdout();
}
}
|
Check for two RecipeContainers on Profile
|
const expect = require('chai').expect;
const React = require('react');
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import fakeStore from './fakeStore';
import Profile from '../../client/components/Profile.js';
import RecipeContainer from '../../client/components/RecipeContainer.js';
const fakeProfile = {
avatar: 'http://www.carderator.com/assets/avatar_placeholder_small.png',
username: 'USERNAME',
};
describe('<Profile />', () => {
let wrapper;
beforeEach('render Profile', () => {
wrapper = mount(
<Provider store={fakeStore}>
<Profile />
</Provider>);
});
it('renders without problems', () => {
expect(wrapper.find(Profile)).to.have.length(1);
});
it('should display the correct username', () => {
expect(wrapper.find('.profile-username').text()).to.equal(fakeStore.getState().profile.username);
});
it('should display the correct avatar', () => {
expect(wrapper.find('.profile-avatar').html()).to.contain(fakeStore.getState().profile.avatar);
});
it('should render two recipe containers', () => {
expect(wrapper.find(RecipeContainer)).to.have.length(2);
})
});
|
const expect = require('chai').expect;
const React = require('react');
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import fakeStore from './fakeStore';
import Profile from '../../client/components/Profile.js';
const fakeProfile = {
avatar: 'http://www.carderator.com/assets/avatar_placeholder_small.png',
username: 'USERNAME',
};
describe('<Profile />', () => {
let wrapper;
beforeEach('render Profile', () => {
wrapper = mount(
<Provider store={fakeStore}>
<Profile />
</Provider>);
});
it('renders without problems', () => {
expect(wrapper.find(Profile)).to.have.length(1);
});
it('should display the correct username', () => {
expect(wrapper.find('.profile-username').text()).to.equal(fakeStore.getState().profile.username);
});
it('should display the correct avatar', () => {
expect(wrapper.find('.profile-avatar').html()).to.contain(fakeStore.getState().profile.avatar);
});
});
|
Fix showing duplicate http blocking messages, because a http connection
is also a socket connection
|
package com.github.games647.lagmonitor.listeners;
import com.github.games647.lagmonitor.LagMonitor;
import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.Bukkit;
public class BlockingConnectionSelector extends ProxySelector {
private final LagMonitor plugin;
private final ProxySelector oldProxySelector;
public BlockingConnectionSelector(LagMonitor plugin, ProxySelector oldProxySelector) {
this.plugin = plugin;
this.oldProxySelector = oldProxySelector;
}
@Override
public List<Proxy> select(URI uri) {
if (!uri.getScheme().startsWith("http") && Bukkit.isPrimaryThread()) {
plugin.getLogger().log(Level.WARNING
, "Server is performing a blocking socket connection {0} on the main thread"
, new Object[]{uri});
plugin.getLogger().log(Level.WARNING, "", new Throwable());
}
return oldProxySelector.select(uri);
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
oldProxySelector.connectFailed(uri, sa, ioe);
}
public ProxySelector getOldProxySelector() {
return oldProxySelector;
}
}
|
package com.github.games647.lagmonitor.listeners;
import com.github.games647.lagmonitor.LagMonitor;
import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.Bukkit;
public class BlockingConnectionSelector extends ProxySelector {
private final LagMonitor plugin;
private final ProxySelector oldProxySelector;
public BlockingConnectionSelector(LagMonitor plugin, ProxySelector oldProxySelector) {
this.plugin = plugin;
this.oldProxySelector = oldProxySelector;
}
@Override
public List<Proxy> select(URI uri) {
if (Bukkit.isPrimaryThread()) {
plugin.getLogger().log(Level.WARNING
, "Server is performing a blocking socket connection {0} on the main thread"
, new Object[]{uri});
plugin.getLogger().log(Level.WARNING, "", new Throwable());
}
return oldProxySelector.select(uri);
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
oldProxySelector.connectFailed(uri, sa, ioe);
}
public ProxySelector getOldProxySelector() {
return oldProxySelector;
}
}
|
Add `json_fields` parameter to set_up_logging
This will allow the main function to add extra fields to JSON log
messages, for example to pass through command-line arguments.
See https://www.pivotaltracker.com/story/show/70748012
|
from logstash_formatter import LogstashFormatter
import logging
import os
import pdb
import sys
import traceback
def get_log_file_handler(path):
handler = logging.FileHandler(path)
handler.setFormatter(logging.Formatter(
"%(asctime)s [%(levelname)s] -> %(message)s"))
return handler
def get_json_log_handler(path, app_name, json_fields):
handler = logging.FileHandler(path)
formatter = LogstashFormatter()
formatter.defaults['@tags'] = ['collector', app_name]
formatter.defaults.update(json_fields)
handler.setFormatter(formatter)
return handler
def uncaught_exception_handler(*exc_info):
text = "".join(traceback.format_exception(*exc_info))
logging.error("Unhandled exception: %s", text)
def set_up_logging(app_name, log_level, logfile_path, json_fields=None):
sys.excepthook = uncaught_exception_handler
logger = logging.getLogger()
logger.setLevel(log_level)
logger.addHandler(get_log_file_handler(
os.path.join(logfile_path, 'collector.log')))
logger.addHandler(get_json_log_handler(
os.path.join(logfile_path, 'collector.log.json'),
app_name,
json_fields=json_fields if json_fields else {}))
logger.info("{0} logging started".format(app_name))
|
from logstash_formatter import LogstashFormatter
import logging
import os
import pdb
import sys
import traceback
def get_log_file_handler(path):
handler = logging.FileHandler(path)
handler.setFormatter(logging.Formatter(
"%(asctime)s [%(levelname)s] -> %(message)s"))
return handler
def get_json_log_handler(path, app_name):
handler = logging.FileHandler(path)
formatter = LogstashFormatter()
formatter.defaults['@tags'] = ['collector', app_name]
handler.setFormatter(formatter)
return handler
def uncaught_exception_handler(*exc_info):
text = "".join(traceback.format_exception(*exc_info))
logging.error("Unhandled exception: %s", text)
def set_up_logging(app_name, log_level, logfile_path):
sys.excepthook = uncaught_exception_handler
logger = logging.getLogger()
logger.setLevel(log_level)
logger.addHandler(get_log_file_handler(
os.path.join(logfile_path, 'collector.log')))
logger.addHandler(get_json_log_handler(
os.path.join(logfile_path, 'collector.log.json'), app_name))
logger.info("{0} logging started".format(app_name))
|
Return null if record doesn't exists in database
|
package ru.ydn.wicket.wicketorientdb.model;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import com.orientechnologies.orient.core.type.ODocumentWrapper;
/**
* {@link IModel} for a {@link ODocumentWrapper}s
*
* @param <T> {@link ODocumentWrapper} type
*/
public class ODocumentWrapperModel<T extends ODocumentWrapper> extends Model<T> {
private static final long serialVersionUID = 1L;
private boolean needToReload=false;
public ODocumentWrapperModel() {
super();
}
public ODocumentWrapperModel(T object) {
super(object);
needToReload=false;
}
@Override
public T getObject() {
try {
T ret = super.getObject();
if(ret != null && needToReload) {
ret.load();
needToReload = false;
}
return ret;
} catch (ORecordNotFoundException e) {
return null;
}
}
@Override
public void setObject(T object) {
super.setObject(object);
needToReload = false;
}
@Override
public void detach() {
T ret = getObject();
if (ret != null && !ret.getDocument().getIdentity().isNew()) {
needToReload = true;
}
super.detach();
}
}
|
package ru.ydn.wicket.wicketorientdb.model;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import com.orientechnologies.orient.core.type.ODocumentWrapper;
/**
* {@link IModel} for a {@link ODocumentWrapper}s
*
* @param <T> {@link ODocumentWrapper} type
*/
public class ODocumentWrapperModel<T extends ODocumentWrapper> extends Model<T> {
private static final long serialVersionUID = 1L;
private boolean needToReload=false;
public ODocumentWrapperModel() {
super();
}
public ODocumentWrapperModel(T object) {
super(object);
needToReload=false;
}
@Override
public T getObject() {
T ret = super.getObject();
if(ret != null && needToReload) {
ret.load();
needToReload = false;
}
return ret;
}
@Override
public void setObject(T object) {
super.setObject(object);
needToReload = false;
}
@Override
public void detach() {
T ret = getObject();
if (ret != null && !ret.getDocument().getIdentity().isNew()) {
needToReload = true;
}
super.detach();
}
}
|
Use `== ""` instead of `len() == 0`
|
package cmd
import (
"fmt"
"net/http"
"os"
"github.com/spf13/cobra"
)
// statusCmd represents the status command
var statusCmd = &cobra.Command{
Use: "status",
Short: "Check if the HTTP server is running",
Long: `Check if the HTTP server has been started and answer 200 for /status.`,
Run: func(cmd *cobra.Command, args []string) {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
resp, err := http.Get("http://localhost:" + port + "/status")
if err != nil {
fmt.Println("Error the HTTP server is not running:", err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Println("Error, unexpected HTTP status code:", resp.Status)
os.Exit(1)
}
fmt.Println("OK, the HTTP server is ready.")
},
}
func init() {
RootCmd.AddCommand(statusCmd)
}
|
package cmd
import (
"fmt"
"net/http"
"os"
"github.com/spf13/cobra"
)
// statusCmd represents the status command
var statusCmd = &cobra.Command{
Use: "status",
Short: "Check if the HTTP server is running",
Long: `Check if the HTTP server has been started and answer 200 for /status.`,
Run: func(cmd *cobra.Command, args []string) {
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8080"
}
resp, err := http.Get("http://localhost:" + port + "/status")
if err != nil {
fmt.Println("Error the HTTP server is not running:", err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Println("Error, unexpected HTTP status code:", resp.Status)
os.Exit(1)
}
fmt.Println("OK, the HTTP server is ready.")
},
}
func init() {
RootCmd.AddCommand(statusCmd)
}
|
Update expects for home page
|
var po = require('./page-objects');
var ptor = protractor.getInstance();
describe('lean coffee', function() {
var global = new po.GlobalFunction();
describe('home page', function(){
var homePage = new po.HomePage();
it('should display the home page', function() {
homePage.get();
expect($('.welcome').getText()).toBe('Welcome to Lean Coffee! ');
expect(ptor.getCurrentUrl()).toContain('#/home');
});
it('should present the user with a default room in the inactive meeting list', function() {
expect($('.meeting-list').getText()).toContain('default');
});
it('should allow user to enter a meeting name', function() {
expect(element(by.model('meetingName')).getAttribute('value')).toBe('');
homePage.setMeetingNameInput('Testing Meeting Name');
expect(element(by.model('meetingName')).getAttribute('value')).toBe('Testing Meeting Name');
homePage.setMeetingNameInput('');
});
it('should display a Create a Meeting! button', function() {
expect(element(by.buttonText('Create a Meeting!')).isPresent()).toBe(true);
});
it('should navigate to submit phase when user clicks Create a Meeting! button', function() {
homePage.createMeeting();
expect(global.getPhaseText()).toMatch(/PHASE: SUBMIT/);
expect(ptor.getCurrentUrl()).toContain('#/meeting');
});
});
});
|
var po = require('./page-objects');
var ptor = protractor.getInstance();
describe('lean coffee', function() {
var global = new po.GlobalFunction();
describe('home page', function(){
var homePage = new po.HomePage();
it('should display the home page', function() {
homePage.get();
expect($('.welcome').getText()).toBe('Welcome to Lean Coffee! ');
});
it('should present the user with a default room in the inactive meeting list', function() {
expect($('.meeting-list').getText()).toContain('default');
});
it('should allow user to enter a meeting name', function() {
expect(element(by.model('meetingName')).getAttribute('value')).toBe('');
homePage.setMeetingNameInput('Testing Meeting Name');
expect(element(by.model('meetingName')).getAttribute('value')).toBe('Testing Meeting Name');
homePage.setMeetingNameInput('');
});
it('should display a Create a Meeting! button', function() {
expect(element(by.buttonText('Create a Meeting!')).isPresent()).toBe(true);
});
it('should navigate to submit phase when user clicks Create a Meeting! button', function() {
homePage.createMeeting();
expect(global.getPhaseText()).toMatch(/PHASE: SUBMIT/);
});
});
});
|
Build out hash item class
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self):
pass
def set(self):
pass
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self):
pass
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self):
pass
def set(self):
pass
|
Change yeat and temp to private class vars.
|
package hadoop;
import gsod.DataSet;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MaxTemperatureMapper extends
Mapper<LongWritable, Text, Text, IntWritable> {
private String line;
private String year;
private int airTemperature;
@Override
public void map(LongWritable key, Text value,
MaxTemperatureMapper.Context context) throws IOException,
InterruptedException {
line = value.toString();
if (line.startsWith("STN---"))
return;
year = DataSet.getYear(line);
airTemperature = DataSet.getMax(line);
if (airTemperature != DataSet.MISSING) {
context.write(new Text(year), new IntWritable(airTemperature));
}
}
}
|
package hadoop;
import gsod.DataSet;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MaxTemperatureMapper extends
Mapper<LongWritable, Text, Text, IntWritable> {
@Override
public void map(LongWritable key, Text value,
MaxTemperatureMapper.Context context) throws IOException,
InterruptedException {
String line = value.toString();
if (line.startsWith("STN---"))
return;
String year = DataSet.getYear(line);
int airTemperature = DataSet.getMax(line);
if (airTemperature != DataSet.MISSING) {
context.write(new Text(year), new IntWritable(airTemperature));
}
}
}
|
Add date drill down to coding assignment activity list
|
from django.contrib import admin
from coding.models import (
Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity)
class SampleAdmin(admin.ModelAdmin):
filter_horizontal = ("pieces",)
admin.site.register(Sample, SampleAdmin)
class AssignmentTagAdmin(admin.ModelAdmin):
list_filter = ("study",)
list_display = ("name", "study",)
admin.site.register(AssignmentTag, AssignmentTagAdmin)
class CodingAssignmentAdmin(admin.ModelAdmin):
list_filter = ("coder", "tags", "piece__tags", "sample", "state")
list_display = (
"piece", "coder",
"sample", "state", "creation_time")
search_fields = ("piece__id", "piece__title", "sample__name")
filter_horizontal = ("tags",)
admin.site.register(CodingAssignment, CodingAssignmentAdmin)
class CodingAssignmentActivityAdmin(admin.ModelAdmin):
search_fields = (
"assignment__piece__id",
"assignment__piece__title",
"actor__name",
)
list_display = ("assignment", "action_time", "actor", "action", "state")
list_filter = ("actor", "action", "state")
date_hierarchy = "action_time"
admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
|
from django.contrib import admin
from coding.models import (
Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity)
class SampleAdmin(admin.ModelAdmin):
filter_horizontal = ("pieces",)
admin.site.register(Sample, SampleAdmin)
class AssignmentTagAdmin(admin.ModelAdmin):
list_filter = ("study",)
list_display = ("name", "study",)
admin.site.register(AssignmentTag, AssignmentTagAdmin)
class CodingAssignmentAdmin(admin.ModelAdmin):
list_filter = ("coder", "tags", "piece__tags", "sample", "state")
list_display = (
"piece", "coder",
"sample", "state", "creation_time")
search_fields = ("piece__id", "piece__title", "sample__name")
filter_horizontal = ("tags",)
admin.site.register(CodingAssignment, CodingAssignmentAdmin)
class CodingAssignmentActivityAdmin(admin.ModelAdmin):
search_fields = (
"assignment__piece__id",
"assignment__piece__title",
"actor__name",
)
list_display = ("assignment", "action_time", "actor", "action", "state")
list_filter = ("actor", "action", "state")
admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
|
Remove dataframe error we were testing
|
### Import our stuff
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
### Set up initial values
position = 555 # feet
velocity = 0 # feet/second
acceleration = -32.17 # feet / second^2
time_steps = np.linspace(0, 5, 501) # creates two entries at time zero
time_step_size = time_steps[1] - time_steps[0]
### Create a way to collect/record data
initial_data = {
'position': [position],
'velocity': [velocity],
'acceleration': [acceleration],
'time': [0]
}
motion_data = pd.DataFrame(initial_data)
### Evolve the simulation forward using our update rules
for time_step in time_steps:
velocity = velocity + (acceleration * time_step_size)
position = position + (velocity * time_step_size)
updated_data = pd.DataFrame({
'position': [position],
'velocity': [velocity],
'acceleration': [acceleration],
'time': [time_step]
})
motion_data = motion_data.append(updated_data)
motion_data.plot.line(
x = 'time',
y = 'position'
)
motion_data
|
### Import our stuff
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
### Set up initial values
position = 555 # feet
velocity = 0 # feet/second
acceleration = -32.17 # feet / second^2
time_steps = np.linspace(0, 5, 501) # creates two entries at time zero
time_step_size = time_steps[1] - time_steps[0]
### Create a way to collect/record data
initial_data = {
'position': [position, 12],
'velocity': [velocity],
'acceleration': [acceleration],
'time': [0]
}
motion_data = pd.DataFrame(initial_data)
### Evolve the simulation forward using our update rules
for time_step in time_steps:
velocity = velocity + (acceleration * time_step_size)
position = position + (velocity * time_step_size)
updated_data = pd.DataFrame({
'position': [position],
'velocity': [velocity],
'acceleration': [acceleration],
'time': [time_step]
})
motion_data = motion_data.append(updated_data)
motion_data.plot.line(
x = 'time',
y = 'position'
)
motion_data
|
Install script ready? who knows
|
$zip = "http://getsparks.org/static/install/spark-manager-0.0.1.zip";
$loader = "http://getsparks.org/static/install/Loader.php.txt";
if(!file_exists("application/core"))
{
echo "Can't find application/core. Currently this script only works with the default instance of Reactor. You may need to try a manual installation..\n";
exit;
}
echo "Pulling down spark manager from $zip ...\n";
copy($zip, "sparks.zip");
echo "Pulling down Loader class core extension from $loader ...\n";
copy($loader, "application/core/MY_Loader.php");
echo "Extracting zip package ...\n";
if(class_exists('ZipArchive'))
{
$zip = new ZipArchive;
if ($zip->open('sparks.zip') === TRUE)
{
$zip->extractTo('./tools');
$zip->close();
} else {
echo "Extraction failed .. exiting.\n";
exit;
}
} elseif(!!@`unzip`) {
`unzip sparks.zip -d ./tools`;
} else
{
echo "It seems you have no PHP zip library or `unzip` in your path. Use the manual installation.\n";
exit;
}
echo "Cleaning up ...\n";
@unlink('sparks.zip');
echo "Spark Manager has been install successfully!\n";
echo "Try: `php tools/spark help`\n";
|
#!/usr/bin/env php
<?php
$zip = "http://getsparks.org/static/install/spark-manager-0.0.1.zip";
$loader = "http://getsparks.org/static/install/Loader.php.txt";
if(!file_exists("application/core"))
{
echo "Can't find application/core. Currently this script only works with the default instance of Reactor. You may need to try a manual installation..\n";
exit;
}
echo "Pulling down spark manager from $zip ...\n";
copy($zip, "sparks.zip");
echo "Pulling down Loader class core extension from $loader ...\n";
copy($loader, "application/core/MY_Loader.php");
echo "Extracting zip package ...\n";
if(class_exists('ZipArchive'))
{
$zip = new ZipArchive;
if ($zip->open('sparks.zip') === TRUE)
{
$zip->extractTo('./tools');
$zip->close();
} else {
echo "Extraction failed .. exiting.\n";
exit;
}
} elseif(!!@`unzip`) {
`unzip sparks.zip -d ./tools`;
} else
{
echo "It seems you have no PHP zip library or `unzip` in your path. Use the manual installation.\n";
exit;
}
echo "Cleaning up ...\n";
@unlink('sparks.zip');
echo "Spark Manager has been install successfully!\n";
echo "Try: `php tools/spark help`\n";
|
Update deprecated config for bodyParser and session
|
/**
* Express global configuration
*/
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var stylus = require('stylus');
var passport = require('passport');
module.exports = function(app, config) {
// Set stylus middleware
app.use(stylus.middleware(
{
src: config.rootPath + '/public',
compile: function (str, path) {
return stylus(str).set('filename', path);
}
})
);
// Parsers
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Sessions
app.use(session({
secret: 'multi vision unicorn',
resave:false,
saveUninitialized:false
}));
// Passport middlewares
app.use(passport.initialize());
app.use(passport.session());
// Set static middleware for static assets
app.use(express.static(config.rootPath + '/public'));
// Set views dir and engine
app.set('views', config.rootPath + '/server/views');
app.set('view engine', 'jade');
// Logger
app.use(logger('dev'));
};
|
/**
* Express global configuration
*/
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var stylus = require('stylus');
var passport = require('passport');
module.exports = function(app, config) {
// Set stylus middleware
app.use(stylus.middleware(
{
src: config.rootPath + '/public',
compile: function (str, path) {
return stylus(str).set('filename', path);
}
})
);
// Parsers
app.use(cookieParser());
app.use(bodyParser());
// Sessions
app.use(session({secret: 'multi vision unicorn'}));
// Passport middlewares
app.use(passport.initialize());
app.use(passport.session());
// Set static middleware for static assets
app.use(express.static(config.rootPath + '/public'));
// Set views dir and engine
app.set('views', config.rootPath + '/server/views');
app.set('view engine', 'jade');
// Logger
app.use(logger('dev'));
};
|
Save mnist classifier model in a file named with the network topology.
|
#!/usr/bin/env python
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Classifier
def get_datasets(self):
return [(x, y.astype('int32')) for x, y in cPickle.load(gzip.open(DATASET))]
m = Main()
path = os.path.join(tempfile.gettempdir(), 'mnist-classifier-%s.pkl.gz' % m.opts.layers)
if os.path.exists(path):
m.net.load(path)
m.train()
m.net.save(path)
|
#!/usr/bin/env python
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Classifier
def get_datasets(self):
return [(x, y.astype('int32')) for x, y in cPickle.load(gzip.open(DATASET))]
path = os.path.join(tempfile.gettempdir(), 'mnist-classifier.pkl.gz')
Main().train().save(path)
print 'saved network to', path
|
Exclude only log4j2 queue from class loader
Right now the complete com.mojang package is excluded from the LaunchClassLoader on the server. This means mods can't transform authlib for example which doesn't need to be excluded for the UI to work. By excluding only the specific log4j2 QueueLogAppender, mods can also transform the classes in the com.mojang.authlib package.
|
package net.minecraftforge.fml.common.launcher;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
public class FMLServerTweaker extends FMLTweaker {
@Override
public String getLaunchTarget()
{
return "net.minecraft.server.MinecraftServer";
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
// The log4j2 queue is excluded so it is correctly visible from the obfuscated
// and deobfuscated parts of the code. Without, the UI won't show anything
classLoader.addClassLoaderExclusion("com.mojang.util.QueueLogAppender");
classLoader.addTransformerExclusion("net.minecraftforge.fml.repackage.");
classLoader.addTransformerExclusion("net.minecraftforge.fml.relauncher.");
classLoader.addTransformerExclusion("net.minecraftforge.fml.common.asm.transformers.");
classLoader.addClassLoaderExclusion("LZMA.");
FMLLaunchHandler.configureForServerLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
}
|
package net.minecraftforge.fml.common.launcher;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
public class FMLServerTweaker extends FMLTweaker {
@Override
public String getLaunchTarget()
{
return "net.minecraft.server.MinecraftServer";
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
// The mojang packages are excluded so the log4j2 queue is correctly visible from
// the obfuscated and deobfuscated parts of the code. Without, the UI won't show anything
classLoader.addClassLoaderExclusion("com.mojang.");
classLoader.addTransformerExclusion("net.minecraftforge.fml.repackage.");
classLoader.addTransformerExclusion("net.minecraftforge.fml.relauncher.");
classLoader.addTransformerExclusion("net.minecraftforge.fml.common.asm.transformers.");
classLoader.addClassLoaderExclusion("LZMA.");
FMLLaunchHandler.configureForServerLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
}
|
Fix variable indention in build classname test
|
'use strict';
var blocks;
describe('block class names', function() {
before(function() {
var testHTML = document.querySelector('#build-classname');
blocks = testHTML.querySelectorAll('.hljs');
});
it('should add language class name to block', function() {
var expected = 'some-class hljs xml',
actual = blocks[0].className;
actual.should.equal(expected);
});
it('should not clutter block class (first)', function () {
var expected = 'hljs some-class xml',
actual = blocks[1].className;
actual.should.equal(expected);
});
it('should not clutter block class (last)', function () {
var expected = 'some-class hljs xml',
actual = blocks[2].className;
actual.should.equal(expected);
});
it('should not clutter block class (spaces around)', function () {
var expected = 'hljs some-class xml',
actual = blocks[3].className;
actual.should.equal(expected);
});
});
|
'use strict';
var blocks;
describe('block class names', function() {
before(function() {
var testHTML = document.querySelector('#build-classname');
blocks = testHTML.querySelectorAll('.hljs');
});
it('should add language class name to block', function() {
var expected = 'some-class hljs xml',
actual = blocks[0].className;
actual.should.equal(expected);
});
it('should not clutter block class (first)', function () {
var expected = 'hljs some-class xml',
actual = blocks[1].className;
actual.should.equal(expected);
});
it('should not clutter block class (last)', function () {
var expected = 'some-class hljs xml',
actual = blocks[2].className;
actual.should.equal(expected);
});
it('should not clutter block class (spaces around)', function () {
var expected = 'hljs some-class xml',
actual = blocks[3].className;
actual.should.equal(expected);
});
});
|
Fix incorrect error subscription on input stream
|
#!/usr/bin/env node
"use strict";
let fs = require("fs");
let peg = require("../lib/peg");
let options = require("./options");
// Helpers
function readStream(inputStream, callback) {
let input = "";
inputStream.on("data", data => { input += data; });
inputStream.on("end", () => { callback(input); });
}
function abort(message) {
console.error(message);
process.exit(1);
}
// Main
let inputStream, outputStream;
if (options.inputFile === "-") {
process.stdin.resume();
inputStream = process.stdin;
} else {
inputStream = fs.createReadStream(options.inputFile);
inputStream.on("error", () => {
abort(`Can't read from file "${options.inputFile}".`);
});
}
if (options.outputFile === "-") {
outputStream = process.stdout;
} else {
outputStream = fs.createWriteStream(options.outputFile);
outputStream.on("error", () => {
abort(`Can't write to file "${options.outputFile}".`);
});
}
readStream(inputStream, input => {
let location, source;
try {
source = peg.generate(input, options);
} catch (e) {
if (e.location !== undefined) {
location = e.location.start;
abort(location.line + ":" + location.column + ": " + e.message);
} else {
abort(e);
}
}
outputStream.write(source);
if (outputStream !== process.stdout) {
outputStream.end();
}
});
|
#!/usr/bin/env node
"use strict";
let fs = require("fs");
let peg = require("../lib/peg");
let options = require("./options");
// Helpers
function readStream(inputStream, callback) {
let input = "";
inputStream.on("data", data => { input += data; });
inputStream.on("end", () => { callback(input); });
}
function abort(message) {
console.error(message);
process.exit(1);
}
// Main
let inputStream, outputStream;
if (options.inputFile === "-") {
process.stdin.resume();
inputStream = process.stdin;
inputStream.on("error", () => {
abort(`Can't read from file "${options.inputFile}".`);
});
} else {
inputStream = fs.createReadStream(options.inputFile);
}
if (options.outputFile === "-") {
outputStream = process.stdout;
} else {
outputStream = fs.createWriteStream(options.outputFile);
outputStream.on("error", () => {
abort(`Can't write to file "${options.outputFile}".`);
});
}
readStream(inputStream, input => {
let location, source;
try {
source = peg.generate(input, options);
} catch (e) {
if (e.location !== undefined) {
location = e.location.start;
abort(location.line + ":" + location.column + ": " + e.message);
} else {
abort(e);
}
}
outputStream.write(source);
if (outputStream !== process.stdout) {
outputStream.end();
}
});
|
Remove implicit cast to fix second conversion
|
package de.philipphager.disclosure.util.time;
import javax.inject.Inject;
import org.threeten.bp.Duration;
import org.threeten.bp.LocalDateTime;
import static de.philipphager.disclosure.util.assertion.Assertions.ensureNotNull;
public class Stopwatch {
private static final int MILLIS = 1000;
private final Clock clock;
private LocalDateTime startedAt;
private Duration duration;
@Inject public Stopwatch(Clock clock) {
this.clock = clock;
}
public void start() {
startedAt = clock.now();
}
public void stop() {
ensureNotNull(startedAt, "called stop() before start()");
LocalDateTime endedAt = clock.now();
duration = Duration.between(startedAt, endedAt);
startedAt = null;
}
public Duration getDuration() {
return duration;
}
private double toSecs() {
return duration.toMillis() / (double) MILLIS;
}
@Override public String toString() {
return String.format("duration %s sec.", toSecs());
}
}
|
package de.philipphager.disclosure.util.time;
import javax.inject.Inject;
import org.threeten.bp.Duration;
import org.threeten.bp.LocalDateTime;
import static de.philipphager.disclosure.util.assertion.Assertions.ensureNotNull;
public class Stopwatch {
private static final int MILLIS = 1000;
private final Clock clock;
private LocalDateTime startedAt;
private Duration duration;
@Inject public Stopwatch(Clock clock) {
this.clock = clock;
}
public void start() {
startedAt = clock.now();
}
public void stop() {
ensureNotNull(startedAt, "called stop() before start()");
LocalDateTime endedAt = clock.now();
duration = Duration.between(startedAt, endedAt);
startedAt = null;
}
public Duration getDuration() {
return duration;
}
private double toSecs() {
return duration.toMillis() / MILLIS;
}
@Override public String toString() {
return String.format("duration %s sec.", toSecs());
}
}
|
Remove an unnecessary call to strval()
|
<?php
/*
* Poll for the response to an out-of-band challenge.
*
* This is called from AJAX, if the user has an out-of-band token. It acts as a proxy for the
* `/validate/polltransaction`-endpoint of PrivacyIDEA.
*/
try{
$authStateId = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($authStateId, 'privacyidea:privacyidea:init');
SimpleSAML_Logger::debug("Loaded state privacyidea:privacyidea:init from polltransaction.php");
} catch (Exception $e){
}
if (isset($state)) {
$serverconfig = $state['privacyidea:serverconfig'];
$authToken = sspmod_privacyidea_Auth_utils::fetchAuthToken($serverconfig);
$transaction_id = $state['privacyidea:privacyidea:checkTokenType']['transaction_id'];
SimpleSAML_Logger::debug("Polling for transaction_id: " . $transaction_id);
$result = sspmod_privacyidea_Auth_utils::curl(
array(),
array("authorization:" . $authToken),
$serverconfig,
"/validate/polltransaction/" . $transaction_id,
"GET")
->result
->value;
}
echo isset($result) && $result ? "true" : "false";
?>
|
<?php
/*
* Poll for the response to an out-of-band challenge.
*
* This is called from AJAX, if the user has an out-of-band token. It acts as a proxy for the
* `/validate/polltransaction`-endpoint of PrivacyIDEA.
*/
try{
$authStateId = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($authStateId, 'privacyidea:privacyidea:init');
SimpleSAML_Logger::debug("Loaded state privacyidea:privacyidea:init from polltransaction.php");
} catch (Exception $e){
}
if (isset($state)) {
$serverconfig = $state['privacyidea:serverconfig'];
$authToken = sspmod_privacyidea_Auth_utils::fetchAuthToken($serverconfig);
$transaction_id = strval($state['privacyidea:privacyidea:checkTokenType']['transaction_id']);
SimpleSAML_Logger::debug("Polling for transaction_id: " . $transaction_id);
$result = sspmod_privacyidea_Auth_utils::curl(
array(),
array("authorization:" . $authToken),
$serverconfig,
"/validate/polltransaction/" . $transaction_id,
"GET")
->result
->value;
}
echo isset($result) && $result ? "true" : "false";
?>
|
Change version from 0.1.dev* to 0.1.0.dev*
The semantic versioning specification requires that the major, minor,
and patch numbers always be present.
|
##
# Package metadata
##
import ah_bootstrap
from astropy_helpers.git_helpers import get_git_devstr
# Name
name = 'plasmapy'
# PlasmaPy uses Semantic Versioning of the form: MAJOR.MINOR.PATCH
#
# - The MAJOR version changes when there are backwards incompatible changes
# - The MINOR version changes when backwards compatible functionality is added
# - The PATCH version changes when the public API remains the same
#
# During initial development releases (with MAJOR = 0), backwards compatibility
# does not need to be maintained when MINOR is incremented.
#
# While a new version is being developed, '.dev' followed by the commit number
# will be appended to the version string.
version = '0.1.0.dev'
release = 'dev' in version
if release:
version += get_git_devstr(False)
# Long description / docstring
description = """
PlasmaPy is a community-developed and community-driven core Python
package for plasma physics.
"""
# Author(s)
author = 'The PlasmaPy Community'
|
##
# Package metadata
##
import ah_bootstrap
from astropy_helpers.git_helpers import get_git_devstr
# Name
name = 'plasmapy'
# PlasmaPy uses Semantic Versioning of the form: MAJOR.MINOR.PATCH
#
# - The MAJOR version changes when there are backwards incompatible changes
# - The MINOR version changes when backwards compatible functionality is added
# - The PATCH version changes when the public API remains the same
#
# During initial development releases (with MAJOR = 0), backwards compatibility
# does not need to be maintained when MINOR is incremented.
#
# While a new version is being developed, '.dev' followed by the commit number
# will be appended to the version string.
version = '0.1.dev'
release = 'dev' in version
if release:
version += get_git_devstr(False)
# Long description / docstring
description = """
PlasmaPy is a community-developed and community-driven core Python
package for plasma physics.
"""
# Author(s)
author = 'The PlasmaPy Community'
|
Allow to retrieve key from instance
|
// Pure backbone stuffs
//
//= require app/settings
//= require bb/underscore-min
//= require bb/backbone-min
//= require_self
var pubSub = _.extend({},Backbone.Events); //http://blog.safaribooksonline.com/2013/10/02/decoupling-backbone-applications-with-pubsub/
(function(Backbone, _, App){
App.View = Backbone.View.extend({
constructor: function(opt) {
this.key = opt.key || this.key;
this.pubSub = opt.pubSub || window.pubSub;
Backbone.View.apply(this,arguments);
},
publishEvt : function(code, data) {
App.logDebug(">>> published event = "+ code);
this.pubSub.trigger(code, _.extend({key : this.key}, data));
},
subscribeEvt : function(code, callback) {
this.listenTo(this.pubSub, code, callback ,this);
},
remove: function() {
// this.$el.remove(); // this View is not removing the $el.
this.$el.unbind(); // just unbind all event
this.stopListening();
return this;
}
});
})(Backbone, _, App);
|
// Pure backbone stuffs
//
//= require app/settings
//= require bb/underscore-min
//= require bb/backbone-min
//= require_self
var pubSub = _.extend({},Backbone.Events); //http://blog.safaribooksonline.com/2013/10/02/decoupling-backbone-applications-with-pubsub/
(function(Backbone, _, App){
App.View = Backbone.View.extend({
constructor: function(opt) {
this.key = opt.key;
this.pubSub = opt.pubSub || window.pubSub;
Backbone.View.apply(this,arguments);
},
publishEvt : function(code, data) {
App.logDebug(">>> published event = "+ code);
this.pubSub.trigger(code, _.extend({key : this.key}, data));
},
subscribeEvt : function(code, callback) {
this.listenTo(this.pubSub, code, callback ,this);
},
remove: function() {
// this.$el.remove(); // this View is not removing the $el.
this.$el.unbind(); // just unbind all event
this.stopListening();
return this;
}
});
})(Backbone, _, App);
|
Add stub for posting valid client
|
'use strict';
/* TODO:
GET client (all/specific/sortBy/pagination/search)
POST client (ok/fail)
PUT client
DELETE client
*/
exports.get = function(assert, client) {
return client.clients.get().then(function(res) {
assert(res.data.length === 0, 'Failed to get clients as expected');
}).catch(function() {
assert(true, 'Failed to get clients as expected');
});
};
exports.postInvalid = function(assert, client) {
return client.clients.post().then(function() {
assert(false, 'Posted client even though shouldn\'t');
}).catch(function() {
assert(true, 'Failed to post client as expected');
});
};
exports.postValid = function(assert, client) {
// TODO: generate a valid client based on schema
return client.clients.post({}).then(function() {
assert(true, 'Posted client as expected');
}).catch(function(err) {
assert(false, 'Failed to post client', err);
});
};
exports.put = function(assert, client) {
return client.clients.put().then(function() {
assert(false, 'Updated client even though shouldn\'t');
}).catch(function() {
assert(true, 'Failed to update client as expected');
});
};
|
'use strict';
/* TODO:
GET client (all/specific/sortBy/pagination/search)
POST client (ok/fail)
PUT client
DELETE client
*/
exports.get = function(assert, client) {
return client.clients.get().then(function(res) {
assert(res.data.length === 0, 'Failed to get clients as expected');
}).catch(function() {
assert(true, 'Failed to get clients as expected');
});
};
exports.post = function(assert, client) {
return client.clients.post().then(function() {
assert(false, 'Posted client even though shouldn\'t');
}).catch(function() {
assert(true, 'Failed to post client as expected');
});
};
exports.put = function(assert, client) {
return client.clients.put().then(function() {
assert(false, 'Updated client even though shouldn\'t');
}).catch(function() {
assert(true, 'Failed to update client as expected');
});
};
|
Add unit test for 75d4675
|
import fieldsToParams from '../../src/fields-to-params'
describe('fieldsToParams', () => {
it('should export a function', () => {
expect(fieldsToParams).toBeInstanceOf(Function)
})
it('should convert some random fields correctly', () => {
const input = {
hitType: 'event',
eventCategory: 'social',
eventAction: 'like',
eventLabel: 'Like!',
eventValue: 10,
metric1: 'howdy',
dimension22: 17
}
const output = {
t: 'event',
ec: 'social',
ea: 'like',
el: 'Like!',
ev: 10,
cm1: 'howdy',
cd22: 17
}
expect(fieldsToParams(input)).toStrictEqual(output)
})
it('should pass 0 as it is, but omit empty string, null and undefined values', () => {
const input = {
hitType: 'event',
eventCategory: 'social',
eventAction: 'like',
eventLabel: null,
eventValue: 0,
metric1: '',
dimension22: undefined
}
const output = {
t: 'event',
ec: 'social',
ev: 0,
ea: 'like'
}
expect(fieldsToParams(input)).toStrictEqual(output)
})
})
|
import fieldsToParams from '../../src/fields-to-params'
describe('fieldsToParams', () => {
it('should export a function', () => {
expect(fieldsToParams).toBeInstanceOf(Function)
})
it('should convert some random fields correctly', () => {
const input = {
hitType: 'event',
eventCategory: 'social',
eventAction: 'like',
eventLabel: 'Like!',
eventValue: 10,
metric1: 'howdy',
dimension22: 17
}
const output = {
t: 'event',
ec: 'social',
ea: 'like',
el: 'Like!',
ev: 10,
cm1: 'howdy',
cd22: 17
}
expect(fieldsToParams(input)).toStrictEqual(output)
})
})
|
Remove test enforcing listening on port 1883
|
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service_running(host):
service = host.service('docker')
assert service.is_running
@pytest.mark.parametrize('socket_def', [
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
socket = host.socket(socket_def)
assert socket.is_listening
# Tests to write:
# - using the localhost listener:
# - verify that a message can be published
# - verify that a published message can be subscribed to
|
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service_running(host):
service = host.service('docker')
assert service.is_running
@pytest.mark.parametrize('socket_def', [
# listening on localhost, for tcp sockets on port 1883 (MQQT)
('tcp://127.0.0.1:1883'),
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
socket = host.socket(socket_def)
assert socket.is_listening
# Tests to write:
# - using the localhost listener:
# - verify that a message can be published
# - verify that a published message can be subscribed to
|
Fix CFFI test when executed multiple times
|
import os
import ctypes
import doctest
from numba import *
import numba
try:
import cffi
ffi = cffi.FFI()
except ImportError:
ffi = None
# ______________________________________________________________________
def test():
if ffi is not None:
test_cffi_calls()
# ______________________________________________________________________
# Tests
@autojit(nopython=True)
def call_cffi_func(func, value):
return func(value)
def test_cffi_calls():
# Test printf for nopython and no segfault
ffi.cdef("int printf(char *, ...);", override=True)
lib = ffi.dlopen(None)
printf = lib.printf
call_cffi_func(printf, "Hello world!\n")
# ______________________________________________________________________
if __name__ == "__main__":
test()
|
import os
import ctypes
import doctest
from numba import *
import numba
try:
import cffi
ffi = cffi.FFI()
except ImportError:
ffi = None
# ______________________________________________________________________
def test():
if ffi is not None:
test_cffi_calls()
# ______________________________________________________________________
# Tests
@autojit(nopython=True)
def call_cffi_func(func, value):
return func(value)
def test_cffi_calls():
# Test printf for nopython and no segfault
ffi.cdef("int printf(char *, ...);")
lib = ffi.dlopen(None)
printf = lib.printf
call_cffi_func(printf, "Hello world!\n")
# ______________________________________________________________________
if __name__ == "__main__":
test()
|
Use lodash assign to support earlier Node versions
|
var hogan = require('hogan.js');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var getServiceProperties = require('./serviceProperties');
var templateFile = fs.readFileSync(path.resolve(__dirname, '../templates/spec.mustache'), 'utf-8');
var template = hogan.compile(templateFile);
var defaultRelease = 1;
function getReleaseNumber(release) {
if (release) {
return release;
}
return defaultRelease;
}
function getRequiredPackages(pkg) {
return _.get(pkg, 'spec.requires', []);
}
function getExecutableFiles(pkg) {
var name = pkg.name;
var executableFiles = _.get(pkg, 'spec.executable', []).map(function (file) {
return path.join('/usr/lib/', name, file);
});
return {
executableFiles: executableFiles,
hasExecutableFiles: executableFiles.length !== 0
};
}
function getPostInstallCommands(pkg) {
return _.get(pkg, 'spec.post', []);
}
module.exports = function (pkg, release) {
var serviceProperties = _.assign({
release: getReleaseNumber(release),
requires: getRequiredPackages(pkg),
postInstallCommands: getPostInstallCommands(pkg),
version: pkg.version
},
getExecutableFiles(pkg),
getServiceProperties(pkg)
);
return template.render(serviceProperties);
};
|
var hogan = require('hogan.js');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var getServiceProperties = require('./serviceProperties');
var templateFile = fs.readFileSync(path.resolve(__dirname, '../templates/spec.mustache'), 'utf-8');
var template = hogan.compile(templateFile);
var defaultRelease = 1;
function getReleaseNumber(release) {
if (release) {
return release;
}
return defaultRelease;
}
function getRequiredPackages(pkg) {
return _.get(pkg, 'spec.requires', []);
}
function getExecutableFiles(pkg) {
var name = pkg.name;
var executableFiles = _.get(pkg, 'spec.executable', []).map(function (file) {
return path.join('/usr/lib/', name, file);
});
return {
executableFiles: executableFiles,
hasExecutableFiles: executableFiles.length !== 0
};
}
function getPostInstallCommands(pkg) {
return _.get(pkg, 'spec.post', []);
}
module.exports = function (pkg, release) {
var serviceProperties = Object.assign({
release: getReleaseNumber(release),
requires: getRequiredPackages(pkg),
postInstallCommands: getPostInstallCommands(pkg),
version: pkg.version
},
getExecutableFiles(pkg),
getServiceProperties(pkg)
);
return template.render(serviceProperties);
};
|
Add missing method to interface
|
<?php declare(strict_types=1);
/*
* This file is part of the FeatureToggle package.
*
* (c) Jad Bitar <jadbitar@mac.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FeatureToggle\Feature;
/**
* Feature interface.
*
* @package FeatureToggle
* @subpackage FeatureToggle.Feature
* @author Jad Bitar <jadbitar@mac.com>
*/
interface FeatureInterface
{
/**
* Returns the feature's description.
*
* @return string
*/
public function getDescription(): string;
/**
* Returns the feature's name.
*
* @return string
*/
public function getName(): string;
/**
* Tells if feature is enabled.
*
* @param array $args
* @return bool
*/
public function isEnabled(array $args = []): bool;
/**
* Sets the feature's descriptions.
*
* @param string $description Feature's description.
* @return void
*/
public function setDescription(string $description);
/**
* Sets the feature's name.
*
* @param string $name Feature's name.
* @return void
*/
public function setName(string $name);
/**
* @param callable $strategy
* @return void
*/
public function pushStrategy(callable $strategy);
}
|
<?php declare(strict_types=1);
/*
* This file is part of the FeatureToggle package.
*
* (c) Jad Bitar <jadbitar@mac.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FeatureToggle\Feature;
/**
* Feature interface.
*
* @package FeatureToggle
* @subpackage FeatureToggle.Feature
* @author Jad Bitar <jadbitar@mac.com>
*/
interface FeatureInterface
{
/**
* Returns the feature's description.
*
* @return string
*/
public function getDescription(): string;
/**
* Returns the feature's name.
*
* @return string
*/
public function getName(): string;
/**
* Tells if feature is enabled.
*
* @param array $args
* @return bool
*/
public function isEnabled(array $args = []): bool;
/**
* Sets the feature's descriptions.
*
* @param string $description Feature's description.
* @return void
*/
public function setDescription(string $description);
/**
* Sets the feature's name.
*
* @param string $name Feature's name.
* @return void
*/
public function setName(string $name);
}
|
Fix php 5.3 syntax issue
|
<?php
namespace SimpleSAML\Metadata;
/**
* Test SAML parsing
*/
class SAMLParserTest extends \PHPUnit_Framework_TestCase
{
/**
* Test Registration Info is parsed
*/
public function testRegistrationInfo()
{
$expected = array(
'registrationAuthority' => 'https://incommon.org',
);
$document = \SAML2_DOMDocumentFactory::fromString(
<<<XML
<EntityDescriptor entityID="theEntityID"
xmlns="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:mdrpi="urn:oasis:names:tc:SAML:metadata:rpi">
<Extensions>
<mdrpi:RegistrationInfo registrationAuthority="https://incommon.org"/>
</Extensions>
<SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
</SPSSODescriptor>
</EntityDescriptor>
XML
);
$entities = \SimpleSAML_Metadata_SAMLParser::parseDescriptorsElement($document->documentElement);
$this->assertArrayHasKey('theEntityID', $entities);
// RegistrationInfo is accessible in the SP or IDP metadata accessors
$metadata = $entities['theEntityID']->getMetadata20SP();
$this->assertEquals($expected, $metadata['RegistrationInfo']);
}
}
|
<?php
namespace SimpleSAML\Metadata;
/**
* Test SAML parsing
*/
class SAMLParserTest extends \PHPUnit_Framework_TestCase
{
/**
* Test Registration Info is parsed
*/
public function testRegistrationInfo()
{
$expected = array(
'registrationAuthority' => 'https://incommon.org',
);
$document = \SAML2_DOMDocumentFactory::fromString(
<<<XML
<EntityDescriptor entityID="theEntityID"
xmlns="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:mdrpi="urn:oasis:names:tc:SAML:metadata:rpi">
<Extensions>
<mdrpi:RegistrationInfo registrationAuthority="https://incommon.org"/>
</Extensions>
<SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
</SPSSODescriptor>
</EntityDescriptor>
XML
);
$entities = \SimpleSAML_Metadata_SAMLParser::parseDescriptorsElement($document->documentElement);
$this->assertArrayHasKey('theEntityID', $entities);
// RegistrationInfo is accessible in the SP or IDP metadata accessors
$this->assertEquals($expected, $entities['theEntityID']->getMetadata20SP()['RegistrationInfo']);
}
}
|
Change order of notification types so that email is shown first and becomes the default
|
from django.db import models
from django.contrib.auth.models import User
from common.models import Audit, Comment
from farms.models import CropSeason, Field
########################################################
### NotificationsRule
###
### Connect notification info with a Field, CropSeason
########################################################
class NotificationsRule(Comment, Audit):
# from Comment: comment
# from Audit: cdate, cuser, mdate, muser
NOTIFICATION_TYPE_VALUES = ['Email', 'SMS']
LEVEL_CHOICES = ['Daily', 'Any Flag', 'Irrigate Today', 'None']
field_list = models.ManyToManyField(Field)
recipients = models.ManyToManyField(User)
level = models.CharField(max_length = 15)
notification_type = models.CharField(max_length = 15)
|
from django.db import models
from django.contrib.auth.models import User
from common.models import Audit, Comment
from farms.models import CropSeason, Field
########################################################
### NotificationsRule
###
### Connect notification info with a Field, CropSeason
########################################################
class NotificationsRule(Comment, Audit):
# from Comment: comment
# from Audit: cdate, cuser, mdate, muser
NOTIFICATION_TYPE_VALUES = ['SMS', 'Email']
LEVEL_CHOICES = ['Daily', 'Any Flag', 'Irrigate Today', 'None']
field_list = models.ManyToManyField(Field)
recipients = models.ManyToManyField(User)
level = models.CharField(max_length = 15)
notification_type = models.CharField(max_length = 15)
|
Fix test to force diff prefixes.
|
package git
import (
"strings"
"testing"
)
func TestPatch(t *testing.T) {
repo := createTestRepo(t)
defer repo.Free()
//defer os.RemoveAll(repo.Workdir())
_, originalTreeId := seedTestRepo(t, repo)
originalTree, err := repo.LookupTree(originalTreeId)
checkFatal(t, err)
_, newTreeId := updateReadme(t, repo, "file changed\n")
newTree, err := repo.LookupTree(newTreeId)
checkFatal(t, err)
opts := &DiffOptions{
OldPrefix: "a",
NewPrefix: "b",
}
diff, err := repo.DiffTreeToTree(originalTree, newTree, opts)
checkFatal(t, err)
patch, err := diff.Patch(0)
checkFatal(t, err)
patchStr, err := patch.String()
checkFatal(t, err)
if strings.Index(patchStr, "diff --git a/README b/README\nindex 257cc56..820734a 100644\n--- a/README\n+++ b/README\n@@ -1 +1 @@\n-foo\n+file changed") == -1 {
t.Fatalf("patch was bad")
}
}
|
package git
import (
"strings"
"testing"
)
func TestPatch(t *testing.T) {
repo := createTestRepo(t)
defer repo.Free()
//defer os.RemoveAll(repo.Workdir())
_, originalTreeId := seedTestRepo(t, repo)
originalTree, err := repo.LookupTree(originalTreeId)
checkFatal(t, err)
_, newTreeId := updateReadme(t, repo, "file changed\n")
newTree, err := repo.LookupTree(newTreeId)
checkFatal(t, err)
diff, err := repo.DiffTreeToTree(originalTree, newTree, nil)
checkFatal(t, err)
patch, err := diff.Patch(0)
checkFatal(t, err)
patchStr, err := patch.String()
checkFatal(t, err)
if strings.Index(patchStr, "diff --git a/README b/README\nindex 257cc56..820734a 100644\n--- a/README\n+++ b/README\n@@ -1 +1 @@\n-foo\n+file changed") == -1 {
t.Fatalf("patch was bad")
}
}
|
Use the angular module pattern instead of using a closure.
|
/*global cardApp*/
/*jslint unparam: true */
cardApp.directive('integer', function () {
'use strict';
// Implements custom validation for card number.
var INTEGER_REGEXP = /^([aAkKjJQq23456789]{1}|(10){1})$/;
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('integer', true);
return viewValue;
}
// it is invalid, return undefined (no model update)
ctrl.$setValidity('integer', false);
return undefined;
});
}
};
});
|
/*global cardApp*/
/*jslint unparam: true */
(function () {
'use strict';
// Implements custom validation for card number.
var INTEGER_REGEXP = /^([aAkKjJQq23456789]{1}|(10){1})$/;
cardApp.directive('integer', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('integer', true);
return viewValue;
}
// it is invalid, return undefined (no model update)
ctrl.$setValidity('integer', false);
return undefined;
});
}
};
});
}());
|
Clarify Address usage in send example
Improved the script to explain the recipient address a little better.
Changed the address concat to a reference to a specific kind of Iota address.
This is loosely inspired by the JAVA sen transaction test case.
|
# coding=utf-8
"""
Example script that shows how to use PyOTA to send a transfer to an address.
"""
from iota import *
SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL2999999999999999999999999999999"
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = SEED1
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2,
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
|
# coding=utf-8
"""
Example script that shows how to use PyOTA to send a transfer to an address.
"""
from iota import *
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = b'SEED9GOES9HERE'
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG'
b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR'
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
|
Portal.Push: Use some additional refined logic
|
<?php namespace App\Commands;
use App;
use App\Commands\Command;
use App\Models\Container;
use DroneMill\EventsocketClient\Client;
use Log;
use Config;
use Illuminate\Contracts\Bus\SelfHandling;
class PushBatondUpdatedContainer extends Command implements SelfHandling {
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
// if we are running unit tests, then don't sent a push noticifation
if (App::environment('testing'))
{
return;
}
$machine = $this->container->machine()->first();
// if we dont have a machine record, then abort push
if (empty($machine))
{
Log::error('Aborting Portal event push becuase machine not found', [
'container_id' => $this->container->id,
'event' => 'batond-container-updated',
]);
return;
}
$event = 'harmony.machine-'. $machine->id . '.batond-container-updated';
$harmony = new Client(Config::get('harmony.portal.url'));
$harmony->emit($event, ['ContainerID' => $this->container->id]);
Log::info('Emitted Portal event', ['event' => $event, 'container_id' => $this->container->id]);
}
}
|
<?php namespace App\Commands;
use App\Commands\Command;
use App\Models\Container;
use DroneMill\EventsocketClient\Client;
use Log;
use Config;
use Illuminate\Contracts\Bus\SelfHandling;
class PushBatondUpdatedContainer extends Command implements SelfHandling {
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
$machineID = $this->container->machine()->first()->id;
$event = 'harmony.machine-'. $machineID . '.batond-container-updated';
$harmony = new Client(Config::get('harmony.portal.url'));
$harmony->emit($event, ['ContainerID' => $this->container->id]);
Log::info('Emitted Portal event', ['event' => $event, 'container_id' => $this->container->id]);
}
}
|
Add Modernizr Box-Sizing test and more concise polyfill
|
/*global Modernizr:true */
// Box sizing
// =============================================================================
Modernizr.addTest("boxsizing", function() {
return Modernizr.testAllProps("boxSizing") && (document.documentMode === undefined || document.documentMode > 7);
});
if (!Modernizr.boxsizing) {
$.fn.boxSizeIE7 = function() {
this.each(function() {
var $this = $(this);
$this.width($this.width()*2 - $this.outerWidth());
});
};
// add more selectors here for box sizing fixes
$('.grid__cell').boxSizeIE7();
}
// Console helper for older browsers
// =============================================================================
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
|
/*global Modernizr:true */
// Box sizing
// =============================================================================
if (Modernizr.boxsizing !== null && Modernizr.boxsizing === false) {
$.fn.boxSizeIE7 = function() {
this.each(function() {
var $this = $(this),
elem_width = $this.width();
$this.width(elem_width - ($this.outerWidth() - elem_width));
});
};
// add more selectors here for box sizing fixes
$('.grid__cell').boxSizeIE7();
}
// Console helper for older browsers
// =============================================================================
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
|
Increment item count in news import mgmt command
|
from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page
from akllt.dataimport.news import import_news
from akllt.models import NewsStory
class Command(BaseCommand):
args = '<directory name>'
help = 'Imports data from old akl.lt website'
def handle(self, news_folder, *args, **options):
news_count = 0
root = Page.get_first_root_node()
if root is None:
root = Page.add_root(title='Root page')
news = import_news(news_folder)
for news_story in news:
root.add_child(instance=NewsStory(
title=news_story['title'],
date=news_story['date'],
blurb=news_story['blurb'],
body=news_story['body'],
))
news_count += 1
self.stdout.write('Successfully imported %d news items\n' % news_count)
|
from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page
from akllt.dataimport.news import import_news
from akllt.models import NewsStory
class Command(BaseCommand):
args = '<directory name>'
help = 'Imports data from old akl.lt website'
def handle(self, news_folder, *args, **options):
news_count = 0
root = Page.get_first_root_node()
if root is None:
root = Page.add_root(title='Root page')
news = import_news(news_folder)
for news_story in news:
root.add_child(instance=NewsStory(
title=news_story['title'],
date=news_story['date'],
blurb=news_story['blurb'],
body=news_story['body'],
))
self.stdout.write('Successfully imported %d news items\n' % news_count)
|
Fix loadBlocks initializing all blocks to Undefined
|
var $ = require('jquery');
var SirTrevor = require('sir-trevor-js');
module.exports = {
loadLocale: function(localeName, locale) {
SirTrevor.Locales[localeName] = SirTrevor.Locales[localeName] || {};
$.extend(true, SirTrevor.Locales[localeName], locale);
},
loadMixin: function(mixin) {
SirTrevor.BlockMixins[this._classify(mixin.mixinName)] = mixin;
SirTrevor.Block.prototype.availableMixins.push(mixin.mixinName.toLowerCase());
},
loadBlock: function(block) {
SirTrevor.Blocks[this._classify(block.prototype.type)] = block;
},
_titleize: function(str){
if (str === null)
return '';
str = String(str).toLowerCase();
return str.replace(/(?:^|\s|-)\S/g, function(c){ return c.toUpperCase(); });
},
_classify: function(str){
return this._titleize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, '');
},
}
|
var $ = require('jquery');
var SirTrevor = require('sir-trevor-js');
module.exports = {
loadLocale: function(localeName, locale) {
SirTrevor.Locales[localeName] = SirTrevor.Locales[localeName] || {};
$.extend(true, SirTrevor.Locales[localeName], locale);
},
loadMixin: function(mixin) {
SirTrevor.BlockMixins[this._classify(mixin.mixinName)] = mixin;
SirTrevor.Block.prototype.availableMixins.push(mixin.mixinName.toLowerCase());
},
loadBlock: function(block) {
SirTrevor.Blocks[this._classify(block.type)] = block;
},
_titleize: function(str){
if (str === null)
return '';
str = String(str).toLowerCase();
return str.replace(/(?:^|\s|-)\S/g, function(c){ return c.toUpperCase(); });
},
_classify: function(str){
return this._titleize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, '');
},
}
|
Change init function to what the plugin exports
Plugins should no longer export an object with an init function, but rather just the init function itself which gets run on plugin load
|
const
{app} = require('electron'),
fs = require('fs-extra'),
Path = require('path'),
klaw = require('klaw-sync');
var PluginManager = {
loadedPlugins: {},
LoadPlugins: function(mod, appEvents) {
var pluginFolders = fs.readdirSync( Path.resolve(app.getAppPath() + '/plugins') )
pluginFolders.forEach((pluginFolder) => {
var pluginPath = Path.resolve('plugins', pluginFolder);
if(fs.statSync(pluginPath).isDirectory()) {
loadPlugin(pluginPath, mod, appEvents);
}
});
}
}
function loadPlugin(dir, mod) {
const pluginManifestPath = Path.resolve(dir, 'package.json');
// Register the plugin
var pluginManifest = fs.readJsonSync(pluginManifestPath);
PluginManager.loadedPlugins[pluginManifest.name] = {
manifest: pluginManifest,
module: mod.require(dir)
};
// Execute the plugin's initial script
PluginManager.loadedPlugins[pluginManifest.name].module()
}
module.exports = PluginManager;
|
const
{app} = require('electron'),
fs = require('fs-extra'),
Path = require('path'),
klaw = require('klaw-sync');
var PluginManager = {
loadedPlugins: {},
LoadPlugins: function(mod, appEvents) {
var pluginFolders = fs.readdirSync( Path.resolve(app.getAppPath() + '/plugins') )
pluginFolders.forEach((pluginFolder) => {
var pluginPath = Path.resolve('plugins', pluginFolder);
if(fs.statSync(pluginPath).isDirectory()) {
loadPlugin(pluginPath, mod, appEvents);
}
});
}
}
function loadPlugin(dir, mod) {
const pluginManifestPath = Path.resolve(dir, 'package.json');
// Register the plugin
var pluginManifest = fs.readJsonSync(pluginManifestPath);
PluginManager.loadedPlugins[pluginManifest.name] = {
manifest: pluginManifest,
module: mod.require(dir)
};
// Execute the plugin's initial script
PluginManager.loadedPlugins[pluginManifest.name].module.init();
}
module.exports = PluginManager;
|
Stop button is not rendered.
|
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
|
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
|
Define save() and define bare validate()
OPEN - task 48: Create "Edit Item" functionality
http://github.com/DevOpsDistilled/OpERP/issues/issue/48
|
package devopsdistilled.operp.client.items.controllers.impl;
import javax.inject.Inject;
import devopsdistilled.operp.client.items.controllers.EditItemPaneController;
import devopsdistilled.operp.client.items.models.BrandModel;
import devopsdistilled.operp.client.items.models.EditItemPaneModel;
import devopsdistilled.operp.client.items.models.ItemModel;
import devopsdistilled.operp.client.items.models.ProductModel;
import devopsdistilled.operp.client.items.views.EditItemPane;
import devopsdistilled.operp.server.data.entity.items.Item;
public class EditItemPaneControllerImpl implements EditItemPaneController {
@Inject
private EditItemPane view;
@Inject
private EditItemPaneModel model;
@Inject
private ItemModel itemModel;
@Inject
private ProductModel productModel;
@Inject
private BrandModel brandModel;
@Override
public void init() {
}
@Override
public void init(Item item) {
view.init();
model.setItem(item);
model.registerObserver(view);
productModel.registerObserver(view);
brandModel.registerObserver(view);
}
@Override
public Item save(Item item) {
return itemModel.saveAndUpdateModel(item);
}
@Override
public void validate(Item item) {
// TODO Auto-generated method stub
}
}
|
package devopsdistilled.operp.client.items.controllers.impl;
import javax.inject.Inject;
import devopsdistilled.operp.client.items.controllers.EditItemPaneController;
import devopsdistilled.operp.client.items.models.BrandModel;
import devopsdistilled.operp.client.items.models.EditItemPaneModel;
import devopsdistilled.operp.client.items.models.ItemModel;
import devopsdistilled.operp.client.items.models.ProductModel;
import devopsdistilled.operp.client.items.views.EditItemPane;
import devopsdistilled.operp.server.data.entity.items.Item;
public class EditItemPaneControllerImpl implements EditItemPaneController {
@Inject
private EditItemPane view;
@Inject
private EditItemPaneModel model;
@Inject
private ItemModel itemModel;
@Inject
private ProductModel productModel;
@Inject
private BrandModel brandModel;
@Override
public void init() {
}
@Override
public void init(Item item) {
view.init();
model.setItem(item);
model.registerObserver(view);
productModel.registerObserver(view);
brandModel.registerObserver(view);
}
}
|
[do_jdbc] Fix omission in previous commit 490d652
* PostgresDriverDefinition should have been updated to
use overloaded constructor in AbstractDriverDefinition.
Signed-off-by: Alex Coles <60c6d277a8bd81de7fdde19201bf9c58a3df08f4@alexcolesportfolio.com>
|
package do_postgres;
import data_objects.drivers.AbstractDriverDefinition;
import java.util.Properties;
public class PostgresDriverDefinition extends AbstractDriverDefinition {
public final static String URI_SCHEME = "postgres";
public final static String JDBC_URI_SCHEME = "postgresql";
public final static String RUBY_MODULE_NAME = "Postgres";
public PostgresDriverDefinition() {
super(URI_SCHEME, JDBC_URI_SCHEME, RUBY_MODULE_NAME);
}
@Override
public boolean supportsJdbcGeneratedKeys()
{
return false;
}
@Override
public boolean supportsJdbcScrollableResultSets() {
return true;
}
@Override
public boolean supportsConnectionEncodings()
{
return true;
}
@Override
public void setEncodingProperty(Properties props, String encodingName) {
// this is redundant as of Postgres 8.0, according to the JDBC documentation:
// http://jdbc.postgresql.org/documentation/80/connect.html
props.put("charSet", encodingName);
}
}
|
package do_postgres;
import data_objects.drivers.AbstractDriverDefinition;
import java.util.Properties;
public class PostgresDriverDefinition extends AbstractDriverDefinition {
public final static String URI_SCHEME = "postgresql";
public final static String JDBC_URI_SCHEME = "postgresql";
public final static String RUBY_MODULE_NAME = "Postgres";
public PostgresDriverDefinition() {
super(URI_SCHEME, RUBY_MODULE_NAME);
}
@Override
protected void verifyScheme(String scheme) {
if (!"postgres".equals(scheme)) {
throw new RuntimeException(
"scheme mismatch, expected: postgres but got: " + scheme);
}
}
@Override
public boolean supportsJdbcGeneratedKeys()
{
return false;
}
@Override
public boolean supportsJdbcScrollableResultSets() {
return true;
}
@Override
public boolean supportsConnectionEncodings()
{
return true;
}
@Override
public void setEncodingProperty(Properties props, String encodingName) {
// this is redundant as of Postgres 8.0, according to the JDBC documentation:
// http://jdbc.postgresql.org/documentation/80/connect.html
props.put("charSet", encodingName);
}
}
|
git: Fix blocking if users push simultaneously
If many git clients push commits into same repository simultaneously,
many of them are blocked because of project table's
OptimisticLockException.
Solution:
* Refresh the project before update it.
* Use synchronized block.
|
/**
* Yobi, Project Hosting SW
*
* Copyright 2013 NAVER Corp.
* http://yobi.io
*
* @Author kjkmadness
*
* 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 playRepository.hooks;
import java.util.Collection;
import java.util.Date;
import models.Project;
import org.eclipse.jgit.transport.PostReceiveHook;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.eclipse.jgit.transport.ReceivePack;
/**
* project 가 마지막 업데이트된 시점 저장
*/
public class UpdateLastPushedDate implements PostReceiveHook {
private Project project;
public UpdateLastPushedDate(Project project) {
this.project = project;
}
@Override
public void onPostReceive(ReceivePack receivePack, Collection<ReceiveCommand> commands) {
synchronized(project) {
project.refresh();
project.lastPushedDate = new Date();
project.save();
}
}
}
|
/**
* Yobi, Project Hosting SW
*
* Copyright 2013 NAVER Corp.
* http://yobi.io
*
* @Author kjkmadness
*
* 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 playRepository.hooks;
import java.util.Collection;
import java.util.Date;
import models.Project;
import org.eclipse.jgit.transport.PostReceiveHook;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.eclipse.jgit.transport.ReceivePack;
/**
* project 가 마지막 업데이트된 시점 저장
*/
public class UpdateLastPushedDate implements PostReceiveHook {
private Project project;
public UpdateLastPushedDate(Project project) {
this.project = project;
}
@Override
public void onPostReceive(ReceivePack receivePack, Collection<ReceiveCommand> commands) {
project.lastPushedDate = new Date();
project.save();
}
}
|
Remove saved file in TestImageSaveBlock test case
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import cv
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipfblock.imagesave
class TestImageSaveBlock(unittest.TestCase):
def setUp(self):
self.block = ipf.ipfblock.imagesave.ImageSave()
self.block.properties["file_name"].value = "test_saved.png"
def test_save_image(self):
""" Test save image to file
"""
image = cv.LoadImage("test.png")
self.block.input_ports["input_image"].pass_value(image)
self.block.process()
saved_image = cv.LoadImage("test_saved.png")
self.assertEqual(saved_image.tostring(), image.tostring())
def tearDown(self):
os.remove("test_saved.png")
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import cv
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipfblock.imagesave
class TestImageSaveBlock(unittest.TestCase):
def setUp(self):
self.block = ipf.ipfblock.imagesave.ImageSave()
self.block.properties["file_name"].value = "test_saved.png"
def test_save_image(self):
""" Test save image to file
"""
image = cv.LoadImage("test.png")
self.block.input_ports["input_image"].pass_value(image)
self.block.process()
saved_image = cv.LoadImage("test_saved.png")
self.assertEqual(saved_image.tostring(), image.tostring())
if __name__ == '__main__':
unittest.main()
|
Convert existing knownIDs objects into arrays
|
exports.checkDeletedIDs = function(knownIDs, returnedIDs) {
if (knownIDs && returnedIDs) {
var newIDs = [],
repeatedIDs = {},
removedIDs = [];
// hack to handle pre-existing objects instead of arrays, should probably have a way to wipe out /Me directories
// after making changes that break existing data
//
if (!(Array.isArray(knownIDs))) {
var tempIDs = knownIDs;
knownIDs = [];
for (var i in tempIDs)
knownIDs.push(i);
}
returnedIDs.forEach(function(id) {
if (knownIDs.indexOf(id) !== -1)
repeatedIDs[id] = 1;
});
knownIDs.forEach(function(id) {
if(!repeatedIDs[id])
removedIDs.push(id);
});
return removedIDs;
} else if (knownIDs) {
return knownIDs;
} else {
return [];
}
}
|
exports.checkDeletedIDs = function(knownIDs, returnedIDs) {
if (knownIDs && returnedIDs) {
var newIDs = [],
repeatedIDs = {},
removedIDs = [];
returnedIDs.forEach(function(id) {
if (knownIDs.indexOf(id) !== -1)
repeatedIDs[id] = 1;
});
knownIDs.forEach(function(id) {
if(!repeatedIDs[id])
removedIDs.push(id);
});
return removedIDs;
} else if (knownIDs) {
return knownIDs;
} else {
return [];
}
}
|
Check that at least one area has been checked
|
from django.forms import (ModelForm, CheckboxSelectMultiple,
MultipleChoiceField)
from .models import AuthorityElection, AuthorityElectionPosition
class AuthorityAreaForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
# import ipdb; ipdb.set_trace().
self.fields['areas'] = MultipleChoiceField(
choices=[
(a.pk, a.name) for a in self.instance.authority.child_areas],
label="Wards",
widget=CheckboxSelectMultiple
)
class Meta:
model = AuthorityElection
fields = []
def clean(self, *args, **kwargs):
if 'areas' in self.cleaned_data:
for area in self.cleaned_data['areas']:
AuthorityElectionPosition.objects.get_or_create(
authority_election=self.instance,
user=self.user,
area_id=area
)
return super().clean(*args, **kwargs)
|
from django.forms import (ModelForm, CheckboxSelectMultiple,
MultipleChoiceField)
from .models import AuthorityElection, AuthorityElectionPosition
class AuthorityAreaForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
# import ipdb; ipdb.set_trace().
self.fields['areas'] = MultipleChoiceField(
choices=[
(a.pk, a.name) for a in self.instance.authority.child_areas],
label="Wards",
widget=CheckboxSelectMultiple
)
class Meta:
model = AuthorityElection
fields = []
def clean(self, *args, **kwargs):
for area in self.cleaned_data['areas']:
AuthorityElectionPosition.objects.get_or_create(
authority_election=self.instance,
user=self.user,
area_id=area
)
return super().clean(*args, **kwargs)
|
Make the read command target to only a single resource
|
package schema
// CommandType is an enum of the type that can be represented by a schema.
type CommandType int //go:generate stringer -type=CommandType :: manual
const (
CommandInvalid CommandType = iota
CommandList
CommandCreate
CommandRead
CommandUpdate
CommandDelete
CommandManipulateMulti
CommandManipulateSingle
CommandManipulateIDOnly
CommandCustom
)
func (c CommandType) IsRequiredIDType() bool {
switch c {
case CommandRead, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly:
return true
default:
return false
}
}
func (c CommandType) IsNeedSingleIDType() bool {
return c == CommandManipulateSingle || c == CommandRead
}
func (c CommandType) IsNeedIDOnlyType() bool {
return c == CommandManipulateIDOnly
}
func (c CommandType) IsNeedConfirmType() bool {
switch c {
case CommandCreate, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly, CommandCustom:
return true
default:
return false
}
}
|
package schema
// CommandType is an enum of the type that can be represented by a schema.
type CommandType int //go:generate stringer -type=CommandType :: manual
const (
CommandInvalid CommandType = iota
CommandList
CommandCreate
CommandRead
CommandUpdate
CommandDelete
CommandManipulateMulti
CommandManipulateSingle
CommandManipulateIDOnly
CommandCustom
)
func (c CommandType) IsRequiredIDType() bool {
switch c {
case CommandRead, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly:
return true
default:
return false
}
}
func (c CommandType) IsNeedSingleIDType() bool {
return c == CommandManipulateSingle
}
func (c CommandType) IsNeedIDOnlyType() bool {
return c == CommandManipulateIDOnly
}
func (c CommandType) IsNeedConfirmType() bool {
switch c {
case CommandCreate, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly, CommandCustom:
return true
default:
return false
}
}
|
Update look and view of direction triangle
|
import {Graphics, Point} from 'pixi.js';
import {toCanvasCoordinates} from './CoordinatesMapper';
import {LEFT, RIGHT, UP, DOWN} from './Direction';
/**
* Draws the direction an Entity wants to go.
*/
export class DirectionGraphics extends Graphics {
constructor(rotation, x, y) {
super();
const triangleScale = .5;
this.rotation = rotation;
const [cellWidth, cellHeight] = toCanvasCoordinates(1, 1);
this.scale = new Point(triangleScale * cellWidth, triangleScale * cellHeight);
this.alpha = .7;
this.x = (x + .5) * cellWidth;
this.y = (y + .5) * cellHeight;
// drawing the graphics
this.beginFill(0x6BF76B);
this.drawPolygon([0, -1/2, 1/2, 1/2, -1/2, 1/2]);
this.endFill();
}
}
/**
* Returns the DirectionGraphics belonging to the given Direction
*/
export function directionGraphics(direction) {
switch(direction) {
case UP: return new DirectionGraphics(0, 0, -1);
case RIGHT: return new DirectionGraphics(.5 * Math.PI, 1, 0);
case DOWN: return new DirectionGraphics(Math.PI, 0, 1);
case LEFT: return new DirectionGraphics(1.5 * Math.PI, -1, 0);
}
}
|
import {Graphics, Point} from 'pixi.js';
import {toCanvasCoordinates} from './CoordinatesMapper';
import {LEFT, RIGHT, UP, DOWN} from './Direction';
/**
* Draws the direction an Entity wants to go.
*/
export class DirectionGraphics extends Graphics {
constructor(rotation, x, y) {
super();
const triangleScale = .5;
this.rotation = rotation;
const [cellWidth, cellHeight] = toCanvasCoordinates(1, 1);
//this.scale = new Point(triangleScale * cellWidth, triangleScale * cellHeight);
this.alpha = .5;
this.x = (x + .5) * cellWidth;
this.y = (y + .5) * cellHeight;
// drawing the graphics
this.beginFill(0x6BF76B);
this.drawPolygon([0, -1/2, 1/6, 1/2, -1/6, 1/2]);
this.endFill();
this.width = cellWidth;
this.height = cellHeight;
}
}
/**
* Returns the DirectionGraphics belonging to the given Direction
*/
export function directionGraphics(direction) {
switch(direction) {
case UP: return new DirectionGraphics(0, 0, -1);
case RIGHT: return new DirectionGraphics(.5 * Math.PI, 1, 0);
case DOWN: return new DirectionGraphics(Math.PI, 0, 1);
case LEFT: return new DirectionGraphics(1.5 * Math.PI, -1, 0);
}
}
|
Move instance count closer to set operator symbol
|
var RoundNode = require("./RoundNode");
module.exports = (function () {
var radius = 40;
var o = function (graph) {
RoundNode.apply(this, arguments);
var that = this,
superHoverHighlightingFunction = this.setHoverHighlighting,
superPostDrawActions = this.postDrawActions;
this.radius(radius);
this.setHoverHighlighting = function (enable) {
superHoverHighlightingFunction(enable);
// Highlight connected links when hovering the set operator
d3.selectAll(".link ." + that.cssClassOfNode()).classed("hovered", enable);
};
this.postDrawActions = function () {
superPostDrawActions();
that.textBlock().clear();
that.textBlock().addInstanceCount(that.individuals().length);
that.textBlock().setTranslation(0, 10);
};
};
o.prototype = Object.create(RoundNode.prototype);
o.prototype.constructor = o;
return o;
}());
|
var RoundNode = require("./RoundNode");
module.exports = (function () {
var radius = 40;
var o = function (graph) {
RoundNode.apply(this, arguments);
var that = this,
superHoverHighlightingFunction = this.setHoverHighlighting,
superPostDrawActions = this.postDrawActions;
this.radius(radius);
this.setHoverHighlighting = function (enable) {
superHoverHighlightingFunction(enable);
// Highlight connected links when hovering the set operator
d3.selectAll(".link ." + that.cssClassOfNode()).classed("hovered", enable);
};
this.postDrawActions = function () {
superPostDrawActions();
that.textBlock().clear();
that.textBlock().addInstanceCount(that.individuals().length);
that.textBlock().setTranslation(0, that.radius() - 15);
};
};
o.prototype = Object.create(RoundNode.prototype);
o.prototype.constructor = o;
return o;
}());
|
Edit find command message example
|
package tars.logic.commands;
import java.util.Set;
/**
* Finds and lists all tasks in address book whose name contains any of the argument keywords.
* Keyword matching is case sensitive.
*/
public class FindCommand extends Command {
public static final String COMMAND_WORD = "find";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of "
+ "the specified keywords (case-insensitive) and displays them as a list with index numbers.\n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
+ "Example: " + COMMAND_WORD + " CS2103 projects";
private final Set<String> keywords;
public FindCommand(Set<String> keywords) {
this.keywords = keywords;
}
@Override
public CommandResult execute() {
model.updateFilteredTaskList(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
}
}
|
package tars.logic.commands;
import java.util.Set;
/**
* Finds and lists all tasks in address book whose name contains any of the argument keywords.
* Keyword matching is case sensitive.
*/
public class FindCommand extends Command {
public static final String COMMAND_WORD = "find";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of "
+ "the specified keywords (case-insensitive) and displays them as a list with index numbers.\n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
+ "Example: " + COMMAND_WORD + " CS2103 CS2016 projects";
private final Set<String> keywords;
public FindCommand(Set<String> keywords) {
this.keywords = keywords;
}
@Override
public CommandResult execute() {
model.updateFilteredTaskList(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
}
}
|
Fix wrong variable name in message list items
|
import moment from 'moment-timezone'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { AnimalLink } from './'
import { asInfiniteListItem } from '../containers'
class MessageListItem extends Component {
static propTypes = {
item: PropTypes.object.isRequired,
}
renderDateAndSender() {
const dateStr = moment(this.props.item.createdAt).format('DD.MM.YY HH:mm')
return (
<div className="list-item-content__title ellipsis">
{ dateStr }
<AnimalLink animal={this.props.item.animal} />
{ this.props.item.isWrittenByMe ? ' (me)' : null }
{ !this.props.item.isRead ? ' *' : null }
</div>
)
}
render() {
return (
<div className="list-item-content">
{ this.renderDateAndSender() }
<div className="list-item-content__description">
{ this.props.item.text }
</div>
</div>
)
}
}
export default asInfiniteListItem(MessageListItem)
|
import moment from 'moment-timezone'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { AnimalLink } from './'
import { asInfiniteListItem } from '../containers'
class MessageListItem extends Component {
static propTypes = {
item: PropTypes.object.isRequired,
}
renderDateAndSender() {
const dateStr = moment(lastSlot.to).format(
'DD.MM.YY HH:mm'
)
return (
<div className="list-item-content__title ellipsis">
{ dateStr }
<AnimalLink animal={this.props.item.animal} />
{ this.props.item.isWrittenByMe ? ' (me)' : null }
{ !this.props.item.isRead ? ' *' : null }
</div>
)
}
render() {
return (
<div className="list-item-content">
{ this.renderDateAndSender() }
<div className="list-item-content__description">
{ this.props.item.text }
</div>
</div>
)
}
}
export default asInfiniteListItem(MessageListItem)
|
Make load-css test more robust
|
define(function(require) {
var test = require('../../test')
var $ = require('../../third-party').jQuery
var count = 0
// normal case
require('./red.css')
test.assert($('#red').width() === 200, '#red width should be 200')
// async case
test.assert($('#blue').width() !== 200, '#blue width should not be 200. The actual value is ' + $('#blue').width())
require.async('./blue.css', function() {
setTimeout(function() {
test.assert($('#blue').width() === 200, '#blue width should be 200 now')
done()
}, 500) // 留够时间给 css 渲染
})
// not-existed case
// 注意:Opera 下不会触发回调
require.async('./not-existed.css', function() {
test.print('[PASS] 404 is ok')
done()
})
// don't load multi times
var linkCount = document.getElementsByTagName('link').length
require.async('./red.css', function() {
var currentLinkCount = document.getElementsByTagName('link').length
test.assert(currentLinkCount === linkCount, 'do NOT load duplicate link')
done()
})
var MAX = 3
if (window.opera) MAX--
function done() {
if (++count === MAX) {
test.done()
}
}
})
|
define(function(require) {
var test = require('../../test')
var $ = require('../../third-party').jQuery
var count = 0
// normal case
require('./red.css')
test.assert($('#red').width() === 200, '#red width should be 200')
// async case
test.assert($('#blue').width() !== 200, '#blue width should not be 200. The actual value is ' + $('#blue').width())
require.async('./blue.css', function() {
setTimeout(function() {
test.assert($('#blue').width() === 200, '#blue width should be 200 now')
done()
}, 100)
})
// not-existed case
// 注意:Opera 下不会触发回调
require.async('./not-existed.css', function() {
test.print('[PASS] 404 is ok')
done()
})
// don't load multi times
var linkCount = document.getElementsByTagName('link').length
require.async('./red.css', function() {
var currentLinkCount = document.getElementsByTagName('link').length
test.assert(currentLinkCount === linkCount, 'do NOT load duplicate link')
done()
})
var MAX = 3
if (window.opera) MAX--
function done() {
if (++count === MAX) {
test.done()
}
}
})
|
Add store tags to settings
|
import { AsyncStorage } from 'react-native';
export { MobileAppSettings } from './MobileAppSettings';
export const SETTINGS_KEYS = {
APP_VERSION: 'AppVersion',
CURRENT_LANGUAGE: 'CurrentLanguage',
MOST_RECENT_USERNAME: 'MostRecentUsername',
SUPPLYING_STORE_ID: 'SupplyingStoreId',
SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
SYNC_IS_INITIALISED: 'SyncIsInitialised',
SYNC_PRIOR_FAILED: 'SyncPriorFailed',
SYNC_URL: 'SyncURL',
SYNC_SITE_ID: 'SyncSiteId',
SYNC_SERVER_ID: 'SyncServerId',
SYNC_SITE_NAME: 'SyncSiteName',
SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
THIS_STORE_ID: 'ThisStoreId',
THIS_STORE_NAME_ID: 'ThisStoreNameId',
HARDWARE_UUID: 'Hardware_UUID',
THIS_STORE_TAGS: 'ThisStoreTags',
};
export const getAppVersion = async () => {
const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
return appVersion;
};
|
import { AsyncStorage } from 'react-native';
export { MobileAppSettings } from './MobileAppSettings';
export const SETTINGS_KEYS = {
APP_VERSION: 'AppVersion',
CURRENT_LANGUAGE: 'CurrentLanguage',
MOST_RECENT_USERNAME: 'MostRecentUsername',
SUPPLYING_STORE_ID: 'SupplyingStoreId',
SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
SYNC_IS_INITIALISED: 'SyncIsInitialised',
SYNC_PRIOR_FAILED: 'SyncPriorFailed',
SYNC_URL: 'SyncURL',
SYNC_SITE_ID: 'SyncSiteId',
SYNC_SERVER_ID: 'SyncServerId',
SYNC_SITE_NAME: 'SyncSiteName',
SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
THIS_STORE_ID: 'ThisStoreId',
THIS_STORE_NAME_ID: 'ThisStoreNameId',
HARDWARE_UUID: 'Hardware_UUID',
};
export const getAppVersion = async () => {
const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
return appVersion;
};
|
Improve transition by using batch.draw directly without creating Sprites
|
package com.ychstudio.screens.transitions;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
public class SlideLeftTransition implements ScreenTransition {
private float duration;
public SlideLeftTransition(float duration) {
this.duration = duration;
}
@Override
public float getDuration() {
return duration;
}
@Override
public void rander(SpriteBatch batch, Texture currentScreenTexture, Texture nextScreenTexture, float alpha) {
float w = Gdx.graphics.getWidth();
alpha = Interpolation.fade.apply(alpha);
batch.begin();
batch.draw(currentScreenTexture, w * alpha, 0, w, currentScreenTexture.getHeight(), 0, 0, (int)w, currentScreenTexture.getHeight(), false, true);
batch.draw(nextScreenTexture, -w + w * alpha, 0, w, nextScreenTexture.getHeight(), 0, 0, (int)w, nextScreenTexture.getHeight(), false, true);
batch.end();
}
}
|
package com.ychstudio.screens.transitions;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
public class SlideLeftTransition implements ScreenTransition {
private float duration;
public SlideLeftTransition(float duration) {
this.duration = duration;
}
@Override
public float getDuration() {
return duration;
}
@Override
public void rander(SpriteBatch batch, Texture currentScreenTexture, Texture nextScreenTexture, float alpha) {
float w = Gdx.graphics.getWidth();
alpha = Interpolation.fade.apply(alpha);
Sprite currentSprite = new Sprite(currentScreenTexture);
currentSprite.flip(false, true);
currentSprite.setPosition(w * alpha, 0);
Sprite nextSprite = new Sprite(nextScreenTexture);
nextSprite.flip(false, true);
nextSprite.setPosition(-w + w * alpha, 0);
batch.begin();
currentSprite.draw(batch);
nextSprite.draw(batch);
batch.end();
}
}
|
Fix null error in Beam SQL
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.extensions.sql.impl;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Exception thrown when BeamSQL cannot convert sql to BeamRelNode. */
public class SqlConversionException extends RuntimeException {
public SqlConversionException(@Nullable Throwable cause) {
super(cause);
}
public SqlConversionException(String message) {
super(message);
}
public SqlConversionException(String message, Throwable cause) {
super(message, cause);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.extensions.sql.impl;
import afu.org.checkerframework.checker.nullness.qual.Nullable;
/** Exception thrown when BeamSQL cannot convert sql to BeamRelNode. */
public class SqlConversionException extends RuntimeException {
public SqlConversionException(@Nullable Throwable cause) {
super(cause);
}
public SqlConversionException(String message) {
super(message);
}
public SqlConversionException(String message, Throwable cause) {
super(message, cause);
}
}
|
WWW: Add viewport meta tag for mobile sites
|
import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render () {
return (
<html>
<head>
<title>
{this.props.title}
</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link type='text/css' rel='stylesheet' href='/static/pure.min.css' />
<link type='text/css' rel='stylesheet' href='/static/app.bundle.css' />
</head>
<body>
<div id='root' dangerouslySetInnerHTML={{ __html: this.props.children }} />
<script src='/static/init.bundle.js' />
<script async src='/static/react.bundle.js' />
<script async src='/static/app.bundle.js' />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
|
import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render () {
return (
<html>
<head>
<title>
{this.props.title}
</title>
<link type='text/css' rel='stylesheet' href='/static/pure.min.css' />
<link type='text/css' rel='stylesheet' href='/static/app.bundle.css' />
</head>
<body>
<div id='root' dangerouslySetInnerHTML={{ __html: this.props.children }} />
<script src='/static/init.bundle.js' onLoad='console.log("hovno")' />
<script async src='/static/react.bundle.js' />
<script async src='/static/app.bundle.js' />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
|
Remove authenticate call to fix issues with pymongo 3.7
|
from .exceptions import ConnectionError
from pymongo import MongoClient
from pymongo.uri_parser import parse_uri
_connections = {}
try:
import gevent
except ImportError:
gevent = None
def _get_connection(uri):
global _connections
parsed_uri = parse_uri(uri)
hosts = parsed_uri['nodelist']
hosts = ['%s:%d' % host for host in hosts]
key = ','.join(hosts)
connection = _connections.get(key)
if connection is None:
try:
connection = _connections[key] = MongoClient(uri)
except Exception as e:
raise ConnectionError(e.message)
return connection
def connect(uri):
parsed_uri = parse_uri(uri)
username = parsed_uri['username']
password = parsed_uri['password']
database = parsed_uri['database']
db = _get_connection(uri)[database]
return db
|
from .exceptions import ConnectionError
from pymongo import MongoClient
from pymongo.uri_parser import parse_uri
_connections = {}
try:
import gevent
except ImportError:
gevent = None
def _get_connection(uri):
global _connections
parsed_uri = parse_uri(uri)
hosts = parsed_uri['nodelist']
hosts = ['%s:%d' % host for host in hosts]
key = ','.join(hosts)
connection = _connections.get(key)
if connection is None:
try:
connection = _connections[key] = MongoClient(uri)
except Exception as e:
raise ConnectionError(e.message)
return connection
def connect(uri):
parsed_uri = parse_uri(uri)
username = parsed_uri['username']
password = parsed_uri['password']
database = parsed_uri['database']
db = _get_connection(uri)[database]
if username and password:
db.authenticate(username, password)
return db
|
Remove a reference to an empty file
|
<?php
/**
* Plugin Name: Airstory
* Plugin URI: http://www.airstory.co/integrations/
* Description: Publish content from Airstory to WordPress.
* Version: 0.1.0
* Author: Liquid Web
* Author URI: https://www.liquidweb.com
* Text Domain: airstory
*
* @package Airstory
*/
namespace Airstory;
define( 'AIRSTORY_INC', __DIR__ . '/includes' );
require_once AIRSTORY_INC . '/class-api.php';
require_once AIRSTORY_INC . '/core.php';
require_once AIRSTORY_INC . '/formatting.php';
require_once AIRSTORY_INC . '/webhook.php';
/**
* Load asynchronous tasks.
*
* To prevent locking the main thread and possibly hitting timeouts, the plugin leverages the
* TechCrunch WP Asynchronous Tasks library. Actions that require some potentially expensive
* processes (for instance, side-loading images) can instead be handled asynchronously, by using
* the wp_async_{hook} pattern.
*
* @link https://github.com/techcrunch/wp-async-task
*/
require_once AIRSTORY_INC . '/lib/wp-async-task/wp-async-task.php';
require_once AIRSTORY_INC . '/async-tasks/import-post.php';
// Each task must be instantiated once.
new AsyncTasks\ImportPost();
|
<?php
/**
* Plugin Name: Airstory
* Plugin URI: http://www.airstory.co/integrations/
* Description: Publish content from Airstory to WordPress.
* Version: 0.1.0
* Author: Liquid Web
* Author URI: https://www.liquidweb.com
* Text Domain: airstory
*
* @package Airstory
*/
namespace Airstory;
define( 'AIRSTORY_INC', __DIR__ . '/includes' );
require_once AIRSTORY_INC . '/async-tasks.php';
require_once AIRSTORY_INC . '/class-api.php';
require_once AIRSTORY_INC . '/core.php';
require_once AIRSTORY_INC . '/formatting.php';
require_once AIRSTORY_INC . '/webhook.php';
/**
* Load asynchronous tasks.
*
* To prevent locking the main thread and possibly hitting timeouts, the plugin leverages the
* TechCrunch WP Asynchronous Tasks library. Actions that require some potentially expensive
* processes (for instance, side-loading images) can instead be handled asynchronously, by using
* the wp_async_{hook} pattern.
*
* @link https://github.com/techcrunch/wp-async-task
*/
require_once AIRSTORY_INC . '/lib/wp-async-task/wp-async-task.php';
require_once AIRSTORY_INC . '/async-tasks/import-post.php';
// Each task must be instantiated once.
new AsyncTasks\ImportPost();
|
Add timezone parameter to fromString
|
<?php
namespace JWX\JWT\Claim\Feature;
/**
* Trait for claims having NumericDate value.
*/
trait NumericDateClaim
{
/**
* Initialize instance from date/time string
*
* @param string $time <code>strtotime</code> compatible time string
* @param string $tz Default timezone
* @return static
*/
public static function fromString($time, $tz = "UTC") {
$dt = new \DateTimeImmutable($time, new \DateTimeZone($tz));
return new static($dt->getTimestamp());
}
/**
* Get date as a unix timestamp
*
* @return int
*/
public function timestamp() {
return (int) $this->_value;
}
/**
* Get date as a datetime object
*
* @return \DateTimeImmutable
*/
public function dateTime() {
return \DateTimeImmutable::createFromFormat("!U", $this->_value,
new \DateTimeZone("UTC"));
}
}
|
<?php
namespace JWX\JWT\Claim\Feature;
/**
* Trait for claims having NumericDate value.
*/
trait NumericDateClaim
{
/**
* Initialize instance from date/time string
*
* @param string $time
* @return static
*/
public static function fromString($time) {
$dt = new \DateTimeImmutable($time, new \DateTimeZone("UTC"));
return new static($dt->getTimestamp());
}
/**
* Get date as a unix timestamp
*
* @return int
*/
public function timestamp() {
return (int)$this->_value;
}
/**
* Get date as a datetime object
*
* @return \DateTimeImmutable
*/
public function dateTime() {
return \DateTimeImmutable::createFromFormat("!U", $this->_value,
new \DateTimeZone("UTC"));
}
}
|
Add lists of provided services
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Html;
class HtmlServiceProvider extends \Illuminate\Html\HtmlServiceProvider {
/**
* Register the HTML builder instance.
*
* @return void
*/
protected function registerHtmlBuilder()
{
$this->app['html'] = $this->app->share(function($app)
{
return new HtmlBuilder($app['url']);
});
$this->app['orchestra.form'] = $this->app->share(function($app)
{
return new Form\Environment;
});
$this->app['orchestra.table'] = $this->app->share(function($app)
{
return new Table\Environment;
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('orchestra/html', 'orchestra/html');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('html', 'form', 'orchestra.form', 'orchestra.table');
}
}
|
<?php namespace Orchestra\Html;
class HtmlServiceProvider extends \Illuminate\Html\HtmlServiceProvider {
/**
* Register the HTML builder instance.
*
* @return void
*/
protected function registerHtmlBuilder()
{
$this->app['html'] = $this->app->share(function($app)
{
return new HtmlBuilder($app['url']);
});
$this->app['orchestra.form'] = $this->app->share(function($app)
{
return new Form\Environment;
});
$this->app['orchestra.table'] = $this->app->share(function($app)
{
return new Table\Environment;
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('orchestra/html', 'orchestra/html');
}
}
|
Save a few SQL queries.
|
# -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
def find_ticket_for_user(user, party):
"""Return the ticket used by the user for the party, or `None` if not
found.
"""
if user.is_anonymous:
return None
return Ticket.query \
.filter(Ticket.used_by == user) \
.options(
db.joinedload_all('occupied_seat.area'),
) \
.for_party(party) \
.first()
def get_attended_parties(user):
"""Return the parties the user has attended."""
return Party.query \
.join(Category).join(Ticket).filter(Ticket.used_by == user) \
.all()
|
# -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
"""
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
def find_ticket_for_user(user, party):
"""Return the ticket used by the user for the party, or `None` if not
found.
"""
if user.is_anonymous:
return None
return Ticket.query \
.filter(Ticket.used_by == user) \
.for_party(party) \
.first()
def get_attended_parties(user):
"""Return the parties the user has attended."""
return Party.query \
.join(Category).join(Ticket).filter(Ticket.used_by == user) \
.all()
|
Revise tower of hanoi alg from Yuanlin
|
"""The tower of Hanoi."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def tower_of_hanoi(height, from_pole, to_pole, with_pole, counter):
if height == 1:
counter[0] += 1
print('{0} -> {1}'.format(from_pole, to_pole))
else:
tower_of_hanoi(height - 1, from_pole, with_pole, to_pole, counter)
tower_of_hanoi(1, from_pole, to_pole, with_pole, counter)
tower_of_hanoi(height - 1, with_pole, to_pole, from_pole, counter)
def main():
from_pole = 'A'
to_pole = 'B'
with_pole = 'C'
height = 1
counter = [0]
print('height: {}'.format(height))
tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
print('counter: {}'.format(counter[0]))
height = 2
counter = [0]
print('height: {}'.format(height))
tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
print('counter: {}'.format(counter[0]))
height = 5
counter = [0]
print('height: {}'.format(height))
tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
print('counter: {}'.format(counter[0]))
if __name__ == '__main__':
main()
|
"""The tower of Hanoi."""
from __future__ import print_function
def move_towers(height, from_pole, to_pole, with_pole):
if height == 1:
print('Moving disk from {0} to {1}'.format(from_pole, to_pole))
else:
move_towers(height - 1, from_pole, with_pole, to_pole)
move_towers(1, from_pole, to_pole, with_pole)
move_towers(height - 1, with_pole, to_pole, from_pole)
def main():
from_pole = 'f'
to_pole = 't'
with_pole = 'w'
height = 1
print('height: {}'.format(height))
move_towers(height, from_pole, to_pole, with_pole)
height = 2
print('height: {}'.format(height))
move_towers(height, from_pole, to_pole, with_pole)
height = 5
print('height: {}'.format(height))
move_towers(height, from_pole, to_pole, with_pole)
if __name__ == '__main__':
main()
|
Make requirements optional. Add help text and fix display in admin form
|
from django.contrib.auth.models import User
from django.db import models
class ConferenceOptionGroup(models.Model):
"""Used to manage relationships"""
name = models.CharField(max_length=255)
def __unicode__(self):
return u'%s' % self.name
class ConferenceOption(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=12, decimal_places=2)
groups = models.ManyToManyField(
ConferenceOptionGroup, related_name='members',
help_text='Groups this option belongs to.')
requirements = models.ManyToManyField(
ConferenceOptionGroup, related_name='enables',
help_text='Option groups that this relies on',
blank=True)
def __unicode__(self):
return u'%s (%.2f)' % (self.name, self.price)
class RegisteredAttendee(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
items = models.ManyToManyField(
ConferenceOption, related_name='attendees')
registered_by = models.ForeignKey(
User, related_name='registerations')
|
from django.contrib.auth.models import User
from django.db import models
class ConferenceOptionGroup(models.Model):
"""Used to manage relationships"""
name = models.CharField(max_length=255)
class ConferenceOption(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=12, decimal_places=2)
groups = models.ManyToManyField(
ConferenceOptionGroup, related_name='members')
requirements = models.ManyToManyField(
ConferenceOptionGroup, related_name='enables')
class RegisteredAttendee(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
items = models.ManyToManyField(
ConferenceOption, related_name='attendees')
registered_by = models.ForeignKey(
User, related_name='registerations')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.