text
stringlengths 3
1.05M
|
|---|
# __init__ for osgeo package.
# making the osgeo package version the same as the gdal version:
from sys import platform, version_info
if version_info >= (3, 8, 0) and platform == 'win32':
import os
if 'USE_PATH_FOR_GDAL_PYTHON' in os.environ and 'PATH' in os.environ:
for p in os.environ['PATH'].split(';'):
if p:
try:
os.add_dll_directory(p)
except FileNotFoundError:
continue
def swig_import_helper():
import importlib
from os.path import dirname, basename
mname = basename(dirname(__file__)) + '._gdal'
try:
return importlib.import_module(mname)
except ImportError:
if version_info >= (3, 8, 0) and platform == 'win32':
import os
if not 'USE_PATH_FOR_GDAL_PYTHON' in os.environ:
msg = 'On Windows, with Python >= 3.8, DLLs are no longer imported from the PATH.\n'
msg += 'If gdalXXX.dll is in the PATH, then set the USE_PATH_FOR_GDAL_PYTHON=YES environment variable\n'
msg += 'to feed the PATH into os.add_dll_directory().'
import sys
import traceback
traceback_string = ''.join(traceback.format_exception(*sys.exc_info()))
raise ImportError(traceback_string + '\n' + msg)
return importlib.import_module('_gdal')
_gdal = swig_import_helper()
del swig_import_helper
__version__ = _gdal.__version__ = _gdal.VersionInfo("RELEASE_NAME")
gdal_version = tuple(int(s) for s in str(__version__).split('.') if s.isdigit())[:3]
python_version = tuple(version_info)[:3]
# Setting this flag to True will cause importing osgeo to fail on an unsupported Python version.
# Otherwise a deprecation warning will be issued instead.
# Importing osgeo fom an unsupported Python version might still partially work
# because the core of GDAL Python bindings might still support an older Python version.
# Hence the default option to just issue a warning.
# To get complete functionality upgrading to the minimum supported version is needed.
fail_on_unsupported_version = False
# The following is a Sequence of tuples in the form of (gdal_version, python_version).
# Each line represents the minimum supported Python version of a given GDAL version.
# Introducing a new line for the next GDAL version will trigger a deprecation warning
# when importing osgeo from a Python version which will not be
# supported in the next version of GDAL.
gdal_version_and_min_supported_python_version = (
((0, 0), (0, 0)),
((1, 0), (2, 0)),
((2, 0), (2, 7)),
((3, 3), (3, 6)),
# ((3, 4), (3, 7)),
# ((3, 5), (3, 8)),
)
def ver_str(ver):
return '.'.join(str(v) for v in ver) if ver is not None else None
minimum_supported_python_version_for_this_gdal_version = None
this_python_version_will_be_deprecated_in_gdal_version = None
last_gdal_version_to_supported_your_python_version = None
next_version_of_gdal_will_use_python_version = None
for gdal_ver, py_ver in gdal_version_and_min_supported_python_version:
if gdal_version >= gdal_ver:
minimum_supported_python_version_for_this_gdal_version = py_ver
if python_version >= py_ver:
last_gdal_version_to_supported_your_python_version = gdal_ver
if not this_python_version_will_be_deprecated_in_gdal_version:
if python_version < py_ver:
this_python_version_will_be_deprecated_in_gdal_version = gdal_ver
next_version_of_gdal_will_use_python_version = py_ver
if python_version < minimum_supported_python_version_for_this_gdal_version:
msg = 'Your Python version is {}, which is no longer supported by GDAL {}. ' \
'Please upgrade your Python version to Python >= {}, ' \
'or use GDAL <= {}, which supports your Python version.'.\
format(ver_str(python_version), ver_str(gdal_version),
ver_str(minimum_supported_python_version_for_this_gdal_version),
ver_str(last_gdal_version_to_supported_your_python_version))
if fail_on_unsupported_version:
raise Exception(msg)
else:
from warnings import warn, simplefilter
simplefilter('always', DeprecationWarning)
warn(msg, DeprecationWarning)
elif this_python_version_will_be_deprecated_in_gdal_version:
msg = 'You are using Python {} with GDAL {}. ' \
'This Python version will be deprecated in GDAL {}. ' \
'Please consider upgrading your Python version to Python >= {}, ' \
'Which will be the minimum supported Python version of GDAL {}.'.\
format(ver_str(python_version), ver_str(gdal_version),
ver_str(this_python_version_will_be_deprecated_in_gdal_version),
ver_str(next_version_of_gdal_will_use_python_version),
ver_str(this_python_version_will_be_deprecated_in_gdal_version))
from warnings import warn, simplefilter
simplefilter('always', DeprecationWarning)
warn(msg, DeprecationWarning)
|
module.exports = {
"env": {
"browser": true,
"es6": true
},
"extends": "eslint:recommended",
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
|
var BlockMediaController = function(params) { this.init(params); };
BlockMediaController.prototype = {
post_id: false,
page_id: false,
block_parent_id: false,
block_id: false,
media_id: false,
top_cat_id: false,
cat: false,
cat_id: false,
categories: false,
s3_upload_url: false,
aws_access_key_id: false,
policy: false,
signature: false,
selected_media: false,
uploader: false,
refresh_unprocessed_images: false,
upload_extensions: "jpg,jpeg,png,gif,tif,tiff,pdf,doc,docx,odt,odp,ods,ppt,pptx,xls,xlsx,zip,tgz,csv,txt",
file_view: 'thumbnail',
init: function(params) {
var that = this;
for (var i in params)
this[i] = params[i];
$("#uploader")
.empty()
//.append($('<p/>')
// .append($('<a/>').attr('href', '#').html('Upload').click(function(e) { e.preventDefault(); that.toggle_uploader(); }))
// .append(' | ')
// .append($('<a/>').attr('href', '#').html('Toggle Thumbnail/List View').click(function(e) { e.preventDefault(); that.toggle_view(); }))
//)
.append($('<div/>').attr('id', 'the_uploader'));
that.refresh();
},
refresh: function()
{
var that = this;
that.refresh_categories(function() {
that.refresh_media();
});
that.print_controls();
},
toggle_uploader: function()
{
var that = this;
if (that.uploader)
{
$("#the_uploader").slideUp(400, function() {
$("#the_uploader").plupload('destroy');
that.uploader = false;
});
}
else
{
$("#the_uploader").hide();
that.uploader = $("#the_uploader").plupload({
runtimes: 'html5,flash,silverlight',
url: that.s3_upload_url,
multipart: true,
multipart_params: {
key: that.cat_id + '_${filename}', // use filename as a key
Filename: that.cat_id + '_${filename}', // adding this to keep consistency across the runtimes
acl: 'public-read',
//'Content-Type': 'image/jpeg',
AWSAccessKeyId: that.aws_access_key_id,
policy: that.policy,
signature: that.signature
},
file_data_name: 'file', // optional, but better be specified directly
filters: {
max_file_size: '100mb', // Maximum file size
mime_types: [{ title: "Upload files", extensions: that.upload_extensions }] // Specify what files to browse for
},
flash_swf_url: '../../js/Moxie.swf', // Flash settings
silverlight_xap_url: '../../js/Moxie.xap', // Silverlight settings
init: {
BeforeUpload: function(up, file) {
$.ajax({
url: '/admin/media/pre-upload',
type: 'post',
data: {
media_category_id: that.cat_id,
name: file.name
},
success: function(resp) {},
async: false
});
controller.refresh();
},
FileUploaded: function(ip, file)
{
that.refresh();
},
UploadComplete: function(up, files) {
that.refresh();
if (that.uploader)
{
$("#the_uploader").slideUp(400, function() {
$("#the_uploader").plupload('destroy');
that.uploader = false;
});
}
}
}
});
$("#the_uploader").slideDown();
}
},
refresh_categories: function(after)
{
var that = this;
$.ajax({
url: '/admin/media-categories/flat-tree',
type: 'get',
async: false,
success: function(resp) {
that.categories = resp;
if (!that.cat_id)
that.cat_id = that.categories[0].id;
that.print_categories();
if (after) after();
}
});
},
refresh_media: function()
{
var that = this;
$.ajax({
url: '/admin/media/json',
type: 'get',
async: false,
data: { media_category_id: that.cat_id },
success: function(resp) {
that.cat = resp;
that.cat_id = that.cat.id;
that.selected_media = [];
that.print_media();
}
});
},
print_categories: function()
{
var that = this;
var ul = $('<ul/>');
if (that.categories.length > 0)
{
$.each(that.categories, function(i, cat) {
var li = $('<li/>')
.addClass('category')
.attr('id', 'cat' + cat.id)
.data('media_category_id', cat.id)
.append($('<a/>').attr('href', '#').html(cat.name + ' (' + cat.media_count + ')').click(function(e) { e.preventDefault(); that.select_category($(this).parent().data('media_category_id')); }));
if (cat.id == that.cat_id)
li.addClass('selected');
ul.append(li);
});
}
else
ul = $('<p/>').html("There are no media categories.");
$('#categories').empty().append(ul);
},
print_controls: function()
{
var that = this;
$('#controls').empty()
//.append($('<p/>').append($('<a/>').attr('href', '#').html('New Category').click(function(e) { e.preventDefault(); that.add_category(); })))
//.append($('<div/>').attr('id', 'new_cat_message'))
//.append($('<p/>').append($('<a/>').attr('href', '#').html('Upload').click(function(e) { e.preventDefault(); that.toggle_uploader(); })))
//.append($('<p/>').append($('<a/>').attr('href', '#').html('Toggle Thumbnail/List View').click(function(e) { e.preventDefault(); that.toggle_file_view(); })));
.append($('<p/>')
.append($('<a/>').attr('href', '#').html('New Category').click(function(e) { e.preventDefault(); that.add_category(); })).append(' | ')
.append($('<a/>').attr('href', '#').html('Upload to this Category' ).click(function(e) { e.preventDefault(); that.toggle_uploader(); })).append(' | ')
.append($('<a/>').attr('href', '#').html(that.file_view == 'thumbnail' ? 'List View' : 'Thumbnail View').click(function(e) { e.preventDefault(); that.toggle_file_view(); }))
)
.append($('<div/>').attr('id', 'new_cat_message'));
},
print_media: function()
{
var that = this;
var ul = $('<ul/>').addClass(that.file_view + '_view');
var processing = false;
var d = new Date();
d = d.getTime();
if (that.cat.media.length > 0)
{
$.each(that.cat.media, function(i, m) {
if (m.media_type == 'image' && m.processed == false)
processing = true
var li = $('<li/>')
.attr('id', 'media' + m.id)
.addClass('media')
.data('media_id', m.id)
.click(function(e) { that.select_media($(this).data('media_id')); })
.append($('<span/>').addClass('name').html(m.original_name));
if (m.image_urls)
li.append($('<img/>').attr('src', m.image_urls.tiny_url + '?' + d));
//if (that.selected_media.indexOf(m.id) > -1)
// li.addClass('selected ui-selected');
if (m.id == that.media_id)
li.addClass('selected ui-selected');
ul.append(li);
});
}
else
ul = $('<p/>').html("This category is empty.");
$('#media').empty().append(ul);
if (that.refresh_unprocessed_images == true && processing)
setTimeout(function() { that.refresh(); }, 2000);
if (modal)
modal.autosize();
$.each(that.cat.media, function(i, m) {
$('li.media').draggable({
multiple: true,
revert: 'invalid',
start: function() { $(this).data("origPosition", $(this).position()); }
});
});
},
//============================================================================
select_media: function(media_id)
{
var that = this;
$.ajax({
url: '/admin/' + (that.page_id ? 'pages/' + that.page_id : 'posts/' + that.post_id) + '/blocks/' + that.block_id,
type: 'put',
data: { media_id: media_id },
success: function(resp) {
window.location = '/admin/pages/' + that.page_id + '/blocks/' + that.block_parent_id + '/edit';
}
});
},
//============================================================================
select_category: function(cat_id)
{
var that = this;
that.cat_id = cat_id;
that.print_categories();
that.refresh_media();
},
add_category: function(name)
{
var that = this;
if (!name)
{
if (!$('#new_cat_message').is(':empty'))
{
$('#new_cat_message').empty();
return;
}
var div = $('<p/>').addClass('note warning')
.append('Name: ')
.append($('<input/>').attr('type', 'text').attr('id', 'new_cat_name')).append(" ")
.append($('<input/>').attr('type', 'button').val('Add').click(function() { that.add_category($('#new_cat_name').val()); })).append(" ")
.append($('<input/>').attr('type', 'button').val('Cancel').click(function() { $('#new_cat_message').empty(); }));
$('#new_cat_message').empty().append(div);
return;
}
$('#new_cat_message').empty().html("<p class='loading'>Adding category...</p>");
$.ajax({
url: '/admin/media-categories',
type: 'post',
data: {
parent_id: that.cat.id,
name: name
},
success: function(resp) {
if (resp.error) $('#new_cat_message').empty().html("<p class='note error'>" + resp.error + "</p>");
if (resp.refresh) { that.cat_id = resp.new_id; that.refresh(); }
}
});
},
toggle_file_view: function()
{
var that = this;
that.file_view = (that.file_view == 'thumbnail' ? 'list' : 'thumbnail');
that.print_controls();
that.print_media();
},
};
|
import { loadable } from 'utils/router'
export default {
path: ':projectId',<% if (!includeRedux) { %>
authRequired: true,<% } %>
component: loadable(() =>
import(/* webpackChunkName: 'Project' */ './components/ProjectPage')
)
}
|
/**
* Copyright (c) 2006-2012, JGraph Ltd
*/
/**
* Constructs the actions object for the given UI.
*/
function Actions(editorUi)
{
this.editorUi = editorUi;
this.actions = new Object();
this.init();
};
/**
* Adds the default actions.
*/
Actions.prototype.init = function()
{
var ui = this.editorUi;
var editor = ui.editor;
var graph = editor.graph;
var isGraphEnabled = function()
{
return Action.prototype.isEnabled.apply(this, arguments) && graph.isEnabled();
};
// File actions
/*
this.addAction('new...', function() { graph.openLink(ui.getUrl()); });
this.addAction('open...', function()
{
window.openNew = true;
window.openKey = 'open';
ui.openFile();
});
this.addAction('import...', function()
{
window.openNew = false;
window.openKey = 'import';
// Closes dialog after open
window.openFile = new OpenFile(mxUtils.bind(this, function()
{
ui.hideDialog();
}));
window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
{
try
{
var doc = mxUtils.parseXml(xml);
editor.graph.setSelectionCells(editor.graph.importGraphModel(doc.documentElement));
}
catch (e)
{
mxUtils.alert(mxResources.get('invalidOrMissingFile') + ': ' + e.message);
}
}));
// Removes openFile if dialog is closed
ui.showDialog(new OpenDialog(this).container, 320, 220, true, true, function()
{
window.openFile = null;
});
}).isEnabled = isGraphEnabled;
this.addAction('save', function() { ui.saveFile(false); }, null, null, Editor.ctrlKey + '+S').isEnabled = isGraphEnabled;
this.addAction('saveAs...', function() { ui.saveFile(true); }, null, null, Editor.ctrlKey + '+Shift+S').isEnabled = isGraphEnabled;
this.addAction('export...', function() { ui.showDialog(new ExportDialog(ui).container, 300, 296, true, true); });
*/
this.addAction('editDiagram...', function()
{
var dlg = new EditDiagramDialog(ui);
ui.showDialog(dlg.container, 620, 420, true, false);
dlg.init();
});
this.addAction('pageSetup...', function() { ui.showDialog(new PageSetupDialog(ui).container, 320, 220, true, true); }).isEnabled = isGraphEnabled;
this.addAction('print...', function() { ui.showDialog(new PrintDialog(ui).container, 300, 180, true, true); }, null, 'sprite-print', Editor.ctrlKey + '+P');
this.addAction('preview', function() { mxUtils.show(graph, null, 10, 10); });
// Edit actions
this.addAction('undo', function() { ui.undo(); }, null, 'sprite-undo', Editor.ctrlKey + '+Z');
this.addAction('redo', function() { ui.redo(); }, null, 'sprite-redo', (!mxClient.IS_WIN) ? Editor.ctrlKey + '+Shift+Z' : Editor.ctrlKey + '+Y');
this.addAction('cut', function() { mxClipboard.cut(graph); }, null, 'sprite-cut', Editor.ctrlKey + '+X');
this.addAction('copy', function() { mxClipboard.copy(graph); }, null, 'sprite-copy', Editor.ctrlKey + '+C');
this.addAction('paste', function()
{
if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
{
mxClipboard.paste(graph);
}
}, false, 'sprite-paste', Editor.ctrlKey + '+V');
this.addAction('pasteHere', function(evt)
{
if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
{
graph.getModel().beginUpdate();
try
{
var cells = mxClipboard.paste(graph);
if (cells != null)
{
var includeEdges = true;
for (var i = 0; i < cells.length && includeEdges; i++)
{
includeEdges = includeEdges && graph.model.isEdge(cells[i]);
}
var t = graph.view.translate;
var s = graph.view.scale;
var dx = t.x;
var dy = t.y;
var bb = null;
if (cells.length == 1 && includeEdges)
{
var geo = graph.getCellGeometry(cells[0]);
if (geo != null)
{
bb = geo.getTerminalPoint(true);
}
}
bb = (bb != null) ? bb : graph.getBoundingBoxFromGeometry(cells, includeEdges);
if (bb != null)
{
var x = Math.round(graph.snap(graph.popupMenuHandler.triggerX / s - dx));
var y = Math.round(graph.snap(graph.popupMenuHandler.triggerY / s - dy));
graph.cellsMoved(cells, x - bb.x, y - bb.y);
}
}
}
finally
{
graph.getModel().endUpdate();
}
}
});
this.addAction('copySize', function(evt)
{
var cell = graph.getSelectionCell();
if (graph.isEnabled() && cell != null && graph.getModel().isVertex(cell))
{
var geo = graph.getCellGeometry(cell);
if (geo != null)
{
ui.copiedSize = new mxRectangle(geo.x, geo.y, geo.width, geo.height);
}
}
}, null, null, 'Alt+Shit+X');
this.addAction('pasteSize', function(evt)
{
if (graph.isEnabled() && !graph.isSelectionEmpty() && ui.copiedSize != null)
{
graph.getModel().beginUpdate();
try
{
var cells = graph.getSelectionCells();
for (var i = 0; i < cells.length; i++)
{
if (graph.getModel().isVertex(cells[i]))
{
var geo = graph.getCellGeometry(cells[i]);
if (geo != null)
{
geo = geo.clone();
geo.width = ui.copiedSize.width;
geo.height = ui.copiedSize.height;
graph.getModel().setGeometry(cells[i], geo);
}
}
}
}
finally
{
graph.getModel().endUpdate();
}
}
}, null, null, 'Alt+Shit+V');
function deleteCells(includeEdges)
{
// Cancels interactive operations
graph.escape();
var cells = graph.getDeletableCells(graph.getSelectionCells());
if (cells != null && cells.length > 0)
{
var parents = (graph.selectParentAfterDelete) ? graph.model.getParents(cells) : null;
graph.removeCells(cells, includeEdges);
// Selects parents for easier editing of groups
if (parents != null)
{
var select = [];
for (var i = 0; i < parents.length; i++)
{
if (graph.model.contains(parents[i]) &&
(graph.model.isVertex(parents[i]) ||
graph.model.isEdge(parents[i])))
{
select.push(parents[i]);
}
}
graph.setSelectionCells(select);
}
}
};
this.addAction('delete', function(evt)
{
deleteCells(evt != null && mxEvent.isShiftDown(evt));
}, null, null, 'Delete');
this.addAction('deleteAll', function()
{
deleteCells(true);
}, null, null, Editor.ctrlKey + '+Delete');
this.addAction('duplicate', function()
{
graph.setSelectionCells(graph.duplicateCells());
}, null, null, Editor.ctrlKey + '+D');
this.put('turn', new Action(mxResources.get('turn') + ' / ' + mxResources.get('reverse'), function()
{
graph.turnShapes(graph.getSelectionCells());
}, null, null, Editor.ctrlKey + '+R'));
this.addAction('selectVertices', function() { graph.selectVertices(); }, null, null, Editor.ctrlKey + '+Shift+I');
this.addAction('selectEdges', function() { graph.selectEdges(); }, null, null, Editor.ctrlKey + '+Shift+E');
this.addAction('selectAll', function() { graph.selectAll(null, true); }, null, null, Editor.ctrlKey + '+A');
this.addAction('selectNone', function() { graph.clearSelection(); }, null, null, Editor.ctrlKey + '+Shift+A');
this.addAction('lockUnlock', function()
{
if (!graph.isSelectionEmpty())
{
graph.getModel().beginUpdate();
try
{
var defaultValue = graph.isCellMovable(graph.getSelectionCell()) ? 1 : 0;
graph.toggleCellStyles(mxConstants.STYLE_MOVABLE, defaultValue);
graph.toggleCellStyles(mxConstants.STYLE_RESIZABLE, defaultValue);
graph.toggleCellStyles(mxConstants.STYLE_ROTATABLE, defaultValue);
graph.toggleCellStyles(mxConstants.STYLE_DELETABLE, defaultValue);
graph.toggleCellStyles(mxConstants.STYLE_EDITABLE, defaultValue);
graph.toggleCellStyles('connectable', defaultValue);
}
finally
{
graph.getModel().endUpdate();
}
}
}, null, null, Editor.ctrlKey + '+L');
// Navigation actions
this.addAction('home', function() { graph.home(); }, null, null, 'Home');
this.addAction('exitGroup', function() { graph.exitGroup(); }, null, null, Editor.ctrlKey + '+Shift+Home');
this.addAction('enterGroup', function() { graph.enterGroup(); }, null, null, Editor.ctrlKey + '+Shift+End');
this.addAction('collapse', function() { graph.foldCells(true); }, null, null, Editor.ctrlKey + '+Home');
this.addAction('expand', function() { graph.foldCells(false); }, null, null, Editor.ctrlKey + '+End');
// Arrange actions
this.addAction('toFront', function() { graph.orderCells(false); }, null, null, Editor.ctrlKey + '+Shift+F');
this.addAction('toBack', function() { graph.orderCells(true); }, null, null, Editor.ctrlKey + '+Shift+B');
this.addAction('group', function()
{
if (graph.getSelectionCount() == 1)
{
graph.setCellStyles('container', '1');
}
else
{
graph.setSelectionCell(graph.groupCells(null, 0));
}
}, null, null, Editor.ctrlKey + '+G');
this.addAction('ungroup', function()
{
if (graph.getSelectionCount() == 1 && graph.getModel().getChildCount(graph.getSelectionCell()) == 0)
{
graph.setCellStyles('container', '0');
}
else
{
graph.setSelectionCells(graph.ungroupCells());
}
}, null, null, Editor.ctrlKey + '+Shift+U');
this.addAction('removeFromGroup', function() { graph.removeCellsFromParent(); });
// Adds action
this.addAction('edit', function()
{
if (graph.isEnabled())
{
graph.startEditingAtCell();
}
}, null, null, 'F2/Enter');
this.addAction('editData...', function()
{
var cell = graph.getSelectionCell() || graph.getModel().getRoot();
ui.showDataDialog(cell);
}, null, null, Editor.ctrlKey + '+M');
this.addAction('editTooltip...', function()
{
var graph = ui.editor.graph;
if (graph.isEnabled() && !graph.isSelectionEmpty())
{
var cell = graph.getSelectionCell();
var tooltip = '';
if (mxUtils.isNode(cell.value))
{
var tmp = cell.value.getAttribute('tooltip');
if (tmp != null)
{
tooltip = tmp;
}
}
var dlg = new TextareaDialog(ui, mxResources.get('editTooltip') + ':', tooltip, function(newValue)
{
graph.setTooltipForCell(cell, newValue);
});
ui.showDialog(dlg.container, 320, 200, true, true);
dlg.init();
}
}, null, null, 'Alt+Shift+T');
this.addAction('openLink', function()
{
var link = graph.getLinkForCell(graph.getSelectionCell());
if (link != null)
{
graph.openLink(link);
}
});
this.addAction('editLink...', function()
{
var graph = ui.editor.graph;
if (graph.isEnabled() && !graph.isSelectionEmpty())
{
var cell = graph.getSelectionCell();
var value = graph.getLinkForCell(cell) || '';
ui.showLinkDialog(value, mxResources.get('apply'), function(link)
{
link = mxUtils.trim(link);
graph.setLinkForCell(cell, (link.length > 0) ? link : null);
});
}
}, null, null, 'Alt+Shift+L');
this.put('insertImage', new Action(mxResources.get('image') + '...', function()
{
if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
{
graph.clearSelection();
ui.actions.get('image').funct();
}
})).isEnabled = isGraphEnabled;
this.put('insertLink', new Action(mxResources.get('link') + '...', function()
{
if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
{
ui.showLinkDialog('', mxResources.get('insert'), function(link, docs)
{
link = mxUtils.trim(link);
if (link.length > 0)
{
var icon = null;
var title = graph.getLinkTitle(link);
if (docs != null && docs.length > 0)
{
icon = docs[0].iconUrl;
title = docs[0].name || docs[0].type;
title = title.charAt(0).toUpperCase() + title.substring(1);
if (title.length > 30)
{
title = title.substring(0, 30) + '...';
}
}
var pt = graph.getFreeInsertPoint();
var linkCell = new mxCell(title, new mxGeometry(pt.x, pt.y, 100, 40),
'fontColor=#0000EE;fontStyle=4;rounded=1;overflow=hidden;' + ((icon != null) ?
'shape=label;imageWidth=16;imageHeight=16;spacingLeft=26;align=left;image=' + icon :
'spacing=10;'));
linkCell.vertex = true;
graph.setLinkForCell(linkCell, link);
graph.cellSizeUpdated(linkCell, true);
graph.getModel().beginUpdate();
try
{
linkCell = graph.addCell(linkCell);
graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [linkCell]));
}
finally
{
graph.getModel().endUpdate();
}
graph.setSelectionCell(linkCell);
graph.scrollCellToVisible(graph.getSelectionCell());
}
});
}
})).isEnabled = isGraphEnabled;
this.addAction('link...', mxUtils.bind(this, function()
{
var graph = ui.editor.graph;
if (graph.isEnabled())
{
if (graph.cellEditor.isContentEditing())
{
var elt = graph.getSelectedElement();
var link = graph.getParentByName(elt, 'A', graph.cellEditor.textarea);
var oldValue = '';
// Workaround for FF returning the outermost selected element after double
// click on a DOM hierarchy with a link inside (but not as topmost element)
if (link == null && elt != null && elt.getElementsByTagName != null)
{
// Finds all links in the selected DOM and uses the link
// where the selection text matches its text content
var links = elt.getElementsByTagName('a');
for (var i = 0; i < links.length && link == null; i++)
{
if (links[i].textContent == elt.textContent)
{
link = links[i];
}
}
}
if (link != null && link.nodeName == 'A')
{
oldValue = link.getAttribute('href') || '';
graph.selectNode(link);
}
var selState = graph.cellEditor.saveSelection();
ui.showLinkDialog(oldValue, mxResources.get('apply'), mxUtils.bind(this, function(value)
{
graph.cellEditor.restoreSelection(selState);
if (value != null)
{
graph.insertLink(value);
}
}));
}
else if (graph.isSelectionEmpty())
{
this.get('insertLink').funct();
}
else
{
this.get('editLink').funct();
}
}
})).isEnabled = isGraphEnabled;
this.addAction('autosize', function()
{
var cells = graph.getSelectionCells();
if (cells != null)
{
graph.getModel().beginUpdate();
try
{
for (var i = 0; i < cells.length; i++)
{
var cell = cells[i];
if (graph.getModel().getChildCount(cell))
{
graph.updateGroupBounds([cell], 20);
}
else
{
var state = graph.view.getState(cell);
var geo = graph.getCellGeometry(cell);
if (graph.getModel().isVertex(cell) && state != null && state.text != null &&
geo != null && graph.isWrapping(cell))
{
geo = geo.clone();
geo.height = state.text.boundingBox.height / graph.view.scale;
graph.getModel().setGeometry(cell, geo);
}
else
{
graph.updateCellSize(cell);
}
}
}
}
finally
{
graph.getModel().endUpdate();
}
}
}, null, null, Editor.ctrlKey + '+Shift+Y');
this.addAction('formattedText', function()
{
var state = graph.getView().getState(graph.getSelectionCell());
if (state != null)
{
var value = '1';
graph.stopEditing();
graph.getModel().beginUpdate();
try
{
if (state.style['html'] == '1')
{
value = null;
var label = graph.convertValueToString(state.cell);
if (mxUtils.getValue(state.style, 'nl2Br', '1') != '0')
{
// Removes newlines from HTML and converts breaks to newlines
// to match the HTML output in plain text
label = label.replace(/\n/g, '').replace(/<br\s*.?>/g, '\n');
}
// Removes HTML tags
var temp = document.createElement('div');
temp.innerHTML = label;
label = mxUtils.extractTextWithWhitespace(temp.childNodes);
graph.cellLabelChanged(state.cell, label);
}
else
{
// Converts HTML tags to text
var label = mxUtils.htmlEntities(graph.convertValueToString(state.cell), false);
if (mxUtils.getValue(state.style, 'nl2Br', '1') != '0')
{
// Converts newlines in plain text to breaks in HTML
// to match the plain text output
label = label.replace(/\n/g, '<br/>');
}
graph.cellLabelChanged(state.cell, graph.sanitizeHtml(label));
}
graph.setCellStyles('html', value);
ui.fireEvent(new mxEventObject('styleChanged', 'keys', ['html'],
'values', [(value != null) ? value : '0'], 'cells',
graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
}
});
this.addAction('wordWrap', function()
{
var state = graph.getView().getState(graph.getSelectionCell());
var value = 'wrap';
graph.stopEditing();
if (state != null && state.style[mxConstants.STYLE_WHITE_SPACE] == 'wrap')
{
value = null;
}
graph.setCellStyles(mxConstants.STYLE_WHITE_SPACE, value);
});
this.addAction('rotation', function()
{
var value = '0';
var state = graph.getView().getState(graph.getSelectionCell());
if (state != null)
{
value = state.style[mxConstants.STYLE_ROTATION] || value;
}
var dlg = new FilenameDialog(ui, value, mxResources.get('apply'), function(newValue)
{
if (newValue != null && newValue.length > 0)
{
graph.setCellStyles(mxConstants.STYLE_ROTATION, newValue);
}
}, mxResources.get('enterValue') + ' (' + mxResources.get('rotation') + ' 0-360)');
ui.showDialog(dlg.container, 375, 80, true, true);
dlg.init();
});
// View actions
this.addAction('resetView', function()
{
graph.zoomTo(1);
ui.resetScrollbars();
}, null, null, Editor.ctrlKey + '+H');
this.addAction('zoomIn', function(evt) { graph.zoomIn(); }, null, null, Editor.ctrlKey + ' + (Numpad) / Alt+Mousewheel');
this.addAction('zoomOut', function(evt) { graph.zoomOut(); }, null, null, Editor.ctrlKey + ' - (Numpad) / Alt+Mousewheel');
this.addAction('fitWindow', function() { graph.fit(); }, null, null, Editor.ctrlKey + '+Shift+H');
this.addAction('fitPage', mxUtils.bind(this, function()
{
if (!graph.pageVisible)
{
this.get('pageView').funct();
}
var fmt = graph.pageFormat;
var ps = graph.pageScale;
var cw = graph.container.clientWidth - 10;
var ch = graph.container.clientHeight - 10;
var scale = Math.floor(20 * Math.min(cw / fmt.width / ps, ch / fmt.height / ps)) / 20;
graph.zoomTo(scale);
if (mxUtils.hasScrollbars(graph.container))
{
var pad = graph.getPagePadding();
graph.container.scrollTop = pad.y * graph.view.scale - 1;
graph.container.scrollLeft = Math.min(pad.x * graph.view.scale, (graph.container.scrollWidth - graph.container.clientWidth) / 2) - 1;
}
}), null, null, Editor.ctrlKey + '+J');
this.addAction('fitTwoPages', mxUtils.bind(this, function()
{
if (!graph.pageVisible)
{
this.get('pageView').funct();
}
var fmt = graph.pageFormat;
var ps = graph.pageScale;
var cw = graph.container.clientWidth - 10;
var ch = graph.container.clientHeight - 10;
var scale = Math.floor(20 * Math.min(cw / (2 * fmt.width) / ps, ch / fmt.height / ps)) / 20;
graph.zoomTo(scale);
if (mxUtils.hasScrollbars(graph.container))
{
var pad = graph.getPagePadding();
graph.container.scrollTop = Math.min(pad.y, (graph.container.scrollHeight - graph.container.clientHeight) / 2);
graph.container.scrollLeft = Math.min(pad.x, (graph.container.scrollWidth - graph.container.clientWidth) / 2);
}
}), null, null, Editor.ctrlKey + '+Shift+J');
this.addAction('fitPageWidth', mxUtils.bind(this, function()
{
if (!graph.pageVisible)
{
this.get('pageView').funct();
}
var fmt = graph.pageFormat;
var ps = graph.pageScale;
var cw = graph.container.clientWidth - 10;
var scale = Math.floor(20 * cw / fmt.width / ps) / 20;
graph.zoomTo(scale);
if (mxUtils.hasScrollbars(graph.container))
{
var pad = graph.getPagePadding();
graph.container.scrollLeft = Math.min(pad.x * graph.view.scale,
(graph.container.scrollWidth - graph.container.clientWidth) / 2);
}
}));
this.put('customZoom', new Action(mxResources.get('custom') + '...', mxUtils.bind(this, function()
{
var dlg = new FilenameDialog(this.editorUi, parseInt(graph.getView().getScale() * 100), mxResources.get('apply'), mxUtils.bind(this, function(newValue)
{
var val = parseInt(newValue);
if (!isNaN(val) && val > 0)
{
graph.zoomTo(val / 100);
}
}), mxResources.get('zoom') + ' (%)');
this.editorUi.showDialog(dlg.container, 300, 80, true, true);
dlg.init();
}), null, null, Editor.ctrlKey + '+0'));
this.addAction('pageScale...', mxUtils.bind(this, function()
{
var dlg = new FilenameDialog(this.editorUi, parseInt(graph.pageScale * 100), mxResources.get('apply'), mxUtils.bind(this, function(newValue)
{
var val = parseInt(newValue);
if (!isNaN(val) && val > 0)
{
ui.setPageScale(val / 100);
}
}), mxResources.get('pageScale') + ' (%)');
this.editorUi.showDialog(dlg.container, 300, 80, true, true);
dlg.init();
}));
// Option actions
var action = null;
action = this.addAction('grid', function()
{
graph.setGridEnabled(!graph.isGridEnabled());
ui.fireEvent(new mxEventObject('gridEnabledChanged'));
}, null, null, Editor.ctrlKey + '+Shift+G');
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.isGridEnabled(); });
action.setEnabled(false);
action = this.addAction('guides', function()
{
graph.graphHandler.guidesEnabled = !graph.graphHandler.guidesEnabled;
ui.fireEvent(new mxEventObject('guidesEnabledChanged'));
});
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.graphHandler.guidesEnabled; });
action.setEnabled(false);
action = this.addAction('tooltips', function()
{
graph.tooltipHandler.setEnabled(!graph.tooltipHandler.isEnabled());
});
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.tooltipHandler.isEnabled(); });
action = this.addAction('collapseExpand', function()
{
var change = new ChangePageSetup(ui);
change.ignoreColor = true;
change.ignoreImage = true;
change.foldingEnabled = !graph.foldingEnabled;
graph.model.execute(change);
});
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.foldingEnabled; });
action.isEnabled = isGraphEnabled;
action = this.addAction('scrollbars', function()
{
ui.setScrollbars(!ui.hasScrollbars());
});
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.scrollbars; });
action = this.addAction('pageView', mxUtils.bind(this, function()
{
ui.setPageVisible(!graph.pageVisible);
}));
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.pageVisible; });
action = this.addAction('connectionArrows', function()
{
graph.connectionArrowsEnabled = !graph.connectionArrowsEnabled;
ui.fireEvent(new mxEventObject('connectionArrowsChanged'));
}, null, null, 'Alt+Shift+A');
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.connectionArrowsEnabled; });
action = this.addAction('connectionPoints', function()
{
graph.setConnectable(!graph.connectionHandler.isEnabled());
ui.fireEvent(new mxEventObject('connectionPointsChanged'));
}, null, null, 'Alt+Shift+P');
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.connectionHandler.isEnabled(); });
action = this.addAction('copyConnect', function()
{
graph.connectionHandler.setCreateTarget(!graph.connectionHandler.isCreateTarget());
ui.fireEvent(new mxEventObject('copyConnectChanged'));
});
action.setToggleAction(true);
action.setSelectedCallback(function() { return graph.connectionHandler.isCreateTarget(); });
action.isEnabled = isGraphEnabled;
action = this.addAction('autosave', function()
{
ui.editor.setAutosave(!ui.editor.autosave);
});
action.setToggleAction(true);
action.setSelectedCallback(function() { return ui.editor.autosave; });
action.isEnabled = isGraphEnabled;
action.visible = false;
// Help actions
this.addAction('help', function()
{
var ext = '';
if (mxResources.isLanguageSupported(mxClient.language))
{
ext = '_' + mxClient.language;
}
graph.openLink(RESOURCES_PATH + '/help' + ext + '.html');
});
var showingAbout = false;
this.put('about', new Action(mxResources.get('about') + ' Graph Editor...', function()
{
if (!showingAbout)
{
ui.showDialog(new AboutDialog(ui).container, 320, 280, true, true, function()
{
showingAbout = false;
});
showingAbout = true;
}
}, null, null, 'F1'));
// Font style actions
var toggleFontStyle = mxUtils.bind(this, function(key, style, fn, shortcut)
{
return this.addAction(key, function()
{
if (fn != null && graph.cellEditor.isContentEditing())
{
fn();
}
else
{
graph.stopEditing(false);
graph.getModel().beginUpdate();
try
{
graph.toggleCellStyleFlags(mxConstants.STYLE_FONTSTYLE, style);
// Removes bold and italic tags and CSS styles inside labels
if ((style & mxConstants.FONT_BOLD) == mxConstants.FONT_BOLD)
{
graph.updateLabelElements(graph.getSelectionCells(), function(elt)
{
elt.style.fontWeight = null;
if (elt.nodeName == 'B')
{
graph.replaceElement(elt);
}
});
}
else if ((style & mxConstants.FONT_ITALIC) == mxConstants.FONT_ITALIC)
{
graph.updateLabelElements(graph.getSelectionCells(), function(elt)
{
elt.style.fontStyle = null;
if (elt.nodeName == 'I')
{
graph.replaceElement(elt);
}
});
}
else if ((style & mxConstants.FONT_UNDERLINE) == mxConstants.FONT_UNDERLINE)
{
graph.updateLabelElements(graph.getSelectionCells(), function(elt)
{
elt.style.textDecoration = null;
if (elt.nodeName == 'U')
{
graph.replaceElement(elt);
}
});
}
}
finally
{
graph.getModel().endUpdate();
}
}
}, null, null, shortcut);
});
toggleFontStyle('bold', mxConstants.FONT_BOLD, function() { document.execCommand('bold', false, null); }, Editor.ctrlKey + '+B');
toggleFontStyle('italic', mxConstants.FONT_ITALIC, function() { document.execCommand('italic', false, null); }, Editor.ctrlKey + '+I');
toggleFontStyle('underline', mxConstants.FONT_UNDERLINE, function() { document.execCommand('underline', false, null); }, Editor.ctrlKey + '+U');
// Color actions
this.addAction('fontColor...', function() { ui.menus.pickColor(mxConstants.STYLE_FONTCOLOR, 'forecolor', '000000'); });
this.addAction('strokeColor...', function() { ui.menus.pickColor(mxConstants.STYLE_STROKECOLOR); });
this.addAction('fillColor...', function() { ui.menus.pickColor(mxConstants.STYLE_FILLCOLOR); });
this.addAction('gradientColor...', function() { ui.menus.pickColor(mxConstants.STYLE_GRADIENTCOLOR); });
this.addAction('backgroundColor...', function() { ui.menus.pickColor(mxConstants.STYLE_LABEL_BACKGROUNDCOLOR, 'backcolor'); });
this.addAction('borderColor...', function() { ui.menus.pickColor(mxConstants.STYLE_LABEL_BORDERCOLOR); });
// Format actions
this.addAction('vertical', function() { ui.menus.toggleStyle(mxConstants.STYLE_HORIZONTAL, true); });
this.addAction('shadow', function() { ui.menus.toggleStyle(mxConstants.STYLE_SHADOW); });
this.addAction('solid', function()
{
graph.getModel().beginUpdate();
try
{
graph.setCellStyles(mxConstants.STYLE_DASHED, null);
graph.setCellStyles(mxConstants.STYLE_DASH_PATTERN, null);
ui.fireEvent(new mxEventObject('styleChanged', 'keys', [mxConstants.STYLE_DASHED, mxConstants.STYLE_DASH_PATTERN],
'values', [null, null], 'cells', graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
});
this.addAction('dashed', function()
{
graph.getModel().beginUpdate();
try
{
graph.setCellStyles(mxConstants.STYLE_DASHED, '1');
graph.setCellStyles(mxConstants.STYLE_DASH_PATTERN, null);
ui.fireEvent(new mxEventObject('styleChanged', 'keys', [mxConstants.STYLE_DASHED, mxConstants.STYLE_DASH_PATTERN],
'values', ['1', null], 'cells', graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
});
this.addAction('dotted', function()
{
graph.getModel().beginUpdate();
try
{
graph.setCellStyles(mxConstants.STYLE_DASHED, '1');
graph.setCellStyles(mxConstants.STYLE_DASH_PATTERN, '1 4');
ui.fireEvent(new mxEventObject('styleChanged', 'keys', [mxConstants.STYLE_DASHED, mxConstants.STYLE_DASH_PATTERN],
'values', ['1', '1 4'], 'cells', graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
});
this.addAction('sharp', function()
{
graph.getModel().beginUpdate();
try
{
graph.setCellStyles(mxConstants.STYLE_ROUNDED, '0');
graph.setCellStyles(mxConstants.STYLE_CURVED, '0');
ui.fireEvent(new mxEventObject('styleChanged', 'keys', [mxConstants.STYLE_ROUNDED, mxConstants.STYLE_CURVED],
'values', ['0', '0'], 'cells', graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
});
this.addAction('rounded', function()
{
graph.getModel().beginUpdate();
try
{
graph.setCellStyles(mxConstants.STYLE_ROUNDED, '1');
graph.setCellStyles(mxConstants.STYLE_CURVED, '0');
ui.fireEvent(new mxEventObject('styleChanged', 'keys', [mxConstants.STYLE_ROUNDED, mxConstants.STYLE_CURVED],
'values', ['1', '0'], 'cells', graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
});
this.addAction('toggleRounded', function()
{
if (!graph.isSelectionEmpty() && graph.isEnabled())
{
graph.getModel().beginUpdate();
try
{
var cells = graph.getSelectionCells();
var state = graph.view.getState(cells[0]);
var style = (state != null) ? state.style : graph.getCellStyle(cells[0]);
var value = (mxUtils.getValue(style, mxConstants.STYLE_ROUNDED, '0') == '1') ? '0' : '1';
graph.setCellStyles(mxConstants.STYLE_ROUNDED, value);
graph.setCellStyles(mxConstants.STYLE_CURVED, null);
ui.fireEvent(new mxEventObject('styleChanged', 'keys', [mxConstants.STYLE_ROUNDED, mxConstants.STYLE_CURVED],
'values', [value, '0'], 'cells', graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
}
});
this.addAction('curved', function()
{
graph.getModel().beginUpdate();
try
{
graph.setCellStyles(mxConstants.STYLE_ROUNDED, '0');
graph.setCellStyles(mxConstants.STYLE_CURVED, '1');
ui.fireEvent(new mxEventObject('styleChanged', 'keys', [mxConstants.STYLE_ROUNDED, mxConstants.STYLE_CURVED],
'values', ['0', '1'], 'cells', graph.getSelectionCells()));
}
finally
{
graph.getModel().endUpdate();
}
});
this.addAction('collapsible', function()
{
var state = graph.view.getState(graph.getSelectionCell());
var value = '1';
if (state != null && graph.getFoldingImage(state) != null)
{
value = '0';
}
graph.setCellStyles('collapsible', value);
ui.fireEvent(new mxEventObject('styleChanged', 'keys', ['collapsible'],
'values', [value], 'cells', graph.getSelectionCells()));
});
this.addAction('editStyle...', mxUtils.bind(this, function()
{
var cells = graph.getSelectionCells();
if (cells != null && cells.length > 0)
{
var model = graph.getModel();
var dlg = new TextareaDialog(this.editorUi, mxResources.get('editStyle') + ':',
model.getStyle(cells[0]) || '', function(newValue)
{
if (newValue != null)
{
graph.setCellStyle(mxUtils.trim(newValue), cells);
}
}, null, null, 400, 220);
this.editorUi.showDialog(dlg.container, 420, 300, true, true);
dlg.init();
}
}), null, null, Editor.ctrlKey + '+E');
this.addAction('setAsDefaultStyle', function()
{
if (graph.isEnabled() && !graph.isSelectionEmpty())
{
ui.setDefaultStyle(graph.getSelectionCell());
}
}, null, null, Editor.ctrlKey + '+Shift+D');
this.addAction('clearDefaultStyle', function()
{
if (graph.isEnabled())
{
ui.clearDefaultStyle();
}
}, null, null, Editor.ctrlKey + '+Shift+R');
this.addAction('addWaypoint', function()
{
var cell = graph.getSelectionCell();
if (cell != null && graph.getModel().isEdge(cell))
{
var handler = editor.graph.selectionCellsHandler.getHandler(cell);
if (handler instanceof mxEdgeHandler)
{
var t = graph.view.translate;
var s = graph.view.scale;
var dx = t.x;
var dy = t.y;
var parent = graph.getModel().getParent(cell);
var pgeo = graph.getCellGeometry(parent);
while (graph.getModel().isVertex(parent) && pgeo != null)
{
dx += pgeo.x;
dy += pgeo.y;
parent = graph.getModel().getParent(parent);
pgeo = graph.getCellGeometry(parent);
}
var x = Math.round(graph.snap(graph.popupMenuHandler.triggerX / s - dx));
var y = Math.round(graph.snap(graph.popupMenuHandler.triggerY / s - dy));
handler.addPointAt(handler.state, x, y);
}
}
});
this.addAction('removeWaypoint', function()
{
// TODO: Action should run with "this" set to action
var rmWaypointAction = ui.actions.get('removeWaypoint');
if (rmWaypointAction.handler != null)
{
// NOTE: Popupevent handled and action updated in Menus.createPopupMenu
rmWaypointAction.handler.removePoint(rmWaypointAction.handler.state, rmWaypointAction.index);
}
});
this.addAction('clearWaypoints', function()
{
var cells = graph.getSelectionCells();
if (cells != null)
{
cells = graph.addAllEdges(cells);
graph.getModel().beginUpdate();
try
{
for (var i = 0; i < cells.length; i++)
{
var cell = cells[i];
if (graph.getModel().isEdge(cell))
{
var geo = graph.getCellGeometry(cell);
if (geo != null)
{
geo = geo.clone();
geo.points = null;
graph.getModel().setGeometry(cell, geo);
}
}
}
}
finally
{
graph.getModel().endUpdate();
}
}
}, null, null, 'Alt+Shift+C');
action = this.addAction('subscript', mxUtils.bind(this, function()
{
if (graph.cellEditor.isContentEditing())
{
document.execCommand('subscript', false, null);
}
}), null, null, Editor.ctrlKey + '+,');
action = this.addAction('superscript', mxUtils.bind(this, function()
{
if (graph.cellEditor.isContentEditing())
{
document.execCommand('superscript', false, null);
}
}), null, null, Editor.ctrlKey + '+.');
this.addAction('image...', function()
{
if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
{
var title = mxResources.get('image') + ' (' + mxResources.get('url') + '):';
var state = graph.getView().getState(graph.getSelectionCell());
var value = '';
if (state != null)
{
value = state.style[mxConstants.STYLE_IMAGE] || value;
}
var selectionState = graph.cellEditor.saveSelection();
ui.showImageDialog(title, value, function(newValue, w, h)
{
// Inserts image into HTML text
if (graph.cellEditor.isContentEditing())
{
graph.cellEditor.restoreSelection(selectionState);
graph.insertImage(newValue, w, h);
}
else
{
var cells = graph.getSelectionCells();
if (newValue != null && (newValue.length > 0 || cells.length > 0))
{
var select = null;
graph.getModel().beginUpdate();
try
{
// Inserts new cell if no cell is selected
if (cells.length == 0)
{
var pt = graph.getFreeInsertPoint();
cells = [graph.insertVertex(graph.getDefaultParent(), null, '', pt.x, pt.y, w, h,
'shape=image;imageAspect=0;aspect=fixed;verticalLabelPosition=bottom;verticalAlign=top;')];
select = cells;
graph.fireEvent(new mxEventObject('cellsInserted', 'cells', select));
}
graph.setCellStyles(mxConstants.STYLE_IMAGE, (newValue.length > 0) ? newValue : null, cells);
// Sets shape only if not already shape with image (label or image)
var state = graph.view.getState(cells[0]);
var style = (state != null) ? state.style : graph.getCellStyle(cells[0]);
if (style[mxConstants.STYLE_SHAPE] != 'image' && style[mxConstants.STYLE_SHAPE] != 'label')
{
graph.setCellStyles(mxConstants.STYLE_SHAPE, 'image', cells);
}
else if (newValue.length == 0)
{
graph.setCellStyles(mxConstants.STYLE_SHAPE, null, cells);
}
if (graph.getSelectionCount() == 1)
{
if (w != null && h != null)
{
var cell = cells[0];
var geo = graph.getModel().getGeometry(cell);
if (geo != null)
{
geo = geo.clone();
geo.width = w;
geo.height = h;
graph.getModel().setGeometry(cell, geo);
}
}
}
}
finally
{
graph.getModel().endUpdate();
}
if (select != null)
{
graph.setSelectionCells(select);
graph.scrollCellToVisible(select[0]);
}
}
}
}, graph.cellEditor.isContentEditing(), !graph.cellEditor.isContentEditing());
}
}).isEnabled = isGraphEnabled;
action = this.addAction('layers', mxUtils.bind(this, function()
{
if (this.layersWindow == null)
{
// LATER: Check outline window for initial placement
this.layersWindow = new LayersWindow(ui, document.body.offsetWidth - 280, 120, 220, 180);
this.layersWindow.window.addListener('show', function()
{
ui.fireEvent(new mxEventObject('layers'));
});
this.layersWindow.window.addListener('hide', function()
{
ui.fireEvent(new mxEventObject('layers'));
});
this.layersWindow.window.setVisible(true);
ui.fireEvent(new mxEventObject('layers'));
}
else
{
this.layersWindow.window.setVisible(!this.layersWindow.window.isVisible());
}
}), null, null, Editor.ctrlKey + '+Shift+L');
action.setToggleAction(true);
action.setSelectedCallback(mxUtils.bind(this, function() { return this.layersWindow != null && this.layersWindow.window.isVisible(); }));
action = this.addAction('formatPanel', mxUtils.bind(this, function()
{
ui.toggleFormatPanel();
}), null, null, Editor.ctrlKey + '+Shift+P');
action.setToggleAction(true);
action.setSelectedCallback(mxUtils.bind(this, function() { return ui.formatWidth > 0; }));
action = this.addAction('outline', mxUtils.bind(this, function()
{
if (this.outlineWindow == null)
{
// LATER: Check layers window for initial placement
this.outlineWindow = new OutlineWindow(ui, document.body.offsetWidth - 260, 100, 180, 180);
this.outlineWindow.window.addListener('show', function()
{
ui.fireEvent(new mxEventObject('outline'));
});
this.outlineWindow.window.addListener('hide', function()
{
ui.fireEvent(new mxEventObject('outline'));
});
this.outlineWindow.window.setVisible(true);
ui.fireEvent(new mxEventObject('outline'));
}
else
{
this.outlineWindow.window.setVisible(!this.outlineWindow.window.isVisible());
}
}), null, null, Editor.ctrlKey + '+Shift+O');
action.setToggleAction(true);
action.setSelectedCallback(mxUtils.bind(this, function() { return this.outlineWindow != null && this.outlineWindow.window.isVisible(); }));
};
/**
* Registers the given action under the given name.
*/
Actions.prototype.addAction = function(key, funct, enabled, iconCls, shortcut)
{
var title;
if (key.substring(key.length - 3) == '...')
{
key = key.substring(0, key.length - 3);
title = mxResources.get(key) + '...';
}
else
{
title = mxResources.get(key);
}
return this.put(key, new Action(title, funct, enabled, iconCls, shortcut));
};
/**
* Registers the given action under the given name.
*/
Actions.prototype.put = function(name, action)
{
this.actions[name] = action;
return action;
};
/**
* Returns the action for the given name or null if no such action exists.
*/
Actions.prototype.get = function(name)
{
return this.actions[name];
};
/**
* Constructs a new action for the given parameters.
*/
function Action(label, funct, enabled, iconCls, shortcut)
{
mxEventSource.call(this);
this.label = label;
this.funct = this.createFunction(funct);
this.enabled = (enabled != null) ? enabled : true;
this.iconCls = iconCls;
this.shortcut = shortcut;
this.visible = true;
};
// Action inherits from mxEventSource
mxUtils.extend(Action, mxEventSource);
/**
* Sets the enabled state of the action and fires a stateChanged event.
*/
Action.prototype.createFunction = function(funct)
{
return funct;
};
/**
* Sets the enabled state of the action and fires a stateChanged event.
*/
Action.prototype.setEnabled = function(value)
{
if (this.enabled != value)
{
this.enabled = value;
this.fireEvent(new mxEventObject('stateChanged'));
}
};
/**
* Sets the enabled state of the action and fires a stateChanged event.
*/
Action.prototype.isEnabled = function()
{
return this.enabled;
};
/**
* Sets the enabled state of the action and fires a stateChanged event.
*/
Action.prototype.setToggleAction = function(value)
{
this.toggleAction = value;
};
/**
* Sets the enabled state of the action and fires a stateChanged event.
*/
Action.prototype.setSelectedCallback = function(funct)
{
this.selectedCallback = funct;
};
/**
* Sets the enabled state of the action and fires a stateChanged event.
*/
Action.prototype.isSelected = function()
{
return this.selectedCallback();
};
|
load("bf4b12814bc95f34eeb130127d8438ab.js");
load("93fae755edd261212639eed30afa2ca4.js");
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.4.4.19-4-10
description: >
Array.prototype.map - the exception is not thrown if exception was
thrown by step 2
---*/
var obj = { 0: 11, 1: 12 };
Object.defineProperty(obj, "length", {
get: function () {
throw new Test262Error();
},
configurable: true
});
assert.throws(Test262Error, function() {
Array.prototype.map.call(obj, undefined);
});
|
/**
* @file htest.js
* @brief Simple Unit Test framework.
* @author Jongmin Park (trip2eee@gmail.com)
*/
/**
* htest class
*/
class htest{
// private fields.
#__test_cases
#__num_failed
#__list_failed
#__is_success
constructor(){
this.#__test_cases = [];
this.#__num_failed = 0;
this.#__list_failed = [];
this.#__is_success = false;
}
SetUp(){
}
TearDown(){
}
test(){
this.#__test_cases = [];
let keys = Reflect.ownKeys(Reflect.getPrototypeOf(this));
for(let key of keys){
if('constructor' != key && 'SetUp' != key && 'TearDown' != key){
// The name of method shall start with 'test_'.
if('test_' == key.substr(0, 5)){
this.#__test_cases.push(key);
}
}
}
const strHeader = '\x1b[32m[============]\x1b[0m';
const strRun = '\x1b[32m[ RUN ]\x1b[0m';
const strOK = '\x1b[32m[ OK ]\x1b[0m';
const strFAIL = '\x1b[31m[ FAIL ]\x1b[0m';
const strPASSED = '\x1b[32m[ PASSED ]\x1b[0m';
const strFAILED = '\x1b[31m[ FAILED ]\x1b[0m';
if(this.#__test_cases.length > 1){
console.log(strHeader + ' Running ' + this.#__test_cases.length + ' tests');
}else{
console.log(strHeader + ' Running ' + this.#__test_cases.length + ' test');
}
const t_start = performance.now();
for(let i = 0; i < this.#__test_cases.length; i++){
console.log(strRun + ' ' + this.#__test_cases[i]);
this.#__is_success = true;
const t_start_test = performance.now();
// prepare for test.
this.SetUp();
// run test.
try{
this[this.#__test_cases[i]]();
}catch(error) {
// If exeption was thrown.
this.#__is_success = false; // Set success flag to be failed.
console.error(error);
}
// release resources.
this.TearDown();
const t_end_test = performance.now();
const t_test = (t_end_test - t_start_test);
const strTime = ' (' + t_test.toFixed(0) + ')';
// if the test case is failed.
if(false == this.#__is_success){
this.#__num_failed++;
this.#__list_failed.push(this.#__test_cases[i]);
console.log(strFAIL + ' ' + this.#__test_cases[i] + strTime);
}
else{
console.log(strOK + ' ' + this.#__test_cases[i] + strTime);
}
}
const t_end = performance.now();
const t_total = t_end - t_start;
const strTotalTime = ' (' + t_total.toFixed(0) + ' ms total)';
if(this.#__test_cases.length > 1){
console.log(strHeader + ' ' + this.#__test_cases.length + ' tests ran' + strTotalTime);
}else{
console.log(strHeader + ' ' + this.#__test_cases.length + ' test ran' + strTotalTime);
}
if((this.#__test_cases.length - this.#__num_failed) > 1){
console.log(strPASSED + ' ' + (this.#__test_cases.length - this.#__num_failed) + ' tests');
}else{
console.log(strPASSED + ' ' + (this.#__test_cases.length - this.#__num_failed) + ' test');
}
if(this.#__num_failed > 0){
if(this.#__num_failed > 1){
console.log(strFAILED + ' ' + this.#__num_failed + ' tests listed below');
}else{
console.log(strFAILED + ' ' + this.#__num_failed + ' test listed below');
}
for(let i = 0; i < this.#__list_failed.length; i++){
console.log(strFAILED + ' ' + this.#__list_failed[i]);
}
}
}
// private assertions.
#__expectFail(){
this.#__is_success = false;
}
#__assertFail(){
this.#__is_success = false;
throw 'Assertion Failed';
}
expectEqual(x, y){
if(x != y){
console.log(x + ' != ' + y)
this.#__expectFail();
}
}
assertEqual(x, y){
if(x != y){
console.log(x + ' != ' + y)
this.#__assertFail();
}
}
expectNear(x, y, eps){
if(Math.abs(x - y) > eps){
console.log('abs( ' + x + ' - ' + y + ' ) > ' + eps);
this.#__expectFail();
}
}
assertNear(x, y){
if(Math.abs(x - y) > eps){
console.log('abs( ' + x + ' - ' + y + ' ) > ' + eps);
this.#__assertFail();
}
}
expectNotEqual(x, y){
if(x == y){
this.#__expectFail();
}
}
assertNotEqual(x, y){
if(x == y){
this.#__assertFail();
}
}
expectTrue(x){
if(false == x){
this.#__expectFail();
}
}
assertTrue(x){
if(false == x){
this.#__assertFail();
}
}
expectFalse(x){
if(true == x){
this.#__expectFail();
}
}
assertFalse(x){
if(true == x){
this.#__assertFail();
}
}
};
module.exports = { htest };
|
# encoding: utf-8
import re
import logging
from peewee import fn, OperationalError
from workflow import MATCH_ALL, MATCH_ALLCHARS
from mstodo import icons
from mstodo.models.taskfolder import TaskFolder
from mstodo.models.preferences import Preferences
from mstodo.models.task import Task
from mstodo.sync import background_sync
from mstodo.util import workflow
log = logging.getLogger(__name__)
_hashtag_prompt_pattern = re.compile(r'#\S*$', re.UNICODE)
def filter(args):
query = ' '.join(args[1:])
wf = workflow()
prefs = Preferences.current_prefs()
matching_hashtags = []
if not query:
wf.add_item('Begin typing to search tasks', '', icon=icons.SEARCH)
hashtag_match = re.search(_hashtag_prompt_pattern, query)
if hashtag_match:
from mstodo.models.hashtag import Hashtag
hashtag_prompt = hashtag_match.group().lower()
hashtags = Hashtag.select().where(Hashtag.id.contains(hashtag_prompt)).order_by(fn.Lower(Hashtag.tag).asc())
for hashtag in hashtags:
# If there is an exact match, do not show hashtags
if hashtag.id == hashtag_prompt:
matching_hashtags = []
break
matching_hashtags.append(hashtag)
# Show hashtag prompt if there is more than one matching hashtag or the
# hashtag being typed does not exactly match the single matching hashtag
if len(matching_hashtags) > 0:
for hashtag in matching_hashtags:
wf.add_item(hashtag.tag[1:], '', autocomplete=u'-search %s%s ' % (query[:hashtag_match.start()], hashtag.tag), icon=icons.HASHTAG)
else:
conditions = True
taskfolders = workflow().stored_data('taskfolders')
matching_taskfolders = None
query = ' '.join(args[1:]).strip()
taskfolder_query = None
# Show all task folders on the main search screen
if not query:
matching_taskfolders = taskfolders
# Filter task folders when colon is used
if ':' in query:
matching_taskfolders = taskfolders
components = re.split(r':\s*', query, 1)
taskfolder_query = components[0]
if taskfolder_query:
matching_taskfolders = workflow().filter(
taskfolder_query,
taskfolders if taskfolders else [],
lambda f: f['title'],
# Ignore MATCH_ALLCHARS which is expensive and inaccurate
match_on=MATCH_ALL ^ MATCH_ALLCHARS
)
# If no matching task folder search against all tasks
if matching_taskfolders:
query = components[1] if len(components) > 1 else ''
# If there is a task folder exactly matching the query ignore
# anything else. This takes care of taskfolders that are substrings
# of other taskfolders
if len(matching_taskfolders) > 1:
for f in matching_taskfolders:
if f['title'].lower() == taskfolder_query.lower():
matching_taskfolders = [f]
break
if matching_taskfolders:
if not taskfolder_query:
wf.add_item('Browse by hashtag', autocomplete='-search #', icon=icons.HASHTAG)
if len(matching_taskfolders) > 1:
for f in matching_taskfolders:
icon = icons.INBOX if f['isDefaultFolder'] else icons.LIST
wf.add_item(f['title'], autocomplete='-search %s: ' % f['title'], icon=icon)
else:
conditions = conditions & (Task.list == matching_taskfolders[0]['id'])
if not matching_taskfolders or len(matching_taskfolders) <= 1:
for arg in query.split(' '):
if len(arg) > 1:
conditions = conditions & (Task.title.contains(arg) | TaskFolder.title.contains(arg))
if conditions:
if not prefs.show_completed_tasks:
conditions = (Task.status != 'completed') & conditions
tasks = Task.select().where(Task.list.is_null(False) & conditions)
tasks = tasks.join(TaskFolder).order_by(Task.lastModifiedDateTime.desc(), TaskFolder.changeKey.asc())
# Avoid excessive results
tasks = tasks.limit(50)
try:
for t in tasks:
wf.add_item(u'%s – %s' % (t.list_title, t.title), t.subtitle(), autocomplete='-task %s ' % t.id, icon=icons.TASK_COMPLETED if t.status == 'completed' else icons.TASK)
except OperationalError:
background_sync()
if prefs.show_completed_tasks:
wf.add_item('Hide completed tasks', arg='-pref show_completed_tasks --alfred %s' % ' '.join(args), valid=True, icon=icons.HIDDEN)
else:
wf.add_item('Show completed tasks', arg='-pref show_completed_tasks --alfred %s' % ' '.join(args), valid=True, icon=icons.VISIBLE)
wf.add_item('New search', autocomplete='-search ', icon=icons.CANCEL)
wf.add_item('Main menu', autocomplete='', icon=icons.BACK)
# Make sure tasks are up-to-date while searching
background_sync()
def commit(args, modifier=None):
action = args[1]
|
/**
* 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.
*/
/* jshint maxlen: false */
'use strict';
var createAPIRequest = require('../../lib/apirequest');
var utils = require('../../lib/utils');
/**
* DoubleClick Bid Manager API
*
* API for viewing and managing your reports in DoubleClick Bid Manager.
*
* @example
* var google = require('googleapis');
* var doubleclickbidmanager = google.doubleclickbidmanager('v1');
*
* @namespace doubleclickbidmanager
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Doubleclickbidmanager
*/
function Doubleclickbidmanager(options) { // eslint-disable-line
var self = this;
self._options = options || {};
self.lineitems = {
/**
* doubleclickbidmanager.lineitems.downloadlineitems
*
* @desc Retrieves line items in CSV format.
*
* @alias doubleclickbidmanager.lineitems.downloadlineitems
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {doubleclickbidmanager(v1).DownloadLineItemsRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
downloadlineitems: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/lineitems/downloadlineitems',
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* doubleclickbidmanager.lineitems.uploadlineitems
*
* @desc Uploads line items in CSV format.
*
* @alias doubleclickbidmanager.lineitems.uploadlineitems
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {doubleclickbidmanager(v1).UploadLineItemsRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
uploadlineitems: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/lineitems/uploadlineitems',
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.queries = {
/**
* doubleclickbidmanager.queries.createquery
*
* @desc Creates a query.
*
* @alias doubleclickbidmanager.queries.createquery
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {doubleclickbidmanager(v1).Query} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
createquery: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/query',
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* doubleclickbidmanager.queries.deletequery
*
* @desc Deletes a stored query as well as the associated stored reports.
*
* @alias doubleclickbidmanager.queries.deletequery
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {string} params.queryId Query ID to delete.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
deletequery: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/query/{queryId}',
method: 'DELETE'
}, options),
params: params,
requiredParams: ['queryId'],
pathParams: ['queryId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* doubleclickbidmanager.queries.getquery
*
* @desc Retrieves a stored query.
*
* @alias doubleclickbidmanager.queries.getquery
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {string} params.queryId Query ID to retrieve.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
getquery: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/query/{queryId}',
method: 'GET'
}, options),
params: params,
requiredParams: ['queryId'],
pathParams: ['queryId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* doubleclickbidmanager.queries.listqueries
*
* @desc Retrieves stored queries.
*
* @alias doubleclickbidmanager.queries.listqueries
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object=} params Parameters for request
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
listqueries: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/queries',
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* doubleclickbidmanager.queries.runquery
*
* @desc Runs a stored query to generate a report.
*
* @alias doubleclickbidmanager.queries.runquery
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {string} params.queryId Query ID to run.
* @param {doubleclickbidmanager(v1).RunQueryRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
runquery: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/query/{queryId}',
method: 'POST'
}, options),
params: params,
requiredParams: ['queryId'],
pathParams: ['queryId'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.reports = {
/**
* doubleclickbidmanager.reports.listreports
*
* @desc Retrieves stored reports.
*
* @alias doubleclickbidmanager.reports.listreports
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {string} params.queryId Query ID with which the reports are associated.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
listreports: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/queries/{queryId}/reports',
method: 'GET'
}, options),
params: params,
requiredParams: ['queryId'],
pathParams: ['queryId'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.sdf = {
/**
* doubleclickbidmanager.sdf.download
*
* @desc Retrieves entities in SDF format.
*
* @alias doubleclickbidmanager.sdf.download
* @memberOf! doubleclickbidmanager(v1)
*
* @param {object} params Parameters for request
* @param {doubleclickbidmanager(v1).DownloadRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
download: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://www.googleapis.com/doubleclickbidmanager/v1/sdf/download',
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* @typedef DownloadLineItemsRequest
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} fileSpec File specification (column names, types, order) in which the line items will be returned. Default to EWF.
* @property {string[]} filterIds Ids of the specified filter type used to filter line items to fetch. If omitted, all the line items will be returned.
* @property {string} filterType Filter type used to filter line items to fetch.
* @property {string} format Format in which the line items will be returned. Default to CSV.
*/
/**
* @typedef DownloadLineItemsResponse
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} lineItems Retrieved line items in CSV format. Refer to Entity Write File Format or Structured Data File Format for more information on file formats.
*/
/**
* @typedef DownloadRequest
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string[]} fileTypes File types that will be returned.
* @property {string[]} filterIds The IDs of the specified filter type. This is used to filter entities to fetch. At least one ID must be specified. Only one ID is allowed for the ADVERTISER_ID filter type. For INSERTION_ORDER_ID or LINE_ITEM_ID filter types all IDs must be from the same Advertiser.
* @property {string} filterType Filter type used to filter line items to fetch.
* @property {string} version SDF Version (column names, types, order) in which the entities will be returned. Default to 3.
*/
/**
* @typedef DownloadResponse
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} adGroups Retrieved ad groups in SDF format.
* @property {string} ads Retrieved ads in SDF format.
* @property {string} insertionOrders Retrieved insertion orders in SDF format.
* @property {string} lineItems Retrieved line items in SDF format.
*/
/**
* @typedef FilterPair
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} type Filter type.
* @property {string} value Filter value.
*/
/**
* @typedef ListQueriesResponse
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} kind Identifies what kind of resource this is. Value: the fixed string "doubleclickbidmanager#listQueriesResponse".
* @property {doubleclickbidmanager(v1).Query[]} queries Retrieved queries.
*/
/**
* @typedef ListReportsResponse
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} kind Identifies what kind of resource this is. Value: the fixed string "doubleclickbidmanager#listReportsResponse".
* @property {doubleclickbidmanager(v1).Report[]} reports Retrieved reports.
*/
/**
* @typedef Parameters
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {doubleclickbidmanager(v1).FilterPair[]} filters Filters used to match traffic data in your report.
* @property {string[]} groupBys Data is grouped by the filters listed in this field.
* @property {boolean} includeInviteData Whether to include data from Invite Media.
* @property {string[]} metrics Metrics to include as columns in your report.
* @property {string} type Report type.
*/
/**
* @typedef Query
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} kind Identifies what kind of resource this is. Value: the fixed string "doubleclickbidmanager#query".
* @property {doubleclickbidmanager(v1).QueryMetadata} metadata Query metadata.
* @property {doubleclickbidmanager(v1).Parameters} params Query parameters.
* @property {string} queryId Query ID.
* @property {string} reportDataEndTimeMs The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if metadata.dataRange is CUSTOM_DATES and ignored otherwise.
* @property {string} reportDataStartTimeMs The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required if metadata.dataRange is CUSTOM_DATES and ignored otherwise.
* @property {doubleclickbidmanager(v1).QuerySchedule} schedule Information on how often and when to run a query.
* @property {string} timezoneCode Canonical timezone code for report data time. Defaults to America/New_York.
*/
/**
* @typedef QueryMetadata
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} dataRange Range of report data.
* @property {string} format Format of the generated report.
* @property {string} googleCloudStoragePathForLatestReport The path to the location in Google Cloud Storage where the latest report is stored.
* @property {string} googleDrivePathForLatestReport The path in Google Drive for the latest report.
* @property {string} latestReportRunTimeMs The time when the latest report started to run.
* @property {string} locale Locale of the generated reports. Valid values are cs CZECH de GERMAN en ENGLISH es SPANISH fr FRENCH it ITALIAN ja JAPANESE ko KOREAN pl POLISH pt-BR BRAZILIAN_PORTUGUESE ru RUSSIAN tr TURKISH uk UKRAINIAN zh-CN CHINA_CHINESE zh-TW TAIWAN_CHINESE
An locale string not in the list above will generate reports in English.
* @property {integer} reportCount Number of reports that have been generated for the query.
* @property {boolean} running Whether the latest report is currently running.
* @property {boolean} sendNotification Whether to send an email notification when a report is ready. Default to false.
* @property {string[]} shareEmailAddress List of email addresses which are sent email notifications when the report is finished. Separate from sendNotification.
* @property {string} title Query title. It is used to name the reports generated from this query.
*/
/**
* @typedef QuerySchedule
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} endTimeMs Datetime to periodically run the query until.
* @property {string} frequency How often the query is run.
* @property {integer} nextRunMinuteOfDay Time of day at which a new report will be generated, represented as minutes past midnight. Range is 0 to 1439. Only applies to scheduled reports.
* @property {string} nextRunTimezoneCode Canonical timezone code for report generation time. Defaults to America/New_York.
*/
/**
* @typedef Report
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {doubleclickbidmanager(v1).ReportKey} key Key used to identify a report.
* @property {doubleclickbidmanager(v1).ReportMetadata} metadata Report metadata.
* @property {doubleclickbidmanager(v1).Parameters} params Report parameters.
*/
/**
* @typedef ReportFailure
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} errorCode Error code that shows why the report was not created.
*/
/**
* @typedef ReportKey
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} queryId Query ID.
* @property {string} reportId Report ID.
*/
/**
* @typedef ReportMetadata
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} googleCloudStoragePath The path to the location in Google Cloud Storage where the report is stored.
* @property {string} reportDataEndTimeMs The ending time for the data that is shown in the report.
* @property {string} reportDataStartTimeMs The starting time for the data that is shown in the report.
* @property {doubleclickbidmanager(v1).ReportStatus} status Report status.
*/
/**
* @typedef ReportStatus
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {doubleclickbidmanager(v1).ReportFailure} failure If the report failed, this records the cause.
* @property {string} finishTimeMs The time when this report either completed successfully or failed.
* @property {string} format The file type of the report.
* @property {string} state The state of the report.
*/
/**
* @typedef RowStatus
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {boolean} changed Whether the stored entity is changed as a result of upload.
* @property {string} entityId Entity Id.
* @property {string} entityName Entity name.
* @property {string[]} errors Reasons why the entity can't be uploaded.
* @property {boolean} persisted Whether the entity is persisted.
* @property {integer} rowNumber Row number.
*/
/**
* @typedef RunQueryRequest
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string} dataRange Report data range used to generate the report.
* @property {string} reportDataEndTimeMs The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if dataRange is CUSTOM_DATES and ignored otherwise.
* @property {string} reportDataStartTimeMs The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required if dataRange is CUSTOM_DATES and ignored otherwise.
* @property {string} timezoneCode Canonical timezone code for report data time. Defaults to America/New_York.
*/
/**
* @typedef UploadLineItemsRequest
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {boolean} dryRun Set to true to get upload status without actually persisting the line items.
* @property {string} format Format the line items are in. Default to CSV.
* @property {string} lineItems Line items in CSV to upload. Refer to Entity Write File Format for more information on file format.
*/
/**
* @typedef UploadLineItemsResponse
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {doubleclickbidmanager(v1).UploadStatus} uploadStatus Status of upload.
*/
/**
* @typedef UploadStatus
* @memberOf! doubleclickbidmanager(v1)
* @type object
* @property {string[]} errors Reasons why upload can't be completed.
* @property {doubleclickbidmanager(v1).RowStatus[]} rowStatus Per-row upload status.
*/
module.exports = Doubleclickbidmanager;
|
"""
If the numbers 1 to 5 are written out in words: one, two, three, four, five,
then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two)
contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
"""
def numToWord(n):
""" Converts Num to Word -- Only for [1,999]
--param
n : int
--return
string : word of num
"""
ones = ['zero','one','two','three','four','five','six','seven','eight','nine']
tens = ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tensSpecial = ['twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
hundred = ' hundred and '
strNum = str(n)
if len(strNum) == 1:
return ones[n]
elif len(strNum) == 2:
if strNum[0] == '1':
return tens[int(strNum[1])]
else:
if strNum[1] == '0':
return tensSpecial[int(strNum[0])-2]
else:
return tensSpecial[int(strNum[0])-2] + " " + ones[int(strNum[1])]
else:
if strNum[-1] == '0' and strNum[-2] == '0':
return ones[int(strNum[0])] + ' hundred'
else:
return ones[int(strNum[0])] + hundred + numToWord(int(strNum[1:]))
# end of numToWord
wordNums = []
for i in range(1,1000):
wordNums.append(numToWord(i))
wordNums += ['one thousand']
characterLength = 0
for i in wordNums:
temp = i.replace(' ','')
characterLength += len(temp)
print(characterLength) # 21124
|
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Dialog, Button } from 'fundamental-react';
import LuigiClient from '@luigi-project/client';
import { useTranslation } from 'react-i18next';
import { useNotification } from 'shared/contexts/NotificationContext';
import { Tooltip } from 'shared/components/Tooltip/Tooltip';
import CustomPropTypes from 'shared/typechecking/CustomPropTypes';
import { useCustomFormValidator } from 'shared/hooks/useCustomFormValidator';
export const ModalWithForm = ({
performRefetch,
sendNotification,
title,
button,
renderForm,
opened,
customCloseAction,
item,
modalOpeningComponent,
confirmText,
invalidPopupMessage,
className,
onModalOpenStateChange,
alwaysOpen,
i18n,
...props
}) => {
const { t } = useTranslation(null, { i18n });
const [isOpen, setOpen] = useState(alwaysOpen || false);
const {
isValid,
formElementRef,
setCustomValid,
revalidate,
} = useCustomFormValidator();
const notificationManager = useNotification();
confirmText = confirmText || t('common.buttons.create');
useEffect(() => {
if (!alwaysOpen) setOpenStatus(opened); // if alwaysOpen===true we can ignore the 'opened' prop
}, [opened]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (isOpen !== undefined) onModalOpenStateChange(isOpen);
}, [isOpen]); // eslint-disable-line react-hooks/exhaustive-deps
function setOpenStatus(status) {
if (status) {
setTimeout(() => revalidate());
LuigiClient.uxManager().addBackdrop();
} else {
LuigiClient.uxManager().removeBackdrop();
if (customCloseAction) customCloseAction();
}
setOpen(status);
}
function handleFormChanged() {
setTimeout(() => revalidate());
}
function handleFormError(title, message, isWarning) {
notificationManager.notifyError({
content: message,
title: title,
type: isWarning ? 'warning' : 'error',
});
}
function handleFormSuccess(message) {
notificationManager.notifySuccess({
content: message,
});
performRefetch();
}
function handleFormSubmit() {
if (isValid) {
formElementRef.current.dispatchEvent(
new Event('submit', { bubbles: true, cancelable: true }),
);
setOpenStatus(false);
}
}
function renderConfirmButton() {
const disabled = !isValid;
const button = (
<Button
disabled={disabled}
aria-disabled={disabled}
onClick={handleFormSubmit}
option="emphasized"
>
{confirmText}
</Button>
);
if (invalidPopupMessage && disabled) {
return (
<Tooltip
content={invalidPopupMessage}
position="top"
trigger="mouseenter"
tippyProps={{
distance: 16,
}}
>
{button}
</Tooltip>
);
}
return button;
}
const renderModalOpeningComponent = _ =>
modalOpeningComponent ? (
<div style={{ display: 'contents' }} onClick={() => setOpenStatus(true)}>
{modalOpeningComponent}
</div>
) : (
<Button
glyph={button.glyph || null}
aria-label={button.label || null}
option={button.option}
compact={button.compact || false}
disabled={!!button.disabled}
onClick={() => setOpenStatus(true)}
>
{button.text}
</Button>
);
return (
<>
{alwaysOpen ? null : renderModalOpeningComponent()}
<Dialog
className={className}
{...props}
show={isOpen}
actions={[
renderConfirmButton(),
<Button onClick={() => setOpenStatus(false)} option="transparent">
Cancel
</Button>,
]}
onClose={() => {
setOpenStatus(false);
}}
title={title}
>
{isOpen &&
renderForm({
formElementRef,
isValid,
setCustomValid,
onChange: handleFormChanged,
onError: handleFormError,
onCompleted: handleFormSuccess,
performManualSubmit: handleFormSubmit,
item: item,
})}
</Dialog>
</>
);
};
ModalWithForm.propTypes = {
performRefetch: PropTypes.func.isRequired,
title: PropTypes.string.isRequired,
renderForm: PropTypes.func.isRequired,
opened: PropTypes.bool,
customCloseAction: PropTypes.func,
item: PropTypes.object,
modalOpeningComponent: PropTypes.node,
confirmText: PropTypes.string,
invalidPopupMessage: PropTypes.string,
button: CustomPropTypes.button,
className: PropTypes.string,
onModalOpenStateChange: PropTypes.func,
alwaysOpen: PropTypes.bool, // set this to true if you want to control the modal by rendering and un-rendering it instead of the open/closed state
};
ModalWithForm.defaultProps = {
performRefetch: () => {},
invalidPopupMessage: '',
onModalOpenStateChange: () => {},
alwaysOpen: false,
};
|
const handling = (err, req, res, next) => {
if (err) {
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.error(err)
}
return res.status(err.status || 500).json(err)
}
next()
}
module.exports = { handling }
|
#!/usr/bin/env python3
import json
import os
from functools import lru_cache
from urllib.request import Request, urlopen
from urllib.parse import urlencode, quote
api_key = os.environ['API_KEY']
endpoint = 'https://api.ausmash.com.au'
def get_request(url):
return Request(url, headers={'X-ApiKey': api_key})
@lru_cache(maxsize=None)
def get_regions():
url = endpoint + '/regions'
with urlopen(get_request(url)) as r:
return json.load(r)
@lru_cache(maxsize=None)
def get_games():
url = endpoint + '/games'
with urlopen(get_request(url)) as r:
return json.load(r)
def get_characters(game_shortname):
url = endpoint + '/characters'
with urlopen(get_request(url)) as r:
return [character for character in json.load(r) if character['GameShort'] == game_shortname]
def get_player(region, name):
url = endpoint + '/players/find/{0}/{1}'.format(quote(name), region)
with urlopen(get_request(url)) as r:
return json.load(r)
def get_player_matches(player_id, start_date=None, end_date=None):
url = endpoint + '/players/{0}/matches'.format(player_id)
params = {}
if start_date:
params['startDate'] = start_date
if end_date:
params['endDate'] = end_date
if params:
url += '?' + urlencode(params)
with urlopen(get_request(url)) as r:
return json.load(r)
def get_player_event_results(player_id, start_date=None, end_date=None):
url = endpoint + '/players/{0}/results'.format(player_id)
params = {}
if start_date:
params['startDate'] = start_date
if end_date:
params['endDate'] = end_date
if params:
url += '?' + urlencode(params)
with urlopen(get_request(url)) as r:
return json.load(r)
def get_event_results(event_id):
url = endpoint + '/events/{0}/results'.format(event_id)
with urlopen(get_request(url)) as r:
return json.load(r)
|
import React from 'react';
import Layout from '../components/Layout';
import { graphql } from 'gatsby';
export const query = graphql`
query GetBlog($slug: String!){
markdownRemark(fields: {slug:{eq:$slug}}){
frontmatter{
title,
date
}
html
}
}
`
const Blog = (props) => {
return (
<Layout>
{console.log(props)}
<h1>{props.data.markdownRemark.frontmatter.title}</h1>
<p>{props.data.markdownRemark.frontmatter.date}</p>
<div dangerouslySetInnerHTML={{__html: props.data.markdownRemark.html}}></div>
</Layout>
)
}
export default Blog;
|
var recorderUi = {
init: function () {
var recorderDialog = $("\
<div id='recorderDialog'>\
<div id='recorderTitle'>Test Recorder</div>\
<div id='recorderToolBar'>\
<input type='button' id='recorderNewTestBtn' value='Reset' class='recorderToolBarButton'/>\
<input type='button' id='recorderPauseBtn' value='Pause' class='recorderToolBarButton'/>\
</div>\
<div id='recorderContent' contenteditable='true'></div>\
</div>\
");
recorderDialog.appendTo("body");
var leftPos = ($(window).width() - $('#recorderDialog').width()) / 2
, topPos = ($(window).height() - $('#recorderDialog').height()) / 2;
$('#recorderDialog').css({
'left': leftPos
, 'top': topPos
});
recorderUi.bindUiEvent();
}
, bindUiEvent: function () {
$(document).ready(function () {
var $dragging = null;
var originalLeft;
var originalTop;
var mouseLeft;
var mouseTop;
$(document.body).on("mousemove", function (e) {
if ($dragging) {
$('#recorderDialog').offset({
top: originalTop + e.clientY - mouseTop
, left: originalLeft + e.clientX - mouseLeft
});
}
});
$("#recorderTitle").on("mousedown", function (e) {
$dragging = $(this);
originalLeft = $('#recorderDialog').offset().left;
originalTop = $('#recorderDialog').offset().top;
mouseLeft = e.clientX;
mouseTop = e.clientY;
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
$("#recorderNewTestBtn").click(function () {
recorder.pause = false;
recorder.testCase = [];
recorderUi.updateTestCaseDiv();
recorder.updateBrowserCache();
});
$("#recorderPauseBtn").click(function () {
if (recorderPauseBtn.value == 'Resume') {
recorder.pause = false;
recorderPauseBtn.value = 'Pause'
}
else {
recorder.pause = true;
recorderPauseBtn.value = 'Resume'
}
});
});
}
, updateTestCaseDiv: function () {
var stepNumber = recorder.testCase.length;
var testCaseStr = ' ';
for (var i = 0; i < stepNumber; i++) {
for (var j = 0; j < recorder.testCase[i].length; j++) {
testCaseStr = testCaseStr + recorder.testCase[i][j] + ' '
}
if (i != stepNumber - 1) {
testCaseStr = testCaseStr + '<br> ';
}
}
$('#recorderContent').html(testCaseStr);
}
}
|
import json
from getpass import getpass
from fabric.operations import local, prompt
from fabric.state import env
# ~$ PATH - CONFIGURATION
# ---------------------------------------------------------------------
SERVERS_FILE = "servers.json"
HOME_PATH = "/webapps"
try:
sfile = open(SERVERS_FILE, 'r')
SERVERS = json.load(sfile)
except Exception as e:
raise Exception('servers.json file required!')
def get_config(stage="develop"):
for server in SERVERS:
if type(server) is dict and "name" in server and server["name"] == stage:
if type(server["settings"]) is dict:
return server["settings"]
raise Exception('Malformed servers.json configuration.')
def make_user(project):
return "%s_user" % project
def make_team(project):
return "%s_team" % project
def make_app(project):
return "%s_app" % project
def get_user_home(stage="develop"):
return "%(home_path)s/%(user)s" % {
"home_path": HOME_PATH,
"user": make_user(SERVERS[stage]["project"]),
}
def get_project_path(stage="develop"):
# import ipdb; ipdb.set_trace()
return "/var/www/%(domain)s" % {
"domain": SERVERS[stage]["domain"],
}
def get_project_src(stage="develop"):
return "/var/www/%(domain)s/src" % {
"domain": SERVERS[stage]["domain"],
}
def get_superuser():
username = SERVERS[env.stage]["superuser"]
password = getpass("Put password for [%s]" % username)
if len(password) == 0:
print("[vagrant] default password setted")
password = "vagrant"
return username, password
def _upload_key():
"""
Upload id_rsa.pub file to server.
This file is obtained from ssh-keygen command.
"""
try:
local("ssh-copy-id %(user)s@%(ip_addres)s" % {
"user": make_user(env.project),
"ip_addres": env.ip
})
except Exception as e:
raise Exception('Unfulfilled local requirements')
def set_stage(stage='develop'):
if stage in SERVERS.keys():
env.stage = stage
env.project = SERVERS[env.stage]["project"]
env.domain = SERVERS[env.stage]["domain"]
env.passwd = SERVERS[env.stage]["password"]
env.urls = SERVERS[env.stage]["urls"]
env.docs = SERVERS[env.stage]["docs"]
env.db_engine = SERVERS[env.stage]["db_engine"]
env.hosts = [SERVERS[env.stage]["ip_address"], ]
env.ip = SERVERS[env.stage]["ip_address"]
# env.https = SERVERS[env.stage]["https"]
else:
pass
def set_user(superuser=False):
if superuser:
env.user, env.password = get_superuser()
else:
env.user = make_user(SERVERS[env.stage]["project"])
env.password = SERVERS[env.stage]["password"]
def isolate_stage(stage):
if not env.stage == stage:
raise ValueError('This implementation is only for %s STAGE' % stage.upper())
|
import React, { useEffect, useState } from "react";
import axios from "../api/axios";
import MovieModal from "./MovieModal";
import "./Row.css";
// import Swiper core and required modules
import { Navigation, Pagination, Scrollbar, A11y } from "swiper";
import { Swiper, SwiperSlide } from "swiper/react";
// Import Swiper styles
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import "swiper/css/scrollbar";
export default function Row({ isLargeRow, title, id, fetchUrl }) {
const [movies, setMovies] = useState([]);
const [modalOpen, setModalOpen] = useState(false);
const [movieSelected, setMovieSelected] = useState({});
useEffect(() => {
fetchMovieData();
}, []);
const fetchMovieData = async () => {
const request = await axios.get(fetchUrl);
console.log("request", request);
setMovies(request.data.results);
};
const handleClick = (movie) => {
setModalOpen(true);
setMovieSelected(movie);
};
return (
<section className="row">
<h2>{title}</h2>
<Swiper
// install Swiper modules
modules={[Navigation, Pagination, Scrollbar, A11y]}
loop={true} // loop 기능을 사용할 것인지
breakpoints={{
1378: {
slidesPerView: 6, // 한번에 보이는 슬라이드 개수
slidesPerGroup: 6, // 몇개씩 슬라이드 할지
},
998: {
slidesPerView: 5,
slidesPerGroup: 5,
},
625: {
slidesPerView: 4,
slidesPerGroup: 4,
},
0: {
slidesPerView: 3,
slidesPerGroup: 3,
},
}}
navigation // arrow 버튼 사용 유무
pagination={{ clickable: true }} // 페이지 버튼 보이게 할지
>
<div id={id} className="row__posters">
{movies.map((movie) => (
<SwiperSlide>
<img
key={movie.id}
style={{ padding: "25px 0" }}
className={`row__poster ${isLargeRow && "row__posterLarge"}`}
src={`https://image.tmdb.org/t/p/original/${
isLargeRow ? movie.poster_path : movie.backdrop_path
} `}
alt={movie.name}
onClick={() => handleClick(movie)}
/>
</SwiperSlide>
))}
</div>
</Swiper>
{modalOpen && (
<MovieModal {...movieSelected} setModalOpen={setModalOpen} />
)}
</section>
);
}
// eslint-disable-next-line no-lone-blocks
{/* <section className="row">
<h2>{title}</h2>
<div className="slider">
<div className="slider__arrow-left">
<span
className="arrow"
onClick={() => {
document.getElementById(id).scrollLeft -= window.innerWidth - 80;
}}
>
{"<"}
</span>
</div>
<div id={id} className="row__posters">
{movies.map((movie) => (
<img
key={movie.id}
className={`row__poster ${isLargeRow && "row__posterLarge"}`}
src={`https://image.tmdb.org/t/p/original/${
isLargeRow ? movie.poster_path : movie.backdrop_path
} `}
alt={movie.name}
onClick={() => handleClick(movie)}
/>
))}
</div>
<div className="slider__arrow-right">
<span
className="arrow"
onClick={() => {
document.getElementById(id).scrollLeft += window.innerWidth - 80;
}}
>
{">"}
</span>
</div>
</div>
{modalOpen && (
<MovieModal {...movieSelected} setModalOpen={setModalOpen} />
)}
</section> */}
|
const { deployProxy } = require('@openzeppelin/truffle-upgrades');
const LPStakingRewardsUpgradeable = artifacts.require("LPStakingRewardsUpgradeable");
module.exports = async function (deployer, network, accounts) {
if (network === 'bscmainnet' || network === 'bscmainnet-fork') {
const rewardDistributorAddress = '0xC2573A26297a0c952C92bb48Fdcb6929524F7F48';
const skillTokenAddress = '0x154A9F9cbd3449AD22FDaE23044319D6eF2a1Fab';
const lpTokenAddress = '0x0dEB588c1EC6f1D9f348126D401f05c4c7B7a80c';
await deployProxy(LPStakingRewardsUpgradeable, [accounts[0], rewardDistributorAddress, skillTokenAddress, lpTokenAddress, 0], { deployer });
}
};
|
function rangeFromPoint(point) {
if (!document.caretRangeFromPoint) {
document.caretRangeFromPoint = (x, y) => {
const position = document.caretPositionFromPoint(x, y);
if (position && position.offsetNode && position.offsetNode.nodeType === Node.TEXT_NODE) {
const range = document.createRange();
range.setStart(position.offsetNode, position.offset);
range.setEnd(position.offsetNode, position.offset);
return range;
}
return null;
};
}
return document.caretRangeFromPoint(point.x, point.y);
}
// const _caretRangeFromPoint = (x, y) => {
// if (typeof document.caretRangeFromPoint === 'function') {
// // Chrome, Edge
// return document.caretRangeFromPoint(x, y);
// }
// if (typeof document.caretPositionFromPoint === 'function') {
// // Firefox
// return _caretPositionFromPoint(x, y);
// }
// // No support
// return null;
// };
// const _caretPositionFromPoint = (x, y) => {
// const position = document.caretPositionFromPoint(x, y);
// if (position === null) {
// return null;
// }
// const node = position.offsetNode;
// if (node === null) {
// return null;
// }
// const range = document.createRange();
// const offset = node.nodeType === Node.TEXT_NODE ? position.offset : 0;
// try {
// range.setStart(node, offset);
// range.setEnd(node, offset);
// } catch (e) {
// // Firefox throws new DOMException("The operation is insecure.")
// // when trying to select a node from within a ShadowRoot.
// return null;
// }
// return range;
// };
// const _caretRangeFromPointExt = (x, y, elements) => {
// const modifications = [];
// try {
// let i = 0;
// let startContinerPre = null;
// while (true) {
// const range = _caretRangeFromPoint(x, y);
// if (range === null) {
// return null;
// }
// const startContainer = range.startContainer;
// if (startContinerPre !== startContainer) {
// if (this._isPointInRange(x, y, range)) {
// return range;
// }
// startContinerPre = startContainer;
// }
// i = this._disableTransparentElement(elements, i, modifications);
// if (i < 0) {
// return null;
// }
// }
// } finally {
// if (modifications.length > 0) {
// this._restoreElementStyleModifications(modifications);
// }
// }
// };
// const wordRegex = /[\w'’()/,.$-]/;
class TextSourceRange {
constructor(range) {
this.rng = range;
}
text() {
return this.rng.toString();
}
setWordRange(forwardcount) {
// let backwardcount = 1
// let forwardcount = 6
if (this.rng.startContainer.data) {
this.setStartOffset(forwardcount);
this.setEndOffset(forwardcount);
}
return null;
}
// backwardcount can only be 1 now
setStartOffset(forwardcount) {
let pos = this.rng.startOffset;
let count = 0;
const text = this.rng.startContainer.textContent;
let wordStartRegex;
if (forwardcount === 1) {
wordStartRegex = /[\w'’-]/;
} else {
wordStartRegex = /[\w'’(),.-]/;
}
while (pos >= 1) {
count += wordStartRegex.test(text[pos - 1]) ? 0 : 1;
if (count === 1) {
break;
} else {
--pos;
}
}
this.rng.setStart(this.rng.startContainer, pos);
}
setEndOffset(forwardcount) {
let pos = this.rng.endOffset;
// let endContainer = this.rng.endContainer;
let text = this.rng.endContainer.textContent;
if (forwardcount === 1) {
if (!text.substr(pos).match(/[-A-Za-z']+/)) {
console.error(text.substr(pos));
return;
}
const word = text.substr(pos).match(/[-A-Za-z']+/)[0];
this.rng.setEnd(this.rng.endContainer, pos + word.length);
} else {
const wordEndRegex = /[\w'’()/,.$-]/;
const wordSpaceRegex = /[\w'’()/,.$ -]/;
let count = wordEndRegex.test(text[pos]) ? 0 : 1;
// if (pos === text.length && count < forwardcount) {
// if (endContainer.nextSibling) {
// endContainer = endContainer.nextSibling;
// text = endContainer.textContent;
// pos = 0;
// } else if (
// endContainer.parentElement.textContent === endContainer.textContent &&
// endContainer.parentElement.nextSibling
// ) {
// endContainer = endContainer.parentElement.nextSibling;
// text = endContainer.textContent;
// pos = 0;
// }
// }
while (pos < text.length && wordSpaceRegex.test(text[pos])) {
count += text[pos] === ' ' ? 1 : 0;
pos += 1;
if (count === forwardcount) {
break;
}
}
this.rng.setEnd(this.rng.endContainer, pos);
}
}
selectText() {
// this.setWordRange()
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(this.rng.cloneRange());
}
// deselect() {
// const selection = window.getSelection()
// selection.removeAllRanges()
// }
}
|
// @flow
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { createHashHistory } from 'history';
import { routerMiddleware } from 'react-router-redux';
import promiseMiddleware from 'redux-promise-middleware';
import rootReducer from '../reducers';
const history = createHashHistory();
const router = routerMiddleware(history);
const promise = promiseMiddleware({
promiseTypeSuffixes: ['START', 'SUCCESS', 'FAIL']
});
const enhancer = applyMiddleware(thunk, router, promise);
function configureStore(initialState?: any) {
return createStore(rootReducer, initialState, enhancer);
}
export default {configureStore, history};
|
import { useShipStyles } from "./usePageStyles"
import React from 'react'
const Ship = (props) => {
const {shipName, picture} = useShipStyles(props)
return (
<>
<div className={shipName}>{props.name}</div>
<div className={picture}></div>
</>
)
}
export default Ship
|
import { connect } from 'react-redux';
import Question from './Question';
import { deleteQuestion } from '../duck';
const mapStateToProps = state => {
const { isDeleting, answer, isEditingQuestion } = state.dashboard;
return {
isDeleting,
answer,
isEditingQuestion
};
};
const mapDispatchToProps = dispatch => {
return {
handleDelete: (id, category) => {
dispatch(deleteQuestion(id, category));
}
};
};
const QuestionContainer = connect(mapStateToProps, mapDispatchToProps)(
Question
);
export default QuestionContainer;
|
// The router is our entire app
var NV = new (Backbone.Router.extend({
routes: {
"": "index"
},
// instantiate/link views and models
initialize: function(){
// the crossfilter holder
this.nessus = new Nessus({
dimensions: [ 'ip',
'port',
'cvss',
'vulnid',
'vulntype']
});
// models and views
// cvss (severity) histogram
this.cvssHistogram = new Histogram({
app: this,
datasource: this.nessus,
bins: 10,
range: [0, 10],
filterOptions: { attribute:'cvss' }
});
this.cvssHistogramView = new HistogramView({
app: this,
model: this.cvssHistogram,
target:'#cvssHistogram',
barwidth: 20,
w: 220,
h: 165,
title: 'cvss'
});
// vulnerability type histogram
// NOTE: This is a hack to make categorical histograms.
// If d3 somehow supports non-numerical histograms, we can remove this
// and lighten the histogram model considerably.
var vulnTypeMap = d3.scale.ordinal()
.domain(['hole', 'port', 'note'])
.range([1,2,3]);
this.vulnTypeHistogram = new Histogram({
app: this,
datasource: this.nessus,
bins: 3,
datamap: vulnTypeMap,
filterOptions: {
attribute: 'vulntype'
}
});
this.vulnTypeHistogramView = new HistogramView({
app: this,
model: this.vulnTypeHistogram,
target:'#vulnTypeHistogram',
barwidth: 20,
w: 66,
h: 165,
title: 'vuln type'
});
// top notes histogram
this.topNoteHistogram = new Histogram({
app: this,
datasource: this.nessus,
limit: 6,
filterOptions: {
attribute: 'vulnid',
filters: [
{ attribute:'vulntype', exact:'note' }
]
}
});
this.topNoteHistogramView = new HistogramView({
app: this,
model: this.topNoteHistogram,
target:'#topNoteHistogram',
barwidth: 30,
w: 180,
h: 165,
title: 'top notes'
});
// top holes histogram
this.topHoleHistogram = new Histogram({
app: this,
datasource: this.nessus,
limit: 6,
filterOptions: {
attribute: 'vulnid',
filters: [
{ attribute:'vulntype', exact:'hole' }
]
}
});
this.topHoleHistogramView = new HistogramView({
app: this,
barwidth: 30,
model: this.topHoleHistogram,
target:'#topHoleHistogram',
w: 180,
h: 165,
title: 'top holes'
});
// treemap hierarchy
this.hierarchy = new Hierarchy({
app: this,
datasource: this.nessus
});
this.hierarchyView = new HierarchyView({
app: this,
model: this.hierarchy,
target:'#hierarchy'
});
// color view
this.colorLegend = new ColorLegend({
app: this,
datasource: this.nessus
});
this.colorLegendView = new ColorLegendView({
app: this,
model: this.colorLegend,
target:'#colorlegend'
});
// TODO treemap hierarchy view
// treemap
this.treemap = new Treemap({
app: this,
datasource: this.nessus,
hierarchy: this.hierarchy,
filterOptions: {
attribute: 'vulnid'
}
});
this.treemapView = new TreemapView({
app: this,
model: this.treemap,
color: this.colorLegend,
target:'#vis'
});
// info view
this.nessusInfo = new NessusInfo({
app: this,
datasource: this.nessus
});
this.nessusInfoView = new NessusInfoView({
app: this,
model: this.nessusInfo,
target:'#nessusinfo'
});
},
// called from outside the app
start: function(){
Backbone.history.start();
},
resize: function(){
this.trigger('resize');
}
}))();
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(React.createElement(React.Fragment, null, React.createElement("path", {
fill: "none",
d: "M0 0h24v24H0V0z"
}), React.createElement("path", {
d: "M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.61 5.64 5.36 8.04 2.35 8.36 0 10.9 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6.17c-2.09 0-3.95-1.53-4.15-3.61C1.79 12.01 3.66 10 6 10c1.92 0 3.53 1.36 3.91 3.17.1.48.5.83.98.83.61 0 1.11-.55.99-1.15-.43-2.24-2.11-4.03-4.29-4.63 1.1-1.46 2.89-2.37 4.89-2.2 2.88.25 5.01 2.82 5.01 5.71V12h1.37c1.45 0 2.79.97 3.07 2.4.39 1.91-1.08 3.6-2.93 3.6z"
})), 'FilterDramaRounded');
|
import calendar
import unittest
from configuration.setbuilders.monthday_setbuilder import MonthdaySetBuilder
class TestMonthdaySetBuilder(unittest.TestCase):
def test_name(self):
years = [2016, 2017] # leap and normal year
for year in years:
for month in range(1, 13):
_, days = calendar.monthrange(year, month)
for day in range(1, days):
self.assertEquals(MonthdaySetBuilder(year, month).build(str(day)), {day})
def test_L_wildcard(self):
years = [2016, 2017] # leap and normal year
for year in years:
for month in range(1, 13):
_, days = calendar.monthrange(year, month)
self.assertEquals(MonthdaySetBuilder(year, month).build("L"), {days})
def test_W_wildcard(self):
years = [2016, 2017] # leap and normal year
for year in years:
for month in range(1, 13):
_, days = calendar.monthrange(year, month)
for day in range(1, days):
weekday = calendar.weekday(year, month, day)
result = day
if weekday == 5:
result = day - 1 if day > 1 else day + 2
elif weekday == 6:
result = day + 1 if day < days else day - 2
self.assertEquals(MonthdaySetBuilder(year, month).build(str(day) + "W"), {result})
def test_exceptions(self):
for h in range(13, 25):
self.assertRaises(ValueError, MonthdaySetBuilder(2016, 1).build, "W")
self.assertRaises(ValueError, MonthdaySetBuilder(2016, 1).build, "32W")
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def earnings(path):
"""Earnings for Three Age Groups
a cross-section from 1988-1989
*number of observations* : 4266
*observation* : individuals
*country* : United States
A dataframe containing :
age
age groups, a factor with levels (g1,g2,g3)
y
average annual earnings, in 1982 US dollars
Mills, Jeffery A. and Sourushe Zandvakili (1997) “Statistical Inference
via Bootstrapping for Measures of Inequality”, *Journal of Applied
Econometrics*, **12(2)**, pp. 133-150.
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there.
Filename is `earnings.csv`.
Returns:
Tuple of np.ndarray `x_train` with 4266 rows and 2 columns and
dictionary `metadata` of column headers (feature names).
"""
import pandas as pd
path = os.path.expanduser(path)
filename = 'earnings.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/Ecdat/Earnings.csv'
maybe_download_and_extract(path, url,
save_file_name='earnings.csv',
resume=False)
data = pd.read_csv(os.path.join(path, filename), index_col=0,
parse_dates=True)
x_train = data.values
metadata = {'columns': data.columns}
return x_train, metadata
|
var board = {};
export default class BoardHelper {
constructor() {
this._setupNewBoard();
}
getBoard(){
return board;
}
_setupNewBoard() {
var r = {};
for (var row = 1; row <= 6; row++) {
var c={};
for (var column = 1; column <= 6; column++) {
var cell = {color: 0, shape: 0,row:row,column:column};
c[column]=cell;
}
r[row]=c;
}
board = r;
}
getColumns(columns,row){
var newColumns={};
for(var i =1;i<=columns;i++){
newColumns[i]= {color: 0, shape: 0,row:row,column:i};
}
return newColumns;
}
addRowToEnd(board,currentRows,currentColumns){
var newRow = currentRows+1;
board[newRow] = this.getColumns(currentColumns,newRow);
return board;
}
addColumnToEnd(board,currentRows,currentColumns){
var newColumn = currentColumns+ 1;
Object.keys(board).forEach((row)=>{
board[row][newColumn] ={color: 0, shape: 0,row:row,column:newColumn};
});
return board;
}
setNewColumn(column,newColumn){
column.column = newColumn;
return column;
}
addColumnToFront(board,currentRows,currentColumns) {
var newColumn = currentColumns +1;
board = this.addColumnToEnd(board,currentRows,currentColumns);
Object.keys(board).forEach((row)=>{
for(var column =newColumn;column>1;column--){
board[row][column]=this.setNewColumn(board[row][column-1],column);
}
board[row][1]={color: 0, shape: 0,row:row,column:1};
});
return board;
}
setNewRow(row,newRow){
Object.keys(row).forEach((c)=>{
row[c].row=newRow;
});
return row;
}
addRowToFront(board,currentRows,currentColumns) {
var newRow = currentRows+1;
board= this.addRowToEnd(board,currentRows,currentColumns);
for(var row = newRow;row>1;row--){
board[row]=this.setNewRow(board[row-1],row);
}
board[1]=this.getColumns(currentColumns,1);
return board;
}
checkForAddRowColumn(state,cell){
if (cell.row==state.currentRows){
state.game.board = this.addRowToEnd(state.game.board,state.currentRows,state.currentColumns);
//state.lastPiecesPlayed = updateLastPiecesPlayed(state.lastPiecesPlayed,{row:-1});
state.currentRows = state.currentRows +1;
}
if (cell.column==state.currentColumns){
state.game.board = this.addColumnToEnd(state.game.board,state.currentRows,state.currentColumns);
//state.lastPiecesPlayed = updateLastPiecesPlayed(state.lastPiecesPlayed,{column:-1});
state.currentColumns = state.currentColumns + 1;
}
if(cell.column == 1){
state.game.board = this.addColumnToFront(state.game.board,state.currentRows,state.currentColumns);
state.lastPiecesPlayed = this.updateLastPiecesPlayed(state.lastPiecesPlayed,{column:1});
state.currentColumns = state.currentColumns + 1;
}
if (cell.row==1){
state.game.board = this.addRowToFront(state.game.board,state.currentRows,state.currentColumns);
state.lastPiecesPlayed = this.updateLastPiecesPlayed(state.lastPiecesPlayed,{row:1});
state.currentRows = state.currentRows +1;
}
console.log("state at end of check",state);
return state;
}
updateLastPiecesPlayed(lastPiecesPlayed,operation){
for(var i=0;i<lastPiecesPlayed.length;i++){
if (operation.row) {
console.log("updateing row");
lastPiecesPlayed[i].cell.row = lastPiecesPlayed[i].cell.row + (operation.row);
}
if (operation.column){
console.log("updating columns");
lastPiecesPlayed[i].cell.column = lastPiecesPlayed[i].cell.column + (operation.column);
}
}
return lastPiecesPlayed;
}
}
|
import urllib.request
page = urllib.request.urlopen("http://www.chiark.greenend.org.uk/~sgtatham/puzzles/").read().decode()
puzzles = page.split("""<span class="puzzle">""")
with open("descriptions.h", "w") as f:
print("NSString *GameDescriptions[][2] = {", file=f)
for p in puzzles[1:]:
r = p.split("<tr>")
name = r[1][r[1].index(">")+1:r[1].index("<", 1)]
desc = r[4][r[4].index(">")+1:r[4].index("</td>", 2)].replace("\n", " ").rstrip()
desc = desc.replace("<code>></code>", ">")
assert "<" not in desc, desc
assert '"' not in desc, desc
print(' {{@"{}", @"{}"}},'.format(name, desc), file=f)
print("};", file=f)
|
# https://github.com/gevent/gevent/issues/615
# Under Python 3, with its use of importlib,
# if the monkey patch is done when the importlib import lock is held
# (e.g., during recursive imports) we could fail to release the lock.
# This is surprisingly common.
__import__('_import_import_patch')
|
import React, { useState } from "react"
import styled from "styled-components"
import { graphql } from "gatsby"
import { useIntl } from "gatsby-plugin-intl"
import Translation from "../../components/Translation"
import { translateMessageId } from "../../utils/translations"
import Icon from "../../components/Icon"
import ButtonLink from "../../components/ButtonLink"
import Link from "../../components/Link"
import Modal from "../../components/Modal"
import PageMetadata from "../../components/PageMetadata"
import Pill from "../../components/Pill"
import Tag from "../../components/Tag"
import TutorialTags from "../../components/TutorialTags"
import Emoji from "../../components/Emoji"
import { Page, ButtonSecondary } from "../../components/SharedStyledComponents"
import { getLocaleTimestamp, INVALID_DATETIME } from "../../utils/time"
import { hasTutorials } from "../../utils/translations"
const SubSlogan = styled.p`
font-size: 20px;
line-height: 140%;
color: ${(props) => props.theme.colors.text200};
margin-bottom: 1rem;
text-align: center;
`
const TutorialCard = styled(Link)`
text-decoration: none;
display: flex;
flex-direction: column;
justify-content: space-between;
color: ${(props) => props.theme.colors.text} !important;
box-shadow: 0 1px 1px ${(props) => props.theme.colors.tableItemBoxShadow};
margin-bottom: 1px;
padding: 2rem;
width: 100%;
color: #000;
&:hover {
border-radius: 4px;
box-shadow: 0 0 1px ${(props) => props.theme.colors.primary};
background: ${(props) => props.theme.colors.tableBackgroundHover};
}
`
const TutorialContainer = styled.div`
box-shadow: ${(props) => props.theme.colors.tableBoxShadow};
margin-bottom: 2rem;
margin-top: 2rem;
width: 66%;
@media (max-width: ${(props) => props.theme.breakpoints.m}) {
width: 100%;
}
`
const StyledPage = styled(Page)`
margin-top: 4rem;
`
const PillContainer = styled.div`
display: flex;
flex-wrap: wrap;
width: 100%;
`
const About = styled.p`
color: ${(props) => props.theme.colors.text200};
`
const Author = styled.p`
color: ${(props) => props.theme.colors.text200};
font-size: 14px;
text-transform: uppercase;
`
const Title = styled.p`
color: ${(props) => props.theme.colors.text};
font-weight: 600;
font-size: 24px;
margin-right: 6rem;
@media (max-width: ${(props) => props.theme.breakpoints.m}) {
margin-right: 0rem;
}
`
const PageTitle = styled.h1`
font-style: normal;
font-weight: normal;
font-family: "SFMono-Regular", monospace;
text-transform: uppercase;
font-weight: 600;
font-size: 32px;
line-height: 140%;
text-align: center;
margin: 0 0 1.625rem;
@media (max-width: ${(props) => props.theme.breakpoints.s}) {
margin: 1rem;
}
`
const TitleContainer = styled.div`
display: flex;
justify-content: space-between;
margin-bottom: -1rem;
align-items: flex-start;
@media (max-width: ${(props) => props.theme.breakpoints.m}) {
flex-direction: column;
margin-bottom: 2rem;
}
`
const TagsContainer = styled.div`
display: flex;
justify-content: center;
margin: 2rem 2rem;
padding-bottom: 2rem;
border-bottom: 1px solid ${(props) => props.theme.colors.border};
@media (max-width: ${(props) => props.theme.breakpoints.m}) {
flex-direction: column;
padding: 1rem 0rem;
}
`
const TagContainer = styled.div`
display: flex;
flex-wrap: wrap;
align-items: center;
@media (max-width: ${(props) => props.theme.breakpoints.m}) {
max-width: 100%;
margin-bottom: 1rem;
}
`
const ClearLink = styled.button`
color: ${(props) => props.theme.colors.primary};
text-decoration: underline;
background: none;
border: none;
cursor: pointer;
`
const ResultsContainer = styled.div`
margin-top: 0rem;
text-align: center;
padding: 3rem;
`
const GithubButton = styled(ButtonLink)`
display: flex;
align-items: center;
justify-content: center;
margin-right: 0.5rem;
`
const GithubIcon = styled(Icon)`
fill: ${(props) => props.theme.colors.text};
margin-right: 0.5rem;
`
const ModalBody = styled.div`
display: flex;
@media (max-width: ${(props) => props.theme.breakpoints.m}) {
flex-direction: column;
max-height: 16rem;
overflow-y: scroll;
}
`
const ModalOption = styled.div`
border: 1px solid ${(props) => props.theme.colors.border};
border-radius: 4px;
padding: 1rem;
display: flex;
flex-direction: column;
width: 50%;
margin: 0.5rem;
justify-content: space-between;
margin-left: 0rem;
margin-bottom: 1.5rem;
@media (max-width: ${(props) => props.theme.breakpoints.m}) {
width: 100%;
}
`
const ModalTitle = styled.h2`
margin-top: 0;
margin-bottom: 1rem;
`
const published = (locale, published) => {
const localeTimestamp = getLocaleTimestamp(locale, published)
return localeTimestamp !== INVALID_DATETIME ? (
<span>
<Emoji text=":calendar:" size={1} ml={`0.5em`} mr={`0.5em`} />{" "}
{localeTimestamp} •
</span>
) : null
}
const TutorialsPage = ({ data, pageContext }) => {
const intl = useIntl()
// Filter tutorials by language and map to object
const allTutorials = data.allTutorials.nodes
.filter((tutorial) =>
hasTutorials(pageContext.language)
? tutorial.frontmatter.lang === pageContext.language
: tutorial.frontmatter.lang === "en"
)
.map((tutorial) => ({
to:
tutorial.fields.slug.substr(0, 3) === "/en"
? tutorial.fields.slug.substr(3)
: tutorial.fields.slug,
title: tutorial.frontmatter.title,
description: tutorial.frontmatter.description,
author: tutorial.frontmatter.author,
tags: tutorial.frontmatter.tags.map((tag) => tag.toLowerCase().trim()),
skill: tutorial.frontmatter.skill,
timeToRead: tutorial.timeToRead,
published: tutorial.frontmatter.published,
}))
// Tally all subject tag counts
const tagsConcatenated = []
for (const tutorial of allTutorials) {
tagsConcatenated.push(...tutorial.tags)
}
const allTags = tagsConcatenated.map((tag) => ({ name: tag, totalCount: 1 }))
const sanitizedAllTags = Array.from(
allTags.reduce(
(m, { name, totalCount }) =>
m.set(
name.toLowerCase().trim(),
(m.get(name.toLowerCase().trim()) || 0) + totalCount
),
new Map()
),
([name, totalCount]) => ({ name, totalCount })
).sort((a, b) => a.name.localeCompare(b.name))
const [state, setState] = useState({
activeTagNames: [],
filteredTutorials: allTutorials,
})
const clearActiveTags = () => {
setState({ activeTagNames: [], filteredTutorials: allTutorials })
}
const handleTagSelect = (tagName) => {
const activeTagNames = state.activeTagNames
// Add or remove the selected tag
const index = activeTagNames.indexOf(tagName)
if (index > -1) {
activeTagNames.splice(index, 1)
} else {
activeTagNames.push(tagName)
}
// If no tags are active, show all tutorials, otherwise filter by active tag
let filteredTutorials = allTutorials
if (activeTagNames.length > 0) {
filteredTutorials = allTutorials.filter((tutorial) => {
for (const tag of activeTagNames) {
if (!tutorial.tags.includes(tag)) {
return false
}
}
return true
})
}
setState({ activeTagNames, filteredTutorials })
}
const hasActiveTags = state.activeTagNames.length > 0
const hasNoTutorials = state.filteredTutorials.length === 0
const [isModalOpen, setModalOpen] = useState(false)
return (
<StyledPage>
<PageMetadata
title={translateMessageId("page-tutorials-meta-title", intl)}
description={translateMessageId(
"page-tutorials-meta-description",
intl
)}
/>
<PageTitle>
<Translation id="page-tutorial-title" />
</PageTitle>
<SubSlogan>
<Translation id="page-tutorial-subtitle" />
</SubSlogan>
<Modal isOpen={isModalOpen} setIsOpen={setModalOpen}>
<ModalTitle>
<Translation id="page-tutorial-submit-btn" />
</ModalTitle>
<p>
<Translation id="page-tutorial-listing-policy-intro" />{" "}
<Link to="https://cloiinkcoin.com/en/contributing/adding-articles/">
<Translation id="page-tutorial-listing-policy" />
</Link>
</p>
<p>
<Translation id="page-tutorial-submit-tutorial" />
</p>
<ModalBody>
<ModalOption>
<p>
<b>
<Translation id="page-tutorial-new-github" />
</b>
<br />
<Translation id="page-tutorial-new-github-desc" />
</p>
<GithubButton
isSecondary
to="https://github.com/cloiinkcoin/cloiinkcoin-org-website/issues/new?assignees=&labels=Type%3A+Feature&template=suggest_tutorial.md&title="
>
<GithubIcon name="github" />{" "}
<span>
<Translation id="page-tutorial-raise-issue-btn" />
</span>
</GithubButton>
</ModalOption>
<ModalOption>
<p>
<b>
<Translation id="page-tutorial-pull-request" />
</b>
<br />
<Translation id="page-tutorial-pull-request-desc-1" />{" "}
<code>
<Translation id="page-tutorial-pull-request-desc-2" />
</code>{" "}
<Translation id="page-tutorial-pull-request-desc-3" />
</p>
<GithubButton
isSecondary
to="https://github.com/cloiinkcoin/cloiinkcoin-org-website/new/dev/src/content/developers/tutorials"
>
<GithubIcon name="github" />{" "}
<span>
<Translation id="page-tutorial-pull-request-btn" />
</span>
</GithubButton>
</ModalOption>
</ModalBody>
</Modal>
<ButtonSecondary onClick={() => setModalOpen(true)}>
<Translation id="page-tutorial-submit-btn" />
</ButtonSecondary>
<TutorialContainer>
<TagsContainer>
<TagContainer>
{sanitizedAllTags.map((tag) => {
const name = `${tag.name} (${tag.totalCount})`
const isActive = state.activeTagNames.includes(tag.name)
return (
<Tag
name={name}
key={name}
isActive={isActive}
shouldShowIcon={false}
onSelect={handleTagSelect}
value={tag.name}
/>
)
})}
{hasActiveTags && (
<ClearLink onClick={clearActiveTags}>
<Translation id="page-find-wallet-clear" />
</ClearLink>
)}
</TagContainer>
</TagsContainer>
{hasNoTutorials && (
<ResultsContainer>
<Emoji text=":crying_face:" size={3} mb={`2em`} mt={`2em`} />
<h2>
<Translation id="page-tutorial-tags-error" />{" "}
<b>
<Translation id="page-find-wallet-yet" />
</b>
</h2>
<p>
<Translation id="page-find-wallet-try-removing" />
</p>
</ResultsContainer>
)}
{state.filteredTutorials.map((tutorial) => {
return (
<TutorialCard key={tutorial.to} to={tutorial.to}>
<TitleContainer>
<Title>{tutorial.title}</Title>
<Pill isSecondary={true}>{tutorial.skill}</Pill>
</TitleContainer>
<Author>
<Emoji text=":writing_hand:" size={1} mr={`0.5em`} />
{tutorial.author} •{published(intl.locale, tutorial.published)}
<Emoji text=":stopwatch:" size={1} ml={`0.5em`} mr={`0.5em`} />
{tutorial.timeToRead}{" "}
<Translation id="page-tutorial-read-time" />
</Author>
<About>{tutorial.description}</About>
<PillContainer>
<TutorialTags tags={tutorial.tags} />
</PillContainer>
</TutorialCard>
)
})}
</TutorialContainer>
</StyledPage>
)
}
export default TutorialsPage
export const query = graphql`
query {
allTutorials: allMdx(
filter: { slug: { regex: "/tutorials/" } }
sort: { fields: frontmatter___published, order: DESC }
) {
nodes {
fields {
slug
}
frontmatter {
title
description
tags
author
skill
published
lang
}
timeToRead
}
}
}
`
|
"""
Purpose:
*.
"""
import pytest
from leafy.graph import Graph
from leafy.digraph import DFS
from .utils import disanostics_table, dfs_diagnostics
"""
Test DFS.is_dag
Test DFS.topological_order
Test DFS.reverse_topological_order
"""
def small_dag():
dag = Graph(13, True)
dag.add_edge(0, 1)
dag.add_edge(0, 2)
dag.add_edge(0, 3)
dag.add_edge(0, 5)
dag.add_edge(0, 6)
dag.add_edge(2, 3)
dag.add_edge(3, 4)
dag.add_edge(3, 5)
dag.add_edge(4, 9)
dag.add_edge(6, 4)
dag.add_edge(6, 9)
dag.add_edge(7, 6)
dag.add_edge(8, 7)
dag.add_edge(9, 10)
dag.add_edge(9, 11)
dag.add_edge(9, 12)
dag.add_edge(11, 12)
return dag
@pytest.fixture()
def dag_dfs():
dag = small_dag()
dfs = DFS(dag, 0)
dfs.run()
return dfs
class TestDagDFS:
def test_is_dag(self, dag_dfs):
assert dag_dfs.is_dag is True, dfs_diagnostics(dag_dfs)
def test_topological_sort(self, dag_dfs):
assert list(dag_dfs.topological_order()) == [
0, 6, 2, 3, 5, 4, 9, 11, 12, 10, 1
], dfs_diagnostics(dag_dfs)
def test_reverse_topological_sort(self, dag_dfs):
assert list(dag_dfs.reverse_topological_order()) == [
1, 10, 12, 11, 9, 4, 5, 3, 2, 6, 0
], dfs_diagnostics(dag_dfs)
|
const BackboneElement = require('./BackboneElement');
const PositiveIntScalar = require('./scalars/PositiveInt.scalar');
class ClaimResponseProcessNote extends BackboneElement {
constructor(opt) {
super(opt);
this.__resourceType = 'ClaimResponseProcessNote';
Object.assign(this, opt);
}
// This is a ClaimResponseProcessNote resource
static get __resourceType() {
return 'ClaimResponseProcessNote';
}
// An integer associated with each note which may be referred to from each service line item.
get number() {
return this.__number;
}
set number(new_value) {
// Throw if new value does not match the pattern
let pattern = PositiveIntScalar.regex();
if (new_value && !pattern.test(new_value)) {
throw new Error(`Invalid format for ${new_value} on field number`);
}
this.__number = new_value;
}
// The note purpose: Print/Display.
get type() {
return this.__type;
}
set type(new_value) {
const CodeableConcept = require('./CodeableConcept');
this.__type = new CodeableConcept(new_value);
}
// The note text.
get text() {
return this.__text;
}
set text(new_value) {
this.__text = new_value;
}
// The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. \'en\' for English, or \'en-US\' for American English versus \'en-EN\' for England English.
get language() {
return this.__language;
}
set language(new_value) {
const CodeableConcept = require('./CodeableConcept');
this.__language = new CodeableConcept(new_value);
}
toJSON() {
return Object.assign(super.toJSON(), {
number: this.__number,
type: this.__type && this.__type.toJSON(),
text: this.__text,
language: this.__language && this.__language.toJSON(),
});
}
}
module.exports = ClaimResponseProcessNote;
|
const vscode = require('vscode')
const { vueEventsCompletion } = require('./_vueEvents')
module.exports = function(context) {
context.subscriptions.push(vscode.languages.registerCompletionItemProvider("vue", vueEventsCompletion, '@'))
}
|
import { celebrate, Segments, Joi } from 'celebrate';
export default celebrate({
[Segments.BODY]: Joi.object().keys({
email: Joi.string()
.email()
.required(),
}),
});
|
"""Hyper parameters."""
__author__ = 'Erdene-Ochir Tuguldur'
class HParams:
"""Hyper parameters"""
disable_progress_bar = False # set True if you don't want the progress bar in the console
logdir = "logdir" # log dir where the checkpoints and tensorboard files are saved
# audio.py options, these values are from https://github.com/Kyubyong/dc_tts/blob/master/hyperparams.py
reduction_rate = 4 # melspectrogram reduction rate, don't change because SSRN is using this rate
n_fft = 2048 # fft points (samples)
n_mels = 80 # Number of Mel banks to generate
power = 1.5 # Exponent for amplifying the predicted magnitude
n_iter = 50 # Number of inversion iterations
preemphasis = .97
max_db = 100
ref_db = 20
sr = 22050 # Sampling rate
frame_shift = 0.0125 # seconds
frame_length = 0.05 # seconds
hop_length = int(sr * frame_shift) # samples. =276.
win_length = int(sr * frame_length) # samples. =1102.
max_N = 300 # Maximum number of characters.
max_T = 400 # Maximum number of mel frames.
e = 128 # embedding dimension
d = 256 # Text2Mel hidden unit dimension
c = 512+128 # SSRN hidden unit dimension
dropout_rate = 0.05 # dropout
dataset_dir = '/m/home/home4/48/kausiar1/unix/tts_data/esfan_vid'
# Text2Mel network options
text2mel_lr = 0.0003 # learning rate
text2mel_max_iteration = 600000 # max train step
text2mel_weight_init = 'none' # 'kaiming', 'xavier' or 'none'
text2mel_normalization = 'layer' # 'layer', 'weight' or 'none'
text2mel_basic_block = 'gated_conv' # 'highway', 'gated_conv' or 'residual'
text2mel_save_every = 1500
text2mel_lr_decay = False
# Synthesize
synthesize_samples_dir = 'esfan_vid'
# SSRN network options
ssrn_lr = 0.0005 # learning rate
ssrn_max_iteration = 150000 # max train step
ssrn_weight_init = 'kaiming' # 'kaiming', 'xavier' or 'none'
ssrn_normalization = 'weight' # 'layer', 'weight' or 'none'
ssrn_basic_block = 'residual' # 'highway', 'gated_conv' or 'residual'
|
/**
* Copyright (c) 2018-2021 Noel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
module.exports = {
plugins: {
autoprefixer: {},
tailwindcss: {},
},
};
|
# project/server/models.py
import jwt
import datetime
from project.server import app, db, bcrypt
class User(db.Model):
""" User Model for storing user related details """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
registered_on = db.Column(db.DateTime, nullable=False)
admin = db.Column(db.Boolean, nullable=False, default=False)
def __init__(self, email, password, admin=False):
self.email = email
self.password = bcrypt.generate_password_hash(
password, app.config.get('BCRYPT_LOG_ROUNDS')
).decode()
self.registered_on = datetime.datetime.now()
self.admin = admin
def encode_auth_token(self, user_id):
"""
Generates the Auth Token
:return: string
"""
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=60),
'iat': datetime.datetime.utcnow(),
'sub': user_id
}
return jwt.encode(
payload,
app.config.get('SECRET_KEY'),
algorithm='HS256'
)
except Exception as e:
return e
@staticmethod
def decode_auth_token(auth_token):
"""
Validates the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
if is_blacklisted_token:
return 'Token blacklisted. Please log in again.'
else:
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt.InvalidTokenError:
return 'Invalid token. Please log in again.'
class BlacklistToken(db.Model):
"""
Token Model for storing JWT tokens
"""
__tablename__ = 'blacklist_tokens'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
token = db.Column(db.String(500), unique=True, nullable=False)
blacklisted_on = db.Column(db.DateTime, nullable=False)
def __init__(self, token):
self.token = token
self.blacklisted_on = datetime.datetime.now()
def __repr__(self):
return '<id: token: {}'.format(self.token)
@staticmethod
def check_blacklist(auth_token):
# check whether auth token has been blacklisted
res = BlacklistToken.query.filter_by(token=str(auth_token)).first()
if res:
return True
else:
return False
|
var charsEndIndex = require('./_charsEndIndex'),
charsStartIndex = require('./_charsStartIndex'),
stringToArray = require('./_stringToArray'),
toString = require('./toString');
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (!string) {
return string;
}
if (guard || chars === undefined) {
return string.replace(reTrim, '');
}
chars = (chars + '');
if (!chars) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars);
return strSymbols
.slice(charsStartIndex(strSymbols, chrSymbols), charsEndIndex(strSymbols, chrSymbols) + 1)
.join('');
}
module.exports = trim;
|
/*=========================================================================================
File Name: material-datatables.js
Description: Material Datatable
----------------------------------------------------------------------------------------
Item Name: Modern Admin - Clean Bootstrap 4 Dashboard HTML Template
Version: 3.0
Author: PIXINVENT
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
$(document).ready(function() {
$('.material-table').DataTable();
});
|
{"version":3,"file":"script.min.js","sources":["script.js"],"names":["window","JCSaleGiftSection","BasketButton","params","superclass","constructor","apply","this","arguments","nameNode","BX","create","props","className","id","text","buttonNode","attrs","ownerClass","style","marginBottom","borderBottom","children","events","contextEvents","browser","IsIE","setAttribute","extend","PopupWindowButton","arParams","productType","showQuantity","showBuyBtn","showAbsent","secondPict","showOldPrice","showPercent","showSkuProps","visual","ID","PICT_ID","SECOND_PICT_ID","QUANTITY_ID","QUANTITY_UP_ID","QUANTITY_DOWN_ID","PRICE_ID","DSC_PERC","SECOND_DSC_PERC","DISPLAY_PROP_DIV","BASKET_PROP_DIV","product","checkQuantity","maxQuantity","stepQuantity","isDblQuantity","canBuy","canSubscription","name","pict","addUrl","buyUrl","basketData","useProps","emptyProps","quantity","basketUrl","defaultPict","precision","precisionFactor","Math","pow","offers","offerNum","treeProps","obTreeRows","showCount","showStart","selectedValues","obProduct","obQuantity","obQuantityUp","obQuantityDown","obPict","obSecondPict","obPrice","obTree","obBuyBtn","obDscPerc","obSecondDscPerc","obSkuProps","obMeasure","obPopupWin","basketParams","treeRowShowSize","treeEnableArrow","display","cursor","opacity","treeDisableArrow","lastElement","containerHeight","errorCode","parseInt","PRODUCT_TYPE","SHOW_QUANTITY","SHOW_BUY_BTN","SHOW_ABSENT","SECOND_PICT","SHOW_OLD_PRICE","SHOW_DISCOUNT_PERCENT","SHOW_SKU_PROPS","VISUAL","PRODUCT","CHECK_QUANTITY","QUANTITY_FLOAT","parseFloat","MAX_QUANTITY","STEP_QUANTITY","round","CAN_BUY","SUBSCRIPTION","NAME","PICT","ADD_URL","BUY_URL","BASKET","ADD_PROPS","EMPTY_PROPS","OFFERS","type","isArray","OFFER_SELECTED","isNaN","TREE_PROPS","DEFAULT_PICTURE","PICTURE","PICTURE_SECOND","QUANTITY","PROPS","BASKET_URL","LAST_ELEMENT","ready","delegate","Init","prototype","i","strPrefix","TreeItems","TREE_ID","TREE_ITEM_ID","length","LEFT","RIGHT","LIST","CONT","QUANTITY_MEASURE","BUY_ID","hide","bind","QuantityUp","QuantityDown","QuantityChange","findChildren","tagName","SelectOfferProp","RowLeft","RowRight","SetCurrent","Basket","parentNode","offsetHeight","setHeight","checkHeight","clearHeight","adjust","height","curValue","boolSet","value","QuantitySet","index","addClass","removeClass","innerHTML","message","disabled","MEASURE","html","strTreeValue","arTreeItem","RowItems","target","proxy_context","hasAttribute","getAttribute","split","SearchOfferPropIndex","strPropID","strPropValue","strName","arShowValues","j","arCanBuyValues","arFilter","tmpFilter","GetRowValues","util","in_array","clone","GetCanBuy","UpdateRow","ChangeInfo","marginLeft","intNumber","activeID","showID","canBuyID","showI","countShow","strNewLen","obData","pictMode","extShowMode","isCurrent","selectIndex","obLeft","obRight","currentShowStart","SHOW_MODE","width","paddingTop","arValues","boolSearch","boolOneSearch","TREE","current","strPrice","PREVIEW_PICTURE","backgroundImage","SRC","PREVIEW_PICTURE_SECOND","DISPLAY_PROPERTIES","PRICE","PRINT_DISCOUNT_VALUE","DISCOUNT_VALUE","VALUE","PRINT_VALUE","DISCOUNT_DIFF_PERCENT","InitBasketUrl","ajax_basket","FillBasketProps","propCollection","foundValues","obBasketProps","contentContainer","getElementsByTagName","toLowerCase","checked","SendToBasket","ajax","loadJSON","BasketResult","contentBasketProps","InitPopupWindow","setTitleBar","content","marginRight","whiteSpace","setContent","setButtons","click","show","arResult","strContent","strPict","successful","buttons","close","STATUS","reload","onCustomEvent","location","href","MESSAGE","PopupWindowManager","autoHide","offsetLeft","offsetTop","overlay","closeByEsc","titleBar","closeIcon","top","right"],"mappings":"CAAA,SAAWA,GAEX,KAAMA,EAAOC,kBACb,CACC,OAGD,GAAIC,GAAe,SAASC,GAE3BD,EAAaE,WAAWC,YAAYC,MAAMC,KAAMC,UAChDD,MAAKE,SAAWC,GAAGC,OAAO,QACzBC,OAAUC,UAAY,yBAA0BC,GAAKP,KAAKO,IAC1DC,KAAMZ,EAAOY,MAE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zO,KAAK4D,YAAYR,KAAKqL,GAEvB,OAEDkC,EAAa,2EAA2EC,EAAQ,8CAA8C3E,EAAQ,YACtJ6E,IACC,GAAInR,IACHgB,WAAYX,KAAKwE,UAAU2F,WAAWA,WAAWA,WAAW7J,UAC5DE,KAAML,GAAG+K,QAAQ,mCACjBlK,QACCwP,MAAOrQ,GAAGqI,SAAS,WAClB2I,SAASC,OAAUpR,KAAKuD,WAAWI,UAAY3D,KAAKuD,WAAWI,UAAYxD,GAAG+K,QAAQ,mBACpFlL,cAMP,CACC2Q,IAAgBD,EAASW,QAAUX,EAASW,QAAUlR,GAAG+K,QAAQ,2BACjE4F,IACC,GAAInR,IACHgB,WAAYX,KAAKwE,UAAU2F,WAAWA,WAAWA,WAAW7J,UAC5DE,KAAML,GAAG+K,QAAQ,yBACjBlK,QACCwP,MAAOrQ,GAAGqI,SAASxI,KAAKqF,WAAW0L,MAAO/Q,KAAKqF,gBAKnDrF,KAAKiQ,iBACLjQ,MAAKqF,WAAW6K,aACfC,QAAShQ,GAAGC,OAAO,OAClBQ,OAASwP,YAAa,OAAQC,WAAY,UAC1C7P,KAAOqQ,EAAa1Q,GAAG+K,QAAQ,wBAA0B/K,GAAG+K,QAAQ,sBAGtElL,MAAKqF,WAAWiL,WAAWK,EAC3B3Q,MAAKqF,WAAWkL,WAAWO,EAC3B9Q,MAAKqF,WAAWoL,OAGjBhR,GAAOC,kBAAkBgJ,UAAUuH,gBAAkB,WAEpD,KAAMjQ,KAAKqF,WACX,CACC,OAEDrF,KAAKqF,WAAalF,GAAGmR,mBAAmBlR,OAAO,wBAAwBJ,KAAKgC,OAAOC,GAAI,MACtFsP,SAAU,MACVC,WAAY,EACZC,UAAW,EACXC,QAAU,KACVC,WAAY,KACZC,SAAU,KACVC,WAAYC,IAAK,OAAQC,MAAO,aAG/BtS"}
|
"""
Implementation of wrapper API
"""
import os
import sys
import ctypes
import numpy
from google import protobuf
from . import utils
from .exceptions import ARTM_EXCEPTION_BY_CODE
from .spec import ARTM_API
class LibArtm(object):
def __init__(self, lib_name=None, logging_config=None):
self.cdll = self._load_cdll(lib_name)
# adding specified functions
for spec in ARTM_API:
func = self.cdll[spec.name]
setattr(self, spec.name, self._wrap_call(func, spec))
# TODO: add docstring for wrapped function
if logging_config is not None:
self.ArtmConfigureLogging(logging_config)
def _load_cdll(self, lib_name):
# choose default library name
default_lib_name = 'libartm.so'
if sys.platform.startswith('win'):
default_lib_name = 'artm.dll'
if sys.platform.startswith('darwin'):
default_lib_name = 'libartm.dylib'
if lib_name is None:
# try to get library path from environment variable
lib_name = os.environ.get('ARTM_SHARED_LIBRARY')
if lib_name is None:
# set the default library name
lib_name = default_lib_name
try:
cdll = ctypes.CDLL(lib_name)
except OSError as e:
exception_message = (
e.message + '\n'
'Failed to load artm shared library. '
'Try to add the location of `{default_lib_name}` file into your PATH '
'system variable, or to set ARTM_SHARED_LIBRARY - a specific system variable '
'which may point to `{default_lib_name}` file, including the full path.'
).format(**locals())
raise OSError(exception_message)
return cdll
def version(self):
self.cdll.ArtmGetVersion.restype = ctypes.c_char_p
return self.cdll.ArtmGetVersion()
def _check_error(self, error_code):
if error_code < -1:
self.cdll.ArtmGetLastErrorMessage.restype = ctypes.c_char_p
error_message = self.cdll.ArtmGetLastErrorMessage()
# remove exception name from error message
error_message = error_message.split(':', 1)[-1].strip()
exception_class = ARTM_EXCEPTION_BY_CODE.get(error_code)
if exception_class is not None:
raise exception_class(error_message)
else:
raise RuntimeError(error_message)
def _get_requested_message(self, length, func):
message_blob = ctypes.create_string_buffer(length)
error_code = self.cdll.ArtmCopyRequestedMessage(length, message_blob)
self._check_error(error_code)
message = func()
message.ParseFromString(message_blob)
return message
def _wrap_call(self, func, spec):
def artm_api_call(*args):
# check the number of arguments
n_args_given = len(args)
n_args_takes = len(spec.arguments)
if n_args_given != n_args_takes:
raise TypeError('{func_name} takes {n_takes} argument ({n_given} given)'.format(
func_name=spec.name,
n_takes=n_args_takes,
n_given=n_args_given,
))
c_args = []
for (arg_pos, arg_value), (arg_name, arg_type) in zip(enumerate(args), spec.arguments):
# try to cast argument to the required type
arg_casted = arg_value
if issubclass(arg_type, protobuf.message.Message) and isinstance(arg_value, dict):
# dict -> protobuf message
arg_casted = utils.dict_to_message(arg_value, arg_type)
# check argument type
if not isinstance(arg_casted, arg_type):
raise TypeError('Argument {arg_position} ({arg_name}) should have '
'type {arg_type} but {given_type} given'.format(
arg_position=arg_pos,
arg_name=arg_name,
arg_type=str(arg_type),
given_type=str(type(arg_value)),
))
arg_value = arg_casted
# construct c-style arguments
if issubclass(arg_type, basestring):
arg_cstr_p = ctypes.create_string_buffer(arg_value)
c_args.append(arg_cstr_p)
elif issubclass(arg_type, protobuf.message.Message):
message_str = arg_value.SerializeToString()
message_cstr_p = ctypes.create_string_buffer(message_str)
c_args += [len(message_str), message_cstr_p]
elif issubclass(arg_type, numpy.ndarray):
c_args += [arg_value.nbytes, ctypes.c_char_p(arg_value.ctypes.data)]
else:
c_args.append(arg_value)
# make api call
if spec.result_type is not None:
func.restype = spec.result_type
result = func(*c_args)
self._check_error(result)
# return result value
if spec.request_type is not None:
return self._get_requested_message(length=result, func=spec.request_type)
if spec.result_type is not None:
return result
return artm_api_call
|
describe('Ionic ActionSheet Service', function() {
var sheet, timeout, ionicPlatform;
beforeEach(module('ionic'));
beforeEach(inject(function($ionicActionSheet, $timeout, $ionicPlatform) {
sheet = $ionicActionSheet;
timeout = $timeout;
ionicPlatform = $ionicPlatform;
}));
it('Should show', function() {
var s = sheet.show();
expect(s.el.classList.contains('active')).toBe(true);
});
it('Should add .action-sheet-up to .action-sheet-wrapper', function() {
var s = sheet.show();
var el = angular.element(s.el);
var wrapper = angular.element(s.el.querySelector('.action-sheet-wrapper'));
expect(wrapper.length).toEqual(1);
expect(wrapper.hasClass('action-sheet-up')).toEqual(false);
timeout.flush();
expect(wrapper.hasClass('action-sheet-up')).toEqual(true);
});
it('should handle hardware back button', function() {
var s = sheet.show();
ionicPlatform.hardwareBackButtonClick();
expect(s.el.classList.contains('active')).toBe(false);
});
it('show & hide should add action-sheet-open to body', inject(function($animate) {
var s = sheet.show();
expect(angular.element(document.body).hasClass('action-sheet-open')).toBe(true);
ionicPlatform.hardwareBackButtonClick();
expect(angular.element(document.body).hasClass('action-sheet-open')).toBe(false);
}));
});
|
#!/usr/bin/env python
# -*- coding=utf-8 -*-
from __future__ import (division, unicode_literals)
import io
import os
import re
import sys
import json
import string
import argparse
import tweepy
__version__ = '2.0'
consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
twitter = tweepy.API(auth)
file_path = os.path.dirname(os.path.abspath(__file__))
class BaseTokenizer(object):
def __init__(self):
# Internet Domains (most frequent ones)
with io.open('%s/merge/DOMAINS' % file_path, encoding='utf-8') as fp:
self.domains = set(fp.read().split())
# List of Emoticons
with io.open('%s/merge/EMOTICONS' % file_path, encoding='utf-8') as fp:
self.emoticons = set(fp.read().split())
# List of Non-breaking Prefixes
with io.open('%s/merge/NONBREAKING_PREFIXES' % file_path, encoding='utf-8') as fp:
self.NBP = set(fp.read().split())
self.punctuation = set(string.punctuation)
self.pemos = set([x for x in self.emoticons if
(any(c in self.punctuation for c in x) and all(ord(c)<256 for c in x))])
self.NBP = self.NBP.union(set(string.ascii_letters[:26]))
self.NBP_NUM = set(['No', 'no', 'Art', 'pp'])
self.contractions = """ 'all 'am 'clock 'd 'll 'm n't
're 's 'sup 'tis 'twas 've 'n' """
self.contractions = self.contractions.split() +\
self.contractions.upper().split()
# precompile regexes
self.base_fit()
def base_fit(self):
# ASCII junk characters
self.ascii_junk = re.compile('[\x00-\x1f]')
# Latin-1 supplementary characters
self.latin = re.compile('([\xa1-\xbf\xd7\xf7])')
# general unicode punctuations except "’"
self.uv_punct = re.compile('([\u2012-\u2018\u201a-\u206f])')
# unicode mathematical operators
self.umathop = re.compile('([\u2200-\u2211\u2213-\u22ff])')
# unicode fractions
self.ufrac = re.compile('([\u2150-\u2160])')
# unicode superscripts and subscripts
self.usupsub = re.compile('([\u2070-\u209f])')
# unicode currency symbols
self.ucurrency = re.compile('([\u20a0-\u20cf])')
# all "other" ASCII special characters
self.specascii = re.compile(r'([\\!@#$%^&*()_+={\[}\]|";:<>?`~/])')
# keep multiple dots together
self.multidot = re.compile(r'(\.\.+)([^\.])')
# seperate "," outside
self.notanumc = re.compile('([^0-9]),')
self.cnotanum = re.compile(',([^0-9])')
# split contractions right (both "'" and "’")
self.rnb = re.compile("([a-zA-Z])('[nN]')([a-zA-Z])")
self.ntc = re.compile("([a-zA-Z'])([nN]'[tT])([a-zA-Z' ])")
self.numcs = re.compile("([0-9])'s")
self.aca = re.compile(
"([a-zA-Z\u0080-\u024f])'([a-zA-Z\u0080-\u024f])")
self.acna = re.compile(
"([a-zA-Z\u0080-\u024f])'([^a-zA-Z\u0080-\u024f])")
self.nacna = re.compile(
"([^a-zA-Z\u0080-\u024f])'([^a-zA-Z\u0080-\u024f])")
# split hyphens
self.multihyphen = re.compile('(-+)')
# restore multi-dots
self.restoredots = re.compile(r'(DOT)(\1*)MULTI')
# split supplementary unicode
try:
self.bigu = re.compile('([\U00010000-\U0010ffff]+)')
except re.error:
# UCS-2 build
self.bigu = re.compile(u'(([\uD800-\uDBFF][\uDC00-\uDFFF])+)')
self.isurl = re.compile(r'[a-z][a-z][.][a-z][a-z]').search
self.joints = re.compile(r'(^[A-Za-z][A-Za-z]+)[.]'
r'([A-Za-z][A-Za-z]+$)')
self.rpunct = re.compile(r'[.,\\!@#$%^&\'*()_+={\[}\]|";:<>?`~/]')
self.rep_punkt = re.compile(r'([%s][%s]+)' % (('.,\\!@#$%^&*()_+={\[}\]|;:<>?~/-',) * 2))
self.rep_quotes = re.compile(r'([\'"`][\'"`]+)')
self.xml_tags = [('<', '<'),
('>', '>'),
('&', '&'),
('"', '"'),
(''', "'"),
('<', '<'),
('>', '>'),
('&', '&'),
('"', '"'),
(''', "'")
]
def xml_dammit(self, text):
for xtag in self.xml_tags:
while xtag[0] in text:
text = text.replace(xtag[0], xtag[1])
return text
def unmask_htag_uref(self, text):
text = text.split()
for i, token in enumerate(text):
if token.startswith('hAsHtAg-'):
ht_id = int(token.split('-')[1])
text[i] = self.htag_dict[ht_id]
elif token.startswith('uSeRrEf-'):
uref_id = int(token.split('-')[1])
text[i] = self.uref_dict[uref_id]
return ' '.join(text)
def mask_htag_uref(self, text):
self.htag_dict = dict()
self.uref_dict = dict()
text = text.split()
n_h = 0
n_u = 0
for i, token in enumerate(text):
if token[0] == '#':
text[i] = 'hAsHtAg-%d' % n_h
self.htag_dict[n_h] = token
n_h += 1
elif token[0] == '@':
text[i] = 'uSeRrEf-%d' % n_u
self.uref_dict[n_u] = token
n_u += 1
self._ht_at = False
if n_h or n_u:
self._ht_at = True
return ' '.join(text)
def unmask_rep_punct(self, text):
text = text.split()
for i, token in enumerate(text):
if token.startswith('rEpPuNcT-'):
rp_id = int(token.split('-')[1])
text[i] = self.punc_dict[rp_id]
return ' '.join(text)
def mask_rep_punct(self, text):
n_p = 0
self.punc_dict = dict()
text = self.rep_quotes.sub(r' \1 ', text)
text = self.rep_punkt.sub(r' \1 ', text)
text = text.split()
for i, token in enumerate(text):
if self.rep_punkt.match(token) or self.rep_quotes.match(token):
text[i] = 'rEpPuNcT-%d' % n_p
self.punc_dict[n_p] = token
n_p += 1
self._rp_pt = False
if n_p:
self._rp_pt = True
return ' '.join(text)
def unmask_sp_contractions(self, text):
text = ' %s ' % text
for i, cn in enumerate(self.contractions):
text = text.replace(' cOnTrAcTiOn-%d ' % i, ' %s ' % cn)
return text
def mask_sp_contractions(self, text):
text = ' %s ' % text
text = self.ntc.sub(r"\1 \2 \3", text)
text = self.rnb.sub(r"\1 \2 \3", text)
for i, cn in enumerate(self.contractions):
text = text.replace(' %s ' % cn, ' cOnTrAcTiOn-%d ' % i)
return text
def normalize_punkt(self, text):
"""replace unicode punctuation by ascii"""
text = re.sub('[\u2010\u2043]', '-', text) # hyphen
text = re.sub('[\u2018\u2019]', "'", text) # single quotes
text = re.sub('[\u201c\u201d]', '"', text) # double quotes
return text
def unmask_emos_urls(self, text):
text = text.split()
for i, token in enumerate(text):
if token.startswith('eMoTiCoN-'):
emo_id = int(token.split('-')[1])
text[i] = self.emos_dict[emo_id]
elif token.startswith('sItEuRl-'):
url_id = int(token.split('-')[1])
text[i] = self.url_dict[url_id]
#text[i] = 'U-R-L'
return ' '.join(text)
def mask_emos_urls(self, text):
n_e, n_u = 0, 0
text = re.sub(r'([\W_])(http://|https://|www.)', r'\1 \2', text)
words = text.split()
text = []
for wd in words:
if any(c in self.punctuation for c in wd) and len(wd) > 2:
for em in self.pemos:
br = len(em)
if wd.startswith(em):
wd = '%s %s' %(wd[:br], wd[br:])
if wd.endswith(em):
wd = '%s %s' %(wd[:-br], wd[-br:])
text.append(wd)
text = ' '.join(text).split()
self.url_dict = dict()
self.emos_dict = dict()
for i, token in enumerate(text):
if token in self.emoticons:
text[i] = 'eMoTiCoN-%d' % n_e
self.emos_dict[n_e] = token
n_e += 1
continue
is_url = False
if (token.startswith('http://') or
token.startswith('https://') or
token.startswith('www.')):
is_url = True
elif self.isurl(token):
tokens = self.rpunct.split(token)
is_url = any(x in self.domains for x in tokens[1:])
if is_url:
t2 = ''
if token[-2:] == "'s":
t2 = "'s"
token = token[:-2]
elif token[-1] in ",.!?;:'\"":
t2 = token[-1]
token = token[:-1]
text[i] = 'sItEuRl-%d' % n_u
self.url_dict[n_u] = '%s %s' % (token, t2)
n_u += 1
continue
text = ' '.join(text)
text = ' %s ' % (text)
return text
def tokenize_prefixes(self, text):
words = text.split()
text_len = len(words) - 1
text = str()
for i, word in enumerate(words):
if word[-1] == '.':
dotless = word[:-1]
if dotless.isdigit():
word = dotless + ' .'
elif (('.' in dotless and re.search('[a-zA-Z]', dotless)) or
dotless in self.NBP):
pass
elif (dotless in self.NBP_NUM and
(i < text_len and words[i + 1][0].isdigit())):
pass
#elif i < text_len and words[i + 1][0].isdigit():
# pass
else:
word = dotless + ' .'
elif self.joints.search(word):
w1, w2 = word.split('.')
if word in self.NBP:
pass
elif w1 in self.NBP:
word = '%s. %s' % (w1, w2)
else:
word = '%s . %s' % (w1, w2)
text += "%s " % word
return ' %s ' % text
def base_tokenize(self, text):
text = ' %s ' % (text)
# seperate out on Latin-1 supplementary characters
text = self.latin.sub(r' \1 ', text)
# seperate out on general unicode punctuations except "’"
text = self.uv_punct.sub(r' \1 ', text)
# seperate out on unicode mathematical operators
text = self.umathop.sub(r' \1 ', text)
# seperate out on unicode fractions
text = self.ufrac.sub(r' \1 ', text)
# seperate out on unicode superscripts and subscripts
text = self.usupsub.sub(r' \1 ', text)
# seperate out on unicode currency symbols
text = self.ucurrency.sub(r' \1 ', text)
# remove ascii junk
text = self.ascii_junk.sub('', text)
# seperate out all "other" ASCII special characters
text = self.specascii.sub(r' \1 ', text)
# keep multiple dots together
text = self.multidot.sub(lambda m: r' %sMULTI %s' % (
'DOT' * len(m.group(1)), m.group(2)), text)
return text
class Tokenizer(BaseTokenizer):
def __init__(self):
super(Tokenizer, self).__init__()
# precompile regexes
self.fit()
def fit(self):
# seperate "," outside
self.notanumc = re.compile('([^0-9]),')
self.cnotanum = re.compile(',([^0-9])')
# split contractions right (both "'" and "’")
self.numcs = re.compile("([0-9])'s")
self.naca = re.compile(
"([^a-zA-Z0-9\u0080-\u024f])'([a-zA-Z\u0080-\u024f])")
# split hyphens
self.hypheninnun = re.compile('(-?[0-9]-+[0-9]-?){,}')
self.ch_hyp_noalnum = re.compile('(.)-([^a-zA-Z0-9])')
self.noalnum_hyp_ch = re.compile('([^a-zA-Z0-9])-(.)')
# split Latin lettrs followed by non-Latin letters and vice-versa
self.nonltn_ltn = re.compile('([^\u0000-\u024f])([\u0000-\u024f])')
self.ltn_nonltn = re.compile('([\u0000-\u024f])([^\u0000-\u024f])')
def tokenize(self, text):
# replace xml-tags
text = self.xml_dammit(text)
# normalize unicode punctituation
text = self.normalize_punkt(text)
# mask emoticons and urls
text = self.mask_emos_urls(text)
# mask #tags and @ddresses
text = self.mask_htag_uref(text)
text = self.mask_rep_punct(text)
# mask splitted contractions
text = self.mask_sp_contractions(text)
text = self.nonltn_ltn.sub(r'\1 \2', text)
text = self.ltn_nonltn.sub(r'\1 \2', text)
# split supplementary unicode
text = self.bigu.sub(r' \1 ', text)
# universal tokenization
text = self.base_tokenize(text)
# seperate "," outside
text = self.notanumc.sub(r'\1 , ', text)
text = self.cnotanum.sub(r' , \1', text)
# split contractions right (both "'" and "’")
text = self.nacna.sub(r"\1 ' \2", text)
text = self.naca.sub(r"\1 ' \2", text)
text = self.acna.sub(r"\1 ' \2", text)
text = self.aca.sub(r"\1 '\2", text)
text = self.numcs.sub(r"\1 's", text)
text = text.replace("''", " ' ' ")
# split dots at word beginings
text = re.sub(r' (\.+)([^0-9])', r' \1 \2', text)
# seperate out hyphens
text = self.multihyphen.sub(
lambda m: r'%s' % (' '.join(m.group(1))),
text)
text = self.hypheninnun.sub(
lambda m: r'%s' % (m.group().replace('-', ' - ')),
text)
text = self.ch_hyp_noalnum.sub(r'\1 - \2', text)
text = self.noalnum_hyp_ch.sub(r'\1 - \2', text)
# handle non-breaking prefixes
text = self.tokenize_prefixes(text)
# restore multi-dots
text = self.restoredots.sub(lambda m: r'.%s' %
('.' * int((len(m.group(2)) / 3))),
text)
# unmask emoticons and urls
text = self.unmask_emos_urls(text)
# unmask splitted contractions
text = self.unmask_sp_contractions(text)
# unmask #tags and @ddress
if self._ht_at:
text = self.unmask_htag_uref(text)
if self._rp_pt:
text = self.unmask_rep_punct(text)
return text.split()
def crawl_tweets(tweet_ids):
tweets = {}
for n_ids in [tweet_ids[i:i+100] for i in range(0, len(tweet_ids), 100)]:
n_tweets = twitter.statuses_lookup(n_ids)
for tw in n_tweets:
if tw:
tweets[tw.id_str] = ' '.join(tw.text.split())
return tweets
if __name__ == '__main__':
prog = 'tweet-crawler'
description = 'Download, tokenize and annotate tweets'
parser = argparse.ArgumentParser(prog=prog,
description=description)
parser.add_argument('-v',
'--version',
action='version',
version='%s %s' % (prog, __version__))
parser.add_argument('-i',
'--idfile',
metavar='',
dest='idfile',
type=str,
help='<tweet-ids file>')
parser.add_argument('-a',
'--annot-file',
metavar='',
dest='annot_file',
type=str,
help='<annotation-file>')
parser.add_argument('-o',
'--output',
metavar='',
dest='outfile',
type=str,
help='<output-file>')
args = parser.parse_args(sys.argv[1:])
with open(args.annot_file) as fp:
annot_map = json.load(fp)
ofp = io.open(args.outfile, mode='w', encoding='utf-8')
# initialize tokenizer
tok = Tokenizer()
# crawl tweets
with open(args.idfile) as fp:
tweet_ids = fp.read().split()
tweets = crawl_tweets(tweet_ids)
#edits
edits = {}
with open('%s/merge/EDITS' %file_path) as fp:
for line in fp:
line = line.strip().split('\t')
tid, eds = line[0], line[1:]
edits.setdefault(tid, [])
for edit in eds:
edits[tid].append(edit.split('|'))
# tokenize tweets and align annotations
for tid in tweet_ids:
annot = annot_map[tid]
err_flag = False
if tid not in tweets:
if not annot['deleted']:
err_flag = True
sys.stderr.write('Tweet not found :: t_id %s :: '
'Contact author for full data-set\n' %tid)
else:
if tid in edits:
for edit in edits[tid]:
tweets[tid] = tweets[tid].replace(edit[0], edit[1])
tweet = tok.tokenize(tweets[tid])
tweet = [wd for wd in tweet[::-1] if wd.isalpha()]
org_tweet = annot['tweet']
for i,wd in enumerate(org_tweet):
if wd.isalpha():
new_wd = tweet.pop()
if new_wd[0] == wd[0]:
org_tweet[i] = new_wd
else:
sys.stderr.write('Annotation mismatch :: t_id %s :: Please report\n' %tid)
err_flag = True
annot['tweet'] = org_tweet
if err_flag:
continue
pad = ['_']*len(annot['ids'])
norm = [n if n!='_' else r for n,r in zip(annot['norm'], annot['tweet'])]
dep_tweet = zip(annot['ids'], annot['tweet'], norm, annot['pos'], annot['cpos'],
annot['chunk'], annot['parent'], annot['drel'], annot['lid'], pad)
dep_tweet = '\n'.join(['\t'.join(x) for x in dep_tweet])
ofp.write('%s\n\n' % dep_tweet)
# close files
ofp.close()
|
define(function (require, exports, module) {
// render function
var _module1 = {
exports: {}
};
(function (module, exports) {
module.exports = {
render: function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',[_c('c-row',[_c('c-span',[_c('div',{staticClass:"c-filter-multi-position"},[_c('input',{directives:[{name:"model",rawName:"a-model",value:(_vm.leftVal),expression:"leftVal"}],ref:"input1",staticClass:"c-input",attrs:{"placeholder":_vm.placeHold},domProps:{"value":_vm.leftVal,"value":(_vm.leftVal)},on:{"blur":_vm.rangeStart,"input":function($event){if($event.target.composing){ return; }_vm.leftVal=$event.target.value}}}),_vm._v(" "),(_vm.rangeInput.input.unit)?(_c('span',{staticClass:"c-filter-multi-price-company"},[_vm._v(_vm._s(_vm.rangeInput.input.unit))])):(_vm._e())])]),_vm._v(" "),_c('div',{staticClass:"c-gap-left-small c-gap-right-small c-filter-multi-line-middle"},[_c('span',{staticClass:"c-color-gray"},[_vm._v("—")])]),_vm._v(" "),_c('c-span',[_c('div',{staticClass:"c-filter-multi-position"},[_c('input',{directives:[{name:"model",rawName:"a-model",value:(_vm.rightVal),expression:"rightVal"}],ref:"input2",staticClass:"c-input",attrs:{"placeholder":_vm.placeHold2},domProps:{"value":_vm.rightVal,"value":(_vm.rightVal)},on:{"blur":_vm.rangeEnd,"input":function($event){if($event.target.composing){ return; }_vm.rightVal=$event.target.value}}}),_vm._v(" "),(_vm.rangeInput.input.unit)?(_c('span',{staticClass:"c-filter-multi-price-company"},[_vm._v(_vm._s(_vm.rangeInput.input.unit))])):(_vm._e())])])],1),_vm._v(" "),(_vm.rangeInput.input.listButton && _vm.rangeInput.input.listButton.length > 0)?(_c('c-row',{staticClass:"c-gap-top"},[_vm._l((_vm.math_ceil(_vm.rangeInput.input.listButton.length / _vm.cols)),function(i){return _vm._l((_vm.cols),function(j){return ((i-1)*_vm.cols+(j-1) < _vm.rangeInput.input.listButton.length)?(_c('c-span',[_c('div',{staticClass:"c-filter-multi-input-item",on:{"click":function($event){_vm.changeBtnSel((i-1)*_vm.cols+(j-1))}}},[_c('div',{staticClass:"WA_LOG_BTN c-line-clamp1"},[_c('span',[_vm._v(_vm._s(_vm.rangeInput.input.listButton[(i-1)*_vm.cols+(j-1)].leftNum))]),_vm._v(" "),_c('span',[_vm._v("-")]),_vm._v(" "),_c('span',[_vm._v(_vm._s(_vm.rangeInput.input.listButton[(i-1)*_vm.cols+(j-1)].rightNum))])])])])):(_c('c-span'))})})],2)):(_vm._e()),_vm._v(" "),(_vm.rangeTip === true && _vm.rangeInput.input.errortip)?(_c('p',{staticClass:"c-color-red c-gap-top c-filter-multi-center"},[_vm._v(_vm._s(_vm.rangeInput.input.errortip))])):(_vm._e())],1)},
staticRenderFns: []
}
})(_module1, _module1.exports)
/* get script output data */
var _module2 = {
exports: {}
};
(function (module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _default = {
mounted: function mounted() {
if (this.rangeInput.input.placeHold) {
this.placeHold = this.rangeInput.input.placeHold;
this.placeHold2 = this.rangeInput.input.placeHold2 ? this.rangeInput.input.placeHold2 : this.rangeInput.input.placeHold;
}
},
methods: {
rangeStart: function rangeStart() {
this.startRange = this.$refs.input1.value;
if (this.checkNum(this.startRange)) {
this.leftVal = this.startRange;
} else {
this.leftVal = '';
}
},
rangeEnd: function rangeEnd() {
this.endRange = this.$refs.input2.value;
if (this.checkNum(this.endRange)) {
this.rightVal = this.endRange;
} else {
this.rightVal = '';
}
},
checkNum: function checkNum(val) {
return !isNaN(val);
},
changeBtnSel: function changeBtnSel(idx) {
var btnVal = this.rangeInput.input.listButton[idx];
this.leftVal = btnVal.leftNum;
this.rightVal = btnVal.rightNum;
},
resetVal: function resetVal() {
this.leftVal = '';
this.rightVal = '';
this.rangeTip = false;
this.rangeFliter = {};
},
sureVal: function sureVal() {
if (this.leftVal !== '' && this.rightVal !== '' && Number(this.leftVal) < Number(this.rightVal)) {
this.rangeTip = false;
this.rangeFliter.filterKey = this.rangeInput.filterKey;
this.rangeFliter.status = '0';
this.rangeFliter[this.rangeInput.filterKey] = this.leftVal + '_' + this.rightVal;
this.$emit('sureSel', this.rangeFliter);
} else {
if (!this.leftVal && !this.rightVal) {
this.rangeTip = false;
this.rangeFliter.status = '0';
} else {
this.rangeFliter.status = '1';
this.rangeTip = true;
}
}
}
}
};
exports["default"] = _default;
})(_module2, _module2.exports);
var obj = _module2.exports.default || _module2.exports;
obj.render = obj.render || _module1.exports.render;
obj.staticRenderFns = _module1.exports.staticRenderFns;
obj.props = ["rangeInput"];
obj.components = {"c-row": require("../Row/Row"),"c-span": require("../Row/Span")};
obj.data = function () {
return {"startRange": "","endRange": "","rangeTip": false,"placeHold": "","placeHold2": "","leftVal": this["rangeInput"]["input"]["leftVal"],"rightVal": this["rangeInput"]["input"]["rightVal"],"rangeFliter": {},"cols": 3};
};
var originCreated = obj.created;
obj.created = function () {
var self = this;
self.$super = {
render: function () {
return _module1.exports.render.apply(self, arguments);
}
};
originCreated && originCreated.call(self);
};
obj._scopeId = "data-a-7b5092f9";
module.exports = obj;
});
|
'use strict';
module.exports = function (grunt) {
// Show elapsed time at the end
require('time-grunt')(grunt);
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
mochaTest: {
options: {
ui: 'bdd',
reporter: 'spec'
},
src: ['test/**/*.js']
},
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'mochaTest']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'mochaTest']
}
}
});
// Default task.
grunt.registerTask('default', ['jshint', 'mochaTest']);
};
|
import styled from 'styled-components';
import Background from '../../assets/PlayBG.png';
export const StyledHeader = styled.header`
@import url('https://fonts.googleapis.com/css?family=Quicksand:400,500,700&display=swap');
height: 80vh;
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
display: grid;
place-content: center;
background-image: url(${Background});
background-size: cover;
@media (min-width: 900px) {
height: 70vh;
padding: 10rem;
justify-content: start;
align-content: center;
background-image: none;
}
h5 {
margin: 0;
text-transform: uppercase;
color: ${({ theme }) => theme.mint};
opacity: 0.5;
font-weight: 400;
font-size: .9rem;
letter-spacing: 0.08em;
@media (min-width: 600px) {
font-size: 1.2rem;
}
}
h1 {
margin: 0.2em 0;
font-size: 4rem;
letter-spacing: 0.05em;
@media (min-width: 600px) {
font-size: 6rem;
}
}
h4 {
letter-spacing: 0.07em;
font-size: 1.6rem;
text-transform: initial;
font-weight: 500;
margin-bottom: 0.5rem;
&:last-of-type {
margin-bottom: 3rem;
}
@media (min-width: 600px) {
font-size: 2rem;
line-height: 2.8rem;
&:last-of-type {
margin-bottom: 4rem;
}
}
}
`;
export const DownloadButton = styled.div`
a {
padding: .7rem 1rem;
background-color: ${({ theme }) => theme.mint};
color: #fff;
/* border: 3px solid ${({ theme }) => theme.mint}; */
border-radius: 15px;
font-weight: 300;
letter-spacing: 0.02em;
@media (min-width: 600px) {
padding: 1rem 2rem;
font-size: 1.4rem;
font-weight: 200;
text-transform: uppercase;
}
}
`;
|
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class RawTransactionsTest(BitcoinTestFramework):
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 4)
def setup_network(self, split=False):
self.nodes = start_nodes(4, self.options.tmpdir, [['-usehd=1'], ['-usehd=1'], ['-usehd=1'], ['-usehd=1']])
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
connect_nodes_bi(self.nodes,0,3)
self.is_network_split=False
self.sync_all()
def run_test(self):
print "Mining blocks..."
min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee']
# This test is not meant to test fee estimation and we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
# if the fee's positive delta is higher than this value tests will fail,
# neg. delta always fail the tests.
# The size of the signature of every input may be at most 2 bytes larger
# than a minimum sized signature.
# = 2 bytes * minRelayTxFeePerByte
feeTolerance = 2 * min_relay_tx_fee/1000
self.nodes[2].generate(1)
self.sync_all()
self.nodes[0].generate(121)
self.sync_all()
watchonly_address = self.nodes[0].getnewaddress()
watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"]
watchonly_amount = Decimal(2000)
self.nodes[3].importpubkey(watchonly_pubkey, "", True)
watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount)
self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 15)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 50)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
###############
# simple test #
###############
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0) #test if we have enought inputs
##############################
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 22 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0) #test if we have enough inputs
##############################
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 26 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0)
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
################################
# simple test with two outputs #
################################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 26, self.nodes[1].getnewaddress() : 25 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert(len(dec_tx['vin']) > 0)
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
#########################################################################
# test a fundrawtransaction with a VIN greater than the required amount #
#########################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 50:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee
#####################################################################
# test a fundrawtransaction with which will not get a change output #
#####################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 50:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : Decimal(50) - fee - feeTolerance }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert_equal(rawtxfund['changepos'], -1)
assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee
#########################################################################
# test a fundrawtransaction with a VIN smaller than the required amount #
#########################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
# 4-byte version + 1-byte vin count + 36-byte prevout then script_len
rawtx = rawtx[:82] + "0100" + rawtx[84:]
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for i, out in enumerate(dec_tx['vout']):
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
else:
assert_equal(i, rawtxfund['changepos'])
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex'])
assert_equal(matchingOuts, 1)
assert_equal(len(dec_tx['vout']), 2)
###########################################
# test a fundrawtransaction with two VINs #
###########################################
utx = False
utx2 = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
if aUtx['amount'] == 50:
utx2 = aUtx
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for out in dec_tx['vout']:
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
assert_equal(matchingOuts, 1)
assert_equal(len(dec_tx['vout']), 2)
matchingIns = 0
for vinOut in dec_tx['vin']:
for vinIn in inputs:
if vinIn['txid'] == vinOut['txid']:
matchingIns+=1
assert_equal(matchingIns, 2) #we now must see two vins identical to vins given as params
#########################################################
# test a fundrawtransaction with two VINs and two vOUTs #
#########################################################
utx = False
utx2 = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
if aUtx['amount'] == 50:
utx2 = aUtx
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60, self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for out in dec_tx['vout']:
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
assert_equal(matchingOuts, 2)
assert_equal(len(dec_tx['vout']), 3)
##############################################
# test a fundrawtransaction with invalid vin #
##############################################
listunspent = self.nodes[2].listunspent()
inputs = [ {'txid' : "1c7f966dab21119bac53213a2bc7532bff1fa844c124fd750a7d0b1332440bd1", 'vout' : 0} ] #invalid vin!
outputs = { self.nodes[0].getnewaddress() : 10}
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
try:
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
raise AssertionError("Spent more than available")
except JSONRPCException as e:
assert("Insufficient" in e.error['message'])
############################################################
#compare fee of a standard pubkeyhash transaction
inputs = []
outputs = {self.nodes[1].getnewaddress():11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a standard pubkeyhash transaction with multiple outputs
inputs = []
outputs = {self.nodes[1].getnewaddress():11,self.nodes[1].getnewaddress():12,self.nodes[1].getnewaddress():1,self.nodes[1].getnewaddress():13,self.nodes[1].getnewaddress():2,self.nodes[1].getnewaddress():3}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendmany("", outputs)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a 2of2 multisig p2sh transaction
# create 2of2 addr
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[1].getnewaddress()
addr1Obj = self.nodes[1].validateaddress(addr1)
addr2Obj = self.nodes[1].validateaddress(addr2)
mSigObj = self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
inputs = []
outputs = {mSigObj:11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(mSigObj, 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a standard pubkeyhash transaction
# create 4of5 addr
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[1].getnewaddress()
addr3 = self.nodes[1].getnewaddress()
addr4 = self.nodes[1].getnewaddress()
addr5 = self.nodes[1].getnewaddress()
addr1Obj = self.nodes[1].validateaddress(addr1)
addr2Obj = self.nodes[1].validateaddress(addr2)
addr3Obj = self.nodes[1].validateaddress(addr3)
addr4Obj = self.nodes[1].validateaddress(addr4)
addr5Obj = self.nodes[1].validateaddress(addr5)
mSigObj = self.nodes[1].addmultisigaddress(4, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey'], addr4Obj['pubkey'], addr5Obj['pubkey']])
inputs = []
outputs = {mSigObj:11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(mSigObj, 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
# spend a 2of2 multisig transaction over fundraw
# create 2of2 addr
addr1 = self.nodes[2].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[2].validateaddress(addr1)
addr2Obj = self.nodes[2].validateaddress(addr2)
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
# send 12 NEWCOIN to msig addr
txId = self.nodes[0].sendtoaddress(mSigObj, 12)
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
oldBalance = self.nodes[1].getbalance()
inputs = []
outputs = {self.nodes[1].getnewaddress():11}
rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[2].fundrawtransaction(rawTx)
signedTx = self.nodes[2].signrawtransaction(fundedTx['hex'])
txId = self.nodes[2].sendrawtransaction(signedTx['hex'])
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
# make sure funds are received at node1
assert_equal(oldBalance+Decimal('11.0000000'), self.nodes[1].getbalance())
############################################################
# locked wallet test
self.nodes[1].encryptwallet("test")
self.nodes.pop(1)
stop_nodes(self.nodes)
wait_bitcoinds()
self.nodes = start_nodes(4, self.options.tmpdir, [['-usehd=1'], ['-usehd=1'], ['-usehd=1'], ['-usehd=1']])
# This test is not meant to test fee estimation and we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
connect_nodes_bi(self.nodes,0,3)
self.is_network_split=False
self.sync_all()
# drain the keypool
self.nodes[1].getnewaddress()
self.nodes[1].getrawchangeaddress()
inputs = []
outputs = {self.nodes[0].getnewaddress():1.1}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
# fund a transaction that requires a new key for the change output
# creating the key must be impossible because the wallet is locked
try:
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e:
assert('Keypool ran out' in e.error['message'])
#refill the keypool
self.nodes[1].walletpassphrase("test", 100)
self.nodes[1].keypoolrefill(2) #need to refill the keypool to get an internal change address
self.nodes[1].walletlock()
try:
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 12)
raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e:
assert('walletpassphrase' in e.error['message'])
oldBalance = self.nodes[0].getbalance()
inputs = []
outputs = {self.nodes[0].getnewaddress():11}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
#now we need to unlock
self.nodes[1].walletpassphrase("test", 100)
signedTx = self.nodes[1].signrawtransaction(fundedTx['hex'])
txId = self.nodes[1].sendrawtransaction(signedTx['hex'])
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
# make sure funds are received at node1
assert_equal(oldBalance+Decimal('511.0000000'), self.nodes[0].getbalance())
###############################################
# multiple (~19) inputs tx test | Compare fee #
###############################################
#empty node1, send some small coins from node0 to node1
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
for i in range(0,20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#fund a tx with ~20 small inputs
inputs = []
outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[1].sendmany("", outputs)
signedFee = self.nodes[1].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs
#############################################
# multiple (~19) inputs tx test | sign/send #
#############################################
#again, empty node1, send some small coins from node0 to node1
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
for i in range(0,20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#fund a tx with ~20 small inputs
oldBalance = self.nodes[0].getbalance()
inputs = []
outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
fundedAndSignedTx = self.nodes[1].signrawtransaction(fundedTx['hex'])
txId = self.nodes[1].sendrawtransaction(fundedAndSignedTx['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(oldBalance+Decimal('500.19000000'), self.nodes[0].getbalance()) #0.19+block reward
#####################################################
# test fundrawtransaction with OP_RETURN and no vin #
#####################################################
rawtx = "0100000000010000000000000000066a047465737400000000"
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(len(dec_tx['vin']), 0)
assert_equal(len(dec_tx['vout']), 1)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert_greater_than(len(dec_tx['vin']), 0) # at least one vin
assert_equal(len(dec_tx['vout']), 2) # one change output added
##################################################
# test a fundrawtransaction using only watchonly #
##################################################
inputs = []
outputs = {self.nodes[2].getnewaddress() : watchonly_amount / 2}
rawtx = self.nodes[3].createrawtransaction(inputs, outputs)
result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 1)
assert_equal(res_dec["vin"][0]["txid"], watchonly_txid)
assert("fee" in result.keys())
assert_greater_than(result["changepos"], -1)
###############################################################
# test fundrawtransaction using the entirety of watched funds #
###############################################################
inputs = []
outputs = {self.nodes[2].getnewaddress() : watchonly_amount}
rawtx = self.nodes[3].createrawtransaction(inputs, outputs)
result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 2)
assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid)
assert_greater_than(result["fee"], 0)
assert_greater_than(result["changepos"], -1)
assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10)
signedtx = self.nodes[3].signrawtransaction(result["hex"])
assert(not signedtx["complete"])
signedtx = self.nodes[0].signrawtransaction(signedtx["hex"])
assert(signedtx["complete"])
self.nodes[0].sendrawtransaction(signedtx["hex"])
if __name__ == '__main__':
RawTransactionsTest().main()
|
jQuery(document).ready(function(){
if( $('.cd-stretchy-nav').length > 0 ) {
var stretchyNavs = $('.cd-stretchy-nav');
stretchyNavs.each(function(){
var stretchyNav = $(this),
stretchyNavTrigger = stretchyNav.find('.cd-nav-trigger');
stretchyNavTrigger.on('click', function(event){
event.preventDefault();
stretchyNav.toggleClass('nav-is-visible');
});
});
$(document).on('click', function(event){
( !$(event.target).is('.cd-nav-trigger') && !$(event.target).is('.cd-nav-trigger span') ) && stretchyNavs.removeClass('nav-is-visible');
});
}
});
particlesJS('particles-js',
{
"particles": {
"number": {
"value": 120,
"density": {
"enable": true,
"value_area": 800
}
},
"color": {
"value": "#ffffff"
},
"shape": {
"type": "circle",
"stroke": {
"width": 0,
"color": "#000000"
},
"polygon": {
"nb_sides": 5
},
"image": {
"src": "img/github.svg",
"width": 100,
"height": 100
}
},
"opacity": {
"value": 0.5,
"random": false,
"anim": {
"enable": false,
"speed": 1,
"opacity_min": 0.1,
"sync": false
}
},
"size": {
"value": 5,
"random": true,
"anim": {
"enable": false,
"speed": 40,
"size_min": 0.1,
"sync": false
}
},
"line_linked": {
"enable": true,
"distance": 150,
"color": "#ffffff",
"opacity": 0.4,
"width": 1
},
"move": {
"enable": true,
"speed": 7,
"direction": "none",
"random": false,
"straight": false,
"out_mode": "out",
"attract": {
"enable": false,
"rotateX": 600,
"rotateY": 1200
}
}
},
"interactivity": {
"detect_on": "canvas",
"events": {
"onhover": {
"enable": true,
"mode": "grab"
},
"onclick": {
"enable": true,
"mode": "push"
},
"resize": true
},
"modes": {
"grab": {
"distance": 200,
"line_linked": {
"opacity": 1
}
},
"bubble": {
"distance": 4000,
"size": 40,
"duration": 2,
"opacity": 8,
"speed": 1
},
"repulse": {
"distance": 200
},
"push": {
"particles_nb": 4
},
"remove": {
"particles_nb": 2
}
}
},
"retina_detect": true,
"config_demo": {
"hide_card": false,
"background_color": "#b61924",
"background_image": "",
"background_position": "50% 50%",
"background_repeat": "no-repeat",
"background_size": "cover"
}
}
);
|
export { default } from 'torii-salesforce-oauth2/torii-providers/salesforce-oauth2';
|
/**
* `acs-source-chooser-modal`
*
* This optional modal ui presents the user with the option to take a
* photo with 'acs-overlay' or add image files with 'afs-file-sources'.
*
*
*
*
*
*
* Properties:
*
*
*
*
*
* Events:
*
*
*
*
*
* Methods:
*
*
*
*
* @customElement
* @polymer
* @demo demo/index.html
*
**/
import {AppElement, html} from '@longlost/app-core/app-element.js';
import htmlString from './acs-source-chooser-modal.html';
import '@longlost/app-core/app-shared-styles.js';
import '@longlost/app-overlays/app-modal.js';
import '@polymer/iron-icon/iron-icon.js';
import '@polymer/paper-button/paper-button.js';
import '../app-camera-icons.js';
class ACSSourceChooserModal extends AppElement {
static get is() { return 'acs-source-chooser-modal'; }
static get template() {
return html([htmlString]);
}
async __modalClicked(event) {
try {
await this.clicked();
await this.$.modal.close();
}
catch (error) {
if (error === 'click disabled') { return; }
console.error(error);
}
}
async __cameraBtnClicked(event) {
try {
await this.clicked();
await this.$.modal.close();
this.fire('source-chooser-modal-open-camera');
}
catch (error) {
if (error === 'click disabled') { return; }
console.error(error);
}
}
async __browseBtnClicked(event) {
try {
await this.clicked();
await this.$.modal.close();
this.fire('source-chooser-modal-open-sources');
}
catch (error) {
if (error === 'click debounced') { return; }
console.error(error);
}
}
open() {
return this.$.modal.open();
}
}
window.customElements.define(ACSSourceChooserModal.is, ACSSourceChooserModal);
|
/* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* global mongo */
var console; // See mongo.util.enableConsoleProtection().
mongo.util = (function () {
/**
* Enables protection from undefined console references on older browsers
* without consoles.
*/
function enableConsoleProtection() {
if (!console || !console.log) { console = { log: function () {} }; }
if (!console.debug || !console.error || !console.info || !console.warn) {
var log = console.log;
console.debug = console.error = console.info = console.warn = log;
}
}
function isNumeric(val) {
return typeof val === 'number' && !isNaN(val);
}
function isInteger(obj) {
return typeof(obj) === 'number' && obj % 1 === 0;
}
function getDBCollectionResURL(resID, collection) {
return getDBResURL(resID) + collection + '/';
}
function getDBResURL(resID) {
return mongo.config.baseUrl + resID + '/db/';
}
function toString(expr){
if (typeof(expr) === 'string') {
return expr;
}
try {
return mongo.jsonUtils.tojson(expr);
} catch (e) {
return 'ERROR: ' + e.message;
}
}
/**
* Helper inserted into the sandbox namespace that performs membership reads
* to allow for the '__methodMissing' functionality
*/
function objectMemberGetter(obj, field) {
if (field in obj || !('__methodMissing' in obj)) {
var rtn = obj[field];
if (typeof(rtn) === 'function') {
rtn = rtn.bind(obj);
}
return rtn;
}
return obj.__methodMissing(field);
}
return {
enableConsoleProtection: enableConsoleProtection,
isNumeric: isNumeric,
isInteger: isInteger,
getDBCollectionResURL: getDBCollectionResURL,
getDBResURL: getDBResURL,
toString: toString,
__get: objectMemberGetter
};
}());
if(typeof(String.prototype.trim) === 'undefined'){
String.prototype.trim = function(){
return String(this).replace(/^\s+|\s+$/g, '');
};
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const exception_1 = require("../exception/exception");
const filtered_1 = require("../tree/filtered");
const host_tree_1 = require("../tree/host-tree");
const interface_1 = require("../tree/interface");
const static_1 = require("../tree/static");
const virtual_1 = require("../tree/virtual");
const call_1 = require("./call");
/**
* A Source that returns an tree as its single value.
*/
function source(tree) {
return () => tree;
}
exports.source = source;
/**
* A source that returns an empty tree.
*/
function empty() {
return () => static_1.empty();
}
exports.empty = empty;
/**
* Chain multiple rules into a single rule.
*/
function chain(rules) {
return (tree, context) => {
return rules.reduce((acc, curr) => {
return call_1.callRule(curr, acc, context);
}, rxjs_1.of(tree));
};
}
exports.chain = chain;
/**
* Apply multiple rules to a source, and returns the source transformed.
*/
function apply(source, rules) {
return (context) => {
return call_1.callRule(chain([
...rules,
// Optimize the tree. Since this is a source tree, there's not much harm here and this might
// avoid further issues.
tree => {
if (tree instanceof virtual_1.VirtualTree) {
tree.optimize();
return tree;
}
else if (tree.actions.length != 0) {
return static_1.optimize(tree);
}
else {
return tree;
}
},
]), call_1.callSource(source, context), context);
};
}
exports.apply = apply;
/**
* Merge an input tree with the source passed in.
*/
function mergeWith(source, strategy = interface_1.MergeStrategy.Default) {
return (tree, context) => {
const result = call_1.callSource(source, context);
return result.pipe(operators_1.map(other => static_1.merge(tree, other, strategy || context.strategy)));
};
}
exports.mergeWith = mergeWith;
function noop() {
return (tree, _context) => tree;
}
exports.noop = noop;
function filter(predicate) {
return ((tree) => {
// TODO: Remove VirtualTree usage in 7.0
if (tree instanceof virtual_1.VirtualTree) {
return new filtered_1.FilteredTree(tree, predicate);
}
else if (tree instanceof host_tree_1.HostTree) {
return new host_tree_1.FilterHostTree(tree, predicate);
}
else {
throw new exception_1.SchematicsException('Tree type is not supported.');
}
});
}
exports.filter = filter;
function asSource(rule) {
return apply(empty(), [rule]);
}
exports.asSource = asSource;
function branchAndMerge(rule, strategy = interface_1.MergeStrategy.Default) {
return (tree, context) => {
const branchedTree = static_1.branch(tree);
return call_1.callRule(rule, rxjs_1.of(branchedTree), context)
.pipe(operators_1.last(), operators_1.map(t => static_1.merge(tree, t, strategy)));
};
}
exports.branchAndMerge = branchAndMerge;
function when(predicate, operator) {
return (entry) => {
if (predicate(entry.path, entry)) {
return operator(entry);
}
else {
return entry;
}
};
}
exports.when = when;
function partitionApplyMerge(predicate, ruleYes, ruleNo) {
return (tree, context) => {
const [yes, no] = static_1.partition(tree, predicate);
if (!ruleNo) {
// Shortcut.
return call_1.callRule(ruleYes, rxjs_1.of(static_1.partition(tree, predicate)[0]), context)
.pipe(operators_1.map(yesTree => static_1.merge(yesTree, no, context.strategy)));
}
return call_1.callRule(ruleYes, rxjs_1.of(yes), context)
.pipe(operators_1.concatMap(yesTree => {
return call_1.callRule(ruleNo, rxjs_1.of(no), context)
.pipe(operators_1.map(noTree => static_1.merge(yesTree, noTree, context.strategy)));
}));
};
}
exports.partitionApplyMerge = partitionApplyMerge;
function forEach(operator) {
return (tree) => {
tree.visit((path, entry) => {
if (!entry) {
return;
}
const newEntry = operator(entry);
if (newEntry === entry) {
return;
}
if (newEntry === null) {
tree.delete(path);
return;
}
if (newEntry.path != path) {
tree.rename(path, newEntry.path);
}
if (!newEntry.content.equals(entry.content)) {
tree.overwrite(newEntry.path, newEntry.content);
}
});
return tree;
};
}
exports.forEach = forEach;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFzZS5qcyIsInNvdXJjZVJvb3QiOiIuLyIsInNvdXJjZXMiOlsicGFja2FnZXMvYW5ndWxhcl9kZXZraXQvc2NoZW1hdGljcy9zcmMvcnVsZXMvYmFzZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBOzs7Ozs7R0FNRztBQUNILCt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AgICAgfVxuICAgICAgaWYgKG5ld0VudHJ5LnBhdGggIT0gcGF0aCkge1xuICAgICAgICB0cmVlLnJlbmFtZShwYXRoLCBuZXdFbnRyeS5wYXRoKTtcbiAgICAgIH1cbiAgICAgIGlmICghbmV3RW50cnkuY29udGVudC5lcXVhbHMoZW50cnkuY29udGVudCkpIHtcbiAgICAgICAgdHJlZS5vdmVyd3JpdGUobmV3RW50cnkucGF0aCwgbmV3RW50cnkuY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gdHJlZTtcbiAgfTtcbn1cbiJdfQ==
|
import { LitElement, html } from "lit-element";
export class WCPSummarySelect extends LitElement {
render() {
return html`
<select> <!-- TODO: register onSelected() event handler for 'change' event -->
<option value="F" >FOUNDATIONS OF WEB COMPONENTS</option>
<option value="F01">– What are they? Can I use them?</option>
<option value="F02">– Custom Elements</option>
<option value="F03">– Shadow DOM</option>
<option value="F04">– Templates & Modules</option>
<option value="U" >CREATING AND USING WEB COMPONENTS</option>
<option value="U01">– How to start?</option>
<option value="U02">– Lit-Element Templates</option>
<option value="U03">– Lit-Element Data bindings</option>
<option value="D" >DATAFLOWS OF WEB COMPONENTS</option>
<option value="D01">– Vanilla data bindings: « data-in via attributes, data-out via events »</option>
<option value="D02">– Fetching data</option>
<option value="E" >THE ECOSYSTEM OF WEB COMPONENTS</option>
<option value="E01">– Understanding the Polymer project</option>
<option value="E02">– Navigate WebComponents.org and discover its main collections</option>
<option value="E03">– Understand Material Design and A11Y</option>
<option value="C" >AS A CONCLUSION</option>
</select>
`;
}
onSelected( event) {
const selectElement = event.target,
selectedIndex = selectElement.selectedIndex,
selectedValue = selectElement.options[ selectedIndex].value;
// TODO: this.dispatchEvent( …)
}
}
customElements.define( "wcp-select", WCPSummarySelect);
|
import Index from "../";
it("provides routes", () => {
expect(Index.Routes).toMatchSnapshot();
})
|
import React from 'react';
import createSvg from './utils/createSvg';
export default createSvg(<path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-3 5h-2v5.37c0 1.27-.9 2.44-2.16 2.6-1.69.23-3.11-1.25-2.8-2.95.2-1.1 1.18-1.95 2.3-2.02.63-.04 1.2.16 1.66.51V6c0-.55.45-1 1-1h2c.55 0 1 .45 1 1s-.45 1-1 1zM3 6c-.55 0-1 .45-1 1v13c0 1.1.9 2 2 2h13c.55 0 1-.45 1-1s-.45-1-1-1H5c-.55 0-1-.45-1-1V7c0-.55-.45-1-1-1z" />, 'LibraryMusicRound', '0 0 24 24');
|
import "typeface-roboto";
import React from "react";
import { createMuiTheme } from "@material-ui/core/styles";
import { ThemeProvider } from "@material-ui/styles";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
const theme = createMuiTheme({
typography: {
fontSize: 11
},
overrides: {
MuiMenuItem: {
root: {
marginLeft: 15,
marginRight: 15
}
}
}
});
export default function App() {
return (
<ThemeProvider theme={theme}>
<Menu anchorEl={document} open={true}>
<MenuItem>First Item</MenuItem>
<MenuItem>Second Item</MenuItem>
<MenuItem>Third Item</MenuItem>
</Menu>
</ThemeProvider>
);
}
|
import React from 'react'
import Device from 'react-device'
import {isIE} from 'react-device-detect';
function FindBrowser(props) {
const onChange = (deviceInfo) => {
console.log('Browser name', deviceInfo.browser.name);
}
return (
<div>
<Device onChange={onChange} />
<h2>You are on {onChange.deviceInfo.browser.name}</h2>
</div>
);
}
export default FindBrowser;
|
#!/usr/bin/env python
from setuptools import setup
version = __import__('papersizes').__version__
setup(
name='papersizes',
packages=[
'papersizes'
],
version=version,
description='Paper sizes and manipulations',
author='Ian Millington',
author_email='idmillington@googlemail.com',
url='http://github.com/idmillington/papersizes',
download_url='https://github.com/idmillington/papersizes/tarball/master',
keywords=['pdf', 'papersizes', 'print', 'design'],
classifiers=[
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Multimedia :: Graphics",
],
zip_safe=False,
# Testing and documentation requirements can be installed with:
# pip install -r dev-requirements.txt
install_requires=[]
)
|
/* ------------------------------------------------------------------------------
*
* # Color pickers
*
* Demo JS code for picker_color.html page
*
* ---------------------------------------------------------------------------- */
// Setup module
// ------------------------------
var ColorPicker = function() {
//
// Setup module components
//
// Location picker
var _componentColorPicker = function() {
if (!$().spectrum) {
console.warn('Warning - spectrum.js is not loaded.');
return;
}
// Color palette
var demoPalette = [
["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
]
// Basic examples
// ------------------------------
// Basic setup
$('.colorpicker-basic').spectrum();
// Clear selection
$('.colorpicker-clear').spectrum({
allowEmpty: true
});
// Display color formats
$('.colorpicker-show-input').spectrum({
showInput: true
});
// Display alpha channel
$('.colorpicker-show-alpha').spectrum({
showAlpha: true
});
// Display initial color
$('.colorpicker-show-initial').spectrum({
showInitial: true
});
// Display input and initial color
$('.colorpicker-input-initial').spectrum({
showInitial: true,
showInput: true
});
// Full featured color picker
$('.colorpicker-full').spectrum({
showInitial: true,
showInput: true,
showAlpha: true,
allowEmpty: true
});
// Container color
$('.colorpicker-container-class').spectrum({
containerClassName: 'bg-secondary text-white'
});
// Replacer color
$('.colorpicker-replacer-class').spectrum({
replacerClassName: 'bg-secondary text-white',
});
//
// Toggle picker state
//
// Initialize
$('.colorpicker-disabled').spectrum({
disabled: true
});
// Define element for state toggle
var toggleState = document.querySelector('#enable_picker');
// Toggle navbar type state toggle
toggleState.addEventListener('change', function() {
if(toggleState.checked) {
$('.colorpicker-disabled').spectrum('enable');
}
else {
$('.colorpicker-disabled').spectrum('disable');
}
});
// Flat pickers
// ------------------------------
// Basic setup
$('.colorpicker-flat').spectrum({
flat: true
});
// Display input field
$('.colorpicker-flat-input').spectrum({
flat: true,
showInput: true
});
// Set picker color
$('.colorpicker-flat-custom').spectrum({
flat: true,
containerClassName: 'bg-secondary text-white'
});
// Display color palette
$('.colorpicker-flat-palette').spectrum({
flat: true,
showPalette: true,
showPaletteOnly: true,
togglePaletteOnly: true,
togglePaletteMoreText: 'More',
togglePaletteLessText: 'Less',
palette: demoPalette
});
// Display initial color
$('.colorpicker-flat-initial').spectrum({
flat: true,
showInitial: true
});
// Full featued flat picker
$('.colorpicker-flat-full').spectrum({
flat: true,
showInitial: true,
showInput: true,
showAlpha: true,
allowEmpty: true
});
// Color palettes
// ------------------------------
// Display color palette
$('.colorpicker-palette').spectrum({
showPalette: true,
palette: demoPalette
});
// Display palette only
$('.colorpicker-palette-only').spectrum({
showPalette: true,
showPaletteOnly: true,
palette: demoPalette
});
// Toggle palette
$('.colorpicker-palette-toggle').spectrum({
showPalette: true,
showPaletteOnly: true,
togglePaletteOnly: true,
togglePaletteMoreText: 'More',
togglePaletteLessText: 'Less',
palette: demoPalette
});
// Selection palette
$('.colorpicker-palette-selection').spectrum({
showPalette: true,
palette: [],
localStorageKey: 'spectrum.homepage'
});
// Limit number of selections
$('.colorpicker-palette-limit').spectrum({
showPalette: true,
palette: [ ],
selectionPalette: ['red', 'green', 'blue'],
maxSelectionSize: 3
});
// Hide after select
$('.colorpicker-palette-hide').spectrum({
showPalette: true,
hideAfterPaletteSelect: true,
palette: demoPalette
});
// Events
// ------------------------------
// Change event
$('.colorpicker-event-change').spectrum({
change: function(c) {
var label = $('#change-result');
label.removeClass('hidden').html('Change called: ' + '<span class="font-weight-semibold">' + c.toHexString() + '</span>');
}
});
// Move event
$('.colorpicker-event-move').spectrum({
move: function(c) {
var label = $('#move-result');
label.removeClass('hidden').html('Move called: ' + '<span class="font-weight-semibold">' + c.toHexString() + '</span>');
}
});
// Hide event
$('.colorpicker-event-hide').spectrum({
hide: function(c) {
var label = $('#hide-result');
label.removeClass('hidden').html('Hide called: ' + '<span class="font-weight-semibold">' + c.toHexString() + '</span>');
}
});
// Show event
$('.colorpicker-event-show').spectrum({
show: function(c) {
var label = $('#show-result');
label.removeClass('hidden').html('Show called: ' + '<span class="font-weight-semibold">' + c.toHexString() + '</span>');
}
});
//
// Drag start event
//
// Initialize
$('.colorpicker-event-dragstart').spectrum();
// Attach event
$('.colorpicker-event-dragstart').on('dragstart.spectrum', function (e, c) {
var label = $('#dragstart-result');
label.removeClass('hidden').html('Dragstart called: ' + '<span class="font-weight-semibold">' + c.toHexString() + '</span>');
});
//
// Drag stop event
//
// Initialize
$('.colorpicker-event-dragstop').spectrum();
// Attach event
$('.colorpicker-event-dragstop').on('dragstop.spectrum', function (e, c) {
var label = $('#dragstop-result');
label.removeClass('hidden').html('Dragstop called: ' + '<span class="font-weight-semibold">' + c.toHexString() + '</span>');
});
};
//
// Return objects assigned to module
//
return {
init: function() {
_componentColorPicker();
}
}
}();
// Initialize module
// ------------------------------
document.addEventListener('DOMContentLoaded', function() {
ColorPicker.init();
});
|
# -*- coding: utf-8 -*-
import datetime
import os
from base64 import b64encode
import django.dispatch
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.storage import default_storage as storage
from django.db import models, transaction
from django.db.models import Q
from django.urls import reverse
from django.utils.encoding import force_str
from django.utils.functional import cached_property
from django.utils.translation import gettext
import jinja2
from olympia.constants.applications import APP_IDS
import waffle
from django_jsonfield_backport.models import JSONField
from django_statsd.clients import statsd
import olympia.core.logger
from olympia import activity, amo, core
from olympia.amo.decorators import use_primary_db
from olympia.amo.fields import PositiveAutoField
from olympia.amo.models import (
BasePreview,
LongNameIndex,
ManagerBase,
ModelBase,
OnChangeMixin,
)
from olympia.amo.utils import sorted_groupby, utc_millesecs_from_epoch
from olympia.applications.models import AppVersion
from olympia.constants.licenses import LICENSES_BY_BUILTIN
from olympia.constants.promoted import PROMOTED_GROUPS_BY_ID
from olympia.constants.scanners import MAD
from olympia.files import utils
from olympia.files.models import File, cleanup_file
from olympia.translations.fields import (
LinkifiedField,
PurifiedField,
TranslatedField,
save_signal,
)
from olympia.scanners.models import ScannerResult
from olympia.users.utils import get_task_user
from .compare import version_int
from .fields import VersionStringField
log = olympia.core.logger.getLogger('z.versions')
# Valid source extensions. Actual validation lives in
# devhub.forms.WithSourceMixin and is slightly more complex (the file
# contents are checked to see if it matches the extension).
# If changing this, make sure devhub.forms.WithSourceMixin.clean_source() and
# source_upload_path() are updated accordingly if needed, and that source
# submission still works both at add-on and version upload time.
VALID_SOURCE_EXTENSIONS = (
'.zip',
'.tar.gz',
'.tgz',
'.tar.bz2',
)
class VersionManager(ManagerBase):
def __init__(self, include_deleted=False):
ManagerBase.__init__(self)
self.include_deleted = include_deleted
def get_queryset(self):
qs = super(VersionManager, self).get_queryset()
if not self.include_deleted:
qs = qs.exclude(deleted=True)
return qs.transform(Version.transformer)
def valid(self):
return self.filter(files__status__in=amo.VALID_FILE_STATUSES).distinct()
def latest_public_compatible_with(self, application, appversions):
"""Return a queryset filtering the versions so that they are public,
listed, and compatible with the application and appversions parameters
passed. The queryset is ordered by creation date descending, allowing
the caller to get the latest compatible version available.
application is an application id
appversions is a dict containing min and max values, as version ints.
"""
return Version.objects.filter(
apps__application=application,
apps__min__version_int__lte=appversions['min'],
apps__max__version_int__gte=appversions['max'],
channel=amo.RELEASE_CHANNEL_LISTED,
files__status=amo.STATUS_APPROVED,
).order_by('-created')
def auto_approvable(self):
"""Returns a queryset filtered with just the versions that should
attempted for auto-approval by the cron job."""
qs = self.filter(
files__status=amo.STATUS_AWAITING_REVIEW, files__is_webextension=True
).filter(
# For listed, add-on can't be incomplete, deleted or disabled.
# It also cannot be disabled by user ("invisible"), and can not
# be a theme either.
Q(
channel=amo.RELEASE_CHANNEL_LISTED,
addon__status__in=(amo.STATUS_NOMINATED, amo.STATUS_APPROVED),
addon__disabled_by_user=False,
addon__type__in=(amo.ADDON_EXTENSION, amo.ADDON_LPAPP, amo.ADDON_DICT),
)
# For unlisted, add-on can't be deleted or disabled.
| Q(
channel=amo.RELEASE_CHANNEL_UNLISTED,
addon__status__in=(
amo.STATUS_NULL,
amo.STATUS_NOMINATED,
amo.STATUS_APPROVED,
),
)
)
return qs
class UnfilteredVersionManagerForRelations(VersionManager):
"""Like VersionManager, but defaults to include deleted objects.
Designed to be used in reverse relations of Versions like this:
<Addon>.versions(manager='unfiltered_for_relations').all(), for when you
want to use the related manager but need to include deleted versions.
unfiltered_for_relations = UnfilteredVersionManagerForRelations() is
defined in Version for this to work.
"""
def __init__(self, include_deleted=True):
super().__init__(include_deleted=include_deleted)
def source_upload_path(instance, filename):
# At this point we already know that ext is one of VALID_SOURCE_EXTENSIONS
# because we already checked for that in
# /src/olympia/devhub/forms.py#WithSourceMixin.clean_source.
ext = ''
for ext in VALID_SOURCE_EXTENSIONS:
if filename.endswith(ext):
break
return os.path.join(
'version_source',
utils.id_to_path(instance.pk),
'{0}-{1}-src{2}'.format(instance.addon.slug, instance.version, ext),
)
class VersionCreateError(ValueError):
pass
class Version(OnChangeMixin, ModelBase):
id = PositiveAutoField(primary_key=True)
addon = models.ForeignKey(
'addons.Addon', related_name='versions', on_delete=models.CASCADE
)
license = models.ForeignKey(
'License', null=True, blank=True, on_delete=models.SET_NULL
)
release_notes = PurifiedField(db_column='releasenotes', short=False)
approval_notes = models.TextField(
db_column='approvalnotes', default='', null=True, blank=True
)
version = VersionStringField(max_length=255, default='0.1')
nomination = models.DateTimeField(null=True)
reviewed = models.DateTimeField(null=True)
deleted = models.BooleanField(default=False)
source = models.FileField(
upload_to=source_upload_path, null=True, blank=True, max_length=255
)
channel = models.IntegerField(
choices=amo.RELEASE_CHANNEL_CHOICES, default=amo.RELEASE_CHANNEL_LISTED
)
git_hash = models.CharField(max_length=40, blank=True)
needs_human_review = models.BooleanField(default=False)
# The order of those managers is very important: please read the lengthy
# comment above the Addon managers declaration/instantiation.
unfiltered = VersionManager(include_deleted=True)
objects = VersionManager()
# See UnfilteredVersionManagerForRelations() docstring for usage of this
# special manager.
unfiltered_for_relations = UnfilteredVersionManagerForRelations()
class Meta(ModelBase.Meta):
db_table = 'versions'
# This is very important: please read the lengthy comment in Addon.Meta
# description
base_manager_name = 'unfiltered'
ordering = ['-created', '-modified']
indexes = [
models.Index(fields=('addon',), name='addon_id'),
models.Index(fields=('license',), name='license_id'),
]
constraints = [
models.UniqueConstraint(
fields=('addon', 'version'),
name='versions_addon_id_version_5a2e75b6_uniq',
),
]
def __str__(self):
return jinja2.escape(self.version)
@classmethod
def from_upload(cls, upload, addon, selected_apps, channel, parsed_data=None):
"""
Create a Version instance and corresponding File(s) from a
FileUpload, an Addon, a list of compatible app ids, a channel id and
the parsed_data generated by parse_addon().
Note that it's the caller's responsability to ensure the file is valid.
We can't check for that here because an admin may have overridden the
validation results.
"""
from olympia.addons.models import AddonReviewerFlags
from olympia.addons.utils import RestrictionChecker
from olympia.git.utils import create_git_extraction_entry
assert parsed_data is not None
if addon.status == amo.STATUS_DISABLED:
raise VersionCreateError(
'Addon is Mozilla Disabled; no new versions are allowed.'
)
if upload.addon and upload.addon != addon:
raise VersionCreateError('FileUpload was made for a different Addon')
if not upload.user or not upload.ip_address or not upload.source:
raise VersionCreateError('FileUpload does not have some required fields')
if not upload.user.last_login_ip or not upload.user.email:
raise VersionCreateError(
'FileUpload user does not have some required fields'
)
license_id = None
if channel == amo.RELEASE_CHANNEL_LISTED:
previous_version = addon.find_latest_version(channel=channel, exclude=())
if previous_version and previous_version.license_id:
license_id = previous_version.license_id
approval_notes = None
if parsed_data.get('is_mozilla_signed_extension'):
approval_notes = (
'This version has been signed with Mozilla internal certificate.'
)
version = cls.objects.create(
addon=addon,
approval_notes=approval_notes,
version=parsed_data['version'],
license_id=license_id,
channel=channel,
)
email = upload.user.email if upload.user and upload.user.email else ''
with core.override_remote_addr(upload.ip_address):
# The following log statement is used by foxsec-pipeline.
# We override the IP because it might be called from a task and we
# want the original IP from the submitter.
log.info(
'New version: %r (%s) from %r' % (version, version.id, upload),
extra={
'email': email,
'guid': addon.guid,
'upload': upload.uuid.hex,
'user_id': upload.user_id,
'from_api': upload.source == amo.UPLOAD_SOURCE_API,
},
)
activity.log_create(
amo.LOG.ADD_VERSION, version, addon, user=upload.user or get_task_user()
)
if addon.type == amo.ADDON_STATICTHEME:
# We don't let developers select apps for static themes
selected_apps = [app.id for app in amo.APP_USAGE]
compatible_apps = {}
for app in parsed_data.get('apps', []):
if app.id not in selected_apps:
# If the user chose to explicitly deselect Firefox for Android
# we're not creating the respective `ApplicationsVersions`
# which will have this add-on then be listed only for
# Firefox specifically.
continue
compatible_apps[app.appdata] = ApplicationsVersions(
version=version, min=app.min, max=app.max, application=app.id
)
compatible_apps[app.appdata].save()
# Pre-generate _compatible_apps property to avoid accidentally
# triggering queries with that instance later.
version._compatible_apps = compatible_apps
# Create relevant file and update the all_files cached property on the
# Version, because we might need it afterwards.
version.all_files = [
File.from_upload(
upload=upload,
version=version,
parsed_data=parsed_data,
)
]
version.inherit_nomination(from_statuses=[amo.STATUS_AWAITING_REVIEW])
version.disable_old_files()
# After the upload has been copied to its permanent location, delete it
# from storage. Keep the FileUpload instance (it gets cleaned up by a
# cron eventually some time after its creation, in amo.cron.gc()),
# making sure it's associated with the add-on instance.
storage.delete(upload.path)
upload.path = ''
if upload.addon is None:
upload.addon = addon
upload.save()
version_uploaded.send(instance=version, sender=Version)
if version.is_webextension:
if (
waffle.switch_is_active('enable-yara')
or waffle.switch_is_active('enable-customs')
or waffle.switch_is_active('enable-wat')
):
ScannerResult.objects.filter(upload_id=upload.id).update(
version=version
)
if waffle.switch_is_active('enable-uploads-commit-to-git-storage'):
# Schedule this version for git extraction.
transaction.on_commit(lambda: create_git_extraction_entry(version=version))
# Generate a preview and icon for listed static themes
if (
addon.type == amo.ADDON_STATICTHEME
and channel == amo.RELEASE_CHANNEL_LISTED
):
theme_data = parsed_data.get('theme', {})
generate_static_theme_preview(theme_data, version.pk)
# Reset add-on reviewer flags to disable auto-approval and require
# admin code review if the package has already been signed by mozilla.
reviewer_flags_defaults = {}
is_mozilla_signed = parsed_data.get('is_mozilla_signed_extension')
if upload.validation_timeout:
reviewer_flags_defaults['needs_admin_code_review'] = True
if is_mozilla_signed and addon.type != amo.ADDON_LPAPP:
reviewer_flags_defaults['needs_admin_code_review'] = True
reviewer_flags_defaults['auto_approval_disabled'] = True
# Check if the approval should be restricted
if not RestrictionChecker(upload=upload).is_auto_approval_allowed():
flag = (
'auto_approval_disabled'
if channel == amo.RELEASE_CHANNEL_LISTED
else 'auto_approval_disabled_unlisted'
)
reviewer_flags_defaults[flag] = True
if reviewer_flags_defaults:
AddonReviewerFlags.objects.update_or_create(
addon=addon, defaults=reviewer_flags_defaults
)
# Authors need to be notified about auto-approval delay again since
# they are submitting a new version.
addon.reset_notified_about_auto_approval_delay()
# Track the time it took from first upload through validation
# (and whatever else) until a version was created.
upload_start = utc_millesecs_from_epoch(upload.created)
now = datetime.datetime.now()
now_ts = utc_millesecs_from_epoch(now)
upload_time = now_ts - upload_start
log.info(
'Time for version {version} creation from upload: {delta}; '
'created={created}; now={now}'.format(
delta=upload_time, version=version, created=upload.created, now=now
)
)
statsd.timing('devhub.version_created_from_upload', upload_time)
return version
def license_url(self, impala=False):
return reverse('addons.license', args=[self.addon.slug, self.version])
def get_url_path(self):
if self.channel == amo.RELEASE_CHANNEL_UNLISTED:
return ''
return reverse('addons.versions', args=[self.addon.slug])
def delete(self, hard=False):
# To avoid a circular import
from .tasks import delete_preview_files
log.info('Version deleted: %r (%s)' % (self, self.id))
activity.log_create(amo.LOG.DELETE_VERSION, self.addon, str(self.version))
if hard:
super(Version, self).delete()
else:
# By default we soft delete so we can keep the files for comparison
# and a record of the version number.
self.files.update(status=amo.STATUS_DISABLED)
self.deleted = True
self.save()
# Clear pending rejection flag (we have the activity log for
# records purposes, the flag serves no purpose anymore if the
# version is deleted).
VersionReviewerFlags.objects.filter(version=self).update(
pending_rejection=None
)
previews_pks = list(
VersionPreview.objects.filter(version__id=self.id).values_list(
'id', flat=True
)
)
for preview_pk in previews_pks:
delete_preview_files.delay(preview_pk)
@property
def is_user_disabled(self):
return (
self.files.filter(status=amo.STATUS_DISABLED)
.exclude(original_status=amo.STATUS_NULL)
.exists()
)
@is_user_disabled.setter
def is_user_disabled(self, disable):
# User wants to disable (and the File isn't already).
if disable:
activity.log_create(amo.LOG.DISABLE_VERSION, self.addon, self)
for file in self.files.exclude(status=amo.STATUS_DISABLED).all():
file.update(original_status=file.status, status=amo.STATUS_DISABLED)
# User wants to re-enable (and user did the disable, not Mozilla).
else:
activity.log_create(amo.LOG.ENABLE_VERSION, self.addon, self)
for file in self.files.exclude(original_status=amo.STATUS_NULL).all():
file.update(
status=file.original_status, original_status=amo.STATUS_NULL
)
@cached_property
def all_activity(self):
# prefetch_related() and not select_related() the ActivityLog to make
# sure its transformer is called.
return self.versionlog_set.prefetch_related('activity_log').order_by('created')
@property
def compatible_apps(self):
# Dicts and search providers don't have compatibility info.
# Fake one for them.
if self.addon and self.addon.type in amo.NO_COMPAT:
return {app: None for app in amo.APP_TYPE_SUPPORT[self.addon.type]}
# Otherwise, return _compatible_apps which is a cached property that
# is filled by the transformer, or simply calculated from the related
# compat instances.
return self._compatible_apps
@cached_property
def _compatible_apps(self):
"""Get a mapping of {APP: ApplicationsVersions}."""
return self._compat_map(self.apps.all().select_related('min', 'max'))
@cached_property
def compatible_apps_ordered(self):
apps = self.compatible_apps.items()
return sorted(apps, key=lambda v: v[0].short)
@cached_property
def is_compatible_by_default(self):
"""Returns whether or not the add-on is considered compatible by
default."""
# Use self.all_files directly since that's cached and more potentially
# prefetched through a transformer already
return not any(
[
file
for file in self.all_files
if file.binary_components or file.strict_compatibility
]
)
def is_compatible_app(self, app):
"""Returns True if the provided app passes compatibility conditions."""
if self.addon.type in amo.NO_COMPAT:
return True
appversion = self.compatible_apps.get(app)
if appversion and app.id in amo.D2C_MIN_VERSIONS:
return version_int(appversion.max.version) >= version_int(
amo.D2C_MIN_VERSIONS.get(app.id, '*')
)
return False
def compat_override_app_versions(self):
"""Returns the incompatible app versions range(s).
If not ranges, returns empty list. Otherwise, this will return all
the app version ranges that this particular version is incompatible
with.
"""
overrides = list(self.addon.compatoverride_set.all())
if not overrides:
return []
app_versions = []
for co in overrides:
for range in co.collapsed_ranges():
if (
version_int(range.min)
<= version_int(self.version)
<= version_int(range.max)
):
app_versions.extend([(a.min, a.max) for a in range.apps])
return app_versions
@cached_property
def all_files(self):
"""Shortcut for list(self.files.all()). Cached."""
return list(self.files.all())
@property
def current_file(self):
"""Shortcut for selecting the first file from self.all_files"""
return self.all_files[0]
@property
def status(self):
return [
f.STATUS_CHOICES.get(f.status, gettext('[status:%s]') % f.status)
for f in self.all_files
]
@property
def statuses(self):
"""Unadulterated statuses, good for an API."""
return [(f.id, f.status) for f in self.all_files]
def is_public(self):
# To be public, a version must not be deleted, must belong to a public
# addon, and all its attached files must have public status.
try:
return (
not self.deleted
and self.addon.is_public()
and all(f.status == amo.STATUS_APPROVED for f in self.all_files)
)
except ObjectDoesNotExist:
return False
@property
def is_restart_required(self):
return any(file_.is_restart_required for file_ in self.all_files)
@property
def is_webextension(self):
return any(file_.is_webextension for file_ in self.all_files)
@property
def is_mozilla_signed(self):
"""Is the file a special "Mozilla Signed Extension"
See https://wiki.mozilla.org/Add-ons/InternalSigning for more details.
We use that information to workaround compatibility limits for legacy
add-ons and to avoid them receiving negative boosts compared to
WebExtensions.
See https://github.com/mozilla/addons-server/issues/6424
"""
return all(file_.is_mozilla_signed_extension for file_ in self.all_files)
@property
def has_files(self):
return bool(self.all_files)
@property
def is_unreviewed(self):
return bool(
list(
filter(
lambda f: f.status in amo.UNREVIEWED_FILE_STATUSES, self.all_files
)
)
)
@property
def is_all_unreviewed(self):
return not bool(
[f for f in self.all_files if f.status not in amo.UNREVIEWED_FILE_STATUSES]
)
@property
def sources_provided(self):
return bool(self.source)
def _compat_map(self, avs):
apps = {}
for av in avs:
av.version = self
app_id = av.application
if app_id in amo.APP_IDS:
apps[amo.APP_IDS[app_id]] = av
return apps
@classmethod
def transformer(cls, versions):
"""Attach all the compatible apps and files to the versions."""
if not versions:
return
ids = set(v.id for v in versions)
avs = ApplicationsVersions.objects.filter(version__in=ids).select_related(
'min', 'max'
)
files = File.objects.filter(version__in=ids)
def rollup(xs):
groups = sorted_groupby(xs, 'version_id')
return dict((k, list(vs)) for k, vs in groups)
av_dict, file_dict = rollup(avs), rollup(files)
for version in versions:
v_id = version.id
version._compatible_apps = version._compat_map(av_dict.get(v_id, []))
version.all_files = file_dict.get(v_id, [])
for f in version.all_files:
f.version = version
@classmethod
def transformer_promoted(cls, versions):
"""Attach the promoted approvals to the versions."""
if not versions:
return
PromotedApproval = versions[0].promoted_approvals.model
ids = set(v.id for v in versions)
approvals = list(
PromotedApproval.objects.filter(version_id__in=ids).values_list(
'version_id', 'group_id', 'application_id', named=True
)
)
approval_dict = {
version_id: list(groups)
for version_id, groups in sorted_groupby(approvals, 'version_id')
}
for version in versions:
v_id = version.id
groups = [
(
PROMOTED_GROUPS_BY_ID.get(approval.group_id),
APP_IDS.get(approval.application_id),
)
for approval in approval_dict.get(v_id, [])
if approval.group_id in PROMOTED_GROUPS_BY_ID
]
version.approved_for_groups = groups
@classmethod
def transformer_activity(cls, versions):
"""Attach all the activity to the versions."""
from olympia.activity.models import VersionLog
ids = set(v.id for v in versions)
if not versions:
return
# Ideally, we'd start from the ActivityLog, but because VersionLog
# to ActivityLog isn't a OneToOneField, we wouldn't be able to find
# the version easily afterwards - we can't even do a
# select_related('versionlog') and try to traverse the relation to find
# the version. So, instead, start from VersionLog, but make sure to use
# prefetch_related() (and not select_related() - yes, it's one extra
# query, but it's worth it to benefit from the default transformer) so
# that the ActivityLog default transformer is called.
al = (
VersionLog.objects.prefetch_related('activity_log')
.filter(version__in=ids)
.order_by('created')
)
def rollup(xs):
groups = sorted_groupby(xs, 'version_id')
return {k: list(vs) for k, vs in groups}
al_dict = rollup(al)
for version in versions:
v_id = version.id
version.all_activity = al_dict.get(v_id, [])
@classmethod
def transformer_license(cls, versions):
"""Attach all the licenses to the versions.
Do not use if you need the license text: it's explicitly deferred in
this transformer, because it should only be used when listing multiple
versions, where returning license text is not supposed to be needed.
The translations app doesn't fully handle evaluating a deferred field,
so the callers need to make sure the license text will never be needed
on instances returned by a queryset transformed by this method."""
if not versions:
return
license_ids = {ver.license_id for ver in versions}
licenses = License.objects.filter(id__in=license_ids).defer('text')
license_dict = {lic.id: lic for lic in licenses}
for version in versions:
license = license_dict.get(version.license_id)
if license:
version.license = license
@classmethod
def transformer_auto_approvable(cls, versions):
"""Attach auto-approvability information to the versions."""
ids = set(v.id for v in versions)
if not ids:
return
auto_approvable = (
Version.objects.auto_approvable()
.filter(pk__in=ids)
.values_list('pk', flat=True)
)
for version in versions:
version.is_ready_for_auto_approval = version.pk in auto_approvable
def disable_old_files(self):
"""
Disable files from versions older than the current one in the same
channel and awaiting review. Used when uploading a new version.
Does nothing if the current instance is unlisted.
"""
if self.channel == amo.RELEASE_CHANNEL_LISTED:
qs = File.objects.filter(
version__addon=self.addon_id,
version__lt=self.id,
version__deleted=False,
version__channel=self.channel,
status=amo.STATUS_AWAITING_REVIEW,
)
# Use File.update so signals are triggered.
for f in qs:
f.update(status=amo.STATUS_DISABLED)
def reset_nomination_time(self, nomination=None):
if not self.nomination or nomination:
nomination = nomination or datetime.datetime.now()
# We need signal=False not to call update_status (which calls us).
self.update(nomination=nomination, _signal=False)
def inherit_nomination(self, from_statuses=None):
last_ver = (
Version.objects.filter(addon=self.addon, channel=amo.RELEASE_CHANNEL_LISTED)
.exclude(nomination=None)
.exclude(id=self.pk)
.order_by('-nomination')
)
if from_statuses:
last_ver = last_ver.filter(files__status__in=from_statuses)
if last_ver.exists():
self.reset_nomination_time(nomination=last_ver[0].nomination)
@property
def unreviewed_files(self):
"""A File is unreviewed if its status is amo.STATUS_AWAITING_REVIEW."""
return self.files.filter(status=amo.STATUS_AWAITING_REVIEW)
@cached_property
def is_ready_for_auto_approval(self):
"""Return whether or not this version could be *considered* for
auto-approval.
Does not necessarily mean that it would be auto-approved, just that it
passes the most basic criteria to be considered a candidate by the
auto_approve command."""
return Version.objects.auto_approvable().filter(id=self.id).exists()
@property
def was_auto_approved(self):
"""Return whether or not this version was auto-approved."""
from olympia.reviewers.models import AutoApprovalSummary
try:
return (
self.is_public()
and AutoApprovalSummary.objects.filter(version=self).get().verdict
== amo.AUTO_APPROVED
)
except AutoApprovalSummary.DoesNotExist:
pass
return False
def get_background_images_encoded(self, header_only=False):
if not self.has_files:
return {}
file_obj = self.all_files[0]
return {
name: force_str(b64encode(background))
for name, background in utils.get_background_images(
file_obj, theme_data=None, header_only=header_only
).items()
}
def can_be_disabled_and_deleted(self):
# see https://github.com/mozilla/addons-server/issues/15121#issuecomment-667226959 # noqa
# "It should apply to the <groups> that require a review to be badged"
from olympia.promoted.models import PromotedApproval
if self != self.addon.current_version or (
not (group := self.addon.promoted_group())
or not (group.badged and group.pre_review)
):
return True
previous_ver = (
self.addon.versions.valid()
.filter(channel=self.channel)
.exclude(id=self.id)
.no_transforms()[:1]
)
previous_approval = PromotedApproval.objects.filter(
group_id=group.id, version__in=previous_ver
)
return previous_approval.exists()
@property
def is_blocked(self):
block = self.addon.block
return bool(block and block.is_version_blocked(self.version))
@property
def pending_rejection(self):
try:
return self.reviewerflags.pending_rejection
except VersionReviewerFlags.DoesNotExist:
return None
@property
def needs_human_review_by_mad(self):
try:
return self.reviewerflags.needs_human_review_by_mad
except VersionReviewerFlags.DoesNotExist:
return False
@property
def maliciousness_score(self):
try:
# We use the score of the MAD scanner because it is the 'ensemble'
# score (i.e. score computed using all other scanner scores).
# We iterate on all .scannerresults instead of doing .filter()
# because there shouldn't be many results, and chances are the
# caller (normally reviewer tools review page) will have prefetched
# all scanner results.
score = [
result.score
for result in self.scannerresults.all()
if result.scanner == MAD
][0]
except IndexError:
score = None
return float(score * 100) if score and score > 0 else 0
@cached_property
def approved_for_groups(self):
approvals = list(self.promoted_approvals.all())
return [
(PROMOTED_GROUPS_BY_ID.get(approval.group_id), approval.application)
for approval in approvals
if approval.group_id in PROMOTED_GROUPS_BY_ID
]
class VersionReviewerFlags(ModelBase):
version = models.OneToOneField(
Version,
primary_key=True,
on_delete=models.CASCADE,
related_name='reviewerflags',
)
needs_human_review_by_mad = models.BooleanField(default=False, db_index=True)
pending_rejection = models.DateTimeField(
default=None, null=True, blank=True, db_index=True
)
def generate_static_theme_preview(theme_data, version_pk):
"""This redirection is so we can mock generate_static_theme_preview, where
needed, in tests."""
# To avoid a circular import
from . import tasks
tasks.generate_static_theme_preview.delay(theme_data, version_pk)
class VersionPreview(BasePreview, ModelBase):
version = models.ForeignKey(
Version, related_name='previews', on_delete=models.CASCADE
)
position = models.IntegerField(default=0)
sizes = JSONField(default=dict)
colors = JSONField(default=None, null=True)
media_folder = 'version-previews'
class Meta:
db_table = 'version_previews'
ordering = ('position', 'created')
indexes = [
LongNameIndex(
fields=('version',), name='version_previews_version_id_fk_versions_id'
),
models.Index(
fields=('version', 'position', 'created'),
name='version_position_created_idx',
),
]
@cached_property
def caption(self):
"""We only don't support defining a caption for previews because
they're auto-generated. This is for compatibility with Addon Preview
objects. (it's a cached_property so it can be set transparently)"""
return None
models.signals.post_delete.connect(
VersionPreview.delete_preview_files,
sender=VersionPreview,
dispatch_uid='delete_preview_files',
)
@use_primary_db
def update_status(sender, instance, **kw):
if not kw.get('raw'):
try:
instance.addon.reload()
instance.addon.update_status()
except models.ObjectDoesNotExist:
log.info(
'Got ObjectDoesNotExist processing Version change signal', exc_info=True
)
pass
def inherit_nomination(sender, instance, **kw):
"""
For new versions pending review, ensure nomination date
is inherited from last nominated version.
"""
if kw.get('raw'):
return
addon = instance.addon
if instance.nomination is None and addon.status in amo.UNREVIEWED_ADDON_STATUSES:
instance.inherit_nomination()
def cleanup_version(sender, instance, **kw):
"""On delete of the version object call the file delete and signals."""
if kw.get('raw'):
return
for file_ in instance.files.all():
cleanup_file(file_.__class__, file_)
@Version.on_change
def watch_changes(old_attr=None, new_attr=None, instance=None, sender=None, **kwargs):
if old_attr is None:
old_attr = {}
if new_attr is None:
new_attr = {}
changes = {
x for x in new_attr if not x.startswith('_') and new_attr[x] != old_attr.get(x)
}
if instance.channel == amo.RELEASE_CHANNEL_UNLISTED and 'deleted' in changes:
# Sync the related add-on to basket when an unlisted version is
# deleted. (When a listed version is deleted, watch_changes() in
# olympia.addon.models should take care of it (since _current_version
# will change).
from olympia.amo.tasks import trigger_sync_objects_to_basket
trigger_sync_objects_to_basket(
'addon', [instance.addon.pk], 'unlisted version deleted'
)
def watch_new_unlisted_version(sender=None, instance=None, **kwargs):
# Sync the related add-on to basket when an unlisted version is uploaded.
# Unlisted version deletion is handled by watch_changes() above, and new
# version approval changes are handled by watch_changes()
# in olympia.addon.models (since _current_version will change).
# What's left here is unlisted version upload.
if instance and instance.channel == amo.RELEASE_CHANNEL_UNLISTED:
from olympia.amo.tasks import trigger_sync_objects_to_basket
trigger_sync_objects_to_basket(
'addon', [instance.addon.pk], 'new unlisted version'
)
version_uploaded = django.dispatch.Signal()
version_uploaded.connect(watch_new_unlisted_version)
models.signals.pre_save.connect(
save_signal, sender=Version, dispatch_uid='version_translations'
)
models.signals.post_save.connect(
update_status, sender=Version, dispatch_uid='version_update_status'
)
models.signals.post_save.connect(
inherit_nomination, sender=Version, dispatch_uid='version_inherit_nomination'
)
models.signals.pre_delete.connect(
cleanup_version, sender=Version, dispatch_uid='cleanup_version'
)
models.signals.post_delete.connect(
update_status, sender=Version, dispatch_uid='version_update_status'
)
class LicenseManager(ManagerBase):
def builtins(self, cc=False):
return self.filter(builtin__gt=0, creative_commons=cc).order_by('builtin')
class License(ModelBase):
OTHER = 0
id = PositiveAutoField(primary_key=True)
name = TranslatedField()
url = models.URLField(null=True)
builtin = models.PositiveIntegerField(default=OTHER)
text = LinkifiedField()
on_form = models.BooleanField(
default=False, help_text='Is this a license choice in the devhub?'
)
some_rights = models.BooleanField(
default=False,
help_text='Show "Some Rights Reserved" instead of the license name?',
)
icons = models.CharField(
max_length=255, null=True, help_text='Space-separated list of icon identifiers.'
)
creative_commons = models.BooleanField(default=False)
objects = LicenseManager()
class Meta:
db_table = 'licenses'
indexes = [models.Index(fields=('builtin',), name='builtin_idx')]
def __str__(self):
license = self._constant or self
return str(license.name)
@property
def _constant(self):
return LICENSES_BY_BUILTIN.get(self.builtin)
models.signals.pre_save.connect(
save_signal, sender=License, dispatch_uid='license_translations'
)
class ApplicationsVersions(models.Model):
id = PositiveAutoField(primary_key=True)
application = models.PositiveIntegerField(
choices=amo.APPS_CHOICES, db_column='application_id'
)
version = models.ForeignKey(Version, related_name='apps', on_delete=models.CASCADE)
min = models.ForeignKey(
AppVersion, db_column='min', related_name='min_set', on_delete=models.CASCADE
)
max = models.ForeignKey(
AppVersion, db_column='max', related_name='max_set', on_delete=models.CASCADE
)
class Meta:
db_table = 'applications_versions'
constraints = [
models.UniqueConstraint(
fields=('application', 'version'), name='application_id'
),
]
def get_application_display(self):
return str(amo.APPS_ALL[self.application].pretty)
def get_latest_application_version(self):
return (
AppVersion.objects.filter(
~models.Q(version__contains='*'), application=self.application
)
.order_by('-version_int')
.first()
)
def __str__(self):
if self.version.is_compatible_by_default and self.version.is_compatible_app(
amo.APP_IDS[self.application]
):
return gettext('{app} {min} and later').format(
app=self.get_application_display(), min=self.min
)
return '%s %s - %s' % (self.get_application_display(), self.min, self.max)
|
/* Copyright (C) 2016 NooBaa */
'use strict';
/**
*
* BUCKET API
*
* client (currently web client) talking to the web server to work on bucket
*
*/
module.exports = {
id: 'bucket_api',
methods: {
create_bucket: {
method: 'POST',
params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
// if tiering is provided then chunk_coder_config & chunk_split_config are ignored!
tiering: { $ref: 'common_api#/definitions/tiering_name' },
chunk_split_config: { $ref: 'common_api#/definitions/chunk_split_config' },
chunk_coder_config: { $ref: 'common_api#/definitions/chunk_coder_config' },
tag: { type: 'string' },
object_lock_configuration: { $ref: '#/definitions/object_lock_configuration' },
namespace: { $ref: '#/definitions/namespace_bucket_config' },
lock_enabled: {
type: 'boolean'
},
bucket_claim: { $ref: '#/definitions/bucket_claim' },
}
},
reply: {
$ref: '#/definitions/bucket_info'
},
auth: {
system: 'admin'
}
},
read_bucket: {
method: 'GET',
params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
reply: {
$ref: '#/definitions/bucket_info'
},
auth: {
system: 'admin'
}
},
put_bucket_tagging: {
method: 'PUT',
params: {
type: 'object',
required: [
'tagging',
'name',
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
tagging: {
$ref: 'common_api#/definitions/tagging'
}
}
},
auth: {
system: ['admin', 'user']
}
},
delete_bucket_tagging: {
method: 'DELETE',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
auth: {
system: ['admin', 'user']
}
},
get_bucket_tagging: {
method: 'GET',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
reply: {
type: 'object',
properties: {
tagging: {
$ref: 'common_api#/definitions/tagging'
}
}
},
auth: {
system: ['admin', 'user']
}
},
put_bucket_encryption: {
method: 'PUT',
params: {
type: 'object',
required: [
'encryption',
'name',
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
encryption: {
$ref: 'common_api#/definitions/bucket_encryption'
}
}
},
auth: {
system: ['admin', 'user']
}
},
delete_bucket_encryption: {
method: 'DELETE',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
auth: {
system: ['admin', 'user']
}
},
delete_bucket_website: {
method: 'DELETE',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
auth: {
system: ['admin', 'user']
}
},
get_bucket_encryption: {
method: 'GET',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
reply: {
type: 'object',
properties: {
encryption: {
$ref: 'common_api#/definitions/bucket_encryption'
},
},
},
auth: {
system: ['admin', 'user']
}
},
get_bucket_website: {
method: 'GET',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
reply: {
type: 'object',
properties: {
website: {
$ref: 'common_api#/definitions/bucket_website'
}
}
},
auth: {
system: ['admin', 'user']
}
},
put_bucket_website: {
method: 'PUT',
params: {
type: 'object',
required: [
'website',
'name',
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
website: {
$ref: 'common_api#/definitions/bucket_website'
}
}
},
auth: {
system: ['admin', 'user']
}
},
get_bucket_policy: {
method: 'GET',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
reply: {
type: 'object',
properties: {
policy: {
$ref: 'common_api#/definitions/bucket_policy'
},
},
},
auth: {
system: ['admin', 'user']
}
},
delete_bucket_policy: {
method: 'DELETE',
params: {
type: 'object',
required: [
'name'
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
auth: {
system: ['admin', 'user']
}
},
put_bucket_policy: {
method: 'PUT',
params: {
type: 'object',
required: [
'policy',
'name',
],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
policy: {
$ref: 'common_api#/definitions/bucket_policy'
}
}
},
auth: {
system: ['admin', 'user'],
}
},
read_bucket_sdk_info: {
method: 'GET',
params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
reply: {
$ref: '#/definitions/bucket_sdk_info'
},
auth: {
system: 'admin',
anonymous: true,
}
},
update_bucket: {
method: 'PUT',
params: {
$ref: '#/definitions/update_bucket_params'
},
auth: {
system: 'admin'
}
},
update_buckets: {
method: 'PUT',
params: {
type: 'array',
items: {
$ref: '#/definitions/update_bucket_params'
},
},
auth: {
system: 'admin'
}
},
delete_bucket: {
method: 'DELETE',
params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
// internal_call is used by bucket_reclaimer to delete the bucket after it's empty
internal_call: { type: 'boolean' },
}
},
auth: {
system: 'admin'
}
},
delete_bucket_and_objects: {
method: 'DELETE',
params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
auth: {
// maybe only allow operator to perform this?
system: 'admin'
}
},
delete_bucket_lifecycle: {
method: 'DELETE',
params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
auth: {
system: 'admin'
}
},
list_buckets: {
method: 'GET',
reply: {
type: 'object',
required: ['buckets'],
properties: {
buckets: {
type: 'array',
items: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
}
}
}
},
auth: {
system: 'admin'
}
},
update_bucket_s3_access: {
method: 'PUT',
params: {
type: 'object',
required: ['name', 'allowed_accounts'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
allowed_accounts: {
type: 'array',
items: { $ref: 'common_api#/definitions/account_name' },
}
}
},
auth: {
system: 'admin'
}
},
export_bucket_bandwidth_usage: {
method: 'GET',
params: {
type: 'object',
required: ['name', 'since', 'till'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
since: {
idate: true
},
till: {
idate: true
},
}
},
reply: {
type: 'string',
},
auth: {
system: 'admin'
}
},
get_bucket_throughput_usage: {
method: 'GET',
params: {
type: 'object',
required: ['since', 'till', 'resolution', 'buckets'],
properties: {
buckets: {
type: 'array',
items: { $ref: 'common_api#/definitions/bucket_name' },
},
since: { idate: true },
till: { idate: true },
resolution: {
type: 'integer'
}
}
},
reply: {
type: 'array',
items: {
type: 'object',
required: ['start_time', 'end_time', 'read_count', 'read_bytes', 'write_count', 'write_bytes'],
properties: {
start_time: {
idate: true
},
end_time: {
idate: true
},
read_count: {
type: 'integer'
},
write_count: {
type: 'integer'
},
read_bytes: {
$ref: 'common_api#/definitions/bigint'
},
write_bytes: {
$ref: 'common_api#/definitions/bigint'
},
}
}
},
auth: {
system: 'admin'
}
},
get_buckets_stats_by_content_type: {
method: 'GET',
reply: {
type: 'array',
items: {
type: 'object',
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
stats: {
type: 'array',
items: {
type: 'object',
properties: {
content_type: {
type: 'string'
},
reads: {
type: 'integer',
},
writes: {
type: 'integer',
},
last_read: {
idate: true
},
last_write: {
idate: true
},
}
}
}
}
}
},
auth: {
system: 'admin'
}
},
get_objects_size_histogram: {
method: 'GET',
reply: {
type: 'array',
items: {
type: 'object',
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
bins: {
type: 'array',
items: {
type: 'object',
properties: {
count: {
type: 'integer'
},
sum: {
type: 'integer'
},
}
}
}
}
}
},
auth: {
system: ['admin']
}
},
get_cloud_buckets: {
method: 'GET',
params: {
type: 'object',
required: ['connection'],
properties: {
connection: {
type: 'string'
}
}
},
reply: {
type: 'array',
items: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
used_by: {
type: 'object',
required: ['name', 'usage_type'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
usage_type: {
type: 'string',
enum: ['CLOUD_RESOURCE', 'NAMESPACE_RESOURCE']
},
}
}
}
}
},
auth: {
system: 'admin'
}
},
set_bucket_lifecycle_configuration_rules: {
method: 'PUT',
params: {
type: 'object',
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
rules: {
type: 'array',
items: {
type: 'object',
required: ['id', 'prefix', 'status', 'expiration'],
properties: {
id: {
type: 'string'
},
prefix: {
type: 'string'
},
status: {
type: 'string'
},
expiration: {
type: 'object',
properties: {
days: {
type: 'integer'
},
date: {
idate: true
},
expired_object_delete_marker: {
type: 'boolean'
}
}
},
abort_incomplete_multipart_upload: {
type: 'object',
properties: {
days_after_initiation: {
type: 'integer'
},
}
},
transition: {
type: 'object',
properties: {
date: {
idate: true
},
storage_class: {
$ref: '#/definitions/storage_class_enum'
}
}
},
noncurrent_version_expiration: {
type: 'object',
properties: {
noncurrent_days: {
type: 'integer'
},
}
},
noncurrent_version_transition: {
type: 'object',
properties: {
noncurrent_days: {
type: 'integer'
},
storage_class: {
$ref: '#/definitions/storage_class_enum'
}
}
},
}
},
}
}
},
auth: {
system: 'admin'
},
},
get_bucket_lifecycle_configuration_rules: {
method: 'GET',
params: {
type: 'object',
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
reply: {
type: 'array',
items: {
type: 'object',
required: ['id', 'prefix', 'status', 'expiration'],
properties: {
id: {
type: 'string'
},
prefix: {
type: 'string'
},
status: {
type: 'string'
},
last_sync: {
idate: true
},
expiration: {
type: 'object',
properties: {
days: {
type: 'integer'
},
date: {
idate: true
},
expired_object_delete_marker: {
type: 'boolean'
}
}
},
abort_incomplete_multipart_upload: {
type: 'object',
properties: {
days_after_initiation: {
type: 'integer'
},
}
},
transition: {
type: 'object',
properties: {
date: {
idate: true
},
storage_class: {
$ref: '#/definitions/storage_class_enum'
}
}
},
noncurrent_version_expiration: {
type: 'object',
properties: {
noncurrent_days: {
type: 'integer'
},
}
},
noncurrent_version_transition: {
type: 'object',
properties: {
noncurrent_days: {
type: 'integer'
},
storage_class: {
$ref: '#/definitions/storage_class_enum'
}
}
},
},
}
},
auth: {
system: 'admin'
}
},
add_bucket_lambda_trigger: {
method: 'PUT',
params: {
$ref: '#/definitions/new_lambda_trigger'
},
auth: {
system: 'admin'
}
},
delete_bucket_lambda_trigger: {
method: 'DELETE',
required: ['id', 'bucket_name'],
params: {
type: 'object',
properties: {
id: {
objectid: true
},
bucket_name: { $ref: 'common_api#/definitions/bucket_name' },
}
},
auth: {
system: 'admin'
}
},
update_bucket_lambda_trigger: {
method: 'PUT',
params: {
$ref: '#/definitions/update_lambda_trigger'
},
auth: {
system: 'admin'
}
},
update_all_buckets_default_pool: {
method: 'PUT',
params: {
type: 'object',
required: ['pool_name'],
properties: {
pool_name: {
type: 'string'
},
}
},
auth: {
system: 'admin'
}
},
claim_bucket: {
method: 'PUT',
required: ['name', 'email', 'create_bucket', 'namespace'],
params: {
type: 'object',
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
tiering: { $ref: 'common_api#/definitions/tiering_name' },
email: { $ref: 'common_api#/definitions/email' },
create_bucket: { type: 'boolean' },
bucket_claim: { $ref: '#/definitions/bucket_claim' },
},
},
reply: {
type: 'object',
required: ['access_keys'],
properties: {
access_keys: {
$ref: 'common_api#/definitions/access_keys'
}
}
},
auth: {
system: 'admin'
}
},
delete_claim: {
method: 'PUT',
required: ['name', 'email', 'delete_bucket'],
params: {
type: 'object',
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
email: { $ref: 'common_api#/definitions/email' },
delete_bucket: { type: 'boolean' }
},
},
auth: {
system: 'admin'
}
},
put_object_lock_configuration: {
method: 'PUT',
params: {
type: 'object',
required: ['name', 'object_lock_configuration'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
object_lock_configuration: { $ref: '#/definitions/object_lock_configuration' },
},
},
auth: {
system: 'admin'
},
},
get_object_lock_configuration: {
method: 'GET',
params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
},
},
reply: {
$ref: '#/definitions/object_lock_configuration'
},
auth: {
system: 'admin'
},
},
},
definitions: {
bucket_info: {
type: 'object',
required: ['name', 'bucket_type', 'versioning', 'usage_by_pool', 'storage', 'data', 'num_objects', 'mode'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
bucket_type: {
enum: ['REGULAR', 'NAMESPACE'],
type: 'string',
},
owner_account: {
type: 'object',
required: ['email', 'id'],
properties: {
email: { $ref: 'common_api#/definitions/email' },
id: { objectid: true }
}
},
versioning: { $ref: '#/definitions/versioning' },
namespace: { $ref: '#/definitions/namespace_bucket_config' },
bucket_claim: { $ref: '#/definitions/bucket_claim' },
tiering: {
$ref: 'tiering_policy_api#/definitions/tiering_policy'
},
spillover: {
type: 'string'
},
object_lock_configuration: { $ref: '#/definitions/object_lock_configuration' },
storage: {
type: 'object',
properties: {
values: {
$ref: 'common_api#/definitions/storage_info'
},
last_update: {
idate: true
}
}
},
quota: {
type: 'object',
required: ['size', 'unit'],
properties: {
size: {
type: 'integer'
},
unit: {
type: 'string',
enum: ['GIGABYTE', 'TERABYTE', 'PETABYTE']
},
}
},
data: {
type: 'object',
properties: {
// This is the sum of all compressed chunks that are related to the bucket.
// Which means that it includes dedup and compression, but not replicas.
size_reduced: {
$ref: 'common_api#/definitions/bigint'
},
// This is logical size aggregation of objects that are related to the bucket.
size: {
$ref: 'common_api#/definitions/bigint'
},
// This is the actual free space of the bucket considering data placement policy.
// On mirror it is the minimum free space of the pools, on spread it is the sum.
// Also we divide by replicas in order to get the actual size that can be written.
free: {
$ref: 'common_api#/definitions/bigint'
},
available_for_upload: {
$ref: 'common_api#/definitions/bigint'
},
// spillover_free: {
// $ref: 'common_api#/definitions/bigint'
// },
last_update: {
idate: true
}
}
},
usage_by_pool: {
type: 'object',
required: ['last_update', 'pools'],
properties: {
last_update: {
idate: true
},
pools: {
type: 'array',
items: {
type: 'object',
required: ['pool_name', 'storage'],
properties: {
pool_name: {
type: 'string'
},
storage: {
type: 'object',
required: ['blocks_size'],
properties: {
blocks_size: {
$ref: 'common_api#/definitions/bigint'
},
},
}
},
},
},
}
},
num_objects: {
type: 'object',
required: ['value', 'last_update'],
properties: {
value: {
type: 'integer'
},
last_update: {
idate: true
}
}
},
host_tolerance: {
type: 'integer'
},
node_tolerance: {
type: 'integer'
},
tag: {
type: 'string'
},
writable: {
type: 'boolean'
},
stats: {
type: 'object',
properties: {
reads: {
type: 'integer'
},
writes: {
type: 'integer'
},
last_read: {
idate: true
},
last_write: {
idate: true
},
},
},
stats_by_type: {
type: 'array',
items: {
type: 'object',
properties: {
data_type: {
type: 'string'
},
reads: {
type: 'integer'
},
writes: {
type: 'integer'
},
size: {
$ref: 'common_api#/definitions/bigint'
},
count: {
type: 'integer'
},
},
}
},
policy_modes: {
$ref: '#/definitions/policy_modes'
},
mode: {
$ref: 'common_api#/definitions/bucket_mode'
},
undeletable: {
$ref: '#/definitions/undeletable_bucket_reason'
},
triggers: {
type: 'array',
items: {
$ref: '#/definitions/lambda_trigger_info'
}
},
tagging: {
$ref: 'common_api#/definitions/tagging'
},
encryption: {
$ref: 'common_api#/definitions/bucket_encryption'
},
website: {
$ref: 'common_api#/definitions/bucket_website'
},
s3_policy: {
$ref: 'common_api#/definitions/bucket_policy'
},
}
},
bucket_claim: {
type: 'object',
required: ['bucket_class', 'namespace'],
properties: {
// TODO: Fill this with relevant info
bucket_class: {
type: 'string',
},
namespace: {
type: 'string',
}
}
},
bucket_sdk_info: {
type: 'object',
required: [
'name', 'system_owner', 'bucket_owner'
],
properties: {
_id: {
objectid: true
},
name: {
$ref: 'common_api#/definitions/bucket_name'
},
system_owner: {
$ref: 'common_api#/definitions/email'
},
bucket_owner: {
$ref: 'common_api#/definitions/email'
},
website: {
$ref: 'common_api#/definitions/bucket_website'
},
namespace: {
type: 'object',
required: [
'read_resources',
'write_resource',
],
properties: {
read_resources: {
type: 'array',
items: {
type: 'object',
required: [
'resource',
],
properties: {
resource: { $ref: 'pool_api#/definitions/namespace_resource_extended_info' },
path: { type: 'string' }
}
}
},
write_resource: {
type: 'object',
required: [
'resource',
],
properties: {
resource: { $ref: 'pool_api#/definitions/namespace_resource_extended_info' },
path: { type: 'string' }
}
},
caching: {
$ref: 'common_api#/definitions/bucket_cache_config'
},
should_create_underlying_storage: {
type: 'boolean'
},
},
},
active_triggers: {
type: 'array',
items: {
type: 'object',
properties: {
event_name: {
$ref: 'common_api#/definitions/bucket_trigger_event'
},
object_prefix: {
type: 'string'
},
object_suffix: {
type: 'string'
}
}
}
},
s3_policy: {
$ref: 'common_api#/definitions/bucket_policy'
},
bucket_info: {
$ref: '#/definitions/bucket_info'
},
}
},
storage_class_enum: {
enum: ['STANDARD_IA', 'GLACIER'],
type: 'string'
},
update_bucket_params: {
type: 'object',
required: ['name'],
properties: {
name: { $ref: 'common_api#/definitions/bucket_name' },
new_name: { $ref: 'common_api#/definitions/bucket_name' },
tiering: { $ref: 'common_api#/definitions/tiering_name' },
new_tag: {
type: 'string',
},
quota: {
anyOf: [{
type: 'null'
}, {
type: 'object',
required: ['size', 'unit'],
properties: {
size: {
type: 'integer'
},
unit: {
type: 'string',
enum: ['GIGABYTE', 'TERABYTE', 'PETABYTE']
},
}
}]
},
// spillover: {
// oneOf: [{
// type: 'string'
// }, {
// type: 'null'
// }]
// },
namespace: { $ref: '#/definitions/namespace_bucket_config' },
versioning: { $ref: '#/definitions/versioning' },
}
},
policy_modes: {
type: 'object',
required: ['resiliency_status', 'quota_status'],
properties: {
resiliency_status: {
type: 'string',
enum: [
'NOT_ENOUGH_RESOURCES',
'POLICY_PARTIALLY_APPLIED',
'RISKY_TOLERANCE',
'DATA_ACTIVITY',
'OPTIMAL'
]
},
quota_status: {
type: 'string',
enum: [
'QUOTA_NOT_SET',
'APPROUCHING_QUOTA',
'EXCEEDING_QUOTA',
'OPTIMAL'
]
},
}
},
undeletable_bucket_reason: {
enum: ['NOT_EMPTY'],
type: 'string',
},
new_lambda_trigger: {
type: 'object',
required: ['bucket_name', 'event_name', 'func_name'],
properties: {
bucket_name: { $ref: 'common_api#/definitions/bucket_name' },
event_name: {
$ref: 'common_api#/definitions/bucket_trigger_event'
},
func_name: {
type: 'string'
},
func_version: {
type: 'string'
},
enabled: {
type: 'boolean',
},
object_prefix: {
type: 'string'
},
object_suffix: {
type: 'string'
},
attempts: {
type: 'integer'
},
}
},
update_lambda_trigger: {
type: 'object',
required: ['id'],
properties: {
id: {
objectid: true
},
bucket_name: { $ref: 'common_api#/definitions/bucket_name' },
event_name: {
$ref: 'common_api#/definitions/bucket_trigger_event'
},
func_name: {
type: 'string'
},
func_version: {
type: 'string'
},
enabled: {
type: 'boolean',
},
object_prefix: {
type: 'string'
},
object_suffix: {
type: 'string'
},
attempts: {
type: 'integer'
},
}
},
versioning: {
type: 'string',
enum: ['DISABLED', 'SUSPENDED', 'ENABLED']
},
lambda_trigger_info: {
type: 'object',
required: ['id', 'event_name', 'func_name'],
properties: {
id: {
objectid: true
},
event_name: {
$ref: 'common_api#/definitions/bucket_trigger_event'
},
func_name: {
type: 'string'
},
func_version: {
type: 'string'
},
enabled: {
type: 'boolean',
},
permission_problem: {
type: 'boolean',
},
last_run: {
idate: true
},
object_prefix: {
type: 'string'
},
object_suffix: {
type: 'string'
},
attempts: {
type: 'integer'
},
}
},
object_lock_configuration: {
type: 'object',
properties: {
object_lock_enabled: { type: 'string' },
rule: {
type: 'object',
properties: {
default_retention: {
oneOf: [{
type: 'object',
properties: {
years: { type: 'integer' },
mode: {
type: 'string',
enum: ['GOVERNANCE', 'COMPLIANCE']
}
}
},
{
type: 'object',
properties: {
days: { type: 'integer' },
mode: {
type: 'string',
enum: ['GOVERNANCE', 'COMPLIANCE']
}
}
}
]
}
}
}
}
},
// namespace bucket configuration
namespace_resource_config: {
type: 'object',
required: ['resource'],
properties: {
resource: { type: 'string' },
path: { type: 'string' }
}
},
namespace_bucket_config: {
type: 'object',
required: ['write_resource', 'read_resources'],
properties: {
write_resource: {
$ref: '#/definitions/namespace_resource_config'
},
read_resources: {
type: 'array',
items: {
$ref: '#/definitions/namespace_resource_config'
},
},
caching: {
$ref: 'common_api#/definitions/bucket_cache_config'
},
should_create_underlying_storage: { type: 'boolean' } // should create underlying storage
}
},
}
};
|
import Dropdown from 'flarum/components/Dropdown';
import icon from 'flarum/helpers/icon';
import NotificationList from 'flarum/components/NotificationList';
export default class NotificationsDropdown extends Dropdown {
static initProps(props) {
props.className = props.className || 'NotificationsDropdown';
props.buttonClassName = props.buttonClassName || 'Button Button--flat';
props.menuClassName = props.menuClassName || 'Dropdown-menu--right';
props.label = props.label || app.translator.trans('core.forum.notifications.tooltip');
props.icon = props.icon || 'fas fa-bell';
super.initProps(props);
}
init() {
super.init();
this.list = new NotificationList();
}
getButton() {
const newNotifications = this.getNewCount();
const vdom = super.getButton();
vdom.attrs.title = this.props.label;
vdom.attrs.className += (newNotifications ? ' new' : '');
vdom.attrs.onclick = this.onclick.bind(this);
return vdom;
}
getButtonContent() {
const unread = this.getUnreadCount();
return [
icon(this.props.icon, {className: 'Button-icon'}),
unread ? <span className="NotificationsDropdown-unread">{unread}</span> : '',
<span className="Button-label">{this.props.label}</span>
];
}
getMenu() {
return (
<div className={'Dropdown-menu ' + this.props.menuClassName} onclick={this.menuClick.bind(this)}>
{this.showing ? this.list.render() : ''}
</div>
);
}
onclick() {
if (app.drawer.isOpen()) {
this.goToRoute();
} else {
this.list.load();
}
}
goToRoute() {
m.route(app.route('notifications'));
}
getUnreadCount() {
return app.session.user.unreadNotificationsCount();
}
getNewCount() {
return app.session.user.newNotificationsCount();
}
menuClick(e) {
// Don't close the notifications dropdown if the user is opening a link in a
// new tab or window.
if (e.shiftKey || e.metaKey || e.ctrlKey || e.which === 2) e.stopPropagation();
}
}
|
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="EntitySnapshotRecord",
fields=[
("uid", models.BigAutoField(primary_key=True, serialize=False)),
("application_name", models.CharField(max_length=32)),
("originator_id", models.UUIDField()),
("originator_version", models.BigIntegerField()),
("topic", models.TextField()),
("state", models.BinaryField()),
],
options={"db_table": "entity_snapshots"},
),
migrations.CreateModel(
name="IntegerSequencedRecord",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
("sequence_id", models.UUIDField()),
("position", models.BigIntegerField()),
("topic", models.TextField()),
("state", models.BinaryField()),
],
options={"db_table": "integer_sequenced_items"},
),
migrations.CreateModel(
name="NotificationTrackingRecord",
fields=[
("uid", models.BigAutoField(primary_key=True, serialize=False)),
("application_name", models.CharField(max_length=32)),
("upstream_application_name", models.CharField(max_length=32)),
("pipeline_id", models.IntegerField()),
("notification_id", models.BigIntegerField()),
],
options={"db_table": "notification_tracking"},
),
migrations.CreateModel(
name="SnapshotRecord",
fields=[
("uid", models.BigAutoField(primary_key=True, serialize=False)),
("sequence_id", models.UUIDField()),
("position", models.BigIntegerField()),
("topic", models.TextField()),
("state", models.BinaryField()),
],
options={"db_table": "snapshots"},
),
migrations.CreateModel(
name="StoredEventRecord",
fields=[
("uid", models.BigAutoField(primary_key=True, serialize=False)),
("application_name", models.CharField(max_length=32)),
("originator_id", models.UUIDField()),
("originator_version", models.BigIntegerField()),
("pipeline_id", models.IntegerField(null=True)),
("notification_id", models.BigIntegerField(null=True)),
("topic", models.TextField()),
("state", models.BinaryField()),
("causal_dependencies", models.TextField()),
],
options={"db_table": "stored_events"},
),
migrations.CreateModel(
name="TimestampSequencedRecord",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
("sequence_id", models.UUIDField()),
("position", models.DecimalField(decimal_places=6, max_digits=24)),
("topic", models.TextField()),
("state", models.BinaryField()),
],
options={"db_table": "timestamp_sequenced_items"},
),
migrations.AddIndex(
model_name="timestampsequencedrecord",
index=models.Index(fields=["position"], name="position_idx"),
),
migrations.AlterUniqueTogether(
name="timestampsequencedrecord",
unique_together={("sequence_id", "position")},
),
migrations.AlterUniqueTogether(
name="storedeventrecord",
unique_together={
("application_name", "originator_id", "originator_version"),
("application_name", "pipeline_id", "notification_id"),
},
),
migrations.AlterUniqueTogether(
name="snapshotrecord", unique_together={("sequence_id", "position")}
),
migrations.AlterUniqueTogether(
name="notificationtrackingrecord",
unique_together={
(
"application_name",
"upstream_application_name",
"pipeline_id",
"notification_id",
)
},
),
migrations.AlterUniqueTogether(
name="integersequencedrecord", unique_together={("sequence_id", "position")}
),
migrations.AlterUniqueTogether(
name="entitysnapshotrecord",
unique_together={
("application_name", "originator_id", "originator_version")
},
),
]
|
import itertools
import json
import logging
import math
import os
import string
import time
from datetime import datetime
from mimetypes import types_map
import bs4
import requests
from django.conf import settings
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.geos import GEOSException, fromstr
from django.urls import resolve
from django.http import HttpResponse
from django.template.exceptions import TemplateDoesNotExist
from django.template.loader import get_template
from django.utils import six
from django.utils import timezone
from django.utils.six.moves.urllib.parse import urljoin, quote
from django.utils.translation import get_language
from .settings import app_settings, API_SRID
logger = logging.getLogger(__name__)
def bbox_split(bbox, by_x=2, by_y=2, cycle=False):
"""Divide a box in rectangle, by_x parts and by_y parts"""
minx, miny, maxx, maxy = bbox
stepx = (maxx - minx) / by_x
stepy = (maxy - miny) / by_y
def gen():
"""define as inner function to decorate it with cycle"""
stepx_tmp = minx
while stepx_tmp + stepx <= maxx:
stepx_next = stepx_tmp + stepx
stepy_tmp = miny
while stepy_tmp + stepy <= maxy:
stepy_next = stepy_tmp + stepy
yield (stepx_tmp, stepy_tmp, stepx_next, stepy_next)
stepy_tmp = stepy_next
stepx_tmp = stepx_next
if cycle:
return itertools.cycle(gen())
else:
return gen()
def bbox_split_srid_2154(*args, **kwargs):
"""Just round"""
gen = bbox_split(*args, **kwargs)
return iter(lambda: map(round, next(gen)), None)
def api_bbox(bbox, srid=None, buffer=0.0):
""" Receives a tuple(xmin, ymin, xmax, ymax) and
returns a tuple in API projection.
:srid: bbox projection (Default: settings.SRID)
:buffer: grow the bbox in ratio of width (Default: 0.0)
"""
srid = srid or settings.SRID
wkt_box = 'POLYGON(({0} {1}, {2} {1}, {2} {3}, {0} {3}, {0} {1}))'
wkt = wkt_box.format(*bbox)
native = wkt_to_geom(wkt, srid_from=srid)
if srid != API_SRID:
native.transform(API_SRID)
if buffer > 0:
extent = native.extent
width = extent[2] - extent[0]
native = native.buffer(width * buffer)
return tuple(native.extent)
def wkt_to_geom(wkt, srid_from=None, silent=False):
if srid_from is None:
srid_from = API_SRID
try:
return fromstr(wkt, srid=srid_from)
except (GDALException, GEOSException) as e:
if not silent:
raise e
return None
def transform_wkt(wkt, srid_from=None, srid_to=None, dim=3):
"""
Changes SRID, and returns 3D wkt
"""
if srid_from is None:
srid_from = API_SRID
if srid_to is None:
srid_to = settings.SRID
try:
geom = fromstr(wkt, srid=srid_from)
if srid_from != srid_to:
geom.transform(srid_to)
extracoords = ' 0.0' * (dim - 2) # add missing dimensions
wkt3d = geom.wkt.replace(',', extracoords + ',')
wkt3d = wkt3d.replace(')', extracoords + ')')
return 'SRID=%s;%s' % (srid_to, wkt3d)
except (GDALException, GEOSException, TypeError, ValueError) as e:
if settings.DEBUG or not getattr(settings, 'TEST', False):
logger.error("wkt_to_geom('%s', %s, %s) : %s" % (wkt, srid_from, srid_to, e))
return None
def smart_urljoin(base, path):
if base[-1] != '/':
base += '/'
if path[0] == '/':
path = path[1:]
return urljoin(base, path)
def is_file_newer(path, date_update, delete_empty=True):
if not os.path.exists(path):
return False
if date_update is None:
return False
if os.path.getsize(path) == 0:
if delete_empty:
os.remove(path)
return False
modified = datetime.utcfromtimestamp(os.path.getmtime(path))
modified = modified.replace(tzinfo=timezone.utc)
return modified > date_update
def get_source(url, headers):
logger.info("Request to: %s" % url)
source = requests.get(url, headers=headers)
status_error = 'Request on %s failed (status=%s)' % (url, source.status_code)
assert source.status_code == 200, status_error
content_error = 'Request on %s returned empty content' % url
assert len(source.content) > 0, content_error
return source
def download_to_stream(url, stream, silent=False, headers=None):
""" Download url and writes response to stream.
"""
source = None
try:
try:
source = get_source(url, headers)
except requests.exceptions.ConnectionError:
time.sleep(1)
source = get_source(url, headers)
except (AssertionError, requests.exceptions.RequestException) as e:
logger.exception(e)
logger.info('Headers sent: %s' % headers)
if hasattr(source, 'text'):
logger.info('Response: %s' % source.text[:150])
if not silent:
raise
if source is None:
return source
try:
stream.write(source.content)
stream.flush()
except IOError as e:
logger.exception(e)
if not silent:
raise
if isinstance(stream, HttpResponse):
stream.status_code = source.status_code
# Copy headers
for header, value in source.headers.items():
stream[header] = value
return source
def convertit_url(url, from_type=None, to_type=None, proxy=False):
if not to_type:
to_type = 'application/pdf'
mimetype = to_type
if '/' not in mimetype:
extension = '.' + mimetype if not mimetype.startswith('.') else mimetype
mimetype = types_map[extension]
fromparam = ("&from=%s" % quote(from_type)) if from_type is not None else ''
params = 'url={url}{fromparam}&to={to}'.format(url=quote(url),
fromparam=fromparam,
to=quote(mimetype))
url = '{server}/?{params}'.format(server=app_settings['CONVERSION_SERVER'],
params=params)
return url
def convertit_download(url, destination, from_type=None, to_type='application/pdf', headers=None):
# Mock for tests
if getattr(settings, 'TEST', False):
open(destination, 'w').write("Mock\n")
return
url = convertit_url(url, from_type, to_type)
fd = open(destination, 'wb') if isinstance(destination, six.string_types) else destination
download_to_stream(url, fd, headers=headers)
def capture_url(url, width=None, height=None, selector=None, waitfor=None):
"""Return URL to request a capture from Screamshotter
"""
server = app_settings['CAPTURE_SERVER']
width = ('&width=%s' % width) if width else ''
height = ('&height=%s' % height) if height else ''
selector = ('&selector=%s' % quote(selector)) if selector else ''
waitfor = ('&waitfor=%s' % quote(waitfor)) if waitfor else ''
params = '{width}{height}{selector}{waitfor}'.format(width=width,
height=height,
selector=selector,
waitfor=waitfor)
capture_url = '{server}/?url={url}{params}'.format(server=server,
url=quote(url),
params=params)
return capture_url
def capture_image(url, stream, **kwargs):
"""Capture url to stream.
"""
url = capture_url(url, **kwargs)
download_to_stream(url, stream)
def capture_map_image(url, destination, size=None, aspect=1.0, waitfor='.leaflet-tile-loaded', printcontext=None):
"""Prepare aspect of the detail page
It relies on JS code in MapEntity.Context
"""
# Control aspect of captured images
if size is None:
size = app_settings['MAP_CAPTURE_SIZE']
if aspect < 1.0:
mapsize = dict(width=size * aspect, height=size)
else:
mapsize = dict(width=size, height=size / aspect)
_printcontext = dict(mapsize=mapsize)
_printcontext['print'] = True
if printcontext:
_printcontext.update(printcontext)
serialized = json.dumps(_printcontext)
# Run head-less capture (takes time)
url += '?lang={}&context={}'.format(get_language(), quote(serialized))
with open(destination, 'wb') as fd:
capture_image(url, fd,
selector='.map-panel',
waitfor=waitfor)
def extract_attributes_html(url, request):
"""
The tidy XHTML version of objects attributes.
Since we have to insert them in document exports, we extract the
``details-panel`` of the detail page, using BeautifulSoup.
With this, we save a lot of efforts, since we do have to build specific Appy.pod
templates for each model.
"""
func, args, kwargs = resolve(url)
response = func(request, *args, **kwargs)
response.render()
soup = bs4.BeautifulSoup(response.content, 'lxml')
details = soup.find(id="properties")
if details is None:
raise ValueError('Content is of detail page is invalid')
# Remove "Add" buttons
for p in details('p'):
if 'autohide' in p.get('class', ''):
p.extract()
# Remove Javascript
for s in details('script'):
s.extract()
# Remove images (Appy.pod fails with them)
for i in details('img'):
i.replaceWith(i.get('title', ''))
# Remove links (Appy.pod sometimes shows empty strings)
for a in details('a'):
a.replaceWith(a.text)
# Prettify (ODT compat.) and convert unicode to XML entities
cooked = details.prettify('ascii', formatter='html').decode()
return cooked
def user_has_perm(user, perm):
# First check if the user has the permission (even anon user)
if user.has_perm(perm):
return True
if user.is_anonymous:
return perm in app_settings['ANONYMOUS_VIEWS_PERMS']
return False
def alphabet_enumeration(length):
"""
Return list of letters : A, B, ... Z, AA, AB, ...
See mapentity/leaflet.enumeration.js
"""
if length == 0:
return []
if length == 1:
return ["A"]
width = int(math.ceil(math.log(length, 26)))
enums = []
alphabet = string.ascii_uppercase
for i in range(length):
enum = ""
for j in range(width):
enum = alphabet[i % 26] + enum
i = i // 26
enums.append(enum)
return enums
def suffix_for(template_name_suffix, template_type, extension):
return "%s%s.%s" % (template_name_suffix, template_type, extension)
def name_for(app, modelname, suffix):
return "%s/%s%s" % (app, modelname, suffix)
def smart_get_template(model, suffix):
for appname, modelname in [(model._meta.app_label, model._meta.object_name.lower()),
("mapentity", "override"),
("mapentity", "mapentity")]:
try:
template_name = name_for(appname, modelname, suffix)
get_template(template_name) # Will raise if not exist
return template_name
except TemplateDoesNotExist:
pass
return None
|
import unittest
import pytest
from algorithms.dynamic_programming import partition_problem as pp
@pytest.mark.parametrize("numbers,expected", [
([1, 2, 3, 4], True)
])
def test_recursive_partition_problem(numbers, expected):
actual, subsets = pp.recursive_partition_problem(numbers)
assert expected == actual
@pytest.mark.parametrize("numbers,expected", [
([1, 2, 3, 4], True)
])
def test_memoized_partition_problem(numbers, expected):
actual, subsets = pp.memoized_partition_problem(numbers)
assert expected == actual
@pytest.mark.parametrize("numbers,expected", [
([1, 2, 3, 4], True),
([2, 4, 5], False)
])
def test_bottom_up_partition_problem(numbers, expected):
assert expected == pp.bottom_up_partition_problem(numbers)
if __name__ == '__main__':
unittest.main()
|
!(function(){"use strict";function t(t){return t&&t.__esModule?t.default:t}function e(t,e){return e={exports:{}},t(e,e.exports),e.exports}function n(t,e){var n=e.authToken,r=e.host;return xe({authToken:n,host:r,isValidating:!0,isInvalid:!1,errorMessage:""})}function r(){return Ve.getInitialState()}function i(t,e){var n=e.errorMessage;return t.withMutations((function(t){return t.set("isValidating",!1).set("isInvalid",!0).set("errorMessage",n)}))}function o(t,e){var n=e.authToken,r=e.host;return Fe({authToken:n,host:r})}function u(){return Ge.getInitialState()}function a(t,e){var n=e.rememberAuth;return n}function s(t){return t.withMutations((function(t){t.set("isStreaming",!0).set("hasError",!1)}))}function c(t){return t.withMutations((function(t){t.set("isStreaming",!1).set("hasError",!0)}))}function f(){return Xe.getInitialState()}function h(t){return{type:"auth",api_password:t}}function l(){return{type:"get_states"}}function p(){return{type:"get_config"}}function _(){return{type:"get_services"}}function d(){return{type:"get_panels"}}function v(t,e,n){var r={type:"call_service",domain:t,service:e};return n&&(r.service_data=n),r}function y(t){var e={type:"subscribe_events"};return t&&(e.event_type=t),e}function m(t){return{type:"unsubscribe_events",subscription:t}}function g(){return{type:"ping"}}function S(t,e){return{type:"result",success:!1,error:{code:t,message:e}}}function b(t){return t.result}function E(t,e){var n=new tn(t,e);return n.connect()}function I(t,e,n,r){void 0===r&&(r=null);var i=t.evaluate(Mo.authInfo),o=i.host+"/api/"+n;return new Promise(function(t,n){var u=new XMLHttpRequest;u.open(e,o,!0),u.setRequestHeader("X-HA-access",i.authToken),u.onload=function(){var e;try{e="application/json"===u.getResponseHeader("content-type")?JSON.parse(u.responseText):u.responseText}catch(t){e=u.responseText}u.status>199&&u.status<300?t(e):n(e)},u.onerror=function(){return n({})},r?(u.setRequestHeader("Content-Type","application/json;charset=UTF-8"),u.send(JSON.stringify(r))):u.send()})}function O(t,e){var n=e.model,r=e.result,i=e.params,o=n.entity;if(!r)return t;var u=i.replace?sn({}):t.get(o),a=Array.isArray(r)?r:[r],s=n.fromJSON||sn;return t.set(o,u.withMutations((function(t){for(var e=0;e<a.length;e++){var n=s(a[e]);t.set(n.id,n)}})))}function w(t,e){var n=e.model,r=e.params;return t.removeIn([n.entity,r.id])}function T(t){if(null===t||void 0===t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function A(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(e).map((function(t){return e[t]}));if("0123456789"!==r.join(""))return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach((function(t){i[t]=t})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},i)).join("")}catch(t){return!1}}function D(t){var e={};return e.incrementData=function(e,n,r){void 0===r&&(r={}),C(e,t,r,n)},e.replaceData=function(e,n,r){void 0===r&&(r={}),C(e,t,ln({},r,{replace:!0}),n)},e.removeData=function(e,n){j(e,t,{id:n})},t.fetch&&(e.fetch=function(e,n){return void 0===n&&(n={}),e.dispatch(un.API_FETCH_START,{model:t,params:n,method:"fetch"}),t.fetch(e,n).then(C.bind(null,e,t,n),z.bind(null,e,t,n))}),e.fetchAll=function(e,n){return void 0===n&&(n={}),e.dispatch(un.API_FETCH_START,{model:t,params:n,method:"fetchAll"}),t.fetchAll(e,n).then(C.bind(null,e,t,ln({},n,{replace:!0})),z.bind(null,e,t,n))},t.save&&(e.save=function(e,n){return void 0===n&&(n={}),e.dispatch(un.API_SAVE_START,{params:n}),t.save(e,n).then(R.bind(null,e,t,n),M.bind(null,e,t,n))}),t.delete&&(e.delete=function(e,n){return void 0===n&&(n={}),e.dispatch(un.API_DELETE_START,{params:n}),t.delete(e,n).then(j.bind(null,e,t,n),L.bind(null,e,t,n))}),e}function C(t,e,n,r){return t.dispatch(un.API_FETCH_SUCCESS,{model:e,params:n,result:r}),r}function z(t,e,n,r){return t.dispatch(un.API_FETCH_FAIL,{model:e,params:n,reason:r}),Promise.reject(r)}function R(t,e,n,r){return t.dispatch(un.API_SAVE_SUCCESS,{model:e,params:n,result:r}),r}function M(t,e,n,r){return t.dispatch(un.API_SAVE_FAIL,{model:e,params:n,reason:r}),Promise.reject(r)}function j(t,e,n,r){return t.dispatch(un.API_DELETE_SUCCESS,{model:e,params:n,result:r}),r}function L(t,e,n,r){return t.dispatch(un.API_DELETE_FAIL,{model:e,params:n,reason:r}),Promise.reject(r)}function N(t){t.registerStores({restApiCache:cn})}function k(t){return[["restApiCache",t.entity],function(t){return!!t}]}function P(t){return[["restApiCache",t.entity],function(t){return t||pn({})}]}function U(t){return function(e){return["restApiCache",t.entity,e]}}function H(t){return new Date(t)}function x(t,e){var n=e.message;return t.set(t.size,n)}function V(){return kn.getInitialState()}function q(t,e){t.dispatch(jn.NOTIFICATION_CREATED,{message:e})}function F(t){t.registerStores({notifications:kn})}function G(t,e){if("lock"===t)return!0;if("garage_door"===t)return!0;var n=e.get(t);return!!n&&n.services.has("turn_on")}function K(t,e){return!!t&&("group"===t.domain?"on"===t.state||"off"===t.state:G(t.domain,e))}function B(t,e){return[Qn(t),function(t){return!!t&&t.services.has(e)}]}function Y(t){return[Rn.byId(t),Xn,K]}function J(t,e){var n=e.component;return t.push(n)}function W(t,e){var n=e.components;return yr(n)}function X(){return mr.getInitialState()}function Q(t,e){var n=e.latitude,r=e.longitude,i=e.location_name,o=e.unit_system,u=e.time_zone,a=e.config_dir,s=e.version;return Sr({latitude:n,longitude:r,location_name:i,unit_system:o,time_zone:u,config_dir:a,serverVersion:s})}function Z(){return br.getInitialState()}function $(t,e){t.dispatch(dr.SERVER_CONFIG_LOADED,e)}function tt(t){on(t,"GET","config").then((function(e){return $(t,e)}))}function et(t,e){t.dispatch(dr.COMPONENT_LOADED,{component:e})}function nt(t){return[["serverComponent"],function(e){return e.contains(t)}]}function rt(t){t.registerStores({serverComponent:mr,serverConfig:br})}function it(t,e){var n=e.pane;return n}function ot(){return jr.getInitialState()}function ut(t,e){var n=e.panels;return Nr(n)}function at(){return kr.getInitialState()}function st(t,e){var n=e.show;return!!n}function ct(){return Ur.getInitialState()}function ft(t,e){t.dispatch(Rr.SHOW_SIDEBAR,{show:e})}function ht(t,e){t.dispatch(Rr.NAVIGATE,{pane:e})}function lt(t,e){t.dispatch(Rr.PANELS_LOADED,{panels:e})}function pt(t,e){var n=e.entityId;return n}function _t(){return Yr.getInitialState()}function dt(t,e){t.dispatch(Kr.SELECT_ENTITY,{entityId:e})}function vt(t){t.dispatch(Kr.SELECT_ENTITY,{entityId:null})}function yt(t){return!t||(new Date).getTime()-t>6e4}function mt(t,e){var n=e.date;return n.toISOString()}function gt(){return Qr.getInitialState()}function St(t,e){var n=e.date,r=e.stateHistory;return 0===r.length?t.set(n,$r({})):t.withMutations((function(t){r.forEach((function(e){return t.setIn([n,e[0].entity_id],$r(e.map(In.fromJSON)))}))}))}function bt(){return ti.getInitialState()}function Et(t,e){var n=e.stateHistory;return t.withMutations((function(t){n.forEach((function(e){return t.set(e[0].entity_id,ii(e.map(In.fromJSON)))}))}))}function It(){return oi.getInitialState()}function Ot(t,e){var n=e.stateHistory,r=(new Date).getTime();return t.withMutations((function(t){n.forEach((function(e){return t.set(e[0].entity_id,r)})),history.length>1&&t.set(si,r)}))}function wt(){return ci.getInitialState()}function Tt(t,e){t.dispatch(Wr.ENTITY_HISTORY_DATE_SELECTED,{date:e})}function At(t,e){void 0===e&&(e=null),t.dispatch(Wr.RECENT_ENTITY_HISTORY_FETCH_START,{});var n="history/period";return null!==e&&(n+="?filter_entity_id="+e),on(t,"GET",n).then((function(e){return t.dispatch(Wr.RECENT_ENTITY_HISTORY_FETCH_SUCCESS,{stateHistory:e})}),(function(){return t.dispatch(Wr.RECENT_ENTITY_HISTORY_FETCH_ERROR,{})}))}function Dt(t,e){return t.dispatch(Wr.ENTITY_HISTORY_FETCH_START,{date:e}),on(t,"GET","history/period/"+e).then((function(n){return t.dispatch(Wr.ENTITY_HISTORY_FETCH_SUCCESS,{date:e,stateHistory:n})}),(function(){return t.dispatch(Wr.ENTITY_HISTORY_FETCH_ERROR,{})}))}function Ct(t){var e=t.evaluate(li);return Dt(t,e)}function zt(t){t.registerStores({currentEntityHistoryDate:Qr,entityHistory:ti,isLoadingEntityHistory:ni,recentEntityHistory:oi,recentEntityHistoryUpdated:ci})}function Rt(t){t.registerStores({moreInfoEntityId:Yr})}function Mt(t,e){var n=e.model,r=e.result,i=e.params;if(null===t||"entity"!==n.entity||!i.replace)return t;for(var o=0;o<r.length;o++)if(r[o].entity_id===t)return t;return null}function jt(t,e){t.dispatch(Mi.SELECT_VIEW,{view:e})}function Lt(t,e,n,r){void 0===r&&(r=!0),n.attributes.entity_id.forEach((function(n){if(!t.has(n)){var i=e.get(n);i&&!i.attributes.hidden&&(t.set(n,i),"group"===i.domain&&r&&Lt(t,e,i,!1))}}))}function Nt(t){t.registerStores({currentView:Li})}function kt(t){return Ji[t.hassId]}function Pt(t,e){var n={pane:t};return"states"===t&&(n.view=e||null),n}function Ut(t,e){return"states"===t&&e?"/"+t+"/"+e:"/"+t}function Ht(t){var e,n;if("/"===window.location.pathname)e=t.evaluate(Vr),n=t.evaluate(Gi.currentView);else{var r=window.location.pathname.substr(1).split("/");e=r[0],n=r[1],t.batch((function(){ht(t,e),n&&Fi.selectView(t,n)}))}history.replaceState(Pt(e,n),Yi,Ut(e,n))}function xt(t,e){var n=e.state,r=n.pane,i=n.view;t.evaluate(zi.hasCurrentEntityId)?(kt(t).ignoreNextDeselectEntity=!0,Ci.deselectEntity(t)):r===t.evaluate(Vr)&&i===t.evaluate(Gi.currentView)||t.batch((function(){ht(t,r),void 0!==i&&Fi.selectView(t,i)}))}function Vt(t){if(Bi){Ht(t);var e={ignoreNextDeselectEntity:!1,popstateChangeListener:xt.bind(null,t),unwatchNavigationObserver:t.observe(Vr,(function(t){t!==history.state.pane&&history.pushState(Pt(t,history.state.view),Yi,Ut(t,history.state.view))})),unwatchViewObserver:t.observe(Gi.currentView,(function(t){t!==history.state.view&&history.pushState(Pt(history.state.pane,t),Yi,Ut(history.state.pane,t))})),unwatchMoreInfoObserver:t.observe(zi.hasCurrentEntityId,(function(t){t?history.pushState(history.state,Yi,window.location.pathname):e.ignoreNextDeselectEntity?e.ignoreNextDeselectEntity=!1:setTimeout((function(){return history.back()}),0)}))};Ji[t.hassId]=e,window.addEventListener("popstate",e.popstateChangeListener)}}function qt(t){if(Bi){var e=kt(t);e&&(e.unwatchNavigationObserver(),e.unwatchViewObserver(),e.unwatchMoreInfoObserver(),window.removeEventListener("popstate",e.popstateChangeListener),Ji[t.hassId]=!1)}}function Ft(t){t.registerStores({currentPanel:jr,panels:kr,showSidebar:Ur})}function Gt(t){return t.dispatch(en.API_FETCH_ALL_START,{}),on(t,"GET","bootstrap").then((function(e){t.batch((function(){zn.replaceData(t,e.states),tr.replaceData(t,e.services),lr.replaceData(t,e.events),Dr.configLoaded(t,e.config),Xi.panelsLoaded(t,e.panels),t.dispatch(en.API_FETCH_ALL_SUCCESS,{})}))}),(function(e){return t.dispatch(en.API_FETCH_ALL_FAIL,{message:e}),Promise.reject(e)}))}function Kt(t){t.registerStores({isFetchingData:rn})}function Bt(t,e,n){function r(){var c=(new Date).getTime()-a;c<e&&c>0?i=setTimeout(r,e-c):(i=null,n||(s=t.apply(u,o),i||(u=o=null)))}var i,o,u,a,s;null==e&&(e=100);var c=function(){u=this,o=arguments,a=(new Date).getTime();var c=n&&!i;return i||(i=setTimeout(r,e)),c&&(s=t.apply(u,o),u=o=null),s};return c.clear=function(){i&&(clearTimeout(i),i=null)},c}function Yt(t){var e=fo[t.hassId];e&&(e.scheduleHealthCheck.clear(),e.conn.close(),fo[t.hassId]=!1)}function Jt(t,e){void 0===e&&(e={});var n=e.syncOnInitialConnect;void 0===n&&(n=!0),Yt(t);var r=t.evaluate(Mo.authToken),i="https:"===document.location.protocol?"wss://":"ws://";i+=document.location.hostname,document.location.port&&(i+=":"+document.location.port),i+="/api/websocket",E(i,{authToken:r}).then((function(e){var r=Bt((function(){return e.ping()}),so);r(),e.socket.addEventListener("message",r),fo[t.hassId]={conn:e,scheduleHealthCheck:r},co.forEach((function(n){return e.subscribeEvents(ao.bind(null,t),n)})),t.batch((function(){t.dispatch(Ye.STREAM_START),n&&io.fetchAll(t)})),e.addEventListener("disconnected",(function(){t.dispatch(Ye.STREAM_ERROR)})),e.addEventListener("ready",(function(){t.batch((function(){t.dispatch(Ye.STREAM_START),io.fetchAll(t)}))}))}))}function Wt(t){t.registerStores({streamStatus:Xe})}function Xt(t,e,n){void 0===n&&(n={});var r=n.rememberAuth;void 0===r&&(r=!1);var i=n.host;void 0===i&&(i=""),t.dispatch(Ue.VALIDATING_AUTH_TOKEN,{authToken:e,host:i}),io.fetchAll(t).then((function(){t.dispatch(Ue.VALID_AUTH_TOKEN,{authToken:e,host:i,rememberAuth:r}),vo.start(t,{syncOnInitialConnect:!1})}),(function(e){void 0===e&&(e={});var n=e.message;void 0===n&&(n=go),t.dispatch(Ue.INVALID_AUTH_TOKEN,{errorMessage:n})}))}function Qt(t){t.dispatch(Ue.LOG_OUT,{})}function Zt(t){t.registerStores({authAttempt:Ve,authCurrent:Ge,rememberAuth:Be})}function $t(){if(!("localStorage"in window))return{};var t=window.localStorage,e="___test";try{return t.setItem(e,e),t.removeItem(e),t}catch(t){return{}}}function te(){var t=new Uo({debug:!1});return t.hassId=Ho++,t}function ee(t,e,n){Object.keys(n).forEach((function(r){var i=n[r];if("register"in i&&i.register(e),"getters"in i&&Object.defineProperty(t,r+"Getters",{value:i.getters,enumerable:!0}),"actions"in i){var o={};Object.getOwnPropertyNames(i.actions).forEach((function(t){"function"==typeof i.actions[t]&&Object.defineProperty(o,t,{value:i.actions[t].bind(null,e),enumerable:!0})})),Object.defineProperty(t,r+"Actions",{value:o,enumerable:!0})}}))}function ne(t,e){return xo(t.attributes.entity_id.map((function(t){return e.get(t)})).filter((function(t){return!!t})))}function re(t){return on(t,"GET","error_log")}function ie(t,e){var n=e.date;return n.toISOString()}function oe(){return Jo.getInitialState()}function ue(t,e){var n=e.date,r=e.entries;return t.set(n,eu(r.map($o.fromJSON)))}function ae(){return nu.getInitialState()}function se(t,e){var n=e.date;return t.set(n,(new Date).getTime())}function ce(){return ou.getInitialState()}function fe(t,e){t.dispatch(Bo.LOGBOOK_DATE_SELECTED,{date:e})}function he(t,e){t.dispatch(Bo.LOGBOOK_ENTRIES_FETCH_START,{date:e}),on(t,"GET","logbook/"+e).then((function(n){return t.dispatch(Bo.LOGBOOK_ENTRIES_FETCH_SUCCESS,{date:e,entries:n})}),(function(){return t.dispatch(Bo.LOGBOOK_ENTRIES_FETCH_ERROR,{})}))}function le(t){return!t||(new Date).getTime()-t>su}function pe(t){t.registerStores({currentLogbookDate:Jo,isLoadingLogbookEntries:Xo,logbookEntries:nu,logbookEntriesUpdated:ou})}function _e(t){return t.set("active",!0)}function de(t){return t.set("active",!1)}function ve(){return Su.getInitialState()}function ye(t){return navigator.serviceWorker.getRegistration().then((function(t){if(!t)throw new Error("No service worker registered.");return t.pushManager.subscribe({userVisibleOnly:!0})})).then((function(e){var n;return n=navigator.userAgent.toLowerCase().indexOf("firefox")>-1?"firefox":"chrome",on(t,"POST","notify.html5",{subscription:e,browser:n}).then((function(){return t.dispatch(yu.PUSH_NOTIFICATIONS_SUBSCRIBE,{})})).then((function(){return!0}))})).catch((function(e){var n;return n=e.message&&e.message.indexOf("gcm_sender_id")!==-1?"Please setup the notify.html5 platform.":"Notification registration failed.",console.error(e),Vn.createNotification(t,n),!1}))}function me(t){return navigator.serviceWorker.getRegistration().then((function(t){if(!t)throw new Error("No service worker registered");return t.pushManager.subscribe({userVisibleOnly:!0})})).then((function(e){return on(t,"DELETE","notify.html5",{subscription:e}).then((function(){return e.unsubscribe()})).then((function(){return t.dispatch(yu.PUSH_NOTIFICATIONS_UNSUBSCRIBE,{})})).then((function(){return!0}))})).catch((function(e){var n="Failed unsubscribing for push notifications.";return console.error(e),Vn.createNotification(t,n),!1}))}function ge(t){t.registerStores({pushNotifications:Su})}function Se(t,e){return on(t,"POST","template",{template:e})}function be(t){return t.set("isListening",!0)}function Ee(t,e){var n=e.interimTranscript,r=e.finalTranscript;return t.withMutations((function(t){return t.set("isListening",!0).set("isTransmitting",!1).set("interimTranscript",n).set("finalTranscript",r)}))}function Ie(t,e){var n=e.finalTranscript;return t.withMutations((function(t){return t.set("isListening",!1).set("isTransmitting",!0).set("interimTranscript","").set("finalTranscript",n)}))}function Oe(){return ku.getInitialState()}function we(){return ku.getInitialState()}function Te(){return ku.getInitialState()}function Ae(t){return Pu[t.hassId]}function De(t){var e=Ae(t);if(e){var n=e.finalTranscript||e.interimTranscript;t.dispatch(ju.VOICE_TRANSMITTING,{finalTranscript:n}),tr.callService(t,"conversation","process",{text:n}).then((function(){t.dispatch(ju.VOICE_DONE)}),(function(){t.dispatch(ju.VOICE_ERROR)}))}}function Ce(t){var e=Ae(t);e&&(e.recognition.stop(),Pu[t.hassId]=!1)}function ze(t){De(t),Ce(t)}function Re(t){var e=ze.bind(null,t);e();var n=new webkitSpeechRecognition;Pu[t.hassId]={recognition:n,interimTranscript:"",finalTranscript:""},n.interimResults=!0,n.onstart=function(){return t.dispatch(ju.VOICE_START)},n.onerror=function(){return t.dispatch(ju.VOICE_ERROR)},n.onend=e,n.onresult=function(e){var n=Ae(t);if(n){for(var r="",i="",o=e.resultIndex;o<e.results.length;o++)e.results[o].isFinal?r+=e.results[o][0].transcript:i+=e.results[o][0].transcript;n.interimTranscript=i,n.finalTranscript+=r,t.dispatch(ju.VOICE_RESULT,{interimTranscript:i,finalTranscript:n.finalTranscript})}},n.start()}function Me(t){t.registerStores({currentVoiceCommand:ku,isVoiceSupported:Mu})}var je="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Le=e((function(t,e){!(function(n,r){"object"==typeof e&&"object"==typeof t?t.exports=r():"function"==typeof define&&define.amd?define([],r):"object"==typeof e?e.Nuclear=r():n.Nuclear=r()})(je,(function(){return (function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)})([function(t,e,n){function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0}),n(1);var i=n(2),o=r(i),u=n(6),a=r(u),s=n(3),c=r(s),f=n(5),h=n(11),l=n(10),p=n(7),_=r(p);e.default={Reactor:a.default,Store:o.default,Immutable:c.default,isKeyPath:h.isKeyPath,isGetter:l.isGetter,toJS:f.toJS,toImmutable:f.toImmutable,isImmutable:f.isImmutable,createReactMixin:_.default},t.exports=e.default},function(t,e){try{window.console&&console.log||(console={log:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){}})}catch(t){}},function(t,e,n){function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t){return t instanceof c}Object.defineProperty(e,"__esModule",{value:!0});var o=(function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}})();e.isStore=i;var u=n(3),a=n(4),s=n(5),c=(function(){function t(e){r(this,t),this.__handlers=(0,u.Map)({}),e&&(0,a.extend)(this,e),this.initialize()}return o(t,[{key:"initialize",value:function(){}},{key:"getInitialState",value:function(){return(0,u.Map)()}},{key:"handle",value:function(t,e,n){var r=this.__handlers.get(e);return"function"==typeof r?r.call(this,t,n,e):t}},{key:"handleReset",value:function(t){return this.getInitialState()}},{key:"on",value:function(t,e){this.__handlers=this.__handlers.set(t,e)}},{key:"serialize",value:function(t){return(0,s.toJS)(t)}},{key:"deserialize",value:function(t){return(0,s.toImmutable)(t)}}]),t})();e.default=(0,a.toFactory)(c)},function(t,e,n){!(function(e,n){t.exports=n()})(this,(function(){function t(t,e){e&&(t.prototype=Object.create(e.prototype)),t.prototype.constructor=t}function e(t){return t.value=!1,t}function n(t){t&&(t.value=!0)}function r(){}function i(t,e){e=e||0;for(var n=Math.max(0,t.length-e),r=new Array(n),i=0;i<n;i++)r[i]=t[i+e];return r}function o(t){return void 0===t.size&&(t.size=t.__iterate(a)),t.size}function u(t,e){if("number"!=typeof e){var n=+e;if(""+n!==e)return NaN;e=n}return e<0?o(t)+e:e}function a(){return!0}function s(t,e,n){return(0===t||void 0!==n&&t<=-n)&&(void 0===e||void 0!==n&&e>=n)}function c(t,e){return h(t,e,0)}function f(t,e){return h(t,e,e)}function h(t,e,n){return void 0===t?n:t<0?Math.max(0,e+t):void 0===e?t:Math.min(e,t)}function l(t){return v(t)?t:C(t)}function p(t){return y(t)?t:z(t)}function _(t){return m(t)?t:R(t)}function d(t){return v(t)&&!g(t)?t:M(t)}function v(t){return!(!t||!t[dn])}function y(t){return!(!t||!t[vn])}function m(t){return!(!t||!t[yn])}function g(t){return y(t)||m(t)}function S(t){return!(!t||!t[mn])}function b(t){this.next=t}function E(t,e,n,r){var i=0===t?e:1===t?n:[e,n];return r?r.value=i:r={value:i,done:!1},r}function I(){return{value:void 0,done:!0}}function O(t){return!!A(t)}function w(t){return t&&"function"==typeof t.next}function T(t){var e=A(t);return e&&e.call(t)}function A(t){var e=t&&(En&&t[En]||t[In]);if("function"==typeof e)return e}function D(t){return t&&"number"==typeof t.length}function C(t){return null===t||void 0===t?U():v(t)?t.toSeq():V(t)}function z(t){return null===t||void 0===t?U().toKeyedSeq():v(t)?y(t)?t.toSeq():t.fromEntrySeq():H(t)}function R(t){return null===t||void 0===t?U():v(t)?y(t)?t.entrySeq():t.toIndexedSeq():x(t)}function M(t){return(null===t||void 0===t?U():v(t)?y(t)?t.entrySeq():t:x(t)).toSetSeq()}function j(t){this._array=t,this.size=t.length}function L(t){var e=Object.keys(t);this._object=t,this._keys=e,this.size=e.length}function N(t){this._iterable=t,this.size=t.length||t.size}function k(t){this._iterator=t,this._iteratorCache=[]}function P(t){return!(!t||!t[wn])}function U(){return Tn||(Tn=new j([]))}function H(t){var e=Array.isArray(t)?new j(t).fromEntrySeq():w(t)?new k(t).fromEntrySeq():O(t)?new N(t).fromEntrySeq():"object"==typeof t?new L(t):void 0;if(!e)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+t);return e}function x(t){var e=q(t);if(!e)throw new TypeError("Expected Array or iterable object of values: "+t);return e}function V(t){var e=q(t)||"object"==typeof t&&new L(t);if(!e)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+t);return e}function q(t){return D(t)?new j(t):w(t)?new k(t):O(t)?new N(t):void 0}function F(t,e,n,r){var i=t._cache;if(i){for(var o=i.length-1,u=0;u<=o;u++){var a=i[n?o-u:u];if(e(a[1],r?a[0]:u,t)===!1)return u+1}return u}return t.__iterateUncached(e,n)}function G(t,e,n,r){var i=t._cache;if(i){var o=i.length-1,u=0;return new b(function(){var t=i[n?o-u:u];return u++>o?I():E(e,r?t[0]:u-1,t[1])})}return t.__iteratorUncached(e,n)}function K(){throw TypeError("Abstract")}function B(){}function Y(){}function J(){}function W(t,e){if(t===e||t!==t&&e!==e)return!0;if(!t||!e)return!1;if("function"==typeof t.valueOf&&"function"==typeof e.valueOf){if(t=t.valueOf(),e=e.valueOf(),t===e||t!==t&&e!==e)return!0;if(!t||!e)return!1}return!("function"!=typeof t.equals||"function"!=typeof e.equals||!t.equals(e))}function X(t,e){return e?Q(e,t,"",{"":t}):Z(t)}function Q(t,e,n,r){return Array.isArray(e)?t.call(r,n,R(e).map((function(n,r){return Q(t,n,r,e)}))):$(e)?t.call(r,n,z(e).map((function(n,r){return Q(t,n,r,e)}))):e}function Z(t){return Array.isArray(t)?R(t).map(Z).toList():$(t)?z(t).map(Z).toMap():t}function $(t){return t&&(t.constructor===Object||void 0===t.constructor)}function tt(t){return t>>>1&1073741824|3221225471&t}function et(t){if(t===!1||null===t||void 0===t)return 0;if("function"==typeof t.valueOf&&(t=t.valueOf(),t===!1||null===t||void 0===t))return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){var n=0|t;for(n!==t&&(n^=4294967295*t);t>4294967295;)t/=4294967295,n^=t;return tt(n)}return"string"===e?t.length>Ln?nt(t):rt(t):"function"==typeof t.hashCode?t.hashCode():it(t)}function nt(t){var e=Pn[t];return void 0===e&&(e=rt(t),kn===Nn&&(kn=0,Pn={}),kn++,Pn[t]=e),e}function rt(t){for(var e=0,n=0;n<t.length;n++)e=31*e+t.charCodeAt(n)|0;return tt(e)}function it(t){var e;if(Rn&&(e=An.get(t),void 0!==e))return e;if(e=t[jn],void 0!==e)return e;if(!zn){if(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[jn],void 0!==e)return e;if(e=ot(t),void 0!==e)return e}if(e=++Mn,1073741824&Mn&&(Mn=0),Rn)An.set(t,e);else{if(void 0!==Cn&&Cn(t)===!1)throw new Error("Non-extensible objects are not allowed as keys.");if(zn)Object.defineProperty(t,jn,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(void 0!==t.propertyIsEnumerable&&t.propertyIsEnumerable===t.constructor.prototype.propertyIsEnumerable)t.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)},t.propertyIsEnumerable[jn]=e;else{if(void 0===t.nodeType)throw new Error("Unable to set a non-enumerable property on object.");t[jn]=e}}return e}function ot(t){if(t&&t.nodeType>0)switch(t.nodeType){case 1:return t.uniqueID;case 9:return t.documentElement&&t.documentElement.uniqueID}}function ut(t,e){if(!t)throw new Error(e)}function at(t){ut(t!==1/0,"Cannot perform this action with an infinite size.")}function st(t,e){this._iter=t,this._useKeys=e,this.size=t.size}function ct(t){this._iter=t,this.size=t.size}function ft(t){this._iter=t,this.size=t.size}function ht(t){this._iter=t,this.size=t.size}function lt(t){var e=jt(t);return e._iter=t,e.size=t.size,e.flip=function(){return t},e.reverse=function(){var e=t.reverse.apply(this);return e.flip=function(){return t.reverse()},e},e.has=function(e){return t.includes(e)},e.includes=function(e){return t.has(e)},e.cacheResult=Lt,e.__iterateUncached=function(e,n){var r=this;return t.__iterate((function(t,n){return e(n,t,r)!==!1}),n)},e.__iteratorUncached=function(e,n){if(e===bn){var r=t.__iterator(e,n);return new b(function(){var t=r.next();if(!t.done){var e=t.value[0];t.value[0]=t.value[1],t.value[1]=e}return t})}return t.__iterator(e===Sn?gn:Sn,n)},e}function pt(t,e,n){var r=jt(t);return r.size=t.size,r.has=function(e){return t.has(e)},r.get=function(r,i){var o=t.get(r,ln);return o===ln?i:e.call(n,o,r,t)},r.__iterateUncached=function(r,i){var o=this;return t.__iterate((function(t,i,u){return r(e.call(n,t,i,u),i,o)!==!1}),i)},r.__iteratorUncached=function(r,i){var o=t.__iterator(bn,i);return new b(function(){var i=o.next();if(i.done)return i;var u=i.value,a=u[0];return E(r,a,e.call(n,u[1],a,t),i)})},r}function _t(t,e){var n=jt(t);return n._iter=t,n.size=t.size,n.reverse=function(){return t},t.flip&&(n.flip=function(){var e=lt(t);return e.reverse=function(){return t.flip()},e}),n.get=function(n,r){return t.get(e?n:-1-n,r)},n.has=function(n){return t.has(e?n:-1-n)},n.includes=function(e){return t.includes(e)},n.cacheResult=Lt,n.__iterate=function(e,n){var r=this;return t.__iterate((function(t,n){return e(t,n,r)}),!n)},n.__iterator=function(e,n){return t.__iterator(e,!n)},n}function dt(t,e,n,r){var i=jt(t);return r&&(i.has=function(r){var i=t.get(r,ln);return i!==ln&&!!e.call(n,i,r,t)},i.get=function(r,i){var o=t.get(r,ln);return o!==ln&&e.call(n,o,r,t)?o:i}),i.__iterateUncached=function(i,o){var u=this,a=0;return t.__iterate((function(t,o,s){if(e.call(n,t,o,s))return a++,i(t,r?o:a-1,u)}),o),a},i.__iteratorUncached=function(i,o){var u=t.__iterator(bn,o),a=0;return new b(function(){for(;;){var o=u.next();if(o.done)return o;var s=o.value,c=s[0],f=s[1];if(e.call(n,f,c,t))return E(i,r?c:a++,f,o)}})},i}function vt(t,e,n){var r=Pt().asMutable();return t.__iterate((function(i,o){r.update(e.call(n,i,o,t),0,(function(t){return t+1}))})),r.asImmutable()}function yt(t,e,n){var r=y(t),i=(S(t)?Ie():Pt()).asMutable();t.__iterate((function(o,u){i.update(e.call(n,o,u,t),(function(t){return t=t||[],t.push(r?[u,o]:o),t}))}));var o=Mt(t);return i.map((function(e){return Ct(t,o(e))}))}function mt(t,e,n,r){var i=t.size;if(void 0!==e&&(e|=0),void 0!==n&&(n|=0),s(e,n,i))return t;var o=c(e,i),a=f(n,i);if(o!==o||a!==a)return mt(t.toSeq().cacheResult(),e,n,r);var h,l=a-o;l===l&&(h=l<0?0:l);var p=jt(t);return p.size=0===h?h:t.size&&h||void 0,!r&&P(t)&&h>=0&&(p.get=function(e,n){return e=u(this,e),e>=0&&e<h?t.get(e+o,n):n}),p.__iterateUncached=function(e,n){var i=this;if(0===h)return 0;if(n)return this.cacheResult().__iterate(e,n);var u=0,a=!0,s=0;return t.__iterate((function(t,n){if(!a||!(a=u++<o))return s++,e(t,r?n:s-1,i)!==!1&&s!==h})),s},p.__iteratorUncached=function(e,n){if(0!==h&&n)return this.cacheResult().__iterator(e,n);var i=0!==h&&t.__iterator(e,n),u=0,a=0;return new b(function(){for(;u++<o;)i.next();if(++a>h)return I();var t=i.next();return r||e===Sn?t:e===gn?E(e,a-1,void 0,t):E(e,a-1,t.value[1],t)})},p}function gt(t,e,n){var r=jt(t);return r.__iterateUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterate(r,i);var u=0;return t.__iterate((function(t,i,a){return e.call(n,t,i,a)&&++u&&r(t,i,o)})),u},r.__iteratorUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterator(r,i);var u=t.__iterator(bn,i),a=!0;return new b(function(){if(!a)return I();var t=u.next();if(t.done)return t;var i=t.value,s=i[0],c=i[1];return e.call(n,c,s,o)?r===bn?t:E(r,s,c,t):(a=!1,I())})},r}function St(t,e,n,r){var i=jt(t);return i.__iterateUncached=function(i,o){var u=this;if(o)return this.cacheResult().__iterate(i,o);var a=!0,s=0;return t.__iterate((function(t,o,c){if(!a||!(a=e.call(n,t,o,c)))return s++,i(t,r?o:s-1,u)})),s},i.__iteratorUncached=function(i,o){var u=this;if(o)return this.cacheResult().__iterator(i,o);var a=t.__iterator(bn,o),s=!0,c=0;return new b(function(){var t,o,f;do{if(t=a.next(),t.done)return r||i===Sn?t:i===gn?E(i,c++,void 0,t):E(i,c++,t.value[1],t);var h=t.value;o=h[0],f=h[1],s&&(s=e.call(n,f,o,u))}while(s);return i===bn?t:E(i,o,f,t)})},i}function bt(t,e){var n=y(t),r=[t].concat(e).map((function(t){return v(t)?n&&(t=p(t)):t=n?H(t):x(Array.isArray(t)?t:[t]),t})).filter((function(t){return 0!==t.size}));if(0===r.length)return t;if(1===r.length){var i=r[0];if(i===t||n&&y(i)||m(t)&&m(i))return i}var o=new j(r);return n?o=o.toKeyedSeq():m(t)||(o=o.toSetSeq()),o=o.flatten(!0),o.size=r.reduce((function(t,e){if(void 0!==t){var n=e.size;if(void 0!==n)return t+n}}),0),o}function Et(t,e,n){var r=jt(t);return r.__iterateUncached=function(r,i){function o(t,s){var c=this;t.__iterate((function(t,i){return(!e||s<e)&&v(t)?o(t,s+1):r(t,n?i:u++,c)===!1&&(a=!0),!a}),i)}var u=0,a=!1;return o(t,0),u},r.__iteratorUncached=function(r,i){var o=t.__iterator(r,i),u=[],a=0;return new b(function(){for(;o;){var t=o.next();if(t.done===!1){var s=t.value;if(r===bn&&(s=s[1]),e&&!(u.length<e)||!v(s))return n?t:E(r,a++,s,t);u.push(o),o=s.__iterator(r,i)}else o=u.pop()}return I()})},r}function It(t,e,n){var r=Mt(t);return t.toSeq().map((function(i,o){return r(e.call(n,i,o,t))})).flatten(!0)}function Ot(t,e){var n=jt(t);return n.size=t.size&&2*t.size-1,n.__iterateUncached=function(n,r){var i=this,o=0;return t.__iterate((function(t,r){return(!o||n(e,o++,i)!==!1)&&n(t,o++,i)!==!1}),r),o},n.__iteratorUncached=function(n,r){var i,o=t.__iterator(Sn,r),u=0;return new b(function(){return(!i||u%2)&&(i=o.next(),i.done)?i:u%2?E(n,u++,e):E(n,u++,i.value,i)})},n}function wt(t,e,n){e||(e=Nt);var r=y(t),i=0,o=t.toSeq().map((function(e,r){return[r,e,i++,n?n(e,r,t):e]})).toArray();return o.sort((function(t,n){return e(t[3],n[3])||t[2]-n[2]})).forEach(r?function(t,e){o[e].length=2}:function(t,e){o[e]=t[1]}),r?z(o):m(t)?R(o):M(o)}function Tt(t,e,n){if(e||(e=Nt),n){var r=t.toSeq().map((function(e,r){return[e,n(e,r,t)]})).reduce((function(t,n){return At(e,t[1],n[1])?n:t}));return r&&r[0]}return t.reduce((function(t,n){return At(e,t,n)?n:t}))}function At(t,e,n){var r=t(n,e);return 0===r&&n!==e&&(void 0===n||null===n||n!==n)||r>0}function Dt(t,e,n){var r=jt(t);return r.size=new j(n).map((function(t){return t.size})).min(),r.__iterate=function(t,e){for(var n,r=this,i=this.__iterator(Sn,e),o=0;!(n=i.next()).done&&t(n.value,o++,r)!==!1;);return o},r.__iteratorUncached=function(t,r){var i=n.map((function(t){return t=l(t),T(r?t.reverse():t)})),o=0,u=!1;
return new b(function(){var n;return u||(n=i.map((function(t){return t.next()})),u=n.some((function(t){return t.done}))),u?I():E(t,o++,e.apply(null,n.map((function(t){return t.value}))))})},r}function Ct(t,e){return P(t)?e:t.constructor(e)}function zt(t){if(t!==Object(t))throw new TypeError("Expected [K, V] tuple: "+t)}function Rt(t){return at(t.size),o(t)}function Mt(t){return y(t)?p:m(t)?_:d}function jt(t){return Object.create((y(t)?z:m(t)?R:M).prototype)}function Lt(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):C.prototype.cacheResult.call(this)}function Nt(t,e){return t>e?1:t<e?-1:0}function kt(t){var e=T(t);if(!e){if(!D(t))throw new TypeError("Expected iterable or array-like: "+t);e=T(l(t))}return e}function Pt(t){return null===t||void 0===t?Jt():Ut(t)&&!S(t)?t:Jt().withMutations((function(e){var n=p(t);at(n.size),n.forEach((function(t,n){return e.set(n,t)}))}))}function Ut(t){return!(!t||!t[Un])}function Ht(t,e){this.ownerID=t,this.entries=e}function xt(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n}function Vt(t,e,n){this.ownerID=t,this.count=e,this.nodes=n}function qt(t,e,n){this.ownerID=t,this.keyHash=e,this.entries=n}function Ft(t,e,n){this.ownerID=t,this.keyHash=e,this.entry=n}function Gt(t,e,n){this._type=e,this._reverse=n,this._stack=t._root&&Bt(t._root)}function Kt(t,e){return E(t,e[0],e[1])}function Bt(t,e){return{node:t,index:0,__prev:e}}function Yt(t,e,n,r){var i=Object.create(Hn);return i.size=t,i._root=e,i.__ownerID=n,i.__hash=r,i.__altered=!1,i}function Jt(){return xn||(xn=Yt(0))}function Wt(t,n,r){var i,o;if(t._root){var u=e(pn),a=e(_n);if(i=Xt(t._root,t.__ownerID,0,void 0,n,r,u,a),!a.value)return t;o=t.size+(u.value?r===ln?-1:1:0)}else{if(r===ln)return t;o=1,i=new Ht(t.__ownerID,[[n,r]])}return t.__ownerID?(t.size=o,t._root=i,t.__hash=void 0,t.__altered=!0,t):i?Yt(o,i):Jt()}function Xt(t,e,r,i,o,u,a,s){return t?t.update(e,r,i,o,u,a,s):u===ln?t:(n(s),n(a),new Ft(e,i,[o,u]))}function Qt(t){return t.constructor===Ft||t.constructor===qt}function Zt(t,e,n,r,i){if(t.keyHash===r)return new qt(e,r,[t.entry,i]);var o,u=(0===n?t.keyHash:t.keyHash>>>n)&hn,a=(0===n?r:r>>>n)&hn,s=u===a?[Zt(t,e,n+cn,r,i)]:(o=new Ft(e,r,i),u<a?[t,o]:[o,t]);return new xt(e,1<<u|1<<a,s)}function $t(t,e,n,i){t||(t=new r);for(var o=new Ft(t,et(n),[n,i]),u=0;u<e.length;u++){var a=e[u];o=o.update(t,0,void 0,a[0],a[1])}return o}function te(t,e,n,r){for(var i=0,o=0,u=new Array(n),a=0,s=1,c=e.length;a<c;a++,s<<=1){var f=e[a];void 0!==f&&a!==r&&(i|=s,u[o++]=f)}return new xt(t,i,u)}function ee(t,e,n,r,i){for(var o=0,u=new Array(fn),a=0;0!==n;a++,n>>>=1)u[a]=1&n?e[o++]:void 0;return u[r]=i,new Vt(t,o+1,u)}function ne(t,e,n){for(var r=[],i=0;i<n.length;i++){var o=n[i],u=p(o);v(o)||(u=u.map((function(t){return X(t)}))),r.push(u)}return ie(t,e,r)}function re(t){return function(e,n,r){return e&&e.mergeDeepWith&&v(n)?e.mergeDeepWith(t,n):t?t(e,n,r):n}}function ie(t,e,n){return n=n.filter((function(t){return 0!==t.size})),0===n.length?t:0!==t.size||t.__ownerID||1!==n.length?t.withMutations((function(t){for(var r=e?function(n,r){t.update(r,ln,(function(t){return t===ln?n:e(t,n,r)}))}:function(e,n){t.set(n,e)},i=0;i<n.length;i++)n[i].forEach(r)})):t.constructor(n[0])}function oe(t,e,n,r){var i=t===ln,o=e.next();if(o.done){var u=i?n:t,a=r(u);return a===u?t:a}ut(i||t&&t.set,"invalid keyPath");var s=o.value,c=i?ln:t.get(s,ln),f=oe(c,e,n,r);return f===c?t:f===ln?t.remove(s):(i?Jt():t).set(s,f)}function ue(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function ae(t,e,n,r){var o=r?t:i(t);return o[e]=n,o}function se(t,e,n,r){var i=t.length+1;if(r&&e+1===i)return t[e]=n,t;for(var o=new Array(i),u=0,a=0;a<i;a++)a===e?(o[a]=n,u=-1):o[a]=t[a+u];return o}function ce(t,e,n){var r=t.length-1;if(n&&e===r)return t.pop(),t;for(var i=new Array(r),o=0,u=0;u<r;u++)u===e&&(o=1),i[u]=t[u+o];return i}function fe(t){var e=de();if(null===t||void 0===t)return e;if(he(t))return t;var n=_(t),r=n.size;return 0===r?e:(at(r),r>0&&r<fn?_e(0,r,cn,null,new le(n.toArray())):e.withMutations((function(t){t.setSize(r),n.forEach((function(e,n){return t.set(n,e)}))})))}function he(t){return!(!t||!t[Gn])}function le(t,e){this.array=t,this.ownerID=e}function pe(t,e){function n(t,e,n){return 0===e?r(t,n):i(t,e,n)}function r(t,n){var r=n===a?s&&s.array:t&&t.array,i=n>o?0:o-n,c=u-n;return c>fn&&(c=fn),function(){if(i===c)return Yn;var t=e?--c:i++;return r&&r[t]}}function i(t,r,i){var a,s=t&&t.array,c=i>o?0:o-i>>r,f=(u-i>>r)+1;return f>fn&&(f=fn),function(){for(;;){if(a){var t=a();if(t!==Yn)return t;a=null}if(c===f)return Yn;var o=e?--f:c++;a=n(s&&s[o],r-cn,i+(o<<r))}}}var o=t._origin,u=t._capacity,a=Ee(u),s=t._tail;return n(t._root,t._level,0)}function _e(t,e,n,r,i,o,u){var a=Object.create(Kn);return a.size=e-t,a._origin=t,a._capacity=e,a._level=n,a._root=r,a._tail=i,a.__ownerID=o,a.__hash=u,a.__altered=!1,a}function de(){return Bn||(Bn=_e(0,0,cn))}function ve(t,n,r){if(n=u(t,n),n!==n)return t;if(n>=t.size||n<0)return t.withMutations((function(t){n<0?Se(t,n).set(0,r):Se(t,0,n+1).set(n,r)}));n+=t._origin;var i=t._tail,o=t._root,a=e(_n);return n>=Ee(t._capacity)?i=ye(i,t.__ownerID,0,n,r,a):o=ye(o,t.__ownerID,t._level,n,r,a),a.value?t.__ownerID?(t._root=o,t._tail=i,t.__hash=void 0,t.__altered=!0,t):_e(t._origin,t._capacity,t._level,o,i):t}function ye(t,e,r,i,o,u){var a=i>>>r&hn,s=t&&a<t.array.length;if(!s&&void 0===o)return t;var c;if(r>0){var f=t&&t.array[a],h=ye(f,e,r-cn,i,o,u);return h===f?t:(c=me(t,e),c.array[a]=h,c)}return s&&t.array[a]===o?t:(n(u),c=me(t,e),void 0===o&&a===c.array.length-1?c.array.pop():c.array[a]=o,c)}function me(t,e){return e&&t&&e===t.ownerID?t:new le(t?t.array.slice():[],e)}function ge(t,e){if(e>=Ee(t._capacity))return t._tail;if(e<1<<t._level+cn){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&hn],r-=cn;return n}}function Se(t,e,n){void 0!==e&&(e|=0),void 0!==n&&(n|=0);var i=t.__ownerID||new r,o=t._origin,u=t._capacity,a=o+e,s=void 0===n?u:n<0?u+n:o+n;if(a===o&&s===u)return t;if(a>=s)return t.clear();for(var c=t._level,f=t._root,h=0;a+h<0;)f=new le(f&&f.array.length?[void 0,f]:[],i),c+=cn,h+=1<<c;h&&(a+=h,o+=h,s+=h,u+=h);for(var l=Ee(u),p=Ee(s);p>=1<<c+cn;)f=new le(f&&f.array.length?[f]:[],i),c+=cn;var _=t._tail,d=p<l?ge(t,s-1):p>l?new le([],i):_;if(_&&p>l&&a<u&&_.array.length){f=me(f,i);for(var v=f,y=c;y>cn;y-=cn){var m=l>>>y&hn;v=v.array[m]=me(v.array[m],i)}v.array[l>>>cn&hn]=_}if(s<u&&(d=d&&d.removeAfter(i,0,s)),a>=p)a-=p,s-=p,c=cn,f=null,d=d&&d.removeBefore(i,0,a);else if(a>o||p<l){for(h=0;f;){var g=a>>>c&hn;if(g!==p>>>c&hn)break;g&&(h+=(1<<c)*g),c-=cn,f=f.array[g]}f&&a>o&&(f=f.removeBefore(i,c,a-h)),f&&p<l&&(f=f.removeAfter(i,c,p-h)),h&&(a-=h,s-=h)}return t.__ownerID?(t.size=s-a,t._origin=a,t._capacity=s,t._level=c,t._root=f,t._tail=d,t.__hash=void 0,t.__altered=!0,t):_e(a,s,c,f,d)}function be(t,e,n){for(var r=[],i=0,o=0;o<n.length;o++){var u=n[o],a=_(u);a.size>i&&(i=a.size),v(u)||(a=a.map((function(t){return X(t)}))),r.push(a)}return i>t.size&&(t=t.setSize(i)),ie(t,e,r)}function Ee(t){return t<fn?0:t-1>>>cn<<cn}function Ie(t){return null===t||void 0===t?Te():Oe(t)?t:Te().withMutations((function(e){var n=p(t);at(n.size),n.forEach((function(t,n){return e.set(n,t)}))}))}function Oe(t){return Ut(t)&&S(t)}function we(t,e,n,r){var i=Object.create(Ie.prototype);return i.size=t?t.size:0,i._map=t,i._list=e,i.__ownerID=n,i.__hash=r,i}function Te(){return Jn||(Jn=we(Jt(),de()))}function Ae(t,e,n){var r,i,o=t._map,u=t._list,a=o.get(e),s=void 0!==a;if(n===ln){if(!s)return t;u.size>=fn&&u.size>=2*o.size?(i=u.filter((function(t,e){return void 0!==t&&a!==e})),r=i.toKeyedSeq().map((function(t){return t[0]})).flip().toMap(),t.__ownerID&&(r.__ownerID=i.__ownerID=t.__ownerID)):(r=o.remove(e),i=a===u.size-1?u.pop():u.set(a,void 0))}else if(s){if(n===u.get(a)[1])return t;r=o,i=u.set(a,[e,n])}else r=o.set(e,u.size),i=u.set(u.size,[e,n]);return t.__ownerID?(t.size=r.size,t._map=r,t._list=i,t.__hash=void 0,t):we(r,i)}function De(t){return null===t||void 0===t?Re():Ce(t)?t:Re().unshiftAll(t)}function Ce(t){return!(!t||!t[Wn])}function ze(t,e,n,r){var i=Object.create(Xn);return i.size=t,i._head=e,i.__ownerID=n,i.__hash=r,i.__altered=!1,i}function Re(){return Qn||(Qn=ze(0))}function Me(t){return null===t||void 0===t?ke():je(t)&&!S(t)?t:ke().withMutations((function(e){var n=d(t);at(n.size),n.forEach((function(t){return e.add(t)}))}))}function je(t){return!(!t||!t[Zn])}function Le(t,e){return t.__ownerID?(t.size=e.size,t._map=e,t):e===t._map?t:0===e.size?t.__empty():t.__make(e)}function Ne(t,e){var n=Object.create($n);return n.size=t?t.size:0,n._map=t,n.__ownerID=e,n}function ke(){return tr||(tr=Ne(Jt()))}function Pe(t){return null===t||void 0===t?xe():Ue(t)?t:xe().withMutations((function(e){var n=d(t);at(n.size),n.forEach((function(t){return e.add(t)}))}))}function Ue(t){return je(t)&&S(t)}function He(t,e){var n=Object.create(er);return n.size=t?t.size:0,n._map=t,n.__ownerID=e,n}function xe(){return nr||(nr=He(Te()))}function Ve(t,e){var n,r=function(o){if(o instanceof r)return o;if(!(this instanceof r))return new r(o);if(!n){n=!0;var u=Object.keys(t);Ge(i,u),i.size=u.length,i._name=e,i._keys=u,i._defaultValues=t}this._map=Pt(o)},i=r.prototype=Object.create(rr);return i.constructor=r,r}function qe(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function Fe(t){return t._name||t.constructor.name||"Record"}function Ge(t,e){try{e.forEach(Ke.bind(void 0,t))}catch(t){}}function Ke(t,e){Object.defineProperty(t,e,{get:function(){return this.get(e)},set:function(t){ut(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}function Be(t,e){if(t===e)return!0;if(!v(e)||void 0!==t.size&&void 0!==e.size&&t.size!==e.size||void 0!==t.__hash&&void 0!==e.__hash&&t.__hash!==e.__hash||y(t)!==y(e)||m(t)!==m(e)||S(t)!==S(e))return!1;if(0===t.size&&0===e.size)return!0;var n=!g(t);if(S(t)){var r=t.entries();return e.every((function(t,e){var i=r.next().value;return i&&W(i[1],t)&&(n||W(i[0],e))}))&&r.next().done}var i=!1;if(void 0===t.size)if(void 0===e.size)"function"==typeof t.cacheResult&&t.cacheResult();else{i=!0;var o=t;t=e,e=o}var u=!0,a=e.__iterate((function(e,r){if(n?!t.has(e):i?!W(e,t.get(r,ln)):!W(t.get(r,ln),e))return u=!1,!1}));return u&&t.size===a}function Ye(t,e,n){if(!(this instanceof Ye))return new Ye(t,e,n);if(ut(0!==n,"Cannot step a Range by 0"),t=t||0,void 0===e&&(e=1/0),n=void 0===n?1:Math.abs(n),e<t&&(n=-n),this._start=t,this._end=e,this._step=n,this.size=Math.max(0,Math.ceil((e-t)/n-1)+1),0===this.size){if(ir)return ir;ir=this}}function Je(t,e){if(!(this instanceof Je))return new Je(t,e);if(this._value=t,this.size=void 0===e?1/0:Math.max(0,e),0===this.size){if(or)return or;or=this}}function We(t,e){var n=function(n){t.prototype[n]=e[n]};return Object.keys(e).forEach(n),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(e).forEach(n),t}function Xe(t,e){return e}function Qe(t,e){return[e,t]}function Ze(t){return function(){return!t.apply(this,arguments)}}function $e(t){return function(){return-t.apply(this,arguments)}}function tn(t){return"string"==typeof t?JSON.stringify(t):t}function en(){return i(arguments)}function nn(t,e){return t<e?1:t>e?-1:0}function rn(t){if(t.size===1/0)return 0;var e=S(t),n=y(t),r=e?1:0,i=t.__iterate(n?e?function(t,e){r=31*r+un(et(t),et(e))|0}:function(t,e){r=r+un(et(t),et(e))|0}:e?function(t){r=31*r+et(t)|0}:function(t){r=r+et(t)|0});return on(i,r)}function on(t,e){return e=Dn(e,3432918353),e=Dn(e<<15|e>>>-15,461845907),e=Dn(e<<13|e>>>-13,5),e=(e+3864292196|0)^t,e=Dn(e^e>>>16,2246822507),e=Dn(e^e>>>13,3266489909),e=tt(e^e>>>16)}function un(t,e){return t^e+2654435769+(t<<6)+(t>>2)|0}var an=Array.prototype.slice,sn="delete",cn=5,fn=1<<cn,hn=fn-1,ln={},pn={value:!1},_n={value:!1};t(p,l),t(_,l),t(d,l),l.isIterable=v,l.isKeyed=y,l.isIndexed=m,l.isAssociative=g,l.isOrdered=S,l.Keyed=p,l.Indexed=_,l.Set=d;var dn="@@__IMMUTABLE_ITERABLE__@@",vn="@@__IMMUTABLE_KEYED__@@",yn="@@__IMMUTABLE_INDEXED__@@",mn="@@__IMMUTABLE_ORDERED__@@",gn=0,Sn=1,bn=2,En="function"==typeof Symbol&&Symbol.iterator,In="@@iterator",On=En||In;b.prototype.toString=function(){return"[Iterator]"},b.KEYS=gn,b.VALUES=Sn,b.ENTRIES=bn,b.prototype.inspect=b.prototype.toSource=function(){return this.toString()},b.prototype[On]=function(){return this},t(C,l),C.of=function(){return C(arguments)},C.prototype.toSeq=function(){return this},C.prototype.toString=function(){return this.__toString("Seq {","}")},C.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},C.prototype.__iterate=function(t,e){return F(this,t,e,!0)},C.prototype.__iterator=function(t,e){return G(this,t,e,!0)},t(z,C),z.prototype.toKeyedSeq=function(){return this},t(R,C),R.of=function(){return R(arguments)},R.prototype.toIndexedSeq=function(){return this},R.prototype.toString=function(){return this.__toString("Seq [","]")},R.prototype.__iterate=function(t,e){return F(this,t,e,!1)},R.prototype.__iterator=function(t,e){return G(this,t,e,!1)},t(M,C),M.of=function(){return M(arguments)},M.prototype.toSetSeq=function(){return this},C.isSeq=P,C.Keyed=z,C.Set=M,C.Indexed=R;var wn="@@__IMMUTABLE_SEQ__@@";C.prototype[wn]=!0,t(j,R),j.prototype.get=function(t,e){return this.has(t)?this._array[u(this,t)]:e},j.prototype.__iterate=function(t,e){for(var n=this,r=this._array,i=r.length-1,o=0;o<=i;o++)if(t(r[e?i-o:o],o,n)===!1)return o+1;return o},j.prototype.__iterator=function(t,e){var n=this._array,r=n.length-1,i=0;return new b(function(){return i>r?I():E(t,i,n[e?r-i++:i++])})},t(L,z),L.prototype.get=function(t,e){return void 0===e||this.has(t)?this._object[t]:e},L.prototype.has=function(t){return this._object.hasOwnProperty(t)},L.prototype.__iterate=function(t,e){for(var n=this,r=this._object,i=this._keys,o=i.length-1,u=0;u<=o;u++){var a=i[e?o-u:u];if(t(r[a],a,n)===!1)return u+1}return u},L.prototype.__iterator=function(t,e){var n=this._object,r=this._keys,i=r.length-1,o=0;return new b(function(){var u=r[e?i-o:o];return o++>i?I():E(t,u,n[u])})},L.prototype[mn]=!0,t(N,R),N.prototype.__iterateUncached=function(t,e){var n=this;if(e)return this.cacheResult().__iterate(t,e);var r=this._iterable,i=T(r),o=0;if(w(i))for(var u;!(u=i.next()).done&&t(u.value,o++,n)!==!1;);return o},N.prototype.__iteratorUncached=function(t,e){if(e)return this.cacheResult().__iterator(t,e);var n=this._iterable,r=T(n);if(!w(r))return new b(I);var i=0;return new b(function(){var e=r.next();return e.done?e:E(t,i++,e.value)})},t(k,R),k.prototype.__iterateUncached=function(t,e){var n=this;if(e)return this.cacheResult().__iterate(t,e);for(var r=this._iterator,i=this._iteratorCache,o=0;o<i.length;)if(t(i[o],o++,n)===!1)return o;for(var u;!(u=r.next()).done;){var a=u.value;if(i[o]=a,t(a,o++,n)===!1)break}return o},k.prototype.__iteratorUncached=function(t,e){if(e)return this.cacheResult().__iterator(t,e);var n=this._iterator,r=this._iteratorCache,i=0;return new b(function(){if(i>=r.length){var e=n.next();if(e.done)return e;r[i]=e.value}return E(t,i,r[i++])})};var Tn;t(K,l),t(B,K),t(Y,K),t(J,K),K.Keyed=B,K.Indexed=Y,K.Set=J;var An,Dn="function"==typeof Math.imul&&Math.imul(4294967295,2)===-2?Math.imul:function(t,e){t|=0,e|=0;var n=65535&t,r=65535&e;return n*r+((t>>>16)*r+n*(e>>>16)<<16>>>0)|0},Cn=Object.isExtensible,zn=(function(){try{return Object.defineProperty({},"@",{}),!0}catch(t){return!1}})(),Rn="function"==typeof WeakMap;Rn&&(An=new WeakMap);var Mn=0,jn="__immutablehash__";"function"==typeof Symbol&&(jn=Symbol(jn));var Ln=16,Nn=255,kn=0,Pn={};t(st,z),st.prototype.get=function(t,e){return this._iter.get(t,e)},st.prototype.has=function(t){return this._iter.has(t)},st.prototype.valueSeq=function(){return this._iter.valueSeq()},st.prototype.reverse=function(){var t=this,e=_t(this,!0);return this._useKeys||(e.valueSeq=function(){return t._iter.toSeq().reverse()}),e},st.prototype.map=function(t,e){var n=this,r=pt(this,t,e);return this._useKeys||(r.valueSeq=function(){return n._iter.toSeq().map(t,e)}),r},st.prototype.__iterate=function(t,e){var n,r=this;return this._iter.__iterate(this._useKeys?function(e,n){return t(e,n,r)}:(n=e?Rt(this):0,function(i){return t(i,e?--n:n++,r)}),e)},st.prototype.__iterator=function(t,e){if(this._useKeys)return this._iter.__iterator(t,e);var n=this._iter.__iterator(Sn,e),r=e?Rt(this):0;return new b(function(){var i=n.next();return i.done?i:E(t,e?--r:r++,i.value,i)})},st.prototype[mn]=!0,t(ct,R),ct.prototype.includes=function(t){return this._iter.includes(t)},ct.prototype.__iterate=function(t,e){var n=this,r=0;return this._iter.__iterate((function(e){return t(e,r++,n)}),e)},ct.prototype.__iterator=function(t,e){var n=this._iter.__iterator(Sn,e),r=0;return new b(function(){var e=n.next();return e.done?e:E(t,r++,e.value,e)})},t(ft,M),ft.prototype.has=function(t){return this._iter.includes(t)},ft.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate((function(e){return t(e,e,n)}),e)},ft.prototype.__iterator=function(t,e){var n=this._iter.__iterator(Sn,e);return new b(function(){var e=n.next();return e.done?e:E(t,e.value,e.value,e)})},t(ht,z),ht.prototype.entrySeq=function(){return this._iter.toSeq()},ht.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate((function(e){if(e){zt(e);var r=v(e);return t(r?e.get(1):e[1],r?e.get(0):e[0],n)}}),e)},ht.prototype.__iterator=function(t,e){var n=this._iter.__iterator(Sn,e);return new b(function(){for(;;){var e=n.next();if(e.done)return e;var r=e.value;if(r){zt(r);var i=v(r);return E(t,i?r.get(0):r[0],i?r.get(1):r[1],e)}}})},ct.prototype.cacheResult=st.prototype.cacheResult=ft.prototype.cacheResult=ht.prototype.cacheResult=Lt,t(Pt,B),Pt.prototype.toString=function(){return this.__toString("Map {","}")},Pt.prototype.get=function(t,e){return this._root?this._root.get(0,void 0,t,e):e},Pt.prototype.set=function(t,e){return Wt(this,t,e)},Pt.prototype.setIn=function(t,e){return this.updateIn(t,ln,(function(){return e}))},Pt.prototype.remove=function(t){return Wt(this,t,ln)},Pt.prototype.deleteIn=function(t){return this.updateIn(t,(function(){return ln}))},Pt.prototype.update=function(t,e,n){return 1===arguments.length?t(this):this.updateIn([t],e,n)},Pt.prototype.updateIn=function(t,e,n){n||(n=e,e=void 0);var r=oe(this,kt(t),e,n);return r===ln?void 0:r},Pt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Jt()},Pt.prototype.merge=function(){return ne(this,void 0,arguments)},Pt.prototype.mergeWith=function(t){var e=an.call(arguments,1);return ne(this,t,e)},Pt.prototype.mergeIn=function(t){var e=an.call(arguments,1);return this.updateIn(t,Jt(),(function(t){return"function"==typeof t.merge?t.merge.apply(t,e):e[e.length-1]}))},Pt.prototype.mergeDeep=function(){return ne(this,re(void 0),arguments)},Pt.prototype.mergeDeepWith=function(t){var e=an.call(arguments,1);return ne(this,re(t),e)},Pt.prototype.mergeDeepIn=function(t){var e=an.call(arguments,1);return this.updateIn(t,Jt(),(function(t){return"function"==typeof t.mergeDeep?t.mergeDeep.apply(t,e):e[e.length-1]}))},Pt.prototype.sort=function(t){return Ie(wt(this,t))},Pt.prototype.sortBy=function(t,e){return Ie(wt(this,e,t))},Pt.prototype.withMutations=function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},Pt.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new r)},Pt.prototype.asImmutable=function(){return this.__ensureOwner()},Pt.prototype.wasAltered=function(){return this.__altered},Pt.prototype.__iterator=function(t,e){return new Gt(this,t,e)},Pt.prototype.__iterate=function(t,e){var n=this,r=0;return this._root&&this._root.iterate((function(e){return r++,t(e[1],e[0],n)}),e),r},Pt.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?Yt(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},Pt.isMap=Ut;var Un="@@__IMMUTABLE_MAP__@@",Hn=Pt.prototype;Hn[Un]=!0,Hn[sn]=Hn.remove,Hn.removeIn=Hn.deleteIn,Ht.prototype.get=function(t,e,n,r){for(var i=this.entries,o=0,u=i.length;o<u;o++)if(W(n,i[o][0]))return i[o][1];return r},Ht.prototype.update=function(t,e,r,o,u,a,s){for(var c=u===ln,f=this.entries,h=0,l=f.length;h<l&&!W(o,f[h][0]);h++);var p=h<l;if(p?f[h][1]===u:c)return this;if(n(s),(c||!p)&&n(a),!c||1!==f.length){if(!p&&!c&&f.length>=Vn)return $t(t,f,o,u);var _=t&&t===this.ownerID,d=_?f:i(f);return p?c?h===l-1?d.pop():d[h]=d.pop():d[h]=[o,u]:d.push([o,u]),_?(this.entries=d,this):new Ht(t,d)}},xt.prototype.get=function(t,e,n,r){void 0===e&&(e=et(n));var i=1<<((0===t?e:e>>>t)&hn),o=this.bitmap;return 0===(o&i)?r:this.nodes[ue(o&i-1)].get(t+cn,e,n,r)},xt.prototype.update=function(t,e,n,r,i,o,u){void 0===n&&(n=et(r));var a=(0===e?n:n>>>e)&hn,s=1<<a,c=this.bitmap,f=0!==(c&s);if(!f&&i===ln)return this;var h=ue(c&s-1),l=this.nodes,p=f?l[h]:void 0,_=Xt(p,t,e+cn,n,r,i,o,u);if(_===p)return this;if(!f&&_&&l.length>=qn)return ee(t,l,c,a,_);if(f&&!_&&2===l.length&&Qt(l[1^h]))return l[1^h];if(f&&_&&1===l.length&&Qt(_))return _;var d=t&&t===this.ownerID,v=f?_?c:c^s:c|s,y=f?_?ae(l,h,_,d):ce(l,h,d):se(l,h,_,d);return d?(this.bitmap=v,this.nodes=y,this):new xt(t,v,y)},Vt.prototype.get=function(t,e,n,r){void 0===e&&(e=et(n));var i=(0===t?e:e>>>t)&hn,o=this.nodes[i];return o?o.get(t+cn,e,n,r):r},Vt.prototype.update=function(t,e,n,r,i,o,u){void 0===n&&(n=et(r));var a=(0===e?n:n>>>e)&hn,s=i===ln,c=this.nodes,f=c[a];if(s&&!f)return this;var h=Xt(f,t,e+cn,n,r,i,o,u);if(h===f)return this;var l=this.count;if(f){if(!h&&(l--,l<Fn))return te(t,c,l,a)}else l++;var p=t&&t===this.ownerID,_=ae(c,a,h,p);return p?(this.count=l,this.nodes=_,this):new Vt(t,l,_)},qt.prototype.get=function(t,e,n,r){for(var i=this.entries,o=0,u=i.length;o<u;o++)if(W(n,i[o][0]))return i[o][1];return r},qt.prototype.update=function(t,e,r,o,u,a,s){void 0===r&&(r=et(o));var c=u===ln;if(r!==this.keyHash)return c?this:(n(s),n(a),Zt(this,t,e,r,[o,u]));for(var f=this.entries,h=0,l=f.length;h<l&&!W(o,f[h][0]);h++);var p=h<l;if(p?f[h][1]===u:c)return this;if(n(s),(c||!p)&&n(a),c&&2===l)return new Ft(t,this.keyHash,f[1^h]);var _=t&&t===this.ownerID,d=_?f:i(f);return p?c?h===l-1?d.pop():d[h]=d.pop():d[h]=[o,u]:d.push([o,u]),_?(this.entries=d,this):new qt(t,this.keyHash,d)},Ft.prototype.get=function(t,e,n,r){return W(n,this.entry[0])?this.entry[1]:r},Ft.prototype.update=function(t,e,r,i,o,u,a){var s=o===ln,c=W(i,this.entry[0]);return(c?o===this.entry[1]:s)?this:(n(a),s?void n(u):c?t&&t===this.ownerID?(this.entry[1]=o,this):new Ft(t,this.keyHash,[i,o]):(n(u),Zt(this,t,e,et(i),[i,o])))},Ht.prototype.iterate=qt.prototype.iterate=function(t,e){for(var n=this.entries,r=0,i=n.length-1;r<=i;r++)if(t(n[e?i-r:r])===!1)return!1},xt.prototype.iterate=Vt.prototype.iterate=function(t,e){for(var n=this.nodes,r=0,i=n.length-1;r<=i;r++){var o=n[e?i-r:r];if(o&&o.iterate(t,e)===!1)return!1}},Ft.prototype.iterate=function(t,e){return t(this.entry)},t(Gt,b),Gt.prototype.next=function(){for(var t=this,e=this._type,n=this._stack;n;){var r,i=n.node,o=n.index++;if(i.entry){if(0===o)return Kt(e,i.entry)}else if(i.entries){if(r=i.entries.length-1,o<=r)return Kt(e,i.entries[t._reverse?r-o:o])}else if(r=i.nodes.length-1,o<=r){var u=i.nodes[t._reverse?r-o:o];if(u){if(u.entry)return Kt(e,u.entry);n=t._stack=Bt(u,n)}continue}n=t._stack=t._stack.__prev}return I()};var xn,Vn=fn/4,qn=fn/2,Fn=fn/4;t(fe,Y),fe.of=function(){return this(arguments)},fe.prototype.toString=function(){return this.__toString("List [","]")},fe.prototype.get=function(t,e){if(t=u(this,t),t>=0&&t<this.size){t+=this._origin;var n=ge(this,t);return n&&n.array[t&hn]}return e},fe.prototype.set=function(t,e){return ve(this,t,e)},fe.prototype.remove=function(t){return this.has(t)?0===t?this.shift():t===this.size-1?this.pop():this.splice(t,1):this},fe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=cn,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):de()},fe.prototype.push=function(){var t=arguments,e=this.size;return this.withMutations((function(n){Se(n,0,e+t.length);for(var r=0;r<t.length;r++)n.set(e+r,t[r])}))},fe.prototype.pop=function(){return Se(this,0,-1)},fe.prototype.unshift=function(){var t=arguments;return this.withMutations((function(e){Se(e,-t.length);for(var n=0;n<t.length;n++)e.set(n,t[n])}))},fe.prototype.shift=function(){return Se(this,1)},fe.prototype.merge=function(){return be(this,void 0,arguments)},fe.prototype.mergeWith=function(t){var e=an.call(arguments,1);return be(this,t,e)},fe.prototype.mergeDeep=function(){return be(this,re(void 0),arguments)},fe.prototype.mergeDeepWith=function(t){var e=an.call(arguments,1);return be(this,re(t),e)},fe.prototype.setSize=function(t){return Se(this,0,t)},fe.prototype.slice=function(t,e){var n=this.size;return s(t,e,n)?this:Se(this,c(t,n),f(e,n))},fe.prototype.__iterator=function(t,e){var n=0,r=pe(this,e);return new b(function(){var e=r();return e===Yn?I():E(t,n++,e)})},fe.prototype.__iterate=function(t,e){for(var n,r=this,i=0,o=pe(this,e);(n=o())!==Yn&&t(n,i++,r)!==!1;);return i},fe.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?_e(this._origin,this._capacity,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)},fe.isList=he;var Gn="@@__IMMUTABLE_LIST__@@",Kn=fe.prototype;Kn[Gn]=!0,Kn[sn]=Kn.remove,Kn.setIn=Hn.setIn,Kn.deleteIn=Kn.removeIn=Hn.removeIn,Kn.update=Hn.update,Kn.updateIn=Hn.updateIn,Kn.mergeIn=Hn.mergeIn,Kn.mergeDeepIn=Hn.mergeDeepIn,Kn.withMutations=Hn.withMutations,Kn.asMutable=Hn.asMutable,Kn.asImmutable=Hn.asImmutable,Kn.wasAltered=Hn.wasAltered,le.prototype.removeBefore=function(t,e,n){if(n===e?1<<e:0===this.array.length)return this;var r=n>>>e&hn;if(r>=this.array.length)return new le([],t);var i,o=0===r;if(e>0){var u=this.array[r];if(i=u&&u.removeBefore(t,e-cn,n),i===u&&o)return this}if(o&&!i)return this;var a=me(this,t);if(!o)for(var s=0;s<r;s++)a.array[s]=void 0;return i&&(a.array[r]=i),a},le.prototype.removeAfter=function(t,e,n){if(n===(e?1<<e:0)||0===this.array.length)return this;var r=n-1>>>e&hn;if(r>=this.array.length)return this;var i;if(e>0){var o=this.array[r];if(i=o&&o.removeAfter(t,e-cn,n),i===o&&r===this.array.length-1)return this}var u=me(this,t);return u.array.splice(r+1),i&&(u.array[r]=i),u};var Bn,Yn={};t(Ie,Pt),Ie.of=function(){return this(arguments)},Ie.prototype.toString=function(){return this.__toString("OrderedMap {","}")},Ie.prototype.get=function(t,e){var n=this._map.get(t);return void 0!==n?this._list.get(n)[1]:e},Ie.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):Te()},Ie.prototype.set=function(t,e){return Ae(this,t,e)},Ie.prototype.remove=function(t){return Ae(this,t,ln)},Ie.prototype.wasAltered=function(){return this._map.wasAltered()||this._list.wasAltered()},Ie.prototype.__iterate=function(t,e){var n=this;return this._list.__iterate((function(e){return e&&t(e[1],e[0],n)}),e)},Ie.prototype.__iterator=function(t,e){return this._list.fromEntrySeq().__iterator(t,e)},Ie.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),n=this._list.__ensureOwner(t);return t?we(e,n,t,this.__hash):(this.__ownerID=t,this._map=e,this._list=n,this)},Ie.isOrderedMap=Oe,Ie.prototype[mn]=!0,Ie.prototype[sn]=Ie.prototype.remove;var Jn;t(De,Y),De.of=function(){return this(arguments)},De.prototype.toString=function(){return this.__toString("Stack [","]")},De.prototype.get=function(t,e){var n=this._head;for(t=u(this,t);n&&t--;)n=n.next;return n?n.value:e},De.prototype.peek=function(){return this._head&&this._head.value},De.prototype.push=function(){var t=arguments;if(0===arguments.length)return this;for(var e=this.size+arguments.length,n=this._head,r=arguments.length-1;r>=0;r--)n={value:t[r],next:n};return this.__ownerID?(this.size=e,this._head=n,this.__hash=void 0,this.__altered=!0,this):ze(e,n)},De.prototype.pushAll=function(t){if(t=_(t),0===t.size)return this;at(t.size);var e=this.size,n=this._head;return t.reverse().forEach((function(t){e++,n={value:t,next:n}})),this.__ownerID?(this.size=e,this._head=n,this.__hash=void 0,this.__altered=!0,this):ze(e,n)},De.prototype.pop=function(){return this.slice(1)},De.prototype.unshift=function(){return this.push.apply(this,arguments)},De.prototype.unshiftAll=function(t){return this.pushAll(t)},De.prototype.shift=function(){return this.pop.apply(this,arguments)},De.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Re()},De.prototype.slice=function(t,e){if(s(t,e,this.size))return this;var n=c(t,this.size),r=f(e,this.size);if(r!==this.size)return Y.prototype.slice.call(this,t,e);for(var i=this.size-n,o=this._head;n--;)o=o.next;return this.__ownerID?(this.size=i,this._head=o,this.__hash=void 0,this.__altered=!0,this):ze(i,o)},De.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?ze(this.size,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},De.prototype.__iterate=function(t,e){var n=this;if(e)return this.reverse().__iterate(t);for(var r=0,i=this._head;i&&t(i.value,r++,n)!==!1;)i=i.next;return r},De.prototype.__iterator=function(t,e){if(e)return this.reverse().__iterator(t);var n=0,r=this._head;return new b(function(){if(r){var e=r.value;return r=r.next,E(t,n++,e)}return I()})},De.isStack=Ce;var Wn="@@__IMMUTABLE_STACK__@@",Xn=De.prototype;Xn[Wn]=!0,Xn.withMutations=Hn.withMutations,Xn.asMutable=Hn.asMutable,Xn.asImmutable=Hn.asImmutable,Xn.wasAltered=Hn.wasAltered;var Qn;t(Me,J),Me.of=function(){return this(arguments)},Me.fromKeys=function(t){return this(p(t).keySeq())},Me.prototype.toString=function(){return this.__toString("Set {","}")},Me.prototype.has=function(t){return this._map.has(t)},Me.prototype.add=function(t){return Le(this,this._map.set(t,!0))},Me.prototype.remove=function(t){return Le(this,this._map.remove(t))},Me.prototype.clear=function(){return Le(this,this._map.clear())},Me.prototype.union=function(){var t=an.call(arguments,0);return t=t.filter((function(t){return 0!==t.size})),0===t.length?this:0!==this.size||this.__ownerID||1!==t.length?this.withMutations((function(e){for(var n=0;n<t.length;n++)d(t[n]).forEach((function(t){return e.add(t)}))})):this.constructor(t[0])},Me.prototype.intersect=function(){var t=an.call(arguments,0);if(0===t.length)return this;t=t.map((function(t){return d(t)}));var e=this;return this.withMutations((function(n){e.forEach((function(e){t.every((function(t){return t.includes(e)}))||n.remove(e)}))}))},Me.prototype.subtract=function(){var t=an.call(arguments,0);if(0===t.length)return this;t=t.map((function(t){return d(t)}));var e=this;return this.withMutations((function(n){e.forEach((function(e){t.some((function(t){return t.includes(e)}))&&n.remove(e)}))}))},Me.prototype.merge=function(){return this.union.apply(this,arguments)},Me.prototype.mergeWith=function(t){var e=an.call(arguments,1);return this.union.apply(this,e)},Me.prototype.sort=function(t){return Pe(wt(this,t))},Me.prototype.sortBy=function(t,e){return Pe(wt(this,e,t))},Me.prototype.wasAltered=function(){return this._map.wasAltered()},Me.prototype.__iterate=function(t,e){var n=this;return this._map.__iterate((function(e,r){return t(r,r,n)}),e)},Me.prototype.__iterator=function(t,e){return this._map.map((function(t,e){return e})).__iterator(t,e)},Me.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?this.__make(e,t):(this.__ownerID=t,this._map=e,this)},Me.isSet=je;var Zn="@@__IMMUTABLE_SET__@@",$n=Me.prototype;$n[Zn]=!0,$n[sn]=$n.remove,$n.mergeDeep=$n.merge,$n.mergeDeepWith=$n.mergeWith,$n.withMutations=Hn.withMutations,$n.asMutable=Hn.asMutable,$n.asImmutable=Hn.asImmutable,$n.__empty=ke,$n.__make=Ne;var tr;t(Pe,Me),Pe.of=function(){return this(arguments)},Pe.fromKeys=function(t){return this(p(t).keySeq())},Pe.prototype.toString=function(){
return this.__toString("OrderedSet {","}")},Pe.isOrderedSet=Ue;var er=Pe.prototype;er[mn]=!0,er.__empty=xe,er.__make=He;var nr;t(Ve,B),Ve.prototype.toString=function(){return this.__toString(Fe(this)+" {","}")},Ve.prototype.has=function(t){return this._defaultValues.hasOwnProperty(t)},Ve.prototype.get=function(t,e){if(!this.has(t))return e;var n=this._defaultValues[t];return this._map?this._map.get(t,n):n},Ve.prototype.clear=function(){if(this.__ownerID)return this._map&&this._map.clear(),this;var t=this.constructor;return t._empty||(t._empty=qe(this,Jt()))},Ve.prototype.set=function(t,e){if(!this.has(t))throw new Error('Cannot set unknown key "'+t+'" on '+Fe(this));var n=this._map&&this._map.set(t,e);return this.__ownerID||n===this._map?this:qe(this,n)},Ve.prototype.remove=function(t){if(!this.has(t))return this;var e=this._map&&this._map.remove(t);return this.__ownerID||e===this._map?this:qe(this,e)},Ve.prototype.wasAltered=function(){return this._map.wasAltered()},Ve.prototype.__iterator=function(t,e){var n=this;return p(this._defaultValues).map((function(t,e){return n.get(e)})).__iterator(t,e)},Ve.prototype.__iterate=function(t,e){var n=this;return p(this._defaultValues).map((function(t,e){return n.get(e)})).__iterate(t,e)},Ve.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?qe(this,e,t):(this.__ownerID=t,this._map=e,this)};var rr=Ve.prototype;rr[sn]=rr.remove,rr.deleteIn=rr.removeIn=Hn.removeIn,rr.merge=Hn.merge,rr.mergeWith=Hn.mergeWith,rr.mergeIn=Hn.mergeIn,rr.mergeDeep=Hn.mergeDeep,rr.mergeDeepWith=Hn.mergeDeepWith,rr.mergeDeepIn=Hn.mergeDeepIn,rr.setIn=Hn.setIn,rr.update=Hn.update,rr.updateIn=Hn.updateIn,rr.withMutations=Hn.withMutations,rr.asMutable=Hn.asMutable,rr.asImmutable=Hn.asImmutable,t(Ye,R),Ye.prototype.toString=function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},Ye.prototype.get=function(t,e){return this.has(t)?this._start+u(this,t)*this._step:e},Ye.prototype.includes=function(t){var e=(t-this._start)/this._step;return e>=0&&e<this.size&&e===Math.floor(e)},Ye.prototype.slice=function(t,e){return s(t,e,this.size)?this:(t=c(t,this.size),e=f(e,this.size),e<=t?new Ye(0,0):new Ye(this.get(t,this._end),this.get(e,this._end),this._step))},Ye.prototype.indexOf=function(t){var e=t-this._start;if(e%this._step===0){var n=e/this._step;if(n>=0&&n<this.size)return n}return-1},Ye.prototype.lastIndexOf=function(t){return this.indexOf(t)},Ye.prototype.__iterate=function(t,e){for(var n=this,r=this.size-1,i=this._step,o=e?this._start+r*i:this._start,u=0;u<=r;u++){if(t(o,u,n)===!1)return u+1;o+=e?-i:i}return u},Ye.prototype.__iterator=function(t,e){var n=this.size-1,r=this._step,i=e?this._start+n*r:this._start,o=0;return new b(function(){var u=i;return i+=e?-r:r,o>n?I():E(t,o++,u)})},Ye.prototype.equals=function(t){return t instanceof Ye?this._start===t._start&&this._end===t._end&&this._step===t._step:Be(this,t)};var ir;t(Je,R),Je.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Je.prototype.get=function(t,e){return this.has(t)?this._value:e},Je.prototype.includes=function(t){return W(this._value,t)},Je.prototype.slice=function(t,e){var n=this.size;return s(t,e,n)?this:new Je(this._value,f(e,n)-c(t,n))},Je.prototype.reverse=function(){return this},Je.prototype.indexOf=function(t){return W(this._value,t)?0:-1},Je.prototype.lastIndexOf=function(t){return W(this._value,t)?this.size:-1},Je.prototype.__iterate=function(t,e){for(var n=this,r=0;r<this.size;r++)if(t(n._value,r,n)===!1)return r+1;return r},Je.prototype.__iterator=function(t,e){var n=this,r=0;return new b(function(){return r<n.size?E(t,r++,n._value):I()})},Je.prototype.equals=function(t){return t instanceof Je?W(this._value,t._value):Be(t)};var or;l.Iterator=b,We(l,{toArray:function(){at(this.size);var t=new Array(this.size||0);return this.valueSeq().__iterate((function(e,n){t[n]=e})),t},toIndexedSeq:function(){return new ct(this)},toJS:function(){return this.toSeq().map((function(t){return t&&"function"==typeof t.toJS?t.toJS():t})).__toJS()},toJSON:function(){return this.toSeq().map((function(t){return t&&"function"==typeof t.toJSON?t.toJSON():t})).__toJS()},toKeyedSeq:function(){return new st(this,!0)},toMap:function(){return Pt(this.toKeyedSeq())},toObject:function(){at(this.size);var t={};return this.__iterate((function(e,n){t[n]=e})),t},toOrderedMap:function(){return Ie(this.toKeyedSeq())},toOrderedSet:function(){return Pe(y(this)?this.valueSeq():this)},toSet:function(){return Me(y(this)?this.valueSeq():this)},toSetSeq:function(){return new ft(this)},toSeq:function(){return m(this)?this.toIndexedSeq():y(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return De(y(this)?this.valueSeq():this)},toList:function(){return fe(y(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(t,e){return 0===this.size?t+e:t+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+e},concat:function(){var t=an.call(arguments,0);return Ct(this,bt(this,t))},includes:function(t){return this.some((function(e){return W(e,t)}))},entries:function(){return this.__iterator(bn)},every:function(t,e){at(this.size);var n=!0;return this.__iterate((function(r,i,o){if(!t.call(e,r,i,o))return n=!1,!1})),n},filter:function(t,e){return Ct(this,dt(this,t,e,!0))},find:function(t,e,n){var r=this.findEntry(t,e);return r?r[1]:n},findEntry:function(t,e){var n;return this.__iterate((function(r,i,o){if(t.call(e,r,i,o))return n=[i,r],!1})),n},findLastEntry:function(t,e){return this.toSeq().reverse().findEntry(t,e)},forEach:function(t,e){return at(this.size),this.__iterate(e?t.bind(e):t)},join:function(t){at(this.size),t=void 0!==t?""+t:",";var e="",n=!0;return this.__iterate((function(r){n?n=!1:e+=t,e+=null!==r&&void 0!==r?r.toString():""})),e},keys:function(){return this.__iterator(gn)},map:function(t,e){return Ct(this,pt(this,t,e))},reduce:function(t,e,n){at(this.size);var r,i;return arguments.length<2?i=!0:r=e,this.__iterate((function(e,o,u){i?(i=!1,r=e):r=t.call(n,r,e,o,u)})),r},reduceRight:function(t,e,n){var r=this.toKeyedSeq().reverse();return r.reduce.apply(r,arguments)},reverse:function(){return Ct(this,_t(this,!0))},slice:function(t,e){return Ct(this,mt(this,t,e,!0))},some:function(t,e){return!this.every(Ze(t),e)},sort:function(t){return Ct(this,wt(this,t))},values:function(){return this.__iterator(Sn)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(t,e){return o(t?this.toSeq().filter(t,e):this)},countBy:function(t,e){return vt(this,t,e)},equals:function(t){return Be(this,t)},entrySeq:function(){var t=this;if(t._cache)return new j(t._cache);var e=t.toSeq().map(Qe).toIndexedSeq();return e.fromEntrySeq=function(){return t.toSeq()},e},filterNot:function(t,e){return this.filter(Ze(t),e)},findLast:function(t,e,n){return this.toKeyedSeq().reverse().find(t,e,n)},first:function(){return this.find(a)},flatMap:function(t,e){return Ct(this,It(this,t,e))},flatten:function(t){return Ct(this,Et(this,t,!0))},fromEntrySeq:function(){return new ht(this)},get:function(t,e){return this.find((function(e,n){return W(n,t)}),void 0,e)},getIn:function(t,e){for(var n,r=this,i=kt(t);!(n=i.next()).done;){var o=n.value;if(r=r&&r.get?r.get(o,ln):ln,r===ln)return e}return r},groupBy:function(t,e){return yt(this,t,e)},has:function(t){return this.get(t,ln)!==ln},hasIn:function(t){return this.getIn(t,ln)!==ln},isSubset:function(t){return t="function"==typeof t.includes?t:l(t),this.every((function(e){return t.includes(e)}))},isSuperset:function(t){return t="function"==typeof t.isSubset?t:l(t),t.isSubset(this)},keySeq:function(){return this.toSeq().map(Xe).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},max:function(t){return Tt(this,t)},maxBy:function(t,e){return Tt(this,e,t)},min:function(t){return Tt(this,t?$e(t):nn)},minBy:function(t,e){return Tt(this,e?$e(e):nn,t)},rest:function(){return this.slice(1)},skip:function(t){return this.slice(Math.max(0,t))},skipLast:function(t){return Ct(this,this.toSeq().reverse().skip(t).reverse())},skipWhile:function(t,e){return Ct(this,St(this,t,e,!0))},skipUntil:function(t,e){return this.skipWhile(Ze(t),e)},sortBy:function(t,e){return Ct(this,wt(this,e,t))},take:function(t){return this.slice(0,Math.max(0,t))},takeLast:function(t){return Ct(this,this.toSeq().reverse().take(t).reverse())},takeWhile:function(t,e){return Ct(this,gt(this,t,e))},takeUntil:function(t,e){return this.takeWhile(Ze(t),e)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=rn(this))}});var ur=l.prototype;ur[dn]=!0,ur[On]=ur.values,ur.__toJS=ur.toArray,ur.__toStringMapper=tn,ur.inspect=ur.toSource=function(){return this.toString()},ur.chain=ur.flatMap,ur.contains=ur.includes,(function(){try{Object.defineProperty(ur,"length",{get:function(){if(!l.noLengthWarning){var t;try{throw new Error}catch(e){t=e.stack}if(t.indexOf("_wrapObject")===-1)return console&&console.warn&&console.warn("iterable.length has been deprecated, use iterable.size or iterable.count(). This warning will become a silent error in a future version. "+t),this.size}}})}catch(t){}})(),We(p,{flip:function(){return Ct(this,lt(this))},findKey:function(t,e){var n=this.findEntry(t,e);return n&&n[0]},findLastKey:function(t,e){return this.toSeq().reverse().findKey(t,e)},keyOf:function(t){return this.findKey((function(e){return W(e,t)}))},lastKeyOf:function(t){return this.findLastKey((function(e){return W(e,t)}))},mapEntries:function(t,e){var n=this,r=0;return Ct(this,this.toSeq().map((function(i,o){return t.call(e,[o,i],r++,n)})).fromEntrySeq())},mapKeys:function(t,e){var n=this;return Ct(this,this.toSeq().flip().map((function(r,i){return t.call(e,r,i,n)})).flip())}});var ar=p.prototype;ar[vn]=!0,ar[On]=ur.entries,ar.__toJS=ur.toObject,ar.__toStringMapper=function(t,e){return JSON.stringify(e)+": "+tn(t)},We(_,{toKeyedSeq:function(){return new st(this,!1)},filter:function(t,e){return Ct(this,dt(this,t,e,!1))},findIndex:function(t,e){var n=this.findEntry(t,e);return n?n[0]:-1},indexOf:function(t){var e=this.toKeyedSeq().keyOf(t);return void 0===e?-1:e},lastIndexOf:function(t){return this.toSeq().reverse().indexOf(t)},reverse:function(){return Ct(this,_t(this,!1))},slice:function(t,e){return Ct(this,mt(this,t,e,!1))},splice:function(t,e){var n=arguments.length;if(e=Math.max(0|e,0),0===n||2===n&&!e)return this;t=c(t,t<0?this.count():this.size);var r=this.slice(0,t);return Ct(this,1===n?r:r.concat(i(arguments,2),this.slice(t+e)))},findLastIndex:function(t,e){var n=this.toKeyedSeq().findLastKey(t,e);return void 0===n?-1:n},first:function(){return this.get(0)},flatten:function(t){return Ct(this,Et(this,t,!1))},get:function(t,e){return t=u(this,t),t<0||this.size===1/0||void 0!==this.size&&t>this.size?e:this.find((function(e,n){return n===t}),void 0,e)},has:function(t){return t=u(this,t),t>=0&&(void 0!==this.size?this.size===1/0||t<this.size:this.indexOf(t)!==-1)},interpose:function(t){return Ct(this,Ot(this,t))},interleave:function(){var t=[this].concat(i(arguments)),e=Dt(this.toSeq(),R.of,t),n=e.flatten(!0);return e.size&&(n.size=e.size*t.length),Ct(this,n)},last:function(){return this.get(-1)},skipWhile:function(t,e){return Ct(this,St(this,t,e,!1))},zip:function(){var t=[this].concat(i(arguments));return Ct(this,Dt(this,en,t))},zipWith:function(t){var e=i(arguments);return e[0]=this,Ct(this,Dt(this,t,e))}}),_.prototype[yn]=!0,_.prototype[mn]=!0,We(d,{get:function(t,e){return this.has(t)?t:e},includes:function(t){return this.has(t)},keySeq:function(){return this.valueSeq()}}),d.prototype.has=ur.includes,We(z,p.prototype),We(R,_.prototype),We(M,d.prototype),We(B,p.prototype),We(Y,_.prototype),We(J,d.prototype);var sr={Iterable:l,Seq:C,Collection:K,Map:Pt,OrderedMap:Ie,List:fe,Stack:De,Set:Me,OrderedSet:Pe,Record:Ve,Range:Ye,Repeat:Je,is:W,fromJS:X};return sr}))},function(t,e){function n(t){return t&&"object"==typeof t&&toString.call(t)}function r(t){return"number"==typeof t&&t>-1&&t%1===0&&t<=Number.MAX_VALUE}var i=Function.prototype.bind;e.isString=function(t){return"string"==typeof t||"[object String]"===n(t)},e.isArray=Array.isArray||function(t){return"[object Array]"===n(t)},"function"!=typeof/./&&"object"!=typeof Int8Array?e.isFunction=function(t){return"function"==typeof t||!1}:e.isFunction=function(t){return"[object Function]"===toString.call(t)},e.isObject=function(t){var e=typeof t;return"function"===e||"object"===e&&!!t},e.extend=function(t){var e=arguments,n=arguments.length;if(!t||n<2)return t||{};for(var r=1;r<n;r++)for(var i=e[r],o=Object.keys(i),u=o.length,a=0;a<u;a++){var s=o[a];t[s]=i[s]}return t},e.clone=function(t){return e.isObject(t)?e.isArray(t)?t.slice():e.extend({},t):t},e.each=function(t,e,n){var i,o,u=t?t.length:0,a=-1;if(n&&(o=e,e=function(t,e,r){return o.call(n,t,e,r)}),r(u))for(;++a<u&&e(t[a],a,t)!==!1;);else for(i=Object.keys(t),u=i.length;++a<u&&e(t[i[a]],i[a],t)!==!1;);return t},e.partial=function(t){var e=Array.prototype.slice,n=e.call(arguments,1);return function(){return t.apply(this,n.concat(e.call(arguments)))}},e.toFactory=function(t){var e=function(){for(var e=arguments,n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=e[o];return new(i.apply(t,[null].concat(r)))};return e.__proto__=t,e.prototype=t.prototype,e}},function(t,e,n){function r(t){return t&&t.__esModule?t:{default:t}}function i(t){return c.default.Iterable.isIterable(t)}function o(t){return i(t)||!(0,f.isObject)(t)}function u(t){return i(t)?t.toJS():t}function a(t){return i(t)?t:c.default.fromJS(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.isImmutable=i,e.isImmutableValue=o,e.toJS=u,e.toImmutable=a;var s=n(3),c=r(s),f=n(4)},function(t,e,n){function r(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var a=(function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}})(),s=n(3),c=i(s),f=n(7),h=i(f),l=n(8),p=r(l),_=n(11),d=n(10),v=n(5),y=n(4),m=n(12),g=(function(){function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];u(this,t);var n=!!e.debug,r=n?m.DEBUG_OPTIONS:m.PROD_OPTIONS,i=new m.ReactorState({debug:n,options:r.merge(e.options||{})});this.prevReactorState=i,this.reactorState=i,this.observerState=new m.ObserverState,this.ReactMixin=(0,h.default)(this),this.__batchDepth=0,this.__isDispatching=!1}return a(t,[{key:"evaluate",value:function(t){var e=p.evaluate(this.reactorState,t),n=e.result,r=e.reactorState;return this.reactorState=r,n}},{key:"evaluateToJS",value:function(t){return(0,v.toJS)(this.evaluate(t))}},{key:"observe",value:function(t,e){var n=this;1===arguments.length&&(e=t,t=[]);var r=p.addObserver(this.observerState,t,e),i=r.observerState,o=r.entry;return this.observerState=i,function(){n.observerState=p.removeObserverByEntry(n.observerState,o)}}},{key:"unobserve",value:function(t,e){if(0===arguments.length)throw new Error("Must call unobserve with a Getter");if(!(0,d.isGetter)(t)&&!(0,_.isKeyPath)(t))throw new Error("Must call unobserve with a Getter");this.observerState=p.removeObserver(this.observerState,t,e)}},{key:"dispatch",value:function(t,e){if(0===this.__batchDepth){if(p.getOption(this.reactorState,"throwOnDispatchInDispatch")&&this.__isDispatching)throw this.__isDispatching=!1,new Error("Dispatch may not be called while a dispatch is in progress");this.__isDispatching=!0}try{this.reactorState=p.dispatch(this.reactorState,t,e)}catch(t){throw this.__isDispatching=!1,t}try{this.__notify()}finally{this.__isDispatching=!1}}},{key:"batch",value:function(t){this.batchStart(),t(),this.batchEnd()}},{key:"registerStore",value:function(t,e){console.warn("Deprecation warning: `registerStore` will no longer be supported in 1.1, use `registerStores` instead"),this.registerStores(o({},t,e))}},{key:"registerStores",value:function(t){this.reactorState=p.registerStores(this.reactorState,t),this.__notify()}},{key:"replaceStores",value:function(t){this.reactorState=p.replaceStores(this.reactorState,t)}},{key:"serialize",value:function(){return p.serialize(this.reactorState)}},{key:"loadState",value:function(t){this.reactorState=p.loadState(this.reactorState,t),this.__notify()}},{key:"reset",value:function(){var t=p.reset(this.reactorState);this.reactorState=t,this.prevReactorState=t,this.observerState=new m.ObserverState}},{key:"__notify",value:function(){var t=this;if(!(this.__batchDepth>0)){var e=this.reactorState.get("dirtyStores");if(0!==e.size){var n=c.default.Set().withMutations((function(n){n.union(t.observerState.get("any")),e.forEach((function(e){var r=t.observerState.getIn(["stores",e]);r&&n.union(r)}))}));n.forEach((function(e){var n=t.observerState.getIn(["observersMap",e]);if(n){var r=n.get("getter"),i=n.get("handler"),o=p.evaluate(t.prevReactorState,r),u=p.evaluate(t.reactorState,r);t.prevReactorState=o.reactorState,t.reactorState=u.reactorState;var a=o.result,s=u.result;c.default.is(a,s)||i.call(null,s)}}));var r=p.resetDirtyStores(this.reactorState);this.prevReactorState=r,this.reactorState=r}}}},{key:"batchStart",value:function(){this.__batchDepth++}},{key:"batchEnd",value:function(){if(this.__batchDepth--,this.__batchDepth<=0){this.__isDispatching=!0;try{this.__notify()}catch(t){throw this.__isDispatching=!1,t}this.__isDispatching=!1}}}]),t})();e.default=(0,y.toFactory)(g),t.exports=e.default},function(t,e,n){function r(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t,e){var n={};return(0,o.each)(e,(function(e,r){n[r]=t.evaluate(e)})),n}Object.defineProperty(e,"__esModule",{value:!0});var o=n(4);e.default=function(t){return{getInitialState:function(){return i(t,this.getDataBindings())},componentDidMount:function(){var e=this;this.__unwatchFns=[],(0,o.each)(this.getDataBindings(),(function(n,i){var o=t.observe(n,(function(t){e.setState(r({},i,t))}));e.__unwatchFns.push(o)}))},componentWillUnmount:function(){for(var t=this;this.__unwatchFns.length;)t.__unwatchFns.shift()()}}},t.exports=e.default},function(t,e,n){function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){return new M({result:t,reactorState:e})}function o(t,e){return t.withMutations((function(t){(0,R.each)(e,(function(e,n){t.getIn(["stores",n])&&console.warn("Store already defined for id = "+n);var r=e.getInitialState();if(void 0===r&&f(t,"throwOnUndefinedStoreReturnValue"))throw new Error("Store getInitialState() must return a value, did you forget a return statement");if(f(t,"throwOnNonImmutableStore")&&!(0,D.isImmutableValue)(r))throw new Error("Store getInitialState() must return an immutable value, did you forget to call toImmutable");t.update("stores",(function(t){return t.set(n,e)})).update("state",(function(t){return t.set(n,r)})).update("dirtyStores",(function(t){return t.add(n)})).update("storeStates",(function(t){return I(t,[n])}))})),E(t)}))}function u(t,e){return t.withMutations((function(t){(0,R.each)(e,(function(e,n){t.update("stores",(function(t){return t.set(n,e)}))}))}))}function a(t,e,n){if(void 0===e&&f(t,"throwOnUndefinedActionType"))throw new Error("`dispatch` cannot be called with an `undefined` action type.");var r=t.get("state"),i=t.get("dirtyStores"),o=r.withMutations((function(r){A.default.dispatchStart(t,e,n),t.get("stores").forEach((function(o,u){var a=r.get(u),s=void 0;try{s=o.handle(a,e,n)}catch(e){throw A.default.dispatchError(t,e.message),e}if(void 0===s&&f(t,"throwOnUndefinedStoreReturnValue")){var c="Store handler must return a value, did you forget a return statement";throw A.default.dispatchError(t,c),new Error(c)}r.set(u,s),a!==s&&(i=i.add(u))})),A.default.dispatchEnd(t,r,i)})),u=t.set("state",o).set("dirtyStores",i).update("storeStates",(function(t){return I(t,i)}));return E(u)}function s(t,e){var n=[],r=(0,D.toImmutable)({}).withMutations((function(r){(0,R.each)(e,(function(e,i){var o=t.getIn(["stores",i]);if(o){var u=o.deserialize(e);void 0!==u&&(r.set(i,u),n.push(i))}}))})),i=w.default.Set(n);return t.update("state",(function(t){return t.merge(r)})).update("dirtyStores",(function(t){return t.union(i)})).update("storeStates",(function(t){return I(t,n)}))}function c(t,e,n){var r=e;(0,z.isKeyPath)(e)&&(e=(0,C.fromKeyPath)(e));var i=t.get("nextId"),o=(0,C.getStoreDeps)(e),u=w.default.Map({id:i,storeDeps:o,getterKey:r,getter:e,handler:n}),a=void 0;return a=0===o.size?t.update("any",(function(t){return t.add(i)})):t.withMutations((function(t){o.forEach((function(e){var n=["stores",e];t.hasIn(n)||t.setIn(n,w.default.Set()),t.updateIn(["stores",e],(function(t){return t.add(i)}))}))})),a=a.set("nextId",i+1).setIn(["observersMap",i],u),{observerState:a,entry:u}}function f(t,e){var n=t.getIn(["options",e]);if(void 0===n)throw new Error("Invalid option: "+e);return n}function h(t,e,n){var r=t.get("observersMap").filter((function(t){var r=t.get("getterKey"),i=!n||t.get("handler")===n;return!!i&&((0,z.isKeyPath)(e)&&(0,z.isKeyPath)(r)?(0,z.isEqual)(e,r):e===r)}));return t.withMutations((function(t){r.forEach((function(e){return l(t,e)}))}))}function l(t,e){return t.withMutations((function(t){var n=e.get("id"),r=e.get("storeDeps");0===r.size?t.update("any",(function(t){return t.remove(n)})):r.forEach((function(e){t.updateIn(["stores",e],(function(t){return t?t.remove(n):t}))})),t.removeIn(["observersMap",n])}))}function p(t){var e=t.get("state");return t.withMutations((function(t){var n=t.get("stores"),r=n.keySeq().toJS();n.forEach((function(n,r){var i=e.get(r),o=n.handleReset(i);if(void 0===o&&f(t,"throwOnUndefinedStoreReturnValue"))throw new Error("Store handleReset() must return a value, did you forget a return statement");if(f(t,"throwOnNonImmutableStore")&&!(0,D.isImmutableValue)(o))throw new Error("Store reset state must be an immutable value, did you forget to call toImmutable");t.setIn(["state",r],o)})),t.update("storeStates",(function(t){return I(t,r)})),v(t)}))}function _(t,e){var n=t.get("state");if((0,z.isKeyPath)(e))return i(n.getIn(e),t);if(!(0,C.isGetter)(e))throw new Error("evaluate must be passed a keyPath or Getter");if(g(t,e))return i(b(t,e),t);var r=(0,C.getDeps)(e).map((function(e){return _(t,e).result})),o=(0,C.getComputeFn)(e).apply(null,r);return i(o,S(t,e,o))}function d(t){var e={};return t.get("stores").forEach((function(n,r){var i=t.getIn(["state",r]),o=n.serialize(i);void 0!==o&&(e[r]=o)})),e}function v(t){return t.set("dirtyStores",w.default.Set())}function y(t){return t}function m(t,e){var n=y(e);return t.getIn(["cache",n])}function g(t,e){var n=m(t,e);if(!n)return!1;var r=n.get("storeStates");return 0!==r.size&&r.every((function(e,n){return t.getIn(["storeStates",n])===e}))}function S(t,e,n){var r=y(e),i=t.get("dispatchId"),o=(0,C.getStoreDeps)(e),u=(0,D.toImmutable)({}).withMutations((function(e){o.forEach((function(n){var r=t.getIn(["storeStates",n]);e.set(n,r)}))}));return t.setIn(["cache",r],w.default.Map({value:n,storeStates:u,dispatchId:i}))}function b(t,e){var n=y(e);return t.getIn(["cache",n,"value"])}function E(t){return t.update("dispatchId",(function(t){return t+1}))}function I(t,e){return t.withMutations((function(t){e.forEach((function(e){var n=t.has(e)?t.get(e)+1:1;t.set(e,n)}))}))}Object.defineProperty(e,"__esModule",{value:!0}),e.registerStores=o,e.replaceStores=u,e.dispatch=a,e.loadState=s,e.addObserver=c,e.getOption=f,e.removeObserver=h,e.removeObserverByEntry=l,e.reset=p,e.evaluate=_,e.serialize=d,e.resetDirtyStores=v;var O=n(3),w=r(O),T=n(9),A=r(T),D=n(5),C=n(10),z=n(11),R=n(4),M=w.default.Record({result:null,reactorState:null})},function(t,e,n){var r=n(8);e.dispatchStart=function(t,e,n){(0,r.getOption)(t,"logDispatches")&&console.group&&(console.groupCollapsed("Dispatch: %s",e),console.group("payload"),console.debug(n),console.groupEnd())},e.dispatchError=function(t,e){(0,r.getOption)(t,"logDispatches")&&console.group&&(console.debug("Dispatch error: "+e),console.groupEnd())},e.dispatchEnd=function(t,e,n){(0,r.getOption)(t,"logDispatches")&&console.group&&((0,r.getOption)(t,"logDirtyStores")&&console.log("Stores updated:",n.toList().toJS()),(0,r.getOption)(t,"logAppState")&&console.debug("Dispatch done, new state: ",e.toJS()),console.groupEnd())}},function(t,e,n){function r(t){return t&&t.__esModule?t:{default:t}}function i(t){return(0,l.isArray)(t)&&(0,l.isFunction)(t[t.length-1])}function o(t){return t[t.length-1]}function u(t){return t.slice(0,t.length-1)}function a(t,e){e||(e=h.default.Set());var n=h.default.Set().withMutations((function(e){if(!i(t))throw new Error("getFlattenedDeps must be passed a Getter");u(t).forEach((function(t){if((0,p.isKeyPath)(t))e.add((0,f.List)(t));else{if(!i(t))throw new Error("Invalid getter, each dependency must be a KeyPath or Getter");e.union(a(t))}}))}));return e.union(n)}function s(t){if(!(0,p.isKeyPath)(t))throw new Error("Cannot create Getter from KeyPath: "+t);return[t,_]}function c(t){if(t.hasOwnProperty("__storeDeps"))return t.__storeDeps;var e=a(t).map((function(t){return t.first()})).filter((function(t){return!!t}));return Object.defineProperty(t,"__storeDeps",{enumerable:!1,configurable:!1,writable:!1,value:e}),e}Object.defineProperty(e,"__esModule",{value:!0});var f=n(3),h=r(f),l=n(4),p=n(11),_=function(t){return t};e.default={isGetter:i,getComputeFn:o,getFlattenedDeps:a,getStoreDeps:c,getDeps:u,fromKeyPath:s},t.exports=e.default},function(t,e,n){function r(t){return t&&t.__esModule?t:{default:t}}function i(t){return(0,s.isArray)(t)&&!(0,s.isFunction)(t[t.length-1])}function o(t,e){var n=a.default.List(t),r=a.default.List(e);return a.default.is(n,r)}Object.defineProperty(e,"__esModule",{value:!0}),e.isKeyPath=i,e.isEqual=o;var u=n(3),a=r(u),s=n(4)},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var r=n(3),i=(0,r.Map)({logDispatches:!1,logAppState:!1,logDirtyStores:!1,throwOnUndefinedActionType:!1,throwOnUndefinedStoreReturnValue:!1,throwOnNonImmutableStore:!1,throwOnDispatchInDispatch:!1});e.PROD_OPTIONS=i;var o=(0,r.Map)({logDispatches:!0,logAppState:!0,logDirtyStores:!0,throwOnUndefinedActionType:!0,throwOnUndefinedStoreReturnValue:!0,throwOnNonImmutableStore:!0,throwOnDispatchInDispatch:!0});e.DEBUG_OPTIONS=o;var u=(0,r.Record)({dispatchId:0,state:(0,r.Map)(),stores:(0,r.Map)(),cache:(0,r.Map)(),storeStates:(0,r.Map)(),dirtyStores:(0,r.Set)(),debug:!1,options:i});e.ReactorState=u;var a=(0,r.Record)({any:(0,r.Set)(),stores:(0,r.Map)({}),observersMap:(0,r.Map)({}),nextId:1});e.ObserverState=a}])}))})),Ne=t(Le),ke=function(t){var e,n={};if(!(t instanceof Object)||Array.isArray(t))throw new Error("keyMirror(...): Argument must be an object.");for(e in t)t.hasOwnProperty(e)&&(n[e]=e);return n},Pe=ke,Ue=Pe({VALIDATING_AUTH_TOKEN:null,VALID_AUTH_TOKEN:null,INVALID_AUTH_TOKEN:null,LOG_OUT:null}),He=Ne.Store,xe=Ne.toImmutable,Ve=new He({getInitialState:function(){return xe({isValidating:!1,authToken:!1,host:null,isInvalid:!1,errorMessage:""})},initialize:function(){this.on(Ue.VALIDATING_AUTH_TOKEN,n),this.on(Ue.VALID_AUTH_TOKEN,r),this.on(Ue.INVALID_AUTH_TOKEN,i)}}),qe=Ne.Store,Fe=Ne.toImmutable,Ge=new qe({getInitialState:function(){return Fe({authToken:null,host:""})},initialize:function(){this.on(Ue.VALID_AUTH_TOKEN,o),this.on(Ue.LOG_OUT,u)}}),Ke=Ne.Store,Be=new Ke({getInitialState:function(){return!0},initialize:function(){this.on(Ue.VALID_AUTH_TOKEN,a)}}),Ye=Pe({STREAM_START:null,STREAM_STOP:null,STREAM_ERROR:null}),Je=Ne.Store,We=Ne.toImmutable,Xe=new Je({getInitialState:function(){return We({isStreaming:!1,hasError:!1})},initialize:function(){this.on(Ye.STREAM_START,s),this.on(Ye.STREAM_ERROR,c),this.on(Ye.LOG_OUT,f)}}),Qe=1,Ze=2,$e=3,tn=function(t,e){this.url=t,this.options=e||{},this.commandId=1,this.commands={},this.connectionTries=0,this.eventListeners={},this.closeRequested=!1};tn.prototype.addEventListener=function(t,e){var n=this.eventListeners[t];n||(n=this.eventListeners[t]=[]),n.push(e)},tn.prototype.fireEvent=function(t){var e=this;(this.eventListeners[t]||[]).forEach((function(t){return t(e)}))},tn.prototype.connect=function(){var t=this;return new Promise(function(e,n){var r=t.commands;Object.keys(r).forEach((function(t){var e=r[t];e.reject&&e.reject(S($e,"Connection lost"))}));var i=!1;t.connectionTries+=1,t.socket=new WebSocket(t.url),t.socket.addEventListener("open",(function(){t.connectionTries=0})),t.socket.addEventListener("message",(function(o){var u=JSON.parse(o.data);switch(u.type){case"event":t.commands[u.id].eventCallback(u.event);break;case"result":u.success?t.commands[u.id].resolve(u):t.commands[u.id].reject(u.error),delete t.commands[u.id];break;case"pong":break;case"auth_required":t.sendMessage(h(t.options.authToken));break;case"auth_invalid":n(Ze),i=!0;break;case"auth_ok":e(t),t.fireEvent("ready"),t.commandId=1,t.commands={},Object.keys(r).forEach((function(e){var n=r[e];n.eventType&&t.subscribeEvents(n.eventCallback,n.eventType).then((function(t){n.unsubscribe=t}))}))}})),t.socket.addEventListener("close",(function(){if(!i&&!t.closeRequested){0===t.connectionTries?t.fireEvent("disconnected"):n(Qe);var e=1e3*Math.min(t.connectionTries,5);setTimeout((function(){return t.connect()}),e)}}))})},tn.prototype.close=function(){this.closeRequested=!0,this.socket.close()},tn.prototype.getStates=function(){return this.sendMessagePromise(l()).then(b)},tn.prototype.getServices=function(){return this.sendMessagePromise(_()).then(b)},tn.prototype.getPanels=function(){return this.sendMessagePromise(d()).then(b)},tn.prototype.getConfig=function(){return this.sendMessagePromise(p()).then(b)},tn.prototype.callService=function(t,e,n){return this.sendMessagePromise(v(t,e,n))},tn.prototype.subscribeEvents=function(t,e){var n=this;return this.sendMessagePromise(y(e)).then((function(r){var i={eventCallback:t,eventType:e,unsubscribe:function(){return n.sendMessagePromise(m(r.id)).then((function(){delete n.commands[r.id]}))}};return n.commands[r.id]=i,function(){return i.unsubscribe()}}))},tn.prototype.ping=function(){return this.sendMessagePromise(g())},tn.prototype.sendMessage=function(t){this.socket.send(JSON.stringify(t))},tn.prototype.sendMessagePromise=function(t){var e=this;return new Promise(function(n,r){e.commandId+=1;var i=e.commandId;t.id=i,e.commands[i]={resolve:n,reject:r},e.sendMessage(t)})};var en=Pe({API_FETCH_ALL_START:null,API_FETCH_ALL_SUCCESS:null,API_FETCH_ALL_FAIL:null,SYNC_SCHEDULED:null,SYNC_SCHEDULE_CANCELLED:null}),nn=Ne.Store,rn=new nn({getInitialState:function(){return!0},initialize:function(){this.on(en.API_FETCH_ALL_START,(function(){return!0})),this.on(en.API_FETCH_ALL_SUCCESS,(function(){return!1})),this.on(en.API_FETCH_ALL_FAIL,(function(){return!1})),this.on(en.LOG_OUT,(function(){return!1}))}}),on=I,un=Pe({API_FETCH_SUCCESS:null,API_FETCH_START:null,API_FETCH_FAIL:null,API_SAVE_SUCCESS:null,API_SAVE_START:null,API_SAVE_FAIL:null,API_DELETE_SUCCESS:null,API_DELETE_START:null,API_DELETE_FAIL:null,LOG_OUT:null}),an=Ne.Store,sn=Ne.toImmutable,cn=new an({getInitialState:function(){return sn({})},initialize:function(){var t=this;this.on(un.API_FETCH_SUCCESS,O),this.on(un.API_SAVE_SUCCESS,O),this.on(un.API_DELETE_SUCCESS,w),this.on(un.LOG_OUT,(function(){return t.getInitialState()}))}}),fn=Object.prototype.hasOwnProperty,hn=Object.prototype.propertyIsEnumerable,ln=A()?Object.assign:function(t,e){for(var n,r,i=arguments,o=T(t),u=1;u<arguments.length;u++){n=Object(i[u]);for(var a in n)fn.call(n,a)&&(o[a]=n[a]);if(Object.getOwnPropertySymbols){r=Object.getOwnPropertySymbols(n);for(var s=0;s<r.length;s++)hn.call(n,r[s])&&(o[r[s]]=n[r[s]]);
}}return o},pn=Ne.toImmutable,_n=D,dn=Object.freeze({createApiActions:_n,register:N,createHasDataGetter:k,createEntityMapGetter:P,createByIdGetter:U}),vn=["playing","paused","unknown"],yn=function(t,e){this.serviceActions=t.serviceActions,this.stateObj=e},mn={isOff:{},isIdle:{},isMuted:{},isPaused:{},isPlaying:{},isMusic:{},isTVShow:{},hasMediaControl:{},volumeSliderValue:{},showProgress:{},currentProgress:{},supportsPause:{},supportsVolumeSet:{},supportsVolumeMute:{},supportsPreviousTrack:{},supportsNextTrack:{},supportsTurnOn:{},supportsTurnOff:{},supportsPlayMedia:{},supportsVolumeButtons:{},supportsPlay:{},primaryText:{},secondaryText:{}};mn.isOff.get=function(){return"off"===this.stateObj.state},mn.isIdle.get=function(){return"idle"===this.stateObj.state},mn.isMuted.get=function(){return this.stateObj.attributes.is_volume_muted},mn.isPaused.get=function(){return"paused"===this.stateObj.state},mn.isPlaying.get=function(){return"playing"===this.stateObj.state},mn.isMusic.get=function(){return"music"===this.stateObj.attributes.media_content_type},mn.isTVShow.get=function(){return"tvshow"===this.stateObj.attributes.media_content_type},mn.hasMediaControl.get=function(){return vn.indexOf(this.stateObj.state)!==-1},mn.volumeSliderValue.get=function(){return 100*this.stateObj.attributes.volume_level},mn.showProgress.get=function(){return(this.isPlaying||this.isPaused)&&"media_position"in this.stateObj.attributes&&"media_position_updated_at"in this.stateObj.attributes},mn.currentProgress.get=function(){return this.stateObj.attributes.media_position+(Date.now()-new Date(this.stateObj.attributes.media_position_updated_at))/1e3},mn.supportsPause.get=function(){return 0!==(1&this.stateObj.attributes.supported_media_commands)},mn.supportsVolumeSet.get=function(){return 0!==(4&this.stateObj.attributes.supported_media_commands)},mn.supportsVolumeMute.get=function(){return 0!==(8&this.stateObj.attributes.supported_media_commands)},mn.supportsPreviousTrack.get=function(){return 0!==(16&this.stateObj.attributes.supported_media_commands)},mn.supportsNextTrack.get=function(){return 0!==(32&this.stateObj.attributes.supported_media_commands)},mn.supportsTurnOn.get=function(){return 0!==(128&this.stateObj.attributes.supported_media_commands)},mn.supportsTurnOff.get=function(){return 0!==(256&this.stateObj.attributes.supported_media_commands)},mn.supportsPlayMedia.get=function(){return 0!==(512&this.stateObj.attributes.supported_media_commands)},mn.supportsVolumeButtons.get=function(){return 0!==(1024&this.stateObj.attributes.supported_media_commands)},mn.supportsPlay.get=function(){return 0!==(16384&this.stateObj.attributes.supported_media_commands)},mn.primaryText.get=function(){return this.stateObj.attributes.media_title||this.stateObj.stateDisplay},mn.secondaryText.get=function(){if(this.isMusic)return this.stateObj.attributes.media_artist;if(this.isTVShow){var t=this.stateObj.attributes.media_series_title;return this.stateObj.attributes.media_season&&(t+=" S"+this.stateObj.attributes.media_season,this.stateObj.attributes.media_episode&&(t+="E"+this.stateObj.attributes.media_episode)),t}return this.stateObj.attributes.app_name?this.stateObj.attributes.app_name:""},yn.prototype.mediaPlayPause=function(){this.callService("media_play_pause")},yn.prototype.nextTrack=function(){this.callService("media_next_track")},yn.prototype.playbackControl=function(){this.callService("media_play_pause")},yn.prototype.previousTrack=function(){this.callService("media_previous_track")},yn.prototype.setVolume=function(t){this.callService("volume_set",{volume_level:t})},yn.prototype.togglePower=function(){this.isOff?this.turnOn():this.turnOff()},yn.prototype.turnOff=function(){this.callService("turn_off")},yn.prototype.turnOn=function(){this.callService("turn_on")},yn.prototype.volumeDown=function(){this.callService("volume_down")},yn.prototype.volumeMute=function(t){if(!this.supportsVolumeMute)throw new Error("Muting volume not supported");this.callService("volume_mute",{is_volume_muted:t})},yn.prototype.volumeUp=function(){this.callService("volume_down")},yn.prototype.callService=function(t,e){var n=e||{};n.entity_id=this.stateObj.entityId,this.serviceActions.callService("media_player",t,n)},Object.defineProperties(yn.prototype,mn);var gn=Ne.Immutable,Sn=Ne.toJS,bn="entity",En=new gn.Record({entityId:null,domain:null,objectId:null,state:null,entityDisplay:null,stateDisplay:null,lastChanged:null,lastChangedAsDate:null,lastUpdated:null,lastUpdatedAsDate:null,attributes:{},isCustomGroup:null},"Entity"),In=(function(t){function e(e,n,r,i,o){void 0===o&&(o={});var u=e.split("."),a=u[0],s=u[1],c=n.replace(/_/g," ");o.unit_of_measurement&&(c+=" "+o.unit_of_measurement),t.call(this,{entityId:e,domain:a,objectId:s,state:n,stateDisplay:c,lastChanged:r,lastUpdated:i,attributes:o,entityDisplay:o.friendly_name||s.replace(/_/g," "),lastChangedAsDate:H(r),lastUpdatedAsDate:H(i),isCustomGroup:"group"===a&&!o.auto})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={id:{}};return n.id.get=function(){return this.entityId},e.prototype.domainModel=function(t){if("media_player"!==this.domain)throw new Error("Domain does not have a model");return new yn(t,this)},e.delete=function(t,e){return on(t,"DELETE","states/"+e.entityId)},e.save=function(t,e){var n=Sn(e),r=n.entityId,i=n.state,o=n.attributes;void 0===o&&(o={});var u={state:i,attributes:o};return on(t,"POST","states/"+r,u)},e.fetch=function(t,e){return on(t,"GET","states/"+e)},e.fetchAll=function(t){return on(t,"GET","states")},e.fromJSON=function(t){var n=t.entity_id,r=t.state,i=t.last_changed,o=t.last_updated,u=t.attributes;return new e(n,r,i,o,u)},Object.defineProperties(e.prototype,n),e})(En);In.entity=bn;var On=_n(In),wn=k(In),Tn=P(In),An=U(In),Dn=[Tn,function(t){return t.filter((function(t){return!t.attributes.hidden}))}],Cn=Object.freeze({hasData:wn,entityMap:Tn,byId:An,visibleEntityMap:Dn}),zn=On,Rn=Cn,Mn=Object.freeze({actions:zn,getters:Rn}),jn=Pe({NOTIFICATION_CREATED:null}),Ln=Ne.Store,Nn=Ne.Immutable,kn=new Ln({getInitialState:function(){return new Nn.OrderedMap},initialize:function(){this.on(jn.NOTIFICATION_CREATED,x),this.on(jn.LOG_OUT,V)}}),Pn=Object.freeze({createNotification:q}),Un=["notifications"],Hn=[Un,function(t){return t.last()}],xn=Object.freeze({notificationMap:Un,lastNotificationMessage:Hn}),Vn=Pn,qn=xn,Fn=Object.freeze({register:F,actions:Vn,getters:qn}),Gn=Ne.Immutable,Kn=Ne.toImmutable,Bn="service",Yn=new Gn.Record({domain:null,services:[]},"ServiceDomain"),Jn=(function(t){function e(e,n){t.call(this,{domain:e,services:n})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={id:{}};return n.id.get=function(){return this.domain},e.fetchAll=function(){return on("GET","services")},e.fromJSON=function(t){var n=t.domain,r=t.services;return new e(n,Kn(r))},Object.defineProperties(e.prototype,n),e})(Yn);Jn.entity=Bn;var Wn=k(Jn),Xn=P(Jn),Qn=U(Jn),Zn=Object.freeze({hasData:Wn,entityMap:Xn,byDomain:Qn,hasService:B,canToggleEntity:Y}),$n=_n(Jn);$n.serviceRegistered=function(t,e,n){var r=t.evaluateToJS(Qn(e));if(r)r.services[n]={};else{var i;r={domain:e,services:(i={},i[n]={},i)}}$n.incrementData(t,r)},$n.callTurnOn=function(t,e,n){return void 0===n&&(n={}),$n.callService(t,"homeassistant","turn_on",ln({},n,{entity_id:e}))},$n.callTurnOff=function(t,e,n){return void 0===n&&(n={}),$n.callService(t,"homeassistant","turn_off",ln({},n,{entity_id:e}))},$n.callService=function(t,e,n,r){return void 0===r&&(r={}),on(t,"POST","services/"+e+"/"+n,r).then((function(i){"turn_on"===n&&r.entity_id?Vn.createNotification(t,"Turned on "+r.entity_id+"."):"turn_off"===n&&r.entity_id?Vn.createNotification(t,"Turned off "+r.entity_id+"."):Vn.createNotification(t,"Service "+e+"/"+n+" called."),zn.incrementData(t,i)}))};var tr=$n,er=Zn,nr=Object.freeze({actions:tr,getters:er}),rr=Ne.Immutable,ir="event",or=new rr.Record({event:null,listenerCount:0},"Event"),ur=(function(t){function e(e,n){void 0===n&&(n=0),t.call(this,{event:e,listenerCount:n})}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={id:{}};return n.id.get=function(){return this.event},e.fetchAll=function(t){return on(t,"GET","events")},e.fromJSON=function(t){var n=t.event,r=t.listener_count;return new e(n,r)},Object.defineProperties(e.prototype,n),e})(or);ur.entity=ir;var ar=_n(ur);ar.fireEvent=function(t,e,n){return void 0===n&&(n={}),on(t,"POST","events/"+e,n).then((function(){Vn.createNotification(t,"Event "+e+" successful fired!")}))};var sr=k(ur),cr=P(ur),fr=U(ur),hr=Object.freeze({hasData:sr,entityMap:cr,byId:fr}),lr=ar,pr=hr,_r=Object.freeze({actions:lr,getters:pr}),dr=Pe({SERVER_CONFIG_LOADED:null,COMPONENT_LOADED:null,LOG_OUT:null}),vr=Ne.Store,yr=Ne.toImmutable,mr=new vr({getInitialState:function(){return yr([])},initialize:function(){this.on(dr.COMPONENT_LOADED,J),this.on(dr.SERVER_CONFIG_LOADED,W),this.on(dr.LOG_OUT,X)}}),gr=Ne.Store,Sr=Ne.toImmutable,br=new gr({getInitialState:function(){return Sr({latitude:null,longitude:null,location_name:"Home",unit_system:"metric",time_zone:"UTC",config_dir:null,serverVersion:"unknown"})},initialize:function(){this.on(dr.SERVER_CONFIG_LOADED,Q),this.on(dr.LOG_OUT,Z)}}),Er=Object.freeze({configLoaded:$,fetchAll:tt,componentLoaded:et}),Ir=[["serverConfig","latitude"],["serverConfig","longitude"],function(t,e){return{latitude:t,longitude:e}}],Or=["serverConfig","location_name"],wr=["serverConfig","config_dir"],Tr=["serverConfig","serverVersion"],Ar=Object.freeze({locationGPS:Ir,locationName:Or,configDir:wr,serverVersion:Tr,isComponentLoaded:nt}),Dr=Er,Cr=Ar,zr=Object.freeze({register:rt,actions:Dr,getters:Cr}),Rr=Pe({NAVIGATE:null,SHOW_SIDEBAR:null,PANELS_LOADED:null,LOG_OUT:null}),Mr=Ne.Store,jr=new Mr({getInitialState:function(){return"states"},initialize:function(){this.on(Rr.NAVIGATE,it),this.on(Rr.LOG_OUT,ot)}}),Lr=Ne.Store,Nr=Ne.toImmutable,kr=new Lr({getInitialState:function(){return Nr({})},initialize:function(){this.on(Rr.PANELS_LOADED,ut),this.on(Rr.LOG_OUT,at)}}),Pr=Ne.Store,Ur=new Pr({getInitialState:function(){return!1},initialize:function(){this.on(Rr.SHOW_SIDEBAR,st),this.on(Rr.LOG_OUT,ct)}}),Hr=Object.freeze({showSidebar:ft,navigate:ht,panelsLoaded:lt}),xr=["panels"],Vr=["currentPanel"],qr=[xr,Vr,function(t,e){return t.get(e)||null}],Fr=["showSidebar"],Gr=Object.freeze({panels:xr,activePanelName:Vr,activePanel:qr,showSidebar:Fr}),Kr=Pe({SELECT_ENTITY:null,LOG_OUT:null}),Br=Ne.Store,Yr=new Br({getInitialState:function(){return null},initialize:function(){this.on(Kr.SELECT_ENTITY,pt),this.on(Kr.LOG_OUT,_t)}}),Jr=Object.freeze({selectEntity:dt,deselectEntity:vt}),Wr=Pe({ENTITY_HISTORY_DATE_SELECTED:null,ENTITY_HISTORY_FETCH_START:null,ENTITY_HISTORY_FETCH_ERROR:null,ENTITY_HISTORY_FETCH_SUCCESS:null,RECENT_ENTITY_HISTORY_FETCH_START:null,RECENT_ENTITY_HISTORY_FETCH_ERROR:null,RECENT_ENTITY_HISTORY_FETCH_SUCCESS:null,LOG_OUT:null}),Xr=Ne.Store,Qr=new Xr({getInitialState:function(){var t=new Date;return t.setDate(t.getDate()-1),t.setHours(0,0,0,0),t.toISOString()},initialize:function(){this.on(Wr.ENTITY_HISTORY_DATE_SELECTED,mt),this.on(Wr.LOG_OUT,gt)}}),Zr=Ne.Store,$r=Ne.toImmutable,ti=new Zr({getInitialState:function(){return $r({})},initialize:function(){this.on(Wr.ENTITY_HISTORY_FETCH_SUCCESS,St),this.on(Wr.LOG_OUT,bt)}}),ei=Ne.Store,ni=new ei({getInitialState:function(){return!1},initialize:function(){this.on(Wr.ENTITY_HISTORY_FETCH_START,(function(){return!0})),this.on(Wr.ENTITY_HISTORY_FETCH_SUCCESS,(function(){return!1})),this.on(Wr.ENTITY_HISTORY_FETCH_ERROR,(function(){return!1})),this.on(Wr.RECENT_ENTITY_HISTORY_FETCH_START,(function(){return!0})),this.on(Wr.RECENT_ENTITY_HISTORY_FETCH_SUCCESS,(function(){return!1})),this.on(Wr.RECENT_ENTITY_HISTORY_FETCH_ERROR,(function(){return!1})),this.on(Wr.LOG_OUT,(function(){return!1}))}}),ri=Ne.Store,ii=Ne.toImmutable,oi=new ri({getInitialState:function(){return ii({})},initialize:function(){this.on(Wr.RECENT_ENTITY_HISTORY_FETCH_SUCCESS,Et),this.on(Wr.LOG_OUT,It)}}),ui=Ne.Store,ai=Ne.toImmutable,si="ALL_ENTRY_FETCH",ci=new ui({getInitialState:function(){return ai({})},initialize:function(){this.on(Wr.RECENT_ENTITY_HISTORY_FETCH_SUCCESS,Ot),this.on(Wr.LOG_OUT,wt)}}),fi=Ne.toImmutable,hi=["isLoadingEntityHistory"],li=["currentEntityHistoryDate"],pi=["entityHistory"],_i=[li,pi,function(t,e){return e.get(t)||fi({})}],di=[li,pi,function(t,e){return!!e.get(t)}],vi=["recentEntityHistory"],yi=["recentEntityHistory"],mi=Object.freeze({isLoadingEntityHistory:hi,currentDate:li,entityHistoryMap:pi,entityHistoryForCurrentDate:_i,hasDataForCurrentDate:di,recentEntityHistoryMap:vi,recentEntityHistoryUpdatedMap:yi}),gi=Object.freeze({changeCurrentDate:Tt,fetchRecent:At,fetchDate:Dt,fetchSelectedDate:Ct}),Si=gi,bi=mi,Ei=Object.freeze({register:zt,actions:Si,getters:bi}),Ii=["moreInfoEntityId"],Oi=[Ii,function(t){return null!==t}],wi=[Ii,Rn.entityMap,function(t,e){return e.get(t)||null}],Ti=[Ii,bi.recentEntityHistoryMap,function(t,e){return e.get(t)}],Ai=[Ii,bi.recentEntityHistoryUpdatedMap,function(t,e){return yt(e.get(t))}],Di=Object.freeze({currentEntityId:Ii,hasCurrentEntityId:Oi,currentEntity:wi,currentEntityHistory:Ti,isCurrentEntityHistoryStale:Ai}),Ci=Jr,zi=Di,Ri=Object.freeze({register:Rt,actions:Ci,getters:zi}),Mi=Pe({SELECT_VIEW:null}),ji=Ne.Store,Li=new ji({getInitialState:function(){return null},initialize:function(){this.on(Mi.SELECT_VIEW,(function(t,e){var n=e.view;return n})),this.on(un.API_FETCH_SUCCESS,Mt)}}),Ni=Object.freeze({selectView:jt}),ki=Ne.Immutable,Pi="group.default_view",Ui=["persistent_notification","configurator"],Hi=["currentView"],xi=[Rn.entityMap,function(t){return t.filter((function(t){return"group"===t.domain&&t.attributes.view&&t.entityId!==Pi}))}],Vi=[Rn.entityMap,Hi,function(t,e){var n;return n=e?t.get(e):t.get(Pi),n?(new ki.Map).withMutations((function(e){Lt(e,t,n),t.valueSeq().forEach((function(t,n){Ui.indexOf(t.domain)!==-1&&e.set(n,t)}))})):t.filter((function(t){return!t.attributes.hidden}))}],qi=Object.freeze({currentView:Hi,views:xi,currentViewEntities:Vi}),Fi=Ni,Gi=qi,Ki=Object.freeze({register:Nt,actions:Fi,getters:Gi}),Bi=history.pushState&&!0,Yi="Home Assistant",Ji={},Wi=Object.freeze({startSync:Vt,stopSync:qt}),Xi=Hr,Qi=Gr,Zi=Wi,$i=Object.freeze({register:Ft,actions:Xi,getters:Qi,urlSync:Zi}),to=Object.freeze({fetchAll:Gt}),eo=[Rn.hasData,pr.hasData,er.hasData,function(t,e,n){return t&&e&&n}],no=["isFetchingData"],ro=Object.freeze({isDataLoaded:eo,isFetching:no}),io=to,oo=ro,uo=Object.freeze({register:Kt,actions:io,getters:oo}),ao=function(t,e){switch(e.event_type){case"state_changed":e.data.new_state?zn.incrementData(t,e.data.new_state):zn.removeData(t,e.data.entity_id);break;case"component_loaded":Dr.componentLoaded(t,e.data.component);break;case"service_registered":tr.serviceRegistered(t,e.data.domain,e.data.service)}},so=6e4,co=["state_changed","component_loaded","service_registered"],fo={},ho=Object.freeze({start:Jt}),lo=["streamStatus","isStreaming"],po=["streamStatus","hasError"],_o=Object.freeze({isStreamingEvents:lo,hasStreamingEventsError:po}),vo=ho,yo=_o,mo=Object.freeze({register:Wt,actions:vo,getters:yo}),go="Unexpected error",So=Object.freeze({validate:Xt,logOut:Qt}),bo=["authAttempt","isValidating"],Eo=["authAttempt","isInvalid"],Io=["authAttempt","errorMessage"],Oo=["rememberAuth"],wo=[["authAttempt","authToken"],["authAttempt","host"],function(t,e){return{authToken:t,host:e}}],To=["authCurrent","authToken"],Ao=[To,["authCurrent","host"],function(t,e){return{authToken:t,host:e}}],Do=[bo,["authAttempt","authToken"],["authCurrent","authToken"],function(t,e,n){return t?e:n}],Co=[bo,wo,Ao,function(t,e,n){return t?e:n}],zo=Object.freeze({isValidating:bo,isInvalidAttempt:Eo,attemptErrorMessage:Io,rememberAuth:Oo,attemptAuthInfo:wo,currentAuthToken:To,currentAuthInfo:Ao,authToken:Do,authInfo:Co}),Ro=So,Mo=zo,jo=Object.freeze({register:Zt,actions:Ro,getters:Mo}),Lo=$t(),No={authToken:{getter:[Mo.currentAuthToken,Mo.rememberAuth,function(t,e){return e?t:null}],defaultValue:null},showSidebar:{getter:Qi.showSidebar,defaultValue:!1}},ko={};Object.keys(No).forEach((function(t){t in Lo||(Lo[t]=No[t].defaultValue),Object.defineProperty(ko,t,{get:function(){try{return JSON.parse(Lo[t])}catch(e){return No[t].defaultValue}}})})),ko.startSync=function(t){Object.keys(No).forEach((function(e){var n=No[e],r=n.getter,i=function(t){Lo[e]=JSON.stringify(t)};t.observe(r,i),i(t.evaluate(r))}))};var Po=ko,Uo=Ne.Reactor,Ho=0,xo=Ne.toImmutable,Vo={UNIT_TEMP_C:"°C",UNIT_TEMP_F:"°F"},qo={expandGroup:ne,isStaleTime:yt,parseDateTime:H,temperatureUnits:Vo},Fo=Object.freeze({fetchErrorLog:re}),Go=Fo,Ko=Object.freeze({actions:Go}),Bo=Pe({LOGBOOK_DATE_SELECTED:null,LOGBOOK_ENTRIES_FETCH_START:null,LOGBOOK_ENTRIES_FETCH_ERROR:null,LOGBOOK_ENTRIES_FETCH_SUCCESS:null}),Yo=Ne.Store,Jo=new Yo({getInitialState:function(){var t=new Date;return t.setHours(0,0,0,0),t.toISOString()},initialize:function(){this.on(Bo.LOGBOOK_DATE_SELECTED,ie),this.on(Bo.LOG_OUT,oe)}}),Wo=Ne.Store,Xo=new Wo({getInitialState:function(){return!1},initialize:function(){this.on(Bo.LOGBOOK_ENTRIES_FETCH_START,(function(){return!0})),this.on(Bo.LOGBOOK_ENTRIES_FETCH_SUCCESS,(function(){return!1})),this.on(Bo.LOGBOOK_ENTRIES_FETCH_ERROR,(function(){return!1})),this.on(Bo.LOG_OUT,(function(){return!1}))}}),Qo=Ne.Immutable,Zo=new Qo.Record({when:null,name:null,message:null,domain:null,entityId:null},"LogbookEntry"),$o=(function(t){function e(e,n,r,i,o){t.call(this,{when:e,name:n,message:r,domain:i,entityId:o})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.fromJSON=function(t){var n=t.when,r=t.name,i=t.message,o=t.domain,u=t.entity_id;return new e(H(n),r,i,o,u)},e})(Zo),tu=Ne.Store,eu=Ne.toImmutable,nu=new tu({getInitialState:function(){return eu({})},initialize:function(){this.on(Bo.LOGBOOK_ENTRIES_FETCH_SUCCESS,ue),this.on(Bo.LOG_OUT,ae)}}),ru=Ne.Store,iu=Ne.toImmutable,ou=new ru({getInitialState:function(){return iu({})},initialize:function(){this.on(Bo.LOGBOOK_ENTRIES_FETCH_SUCCESS,se),this.on(Bo.LOG_OUT,ce)}}),uu=Object.freeze({changeCurrentDate:fe,fetchDate:he}),au=Ne.toImmutable,su=6e4,cu=["currentLogbookDate"],fu=[cu,["logbookEntriesUpdated"],function(t,e){return le(e.get(t))}],hu=[cu,["logbookEntries"],function(t,e){return e.get(t)||au([])}],lu=["isLoadingLogbookEntries"],pu=Object.freeze({currentDate:cu,isCurrentStale:fu,currentEntries:hu,isLoadingEntries:lu}),_u=uu,du=pu,vu=Object.freeze({register:pe,actions:_u,getters:du}),yu=Pe({PUSH_NOTIFICATIONS_SUBSCRIBE:null,PUSH_NOTIFICATIONS_UNSUBSCRIBE:null}),mu=Ne.Store,gu=Ne.toImmutable,Su=new mu({getInitialState:function(){return gu({supported:"PushManager"in window&&("https:"===document.location.protocol||"localhost"===document.location.hostname||"127.0.0.1"===document.location.hostname),active:"Notification"in window&&"granted"===Notification.permission})},initialize:function(){this.on(yu.PUSH_NOTIFICATIONS_SUBSCRIBE,_e),this.on(yu.PUSH_NOTIFICATIONS_UNSUBSCRIBE,de),this.on(yu.LOG_OUT,ve)}}),bu=Object.freeze({subscribePushNotifications:ye,unsubscribePushNotifications:me}),Eu=["pushNotifications","supported"],Iu=["pushNotifications","active"],Ou=Object.freeze({isSupported:Eu,isActive:Iu}),wu=bu,Tu=Ou,Au=Object.freeze({register:ge,actions:wu,getters:Tu}),Du=Object.freeze({render:Se}),Cu=Du,zu=Object.freeze({actions:Cu}),Ru=Ne.Store,Mu=new Ru({getInitialState:function(){return"webkitSpeechRecognition"in window}}),ju=Pe({VOICE_START:null,VOICE_RESULT:null,VOICE_TRANSMITTING:null,VOICE_DONE:null,VOICE_ERROR:null}),Lu=Ne.Store,Nu=Ne.toImmutable,ku=new Lu({getInitialState:function(){return Nu({isListening:!1,isTransmitting:!1,interimTranscript:"",finalTranscript:""})},initialize:function(){this.on(ju.VOICE_START,be),this.on(ju.VOICE_RESULT,Ee),this.on(ju.VOICE_TRANSMITTING,Ie),this.on(ju.VOICE_DONE,Oe),this.on(ju.VOICE_ERROR,we),this.on(ju.LOG_OUT,Te)}}),Pu={},Uu=Object.freeze({stop:Ce,finish:ze,listen:Re}),Hu=["isVoiceSupported"],xu=["currentVoiceCommand","isListening"],Vu=["currentVoiceCommand","isTransmitting"],qu=["currentVoiceCommand","interimTranscript"],Fu=["currentVoiceCommand","finalTranscript"],Gu=[qu,Fu,function(t,e){return t.slice(e.length)}],Ku=Object.freeze({isVoiceSupported:Hu,isListening:xu,isTransmitting:Vu,interimTranscript:qu,finalTranscript:Fu,extraInterimTranscript:Gu}),Bu=Uu,Yu=Ku,Ju=Object.freeze({register:Me,actions:Bu,getters:Yu}),Wu=function(){var t=te();Object.defineProperties(this,{demo:{value:!1,enumerable:!0},dev:{value:!1,enumerable:!0},localStoragePreferences:{value:Po,enumerable:!0},reactor:{value:t,enumerable:!0},util:{value:qo,enumerable:!0},callApi:{value:on.bind(null,t)},startLocalStoragePreferencesSync:{value:Po.startSync.bind(Po,t)},startUrlSync:{value:Zi.startSync.bind(null,t)},stopUrlSync:{value:Zi.stopSync.bind(null,t)}}),ee(this,t,{auth:jo,config:zr,entity:Mn,entityHistory:Ei,errorLog:Ko,event:_r,logbook:vu,moreInfo:Ri,navigation:$i,notification:Fn,pushNotification:Au,restApi:dn,service:nr,stream:mo,sync:uo,template:zu,view:Ki,voice:Ju})},Xu=new Wu;window.validateAuth=function(t,e){Xu.authActions.validate(t,{rememberAuth:e,useStreaming:Xu.localStoragePreferences.useStreaming})},window.removeInitMsg=function(){var t=document.getElementById("ha-init-skeleton");t&&t.parentElement.removeChild(t)},Xu.reactor.batch((function(){Xu.navigationActions.showSidebar(Xu.localStoragePreferences.showSidebar),window.noAuth?window.validateAuth("",!1):Xu.localStoragePreferences.authToken&&window.validateAuth(Xu.localStoragePreferences.authToken,!0)})),setTimeout(Xu.startLocalStoragePreferencesSync,5e3),"serviceWorker"in navigator&&window.addEventListener("load",(function(){navigator.serviceWorker.register("/service_worker.js")})),window.hass=Xu})();
|
import maya.cmds as mc
def ui():
'''
Toggles override display state of selected element surfaces
Open existing asset scene, select a control on your asset(example - supermover)
Launch toggleOverride_GUI from the rigTools menu, select the options you want and execute.
@keyword: rig, cfin, utilities, gui, interface, window
@appVersion: 8.5, 2008
'''
if mc.window('toggleUIwin', q=1, ex=1):
mc.deleteUI('toggleUIwin')
uiWidth = 500
uiHeight = 200
# VERY IMPORTANT TO TURN OFF "REMEMBER SIZE AND POSITION" IN PREFERENCES
# define the interface
toggleUI = mc.window('toggleUIwin', title='toggleOverride_GUI - v.5', iconName='toggleOverride_GUI', w=uiWidth, h=uiHeight, resizeToFitChildren=False)
mc.frameLayout(marginHeight=30, labelVisible=0, borderStyle='out')
genForm = mc.formLayout(numberOfDivisions=100)
genColumn =mc.columnLayout(adjustableColumn=True, rowSpacing=5)
mc.rowLayout(nc=4, cat=[(1, 'right', 5), (2, 'both', 5), (3, 'right', 5), (4, 'both', 5)], cw=[(1,100),(2,110),(3,100),(4,100)])
mc.text(label ='Toggle To', annotation='select PolyCage toggle type.')
mc.optionMenu('polyToggleTypeDropdown', label='')
## should read these values to find the current state
mc.menuItem(label='Normal')
mc.menuItem(label='Template')
mc.menuItem(label='Reference')
# back up to Column Layout
mc.setParent('..')
mc.rowLayout(nc=2, cat=[(1, 'right', 116)], cw=[(1,305),(2,305)])
radioPolyEnableOverrides = mc.checkBox('polyEnable', v=True, label='overrides', h=30)
# back up to Column Layout
mc.setParent('..')
mc.rowLayout(nc=2, cat=[(1, 'right', 128)],cw=[(1,305),(2,305)])
radioPolyEnableShadingOverrides = mc.checkBox('polyEnableShading', v=True, label='shading', h=30)
# back up to Column Layout
mc.setParent('..')
mc.rowLayout(nc=2, cat=[(1, 'right', 116), (2, 'right', 290)], cw=[(1,305),(2,305)])
ok = mc.button(w=85, h=30, backgroundColor=(0, 1, 0), al='center', command='glTools.utils.toggleOverride.toggleOverride_WRP()', label='OK')
cancel = mc.button(w=85, h=30, backgroundColor=(1, 0, 0), al='center', command='mc.deleteUI("'+toggleUI+'")', label='Cancel')
# tell Maya to draw the window
mc.showWindow('toggleUIwin')
def toggleOverride_WRP():
'''
Wrapper to execute toggleOverride with inputs from
toggleOverride_GUI
@keyword: rig, cfin, utilities, gui, interface, window
@appVersion: 8.5, 2008
'''
sel=mc.ls(sl=True)
mEnableOverrides = mc.checkBox('polyEnable', q=True, v=True)
mDisplayMode = mc.optionMenu('polyToggleTypeDropdown', q=True, select=True)
mEnableShading = mc.checkBox('polyEnableShading', q=True, v=True)
if not len(sel):
raise Exception('error You must select a control in order to toggle display override on!')
toggleOverride(sel[0], 'model', mEnableOverrides, (mDisplayMode - 1), mEnableShading)
def toggleOverride(assetNode, geoGroup, enableOverrides, displayMode, enableShading):
'''
executable for toggleOverride. The executable needs to be given a node
from the asset in your scene to perform the operation on
available modes are as follows:
Normal(0) - geometry is selectable
Template(1) - geometry is in template mode
Reference(2) - geometry is in reference mode
@param assetNode: Node on the asset on which to toggleOverrides
@type assetNode: str
@param geoGroup: Node which contains all meshes for asset
@type geoGroup: str
@param enableOverrides: 1 or 0 to enable the overrides. Default is on
@type enableOverrides: int
@param displayNode: 0, 1, or 2 to define modes
@type displayNode: int
@param enableShading: 1 or 0 to enable the shading. Default is on.
@type: displayNode: int
@keyword: rig, cfin, utilities, gui, interface, window
@example: toggleOverride jack:cn_hed01_ccc model 1 2 1;
@appVersion: 8.5, 2008
'''
##find all the geo in that group
if not mc.objExists(assetNode): raise Exception('')
if assetNode.count(':'):
geoGroup = assetNode.split(':')[0] + ':' + geoGroup
if not mc.objExists(geoGroup): raise Exception('')
geo = mc.listRelatives(geoGroup, ad=1, ni=1, typ=['mesh','nurbsSurface'])
##cycle through that geo and set its state based on the mode, overrides, and shading
for shape in geo:
mc.setAttr(shape + ".overrideEnabled",enableOverrides)
if(enableOverrides):
mc.setAttr(shape + ".overrideShading",enableShading)
mc.setAttr(shape + ".overrideDisplayType",displayMode)
##finished
print 'Done toggling overrides'
|
export default {
/**
* @description 配置显示在浏览器标签的title
*/
title: 'iView-admin',
/**
* @description token在Cookie中存储的天数,默认1天
*/
cookieExpires: 1,
/**
* @description 是否使用国际化,默认为false
* 如果不使用,则需要在路由中给需要在菜单中展示的路由设置meta: {title: 'xxx'}
* 用来在菜单中显示文字
*/
useI18n: true,
/**
* @description api请求基础路径
*/
baseUrl: {
// dev: 'https://www.easy-mock.com/mock/5add9213ce4d0e69998a6f51/iview-admin/',
// pro: 'https://produce.com'
authURL:'https://produce.com',
managerURL:'https://produce1.com'
},
/**
* @description 默认打开的首页的路由name值,默认为home
*/
homeName: 'home',
/**
* @description 需要加载的插件
*/
plugin: {
'error-store': {
showInHeader: true, // 设为false后不会在顶部显示错误日志徽标
developmentOff: true // 设为true后在开发环境不会收集错误信息,方便开发中排查错误
}
}
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _shared = require("../DateTimePicker/shared");
var _DateTimePickerToolbar = _interopRequireDefault(require("../DateTimePicker/DateTimePickerToolbar"));
var _DesktopWrapper = _interopRequireDefault(require("../internal/pickers/wrappers/DesktopWrapper"));
var _Picker = _interopRequireDefault(require("../internal/pickers/Picker/Picker"));
var _useValidation = require("../internal/pickers/hooks/useValidation");
var _dateUtils = require("../internal/pickers/date-utils");
var _KeyboardDateInput = require("../internal/pickers/KeyboardDateInput");
var _usePickerState = require("../internal/pickers/hooks/usePickerState");
var _jsxRuntime = require("react/jsx-runtime");
const _excluded = ["onChange", "PopperProps", "ToolbarComponent", "TransitionComponent", "value"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const valueManager = {
emptyValue: null,
parseInput: _dateUtils.parsePickerInputValue,
areValuesEqual: (utils, a, b) => utils.isEqual(a, b)
};
/**
*
* Demos:
*
* - [Date Time Picker](https://material-ui.com/components/date-time-picker/)
*
* API:
*
* - [DesktopDateTimePicker API](https://material-ui.com/api/desktop-date-time-picker/)
*/
const DesktopDateTimePicker = /*#__PURE__*/React.forwardRef(function DesktopDateTimePicker(inProps, ref) {
// TODO: TDate needs to be instantiated at every usage.
const props = (0, _shared.useDateTimePickerDefaultizedProps)(inProps, 'MuiDesktopDateTimePicker');
const validationError = (0, _useValidation.useDateTimeValidation)(props) !== null;
const {
pickerProps,
inputProps,
wrapperProps
} = (0, _usePickerState.usePickerState)(props, valueManager);
const {
PopperProps,
ToolbarComponent = _DateTimePickerToolbar.default,
TransitionComponent
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const AllDateInputProps = (0, _extends2.default)({}, inputProps, other, {
ref,
validationError
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_DesktopWrapper.default, (0, _extends2.default)({}, wrapperProps, {
DateInputProps: AllDateInputProps,
KeyboardDateInputComponent: _KeyboardDateInput.KeyboardDateInput,
PopperProps: PopperProps,
TransitionComponent: TransitionComponent,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Picker.default, (0, _extends2.default)({}, pickerProps, {
autoFocus: true,
toolbarTitle: props.label || props.toolbarTitle,
ToolbarComponent: ToolbarComponent,
DateInputProps: AllDateInputProps
}, other))
}));
});
process.env.NODE_ENV !== "production" ? DesktopDateTimePicker.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Regular expression to detect "accepted" symbols.
* @default /\dap/gi
*/
acceptRegex: _propTypes.default.instanceOf(RegExp),
/**
* If `true`, `onChange` is fired on click even if the same date is selected.
* @default false
*/
allowSameDateSelection: _propTypes.default.bool,
/**
* 12h/24h view for hour selection clock.
* @default false
*/
ampm: _propTypes.default.bool,
/**
* Display ampm controls under the clock (instead of in the toolbar).
* @default false
*/
ampmInClock: _propTypes.default.bool,
/**
* @ignore
*/
autoFocus: _propTypes.default.bool,
/**
* @ignore
*/
children: _propTypes.default.node,
/**
* className applied to the root component.
*/
className: _propTypes.default.string,
/**
* The components used for each slot.
* Either a string to use a HTML element or a component.
* @default {}
*/
components: _propTypes.default.shape({
LeftArrowButton: _propTypes.default.elementType,
LeftArrowIcon: _propTypes.default.elementType,
OpenPickerIcon: _propTypes.default.elementType,
RightArrowButton: _propTypes.default.elementType,
RightArrowIcon: _propTypes.default.elementType,
SwitchViewButton: _propTypes.default.elementType,
SwitchViewIcon: _propTypes.default.elementType
}),
/**
* The props used for each slot inside.
* @default {}
*/
componentsProps: _propTypes.default.object,
/**
* Date tab icon.
*/
dateRangeIcon: _propTypes.default.node,
/**
* Default calendar month displayed when `value={null}`.
*/
defaultCalendarMonth: _propTypes.default.any,
/**
* If `true` the popup or dialog will immediately close after submitting full date.
* @default `true` for Desktop, `false` for Mobile (based on the chosen wrapper and `desktopModeMediaQuery` prop).
*/
disableCloseOnSelect: _propTypes.default.bool,
/**
* If `true`, the picker and text field are disabled.
*/
disabled: _propTypes.default.bool,
/**
* @default false
*/
disableFuture: _propTypes.default.bool,
/**
* If `true`, todays date is rendering without highlighting with circle.
* @default false
*/
disableHighlightToday: _propTypes.default.bool,
/**
* Do not ignore date part when validating min/max time.
* @default false
*/
disableIgnoringDatePartForTimeValidation: _propTypes.default.bool,
/**
* Disable mask on the keyboard, this should be used rarely. Consider passing proper mask for your format.
* @default false
*/
disableMaskedInput: _propTypes.default.bool,
/**
* Do not render open picker button (renders only text field with validation).
* @default false
*/
disableOpenPicker: _propTypes.default.bool,
/**
* @default false
*/
disablePast: _propTypes.default.bool,
/**
* Accessible text that helps user to understand which time and view is selected.
* @default <TDate extends any>(
* view: ClockView,
* time: TDate | null,
* adapter: MuiPickersAdapter<TDate>,
* ) =>
* `Select ${view}. ${
* time === null ? 'No time selected' : `Selected time is ${adapter.format(time, 'fullTime')}`
* }`
*/
getClockLabelText: _propTypes.default.func,
/**
* Get aria-label text for control that opens picker dialog. Aria-label text must include selected date. @DateIOType
* @default (value, utils) => `Choose date, selected date is ${utils.format(utils.date(value), 'fullDate')}`
*/
getOpenDialogAriaText: _propTypes.default.func,
/**
* Get aria-label text for switching between views button.
*/
getViewSwitchingButtonText: _propTypes.default.func,
/**
* To show tabs.
*/
hideTabs: _propTypes.default.bool,
/**
* @ignore
*/
ignoreInvalidInputs: _propTypes.default.bool,
/**
* Props to pass to keyboard input adornment.
*/
InputAdornmentProps: _propTypes.default.object,
/**
* Format string.
*/
inputFormat: _propTypes.default.string,
/**
* @ignore
*/
InputProps: _propTypes.default.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: _propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.shape({
current: _propTypes.default.object
})]),
/**
* @ignore
*/
key: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),
/**
* @ignore
*/
label: _propTypes.default.node,
/**
* Left arrow icon aria-label text.
*/
leftArrowButtonText: _propTypes.default.string,
/**
* If `true` renders `LoadingComponent` in calendar instead of calendar view.
* Can be used to preload information and show it in calendar.
* @default false
*/
loading: _propTypes.default.bool,
/**
* Custom mask. Can be used to override generate from format. (e.g. `__/__/____ __:__` or `__/__/____ __:__ _M`).
*/
mask: _propTypes.default.string,
/**
* @ignore
*/
maxDate: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.instanceOf(Date), _propTypes.default.number, _propTypes.default.string]),
/**
* Minimal selectable moment of time with binding to date, to set max time in each day use `maxTime`.
*/
maxDateTime: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.instanceOf(Date), _propTypes.default.number, _propTypes.default.string]),
/**
* @ignore
*/
maxTime: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.instanceOf(Date), _propTypes.default.number, _propTypes.default.string]),
/**
* @ignore
*/
minDate: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.instanceOf(Date), _propTypes.default.number, _propTypes.default.string]),
/**
* Minimal selectable moment of time with binding to date, to set min time in each day use `minTime`.
*/
minDateTime: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.instanceOf(Date), _propTypes.default.number, _propTypes.default.string]),
/**
* @ignore
*/
minTime: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.instanceOf(Date), _propTypes.default.number, _propTypes.default.string]),
/**
* Step over minutes.
* @default 1
*/
minutesStep: _propTypes.default.number,
/**
* Callback fired when date is accepted @DateIOType.
*/
onAccept: _propTypes.default.func,
/**
* Callback fired when the value (the selected date) changes @DateIOType.
*/
onChange: _propTypes.default.func.isRequired,
/**
* Callback fired when the popup requests to be closed.
* Use in controlled mode (see open).
*/
onClose: _propTypes.default.func,
/**
* Callback that fired when input value or new `value` prop validation returns **new** validation error (or value is valid after error).
* In case of validation error detected `reason` prop return non-null value and `TextField` must be displayed in `error` state.
* This can be used to render appropriate form error.
*
* [Read the guide](https://next.material-ui-pickers.dev/guides/forms) about form integration and error displaying.
* @DateIOType
*/
onError: _propTypes.default.func,
/**
* Callback firing on month change. @DateIOType
*/
onMonthChange: _propTypes.default.func,
/**
* Callback fired when the popup requests to be opened.
* Use in controlled mode (see open).
*/
onOpen: _propTypes.default.func,
/**
* Callback fired on view change.
*/
onViewChange: _propTypes.default.func,
/**
* Callback firing on year change @DateIOType.
*/
onYearChange: _propTypes.default.func,
/**
* Control the popup or dialog open state.
*/
open: _propTypes.default.bool,
/**
* Props to pass to keyboard adornment button.
*/
OpenPickerButtonProps: _propTypes.default.object,
/**
* First view to show.
*/
openTo: _propTypes.default.oneOf(['day', 'hours', 'minutes', 'month', 'year']),
/**
* Force rendering in particular orientation.
*/
orientation: _propTypes.default.oneOf(['landscape', 'portrait']),
/**
* Popper props passed down to [Popper](https://material-ui.com/api/popper/) component.
*/
PopperProps: _propTypes.default.object,
/**
* Make picker read only.
*/
readOnly: _propTypes.default.bool,
/**
* Disable heavy animations.
* @default typeof navigator !== 'undefined' && /(android)/i.test(navigator.userAgent)
*/
reduceAnimations: _propTypes.default.bool,
/**
* Custom renderer for day. Check the [PickersDay](https://material-ui.com/api/pickers-day/) component.
*/
renderDay: _propTypes.default.func,
/**
* The `renderInput` prop allows you to customize the rendered input.
* The `props` argument of this render prop contains props of [TextField](https://material-ui.com/api/text-field/#textfield-api) that you need to forward.
* Pay specific attention to the `ref` and `inputProps` keys.
* @example ```jsx
* renderInput={props => <TextField {...props} />}
* ````
*/
renderInput: _propTypes.default.func.isRequired,
/**
* Component displaying when passed `loading` true.
* @default () => <span data-mui-test="loading-progress">...</span>
*/
renderLoading: _propTypes.default.func,
/**
* Custom formatter to be passed into Rifm component.
*/
rifmFormatter: _propTypes.default.func,
/**
* Right arrow icon aria-label text.
*/
rightArrowButtonText: _propTypes.default.string,
/**
* Disable specific date. @DateIOType
*/
shouldDisableDate: _propTypes.default.func,
/**
* Dynamically check if time is disabled or not.
* If returns `false` appropriate time point will ot be acceptable.
*/
shouldDisableTime: _propTypes.default.func,
/**
* Disable specific years dynamically.
* Works like `shouldDisableDate` but for year selection view @DateIOType.
*/
shouldDisableYear: _propTypes.default.func,
/**
* If `true`, days that have `outsideCurrentMonth={true}` are displayed.
* @default false
*/
showDaysOutsideCurrentMonth: _propTypes.default.bool,
/**
* If `true`, show the toolbar even in desktop mode.
*/
showToolbar: _propTypes.default.bool,
/**
* Time tab icon.
*/
timeIcon: _propTypes.default.node,
/**
* Component that will replace default toolbar renderer.
* @default DateTimePickerToolbar
*/
ToolbarComponent: _propTypes.default.elementType,
/**
* Date format, that is displaying in toolbar.
*/
toolbarFormat: _propTypes.default.string,
/**
* Mobile picker date value placeholder, displaying if `value` === `null`.
* @default "–"
*/
toolbarPlaceholder: _propTypes.default.node,
/**
* Mobile picker title, displaying in the toolbar.
* @default "SELECT DATE"
*/
toolbarTitle: _propTypes.default.node,
/**
* Custom component for popper [Transition](https://material-ui.com/components/transitions/#transitioncomponent-prop).
*/
TransitionComponent: _propTypes.default.elementType,
/**
* The value of the picker.
*/
value: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.instanceOf(Date), _propTypes.default.number, _propTypes.default.string]),
/**
* Array of views to show.
*/
views: _propTypes.default.arrayOf(_propTypes.default.oneOf(['day', 'hours', 'minutes', 'month', 'year']).isRequired)
} : void 0;
var _default = DesktopDateTimePicker;
exports.default = _default;
|
'''
Implementation of Classifier Training, partly described inside Fanello et al.
'''
import sys
import signal
import errno
import glob
import numpy as np
import class_objects as co
import action_recognition_alg as ara
import cv2
import os.path
import cPickle as pickle
import logging
import yaml
import time
from OptGridSearchCV import optGridSearchCV
# pylint: disable=no-member,R0902,too-many-public-methods,too-many-arguments
# pylint: disable=too-many-locals, too-many-branches, too-many-statements
def timeit(func):
'''
Decorator to time extraction
'''
def wrapper(self, *arg, **kw):
t1 = time.time()
res = func(self, *arg, **kw)
t2 = time.time()
self.time.append(t2 - t1)
del self.time[:-5000]
return res
return wrapper
class Classifier(object):
'''
Class to hold all Classifier specific methods.
<descriptors>:['pca','ghog','3dhof']
<action_type>:True if no buffers are used
<sparsecoding_level> is True if sparse coding is used
Classifier Parameters, for example <AdaBoost_n_estimators> or
<RDF_n_estimators> or <kernel> can be
a list, which will be reduced using optimized grid search with cross
validation.
'''
def __init__(self, log_lev='INFO',
visualize=False, masks_needed=True,
buffer_size=co.CONST['buffer_size'],
sparse_dim_rat=co.CONST['sparse_dim_rat'],
descriptors='',
ptpca=False,
ptpca_components=None,
action_type='Dynamic',
classifiers_used='SVM', num_of_cores=4, name='',
svm_c=None,
AdaBoost_n_estimators=None,
RDF_n_estimators=None,
add_info=None,
sparsecoding_level=None,
kernel=None,
save_all_steps=False,
post_scores_processing_method=None,
hardcore=False,
for_app=False):
'''
sparsecoding_level = [Buffer, Features, None]
'''
if not os.path.isdir(co.CONST['AppData']):
os.makedirs(co.CONST['AppData'])
self.app_dir = co.CONST['AppData']
self.for_app = for_app
self.time = []
self.classifiers_ids = None
self.test_ind = None
# General configuration
if not isinstance(descriptors, list):
descriptors = [descriptors]
descriptors = sorted(descriptors)
###
features_params = {}
coders_params = {}
for descriptor in descriptors:
features_params[descriptor] = {}
features_params[descriptor]['params'] = {attrib.replace(descriptor, ''):
co.CONST[attrib] for
attrib in co.CONST if
attrib.startswith(descriptor)}
features_params[descriptor]['sparsecoded'] = sparsecoding_level
features_params[descriptor]['action_type'] = action_type
coders_params[descriptor] = {}
if not sparsecoding_level:
features_params[descriptor]['sparse_params'] = None
else:
features_params[descriptor]['sparse_params'] = {
attrib.replace('sparse', ''):
co.CONST[attrib] for
attrib in co.CONST if
attrib.startswith('sparse')}
coders_params[descriptor] = {
attrib.replace('sparse', ''):
co.CONST[attrib] for
attrib in co.CONST if
attrib.startswith('sparse') and
'fss' not in attrib}
self.test_name = None
self.kernel = kernel
self.svm_c = svm_c
self.RDF_n_estimators = RDF_n_estimators
self.AdaBoost_n_estimators = AdaBoost_n_estimators
self.sparse_dim_rat = sparse_dim_rat
if 'SVM' in classifiers_used and kernel is None:
self.kernel = 'linear'
if 'SVM' in classifiers_used:
if svm_c is None:
self.svm_c = co.CONST['SVM_C']
if post_scores_processing_method == 'CProb':
LOG.warning('Invalid post_scores_processing_method for SVM')
if hardcore:
raise Exception
else:
LOG.warning('Changing method to CSTD')
post_scores_processing_method = 'CSTD'
if 'RDF' in classifiers_used or 'AdaBoost' in classifiers_used:
if svm_c is not None:
LOG.warning(
'svm_c is not None for RDF or AdaBoost experimentation')
if hardcore:
raise Exception
if post_scores_processing_method is None:
if 'RDF' in classifiers_used or 'AdaBoost' in classifiers_used:
post_scores_processing_method = 'CProb'
else:
post_scores_processing_method = 'CSTD'
classifier_params = {}
if 'RDF' in classifiers_used and RDF_n_estimators is None:
self.RDF_n_estimators = co.CONST['RDF_trees']
if 'AdaBoost' in classifiers_used and AdaBoost_n_estimators is None:
self.AdaBoost_n_estimators = co.CONST['AdaBoost_Estimators']
if 'SVM' in classifiers_used:
classifier_params['SVM_kernel'] = self.kernel
classifier_params['SVM_C'] = self.svm_c
if 'RDF' in classifiers_used:
classifier_params['RDF_n_estimators'] = self.RDF_n_estimators
if 'AdaBoost' in classifiers_used:
classifier_params['AdaBoost_n_estimators'] = self.AdaBoost_n_estimators
if action_type != 'Passive':
dynamic_params = {'buffer_size': buffer_size,
'buffer_confidence_tol': co.CONST['buffer_confidence_tol'],
'filter_window_size':
co.CONST['STD_big_filt_window']}
else:
dynamic_params = {'buffer_size': 1}
if ptpca and ptpca_components is None:
ptpca_components = co.CONST['PTPCA_components']
ptpca_params = {'PTPCA_components': ptpca_components}
for descriptor in descriptors:
features_params[descriptor]['dynamic_params'] = dynamic_params
if sparsecoding_level:
if not isinstance(sparse_dim_rat, list):
sparse_dim_rat = [sparse_dim_rat] * len(descriptors)
if len(list(sparse_dim_rat)) != len(descriptors):
raise Exception('<sparse_dim_rat> should be either an integer/None or' +
' a list with same length with <descriptors>')
sparse_params = dict(zip(descriptors, sparse_dim_rat))
sparse_params['fss_max_iter'] = co.CONST['sparse_fss_max_iter']
else:
sparse_params = None
testing_params = {'online': None}
testing_params['post_scores_processing_method'] = \
post_scores_processing_method
fil = os.path.join(co.CONST['rosbag_location'],
'gestures_type.csv')
self.passive_actions = None
self.dynamic_actions = None
if os.path.exists(fil):
with open(fil, 'r') as inp:
for line in inp:
if line.split(':')[0] == 'Passive':
self.passive_actions = line.split(
':')[1].rstrip('\n').split(',')
elif line.split(':')[0] == 'Dynamic':
self.dynamic_actions = line.split(
':')[1].rstrip('\n').split(',')
action_params = {'Passive': self.passive_actions,
'Dynamic': self.dynamic_actions}
LOG.debug('Extracting: ' + str(descriptors))
self.parameters = {'classifier': classifiers_used,
'descriptors': descriptors,
'features_params': features_params,
'coders_params': coders_params,
'dynamic_params': dynamic_params,
'classifier_params': classifier_params,
'sparse_params': sparse_params,
'action_type': action_type,
'sparsecoded': sparsecoding_level,
'testing': False,
'testing_params': testing_params,
'actions_params': action_params,
'PTPCA': ptpca,
'PTPCA_params': ptpca_params}
self.training_parameters = {k: self.parameters[k] for k in
('classifier', 'descriptors',
'features_params',
'dynamic_params',
'classifier_params',
'sparse_params',
'action_type',
'sparsecoded',
'PTPCA',
'PTPCA_params') if k in
self.parameters}
self.descriptors = descriptors
self.add_info = add_info
self.log_lev = log_lev
self.visualize = visualize
self.buffer_size = buffer_size
self.masks_needed = masks_needed
self.action_type = action_type
self.classifiers_used = classifiers_used
self.num_of_cores = num_of_cores
self.name = name
self.ptpca = ptpca
self.action_recog = ara.ActionRecognition(
self.parameters,
log_lev=log_lev)
if not self.for_app:
self.available_tests = sorted(os.listdir(co.CONST['test_save_path']))
else:
self.available_tests = []
self.update_experiment_info()
if 'SVM' in self.classifiers_used:
from sklearn.svm import LinearSVC
self.classifier_type = LinearSVC(
class_weight='balanced', C=self.svm_c,
multi_class='ovr',
dual=False)
elif 'RDF' in self.classifiers_used:
from sklearn.ensemble import RandomForestClassifier
self.classifier_type =\
RandomForestClassifier(self.RDF_n_estimators)
elif 'AdaBoost' in self.classifiers_used:
from sklearn.ensemble import AdaBoostClassifier
self.classifier_type =\
AdaBoostClassifier(n_estimators=self.AdaBoost_n_estimators)
self.unified_classifier = None
if sparsecoding_level:
if not(sparsecoding_level == 'Features' or sparsecoding_level == 'Buffer'):
raise Exception('Invalid sparsecoding_level, its value shoud be '
+ 'None/False/Buffer/Features')
self.sparsecoded = sparsecoding_level
self.decide = None
# Training variables
self.training_data = None
self.train_ground_truth = None # is loaded from memory after training
self.train_classes = None # is loaded from memory after training
# Testing general variables
self.accuracy = None
self.f1_scores = None
self.confusion_matrix = None
self.scores_savepath = None
self.scores_std = []
self.scores_std_mean = []
self.scores = None
self.scores_filter_shape = None
self.std_big_filter_shape = None
self.std_small_filter_shape = None
self.recognized_classes = []
self.crossings = None
self.testname = ''
self.save_fold = None
self.online = False
# Testing offline variables
self.testdataname = ''
self.test_instances = None
# Testing online variables
self.count_prev = None
self.buffer_exists = None
self.scores_exist = None
self.img_count = -1
self._buffer = []
self.scores_running_mean_vec = []
self.big_std_running_mean_vec = []
self.small_std_running_mean_vec = []
self.saved_buffers_scores = []
self.new_action_starts_count = 0
self.test_ground_truth = None
self.mean_from = -1
self.on_action = False
self.act_inds = []
self.max_filtered_score = 0
self.less_filtered_scores_std = None
self.high_filtered_scores_std = None
self.classifier_folder = None
self.testing_initialized = False
self.classifiers_list = {}
self.classifier_savename = 'trained_'
self.classifier_savename += self.full_info.replace(' ', '_').lower()
try:
[self.unified_classifier,
info] = co.file_oper.load_labeled_data(
['Classifier'] + self.classifier_id)
co.file_oper.save_labeled_data(['Classifier'],
[self.unified_classifier,
self.training_parameters],
name=self.app_dir)
if isinstance(info, tuple):
self.training_params = info[0]
self.additional_params = info[1:]
else:
self.training_params = info
self.loaded_classifier = True
LOG.info('Loaded Classifier')
except TypeError:
if self.for_app:
[self.unified_classifier,
info] = co.file_oper.load_labeled_data(
['Classifier'],
name=self.app_dir)
self.loaded_classifier = True
else:
self.loaded_classifier = False
LOG.info('Classifier not Loaded')
self.load_tests()
try:
self.classifier_folder = str(self.classifiers_list[
self.classifier_savename])
except KeyError:
self.classifier_folder = str(len(self.classifiers_list))
self.coders_to_train = []
# parameters bound variables
self.frames_preproc = ara.FramesPreprocessing(self.parameters)
available_descriptors =\
ara.Actions(self.parameters).available_descriptors
try:
self.features_extractors = [available_descriptors[nam](
self.parameters, self.frames_preproc)
for nam in self.parameters['descriptors']]
self.buffer_operators = [
ara.BufferOperations(self.parameters)
for nam in self.parameters['descriptors']]
if self.sparsecoded:
[self.action_recog.
actions.load_sparse_coder(ind) for ind in range(
len(self.parameters['descriptors']))]
except BaseException: pass
def load_tests(self, reset=True):
if reset:
self.testdata = [None] * len(self.available_tests)
self.fscores = [None] * len(self.available_tests)
self.accuracies = [None] * len(self.available_tests)
self.results = [None] * len(self.available_tests)
self.conf_mats = [None] * len(self.available_tests)
self.test_times = [None] * len(self.available_tests)
for count, test in enumerate(self.available_tests):
if (self.testdata[count] is None or
self.testdata[count]['Accuracy'] is None):
self.testdata[count] = co.file_oper.load_labeled_data(
['Testing'] + self.tests_ids[count])
if (self.testdata[count] is not None and
self.testdata[count]['Accuracy'] is not None):
self.accuracies[count] = self.testdata[count]['Accuracy']
self.fscores[count] = self.testdata[count]['FScores']
self.results[count] = self.testdata[count]['Results']
self.conf_mats[count] = self.testdata[count]['ConfMat']
self.test_times[count] = self.testdata[count]['TestTime']
try:
self.partial_accuracies[count] = self.testdata[count][
'PartialAccuracies']
except BaseException: pass
else:
self.testdata[count] = {}
self.testdata[count]['Accuracy'] = {}
self.testdata[count]['FScores'] = {}
self.testdata[count]['Results'] = {}
self.testdata[count]['ConfMat'] = {}
self.testdata[count]['TestTime'] = {}
self.testdata[count]['Labels'] = {}
try:
self.testdata[count]['PartialAccuracies'] = {}
except BaseException: pass
def update_experiment_info(self):
if self.parameters['action_type'] == 'Passive':
info = 'passive '
else:
info = 'dynamic '
info = info + self.name + ' ' + self.classifiers_used + ' '
info += 'using'
if self.parameters['sparsecoded']:
info += ' sparsecoded'
for feature in self.parameters['descriptors']:
info += ' ' + feature
info += ' descriptors '
if 'SVM' in self.parameters['classifier']:
info += 'with ' + self.parameters[
'classifier_params']['SVM_kernel'] + ' kernel'
elif 'RDF' in self.parameters['classifier']:
info += ('with ' + str(self.parameters['classifier_params'][
'RDF_n_estimators']) + ' estimators')
elif 'AdaBoost' in self.parameters['classifier']:
info += ('with ' + str(self.parameters['classifier_params'][
'AdaBoost_n_estimators']) + ' estimators')
if self.parameters['action_type'] == 'Dynamic':
info += ' with buffer size ' + str(self.buffer_size)
if self.parameters['sparsecoded']:
info += ' with sparsecoding by ratio of ' + \
str(self.sparse_dim_rat)
if self.ptpca:
info += (' with ' +
str(self.parameters['PTPCA_params']['PTPCA_components']) +
' post-time-pca components')
self.full_info = info.title()
if self.add_info:
info += self.add_info
self.classifier_savename = 'trained_'
self.classifier_savename += self.full_info.replace(' ', '_').lower()
self.update_classifier_id()
self.update_tests_ids()
def update_classifier_id(self):
self.features_file_id = []
self.features_id = []
for count in range(len(self.parameters['descriptors'])):
_id, file_id = self.action_recog.actions.retrieve_descriptor_possible_ids(count,
assume_existence=True)
self.features_id.append(_id)
self.features_file_id.append(file_id)
self.classifier_id = [co.dict_oper.create_sorted_dict_view(
{'Classifier': str(self.classifiers_used)}),
co.dict_oper.create_sorted_dict_view(
{'ClassifierParams': str(co.dict_oper.create_sorted_dict_view(
self.parameters['classifier_params']))}),
co.dict_oper.create_sorted_dict_view(
{'ActionsType': str(self.action_type)}),
co.dict_oper.create_sorted_dict_view(
{'FeaturesParams': str(self.features_file_id)})]
def update_tests_ids(self):
self.tests_ids = []
for count, test in enumerate(self.available_tests):
self.tests_ids.append([co.dict_oper.create_sorted_dict_view({'Test': str(test)}),
co.dict_oper.create_sorted_dict_view(
{'TestingParams': str(co.dict_oper.create_sorted_dict_view(
self.parameters['testing_params']))})]
+ [self.classifier_id])
def initialize_classifier(self, classifier):
'''
Add type to classifier and set methods
'''
self.unified_classifier = classifier
if 'SVM' in self.classifiers_used:
self.unified_classifier.decide = self.unified_classifier.decision_function
self.unified_classifier.predict = self.unified_classifier.predict
elif 'RDF' in self.classifiers_used or 'AdaBoost' in self.classifiers_used:
self.unified_classifier.decide = self.unified_classifier.predict_proba
self.unified_classifier.predict = self.unified_classifier.predict
co.file_oper.save_labeled_data(['Classifier'] + self.classifier_id,
[self.unified_classifier,
self.training_parameters])
co.file_oper.save_labeled_data(['Classifier'],
[self.unified_classifier,
self.training_parameters],
name=self.app_dir)
def reset_offline_test(self):
'''
Reset offline testing variables
'''
# Testing general variables
self.scores_std = []
self.scores_std_mean = []
self.scores = None
self.recognized_classes = []
self.crossings = None
self.save_fold = None
self.testing_initialized = True
# Testing offline variables
def reset_online_test(self):
'''
Reset online testing variables
'''
# Testing general variables
self.scores_std = []
self.scores_std_mean = []
self.scores = []
self.recognized_classes = []
self.crossings = []
self.save_fold = None
# Testing online variables
self.count_prev = None
self.buffer_exists = []
self.scores_exist = []
self.img_count = -1
self._buffer = []
self.scores_running_mean_vec = []
self.big_std_running_mean_vec = []
self.small_std_running_mean_vec = []
self.saved_buffers_scores = []
self.new_action_starts_count = 0
self.test_ground_truth = None
self.mean_from = -1
self.on_action = False
self.act_inds = []
self.max_filtered_score = 0
self.less_filtered_scores_std = None
self.high_filtered_scores_std = None
self.testing_initialized = True
def add_train_classes(self, training_datapath):
'''
Set the training classes of the classifier
'''
try:
self.train_classes = [name for name in os.listdir(training_datapath)
if os.path.isdir(os.path.join(training_datapath, name))][::-1]
except:
if self.for_app:
with open(os.path.join(self.app_dir,
'train_classes'),'r') as inp:
self.train_classes = pickle.load(inp)
else:
raise
self.all_actions = ['Undefined'] + self.train_classes
# Compare actions in memory with actions in file 'gestures_type.csv'
if self.passive_actions is not None:
passive_actions = [clas for clas in
(self.passive_actions) if clas
in self.train_classes]
if self.dynamic_actions is not None:
dynamic_actions = [clas for clas in
(self.dynamic_actions) if clas
in self.train_classes]
if (self.dynamic_actions is not None and
self.passive_actions is not None):
if 'Sync' in self.classifiers_used:
self.train_classes = {'Passive': passive_actions,
'Dynamic': dynamic_actions}
else:
classes = []
if self.action_type == 'Dynamic' or self.action_type == 'All':
classes += dynamic_actions
if self.action_type == 'Passive' or self.action_type == 'All':
classes += passive_actions
self.train_classes = classes
with open(os.path.join(self.app_dir,
'train_classes'),'w') as out:
pickle.dump(self.train_classes, out)
def run_training(self, coders_retrain=False,
classifiers_retrain=False,
training_datapath=None, classifier_savename=None,
num_of_cores=4, classifier_save=True,
max_act_samples=None,
min_dict_iterations=5,
visualize_feat=False, just_sparse=False,
init_sc_traindata_num=200,
train_all=False):
'''
<Arguments>
For coders training:
Do not train coders if coder already exists or <coders_retrain>
is False. <min_dict_iterations> denote the minimum training iterations to
take place after the whole data has been processed from the trainer
of the coder.<init_dict_traindata_num> denotes how many samples
will be used in the first iteration of the sparse coder training
For svm training:
Train ClassifierS with <num_of_cores>.
Save them if <classifier_save> is True to <classifiers_savepath>. Do not train
if <classifiers_savepath> already exists and <classifiers_retrain> is False.
'''
self.train_all = train_all
self.parameters['testing'] = False
LOG.info(self.full_info + ':')
if classifier_savename is not None:
self.classifier_savename = classifier_savename
if training_datapath is None:
training_datapath = co.CONST['actions_path']
self.add_train_classes(training_datapath)
if self.unified_classifier is None:
LOG.info('Missing trained classifier:' +
self.full_info)
LOG.info('Classifier will be retrained')
classifiers_retrain = True
else:
if not self.sparsecoded:
return
self.prepare_training_data(training_datapath, max_act_samples,
visualize_feat=visualize_feat)
if just_sparse:
return
if self.sparsecoded and self.coders_to_train and classifiers_retrain:
# Enters only if coders were not initially trained or had to be
# retrained. Otherwise, sparse descriptors are computed when
#<Action.add_features> is called
LOG.info('Trained' + str([self.parameters['descriptors'][coder] for coder in
self.coders_to_train]))
LOG.info('Making Sparse Features..')
self.action_recog = ara.ActionRecognition(
self.parameters,
log_lev=self.log_lev,
feat_filename=os.path.join(co.CONST['feat_save_path'],
'saved'))
self.prepare_training_data(training_datapath, max_act_samples,
visualize_feat=visualize_feat)
self.process_training(num_of_cores, classifiers_retrain,
self.classifier_savename, classifier_save)
def prepare_training_data(self, path=None, max_act_samples=None,
visualize_feat=False):
'''
Read actions from the <path> and name them according to their parent
folder name
'''
LOG.info('Adding actions..')
while True:
self.training_data = []
self.training_samples_inds = []
for act_count, action in enumerate(self.train_classes):
LOG.info('Action:' + action)
descriptors, samples_indices, mean_depths, _, trained_coders, _ = self.add_action(name=action,
data=os.path.join(
path, action),
use_dexter=False,
action_type=self.action_type,
max_act_samples=max_act_samples)
if not(self.sparsecoded and None in trained_coders):
descriptors = np.hstack(tuple(descriptors))
fmask = np.prod(np.isfinite(
descriptors), axis=1).astype(bool)
descriptors = descriptors[fmask]
LOG.info('Action \'' + action + '\' has ' +
'descriptors of shape ' + str(descriptors.shape))
self.training_data.append(descriptors)
self.training_samples_inds.append(
np.array(samples_indices)[fmask])
else:
self.training_samples_inds = []
self.training_data = []
self.train_ground_truth = []
if self.training_data:
if self.action_type == 'Dynamic':
self.training_data = co.preproc_oper.equalize_samples(
samples=self.training_data,
utterance_indices=self.training_samples_inds,
mode='random')
self.train_ground_truth = []
for act_count, clas in enumerate(self.training_data):
self.train_ground_truth += clas.shape[0] * [act_count]
self.training_data = np.vstack((self.training_data))
if None in trained_coders and self.sparsecoded:
self.action_recog.actions.train_sparse_dictionary()
else:
break
finite_samples = np.prod(
np.isfinite(
self.training_data),
axis=1).astype(bool)
self.train_ground_truth = np.array(
self.train_ground_truth)[finite_samples]
self.training_data = self.training_data[finite_samples, :]
LOG.info('Total Training Data has shape:'
+ str(self.training_data.shape))
def process_training(self, num_of_cores=4, retrain=False,
savepath=None, save=True):
'''
Train (or load trained) Classifiers with number of cores num_of_cores, with buffer size (stride
is 1) <self.buffer_size>. If <retrain> is True, Classifiers are retrained, even if
<save_path> exists.
'''
loaded = 0
if save and savepath is None:
raise Exception('savepath needed')
if retrain or self.unified_classifier is None:
if retrain and self.unified_classifier is not None:
LOG.info('retrain switch is True, so the Classifier ' +
'is retrained')
classifier_params = {elem.replace(self.classifiers_used + '_', ''):
self.parameters['classifier_params'][elem]
for elem in
self.parameters['classifier_params']
if elem.startswith(self.classifiers_used)}
if any([isinstance(classifier_params[elem], list)
for elem in classifier_params]):
grid_search_params = classifier_params.copy()
from sklearn.multiclass import OneVsRestClassifier
if isinstance(self.classifier_type, OneVsRestClassifier):
grid_search_params = {('estimator__' + key): classifier_params[key]
for key in classifier_params}
grid_search_params = {key: (grid_search_params[key] if
isinstance(
grid_search_params[key], list)
else [
grid_search_params[key]]) for key in
classifier_params}
best_params, best_scores, best_estimators = optGridSearchCV(
self.classifier_type, self.training_data,
self.train_ground_truth, grid_search_params, n_jobs=4,
fold_num=3)
best_params = best_params[-1]
best_scores = best_scores[-1]
best_estimator = best_estimators[-1]
if isinstance(self.classifier_type, OneVsRestClassifier):
best_params = {key.replace('estimator__', ''):
classifier_params[
key.replace('estimator__', '')]
for key in best_params}
classifier_params = {self.classifiers_used + '_' + key: best_params[key] for key
in best_params}
self.parameters['classifier_params'].update(classifier_params)
self.training_parameters['classifier_params'].update(
classifier_params)
self.classifier_type = best_estimator
self.update_experiment_info()
savepath = self.classifier_savename
self.initialize_classifier(self.classifier_type.fit(self.training_data,
self.train_ground_truth))
def compute_testing_time(self, testname):
testing_time = {}
features_extraction_time = 0
if not self.online:
for count in range(len(self.parameters['descriptors'])):
try:
loaded = co.file_oper.load_labeled_data(
[str(self.features_id[count][-1])] +
self.features_file_id[count] +
[str(testname)])
(_, _, _, feat_times) = loaded
except BaseException:
return None
for key in feat_times:
LOG.info('Time:' + str(key) + ':' +
str(np.mean(feat_times[key])))
features_extraction_time += np.mean(feat_times[key])
try:
testing_time['Classification'] = self.time[
-1] / float(self.scores.shape[0])
except IndexError:
testing_time['Classification'] = (
co.file_oper.load_labeled_data(
['Testing'] + self.tests_ids[
self.available_tests.index(
testname)])['TestTime'][
'Classification'])
else:
testing_time['Classification'] = np.mean(self.time)
testing_time['Features Extraction'] = features_extraction_time
return testing_time
def add_action(self, name=None, data=None, visualize=False, offline_vis=False,
to_visualize=[], exit_after_visualization=False,
use_dexter=False,
action_type=None,
max_act_samples=None):
return self.action_recog.add_action(
name=name,
use_dexter=use_dexter,
action_type=self.action_type,
max_act_samples=max_act_samples,
data=data,
offline_vis=offline_vis,
to_visualize=to_visualize,
exit_after_visualization=exit_after_visualization)
def offline_testdata_processing(self, datapath):
'''
Offline testing data processing, using data in <datapath>.
'''
LOG.info('Processing test data..')
LOG.info('Extracting descriptors..')
(descriptors, _, mean_depths, test_name, _, _) = self.add_action(
name=None, data=datapath)
testdata = np.hstack(tuple(descriptors))
self.parameters['testing_params'][test_name] = test_name
self.parameters['testing_params']['current'] = test_name
return testdata
def save_plot(self, fig, lgd=None, display_all=False, info=None):
'''
<fig>: figure
<lgd>: legend of figure
<display_all>: whether to save as Total plot
Saves plot if the action resides in self.available_tests
'''
filename = None
if display_all:
testname = self.action_type.lower()
filename = os.path.join(*self.save_fold.split(os.sep)[:-1] +
['Total', testname + '.pdf'])
else:
if self.test_name is None:
self.test_name = (self.name + ' ' + self.classifiers_used).title()
if self.test_name in self.available_tests:
if self.save_fold is None:
if not self.online:
fold_name = co.file_oper.load_labeled_data(['Testing'],
just_catalog=True,
include_all_catalog=True)[
str(self.tests_ids[
self.available_tests.
index(self.test_name)])]
else:
fold_name = 'Online'
self.save_fold = os.path.join(
co.CONST['results_fold'], 'Classification', fold_name,
self.test_name)
if self.add_info is not None:
self.save_fold = os.path.join(
self.save_fold, self.add_info.replace(' ', '_').lower())
co.makedir(self.save_fold)
LOG.info('Saving to ' + self.save_fold)
if info is not None:
filename = os.path.join(
self.save_fold, (self.testname + ' ' + info +
'.pdf').replace(' ','_'))
else:
filename = os.path.join(
self.save_fold, self.testname.replace(' ','_') + '.pdf')
else:
LOG.warning('Requested figure to plot belongs to an' +
' action that does not reside in <self.'+
'available_tests> .Skipping..')
filename = None
import matplotlib.pyplot as plt
if filename is not None:
if lgd is None:
plt.savefig(filename)
else:
plt.savefig(filename,
bbox_extra_artists=(lgd,), bbox_inches='tight')
plt.close()
def plot_result(self, data, info=None, save=True, xlabel='Frames', ylabel='',
labels=None, colors=None, linewidths=None, alphas=None,
xticks_names=None, yticks_names=None, xticks_locs=None,
yticks_locs=None, markers=None, markers_sizes=None, zorders=None, ylim=None, xlim=None,
display_all=False, title=False):
'''
<data> is a numpy array dims (n_points, n_plots),
<labels> is a string list of dimension (n_plots)
<colors> ditto
'''
import matplotlib
from matplotlib import pyplot as plt
#matplotlib.rcParams['text.usetex'] = True
#matplotlib.rcParams['text.latex.unicode'] = True
# plt.style.classifiers_used('seaborn-ticks')
if len(data.shape) == 1:
data = np.atleast_2d(data).T
fig, axes = plt.subplots()
if xticks_locs is not None:
axes.set_xticks(xticks_locs, minor=True)
axes.xaxis.grid(True, which='minor')
if yticks_locs is not None:
axes.set_yticks(yticks_locs, minor=True)
axes.yaxis.grid(True, which='minor')
if xticks_names is not None:
plt.xticks(range(len(xticks_names)), xticks_names)
if yticks_names is not None:
plt.yticks(range(len(yticks_names)), yticks_names)
if markers is None:
markers = [','] * data.shape[1]
if markers_sizes is None:
markers_sizes = [10] * data.shape[1]
if colors is None:
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
if alphas is None:
alphas = data.shape[1] * [1]
if zorders is None:
zorders = data.shape[1] * [0]
while len(colors) < data.shape[1]:
colors += [tuple(np.random.random(3))]
if linewidths is None:
linewidths = [1] * data.shape[1]
lgd = None
for count in range(data.shape[1]):
if labels is not None:
axes.plot(data[:, count], label='%s' % labels[count],
color=colors[count],
linewidth=linewidths[count],
marker=markers[count], alpha=alphas[count],
zorder=zorders[count],
markersize=markers_sizes[count])
lgd = co.plot_oper.put_legend_outside_plot(axes,
already_reshaped=True)
else:
axes.plot(data[:, count],
color=colors[count],
linewidth=linewidths[count],
marker=markers[count], alpha=alphas[count],
zorder=zorders[count],
markersize=markers_sizes[count])
if title:
if info is not None:
plt.title(self.testname +
'\n Dataset: ' + self.testdataname +
'\n' + info.title())
else:
plt.title(self.testname +
'\n Dataset ' + self.testdataname)
info = ''
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if ylim is not None:
plt.ylim(ylim)
if xlim is not None:
plt.xlim(xlim)
if save:
self.save_plot(fig, lgd, display_all=display_all, info=info)
return fig, lgd, axes
def init_testing(self, data=None, online=True, save=True, load=True,
testname=None, scores_savepath=None,
scores_filter_shape=5,
std_small_filter_shape=co.CONST['STD_small_filt_window'],
std_big_filter_shape=co.CONST['STD_big_filt_window'],
testdatapath=None, save_results=True):
'''
Initializes paths and names used in testing to save, load and visualize
data.
Built as a convenience method, in case <self.run_testing> gets overriden.
'''
self.parameters['testing'] = True
self.parameters['testing_params']['online'] = online
if online:
self.reset_online_test()
else:
self.reset_offline_test()
self.scores_filter_shape = scores_filter_shape
self.std_small_filter_shape = std_small_filter_shape
self.std_big_filter_shape = std_big_filter_shape
self.online = online
if testname is not None:
self.testname = testname.title()
else:
self.testname = (self.name + ' ' + self.classifiers_used).title()
if self.add_info is not None:
self.testname += ' ' + self.add_info.title()
self.parameters['testing_params']['current'] = self.testname
if online:
if testdatapath is not None:
self.testdataname = ('online (using '
+ os.path.basename(testdatapath) + ')')
else:
self.testdataname = 'online'
else:
self.testdataname = os.path.basename(data)
if not self.online:
if self.test_ind is not None:
available_tests_ids = co.file_oper.load_labeled_data(['Testing'],
just_catalog=True,
include_all_catalog=True)
if available_tests_ids is None:
fold_name = '0'
else:
curr_test_id = self.tests_ids[self.available_tests.
index(self.test_name)]
if str(curr_test_id) in available_tests_ids:
fold_name = str(available_tests_ids[str(curr_test_id)])
else:
fold_name = str(len(available_tests_ids))
else:
self.test_name = 'Online'
try:
fold_name = os.path.join(*[co.CONST['results_fold'],
'Classification', 'Online'])
except OSError:
fold_name = '0'
if self.test_ind is not None:
self.save_fold = os.path.join(
co.CONST['results_fold'], 'Classification', self.test_name,
fold_name)
co.makedir(self.save_fold)
if save or load:
fold_name = self.classifier_folder
if scores_savepath is None:
self.scores_savepath = self.testdataname + '_scores_for_'
self.scores_savepath += self.full_info.replace(' ',
'_').lower()
self.scores_savepath += '.pkl'
else:
self.scores_savepath = scores_savepath
return True
def run_testing(self, data=None, derot_angle=None, derot_center=None,
online=True,
scores_filter_shape=5,
std_small_filter_shape=co.CONST['STD_small_filt_window'],
std_big_filter_shape=co.CONST['STD_big_filt_window'],
ground_truth_type=None,
img_count=None, save=True, scores_savepath=None,
load=False, testname=None, display_scores=True,
construct_gt=True, just_scores=False, testdatapath=None,
compute_perform=True,
save_results=True):
'''
Test Classifiers using data (.png files) located in <data>. If <online>, the
testing is online, with <data> being a numpy array, which has been
firstly processed by <hand_segmentation_alg>. The scores retrieved from
testing are filtered using a box filter of shape <box_filter_shape>.
The running mean along a buffer
of the data is computed with a running window of length
<mean_filter_shape>. The ground truth for the testing data is given by
<ground_truth_type> (for further info about the variable refer to
<co.gd_oper.construct_ground_truth>). If the training is online, the count of
the frame is passed by <img_count>. If <save> is True,
testing results are saved to <scores_savepath>, or a path constructed
by the configuration. <testname> overrides the first line of the plots.
If <load> is True and <scores_save_path> exists, testing is bypassed and all the
necessary results are loaded from memory. If <just_scores> is True, the
classification stage is not done and only scores are computed. If
<testdatapath> is not <None> and <online> is True, then it will be
assumed that a pseudoonline testing is taking place
'''
loaded = False
if not online:
LOG.info('Testing:' + data)
try:
self.test_ind = self.available_tests.index(data)
self.test_name = data
except BaseException:
if data.split(os.sep)[-1] in self.available_tests:
self.test_ind = (
self.available_tests.index(data.split(os.sep)[-1]))
self.test_name = data.split(os.sep)[-1]
elif data in self.dynamic_actions or data in self.passive_actions:
self.test_ind = None
elif data.split(os.sep)[-1] in self.dynamic_actions or \
data.split(os.sep)[-1] in self.passive_actions:
self.test_ind = None
else:
raise Exception('test data must be inside test_save_path,' +
' check config.yaml')
if construct_gt and ground_truth_type is None:
ground_truth_type =os.path.join(
co.CONST['ground_truth_fold'],
self.test_name + '.csv')
elif isinstance(data, tuple):
derot_angle = data[1]
derot_center = data[2]
data = data[0]
if not self.testing_initialized or not online:
if not self.init_testing(data=data,
online=online,
save=save,
load=load,
testname=testname,
scores_savepath=scores_savepath,
scores_filter_shape=scores_filter_shape,
std_small_filter_shape=std_small_filter_shape,
std_big_filter_shape=std_big_filter_shape,
testdatapath=testdatapath,
save_results=save_results):
return False
if not online:
if self.test_ind is not None and (
load and self.accuracies[self.available_tests.index(self.test_name)]
is not None):
LOG.info('Tests already performed, loaded data')
try:
self.scores = self.results['Scores']
loaded = True
except:
pass
if not loaded:
if self.test_ind is not None:
testdata = self.offline_testdata_processing(
os.path.join(co.CONST['test_save_path'],
self.test_name))
else:
testdata = self.offline_testdata_processing(
data)
try:
self.test_ind = self.available_tests.index(data)
except BaseException: self.test_ind = None
LOG.info(self.full_info + ':')
LOG.info('Testing Classifiers using testdata with size: '
+ str(testdata.shape))
fmask = np.prod(np.isfinite(testdata), axis=1).astype(bool)
fin_scores = self.unified_classifier.decide(
testdata[fmask, :])
self.scores = np.zeros(
(testdata.shape[0], fin_scores.shape[1]))
self.scores[:] = None
self.scores[fmask] = fin_scores
if self.test_ind is not None:
self.testdata[self.test_ind]['Results']['Scores'] = self.scores
if construct_gt:
LOG.info('Constructing ground truth vector..')
self.test_ground_truth, self.test_breakpoints = co.gd_oper.construct_ground_truth(
os.path.join(co.CONST['test_save_path'], self.test_name),
classes_namespace=self.train_classes,
length=self.scores.shape[0],
ground_truth_type=ground_truth_type,
ret_breakpoints=True)
utterances_inds = co.gd_oper.merge_utterances_vectors(
co.gd_oper.create_utterances_vectors(
self.test_breakpoints, len(self.test_ground_truth)),
self.train_classes)
if not just_scores:
self.classify_offline(save=save, display=display_scores,
compute_perform=compute_perform,
extraction_method=
self.parameters[
'testing_params']['post_scores_processing_method'])
self.correlate_with_ground_truth(save=save,
display=display_scores,
compute_perform=compute_perform,
utterances_inds=utterances_inds)
self.display_scores_and_time(save=save)
if self.test_ind is not None:
co.file_oper.save_labeled_data(['Testing'] +self.tests_ids[
self.test_ind], self.testdata[self.test_ind])
if not just_scores:
if display_scores:
if self.parameters['testing_params'][
'post_scores_processing_method'] == 'CSTD':
self.plot_result(np.concatenate((
self.less_filtered_scores_std[:, None],
self.high_filtered_scores_std[:, None]), axis=1),
info='Scores Statistics',
xlabel='Frames',
labels=['STD', 'STD Mean'],
colors=['r', 'g'],
save=save)
mean_diff = (np.array(self.high_filtered_scores_std) -
np.array(self.less_filtered_scores_std))
mean_diff = (mean_diff) / float(np.max(np.abs(mean_diff[
np.isfinite(mean_diff)])))
plots = [mean_diff]
labels = ['ScoresSTD - ScoresSTDMean']
if self.test_ground_truth is not None:
plots += [((self.test_ground_truth - np.mean(self.test_ground_truth[
np.isfinite(self.test_ground_truth)])) / float(
np.max(self.test_ground_truth[
np.isfinite(self.test_ground_truth)])))[:, None]]
labels += ['Ground Truth']
self.plot_result(np.concatenate(plots, axis=1), labels=labels,
info='Metric of actions starting and ending ' +
'points', xlabel='Frames', save=save)
if display_scores:
self.plot_result(self.scores,
labels=self.train_classes,
info='Scores',
xlabel='Frames',
save=save,
)
return True, self.scores
else:
'''
input is processed from hand_segmentation_alg (any data
processed in such way, that the result is the same with my processing,
is acceptable, eg. Dexter)
There must be a continuous data streaming (method called in every
loop), even if the result of the previous algorithm is None
'''
scores_exist, score = self.process_online_data(data, img_count,
derot_angle,
derot_center,
just_scores=just_scores)
return scores_exist, score
def visualize_action(self, action, save=True,
save_name=None, *args, **kwargs):
'''
Visualizes action or a testing dataset using predefined locations in
config.yaml and the method co.draw_oper.plot_utterances
'''
dataset_loc = '/media/vassilis/Thesis/Datasets/PersonalFarm/'
results_loc = '/home/vassilis/Thesis/KinectPainting/Results/DataVisualization'
ground_truth, breakpoints, labels = co.gd_oper.load_ground_truth(action, ret_labs=True,
ret_breakpoints=True)
testing =True
images_base_loc = os.path.join(dataset_loc, 'actions',
'sets' if not testing else 'whole_result')
images_loc = os.path.join(
images_base_loc, action.replace(
'_', ' ').title())
imgs, masks, sync, angles, centers, samples_indices = co.imfold_oper.load_frames_data(
images_loc, masks_needed=True)
import cv2
masks_centers = []
xdim = 0
ydim = 0
conts = []
tmp = []
for mask, img in zip(masks, imgs):
conts = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[1]
conts_areas = [cv2.contourArea(cont) for cont in conts]
tmp.append(np.sum(mask*img >0))
if np.sum(mask*img >0) < 500:
masks_centers.append(None)
else:
cont = conts[np.argmax(conts_areas)]
x, y, w, h = cv2.boundingRect(cont)
if w == 0 or h == 0:
masks_centers.append(None)
else:
masks_centers.append([y +h/2, x+w/2])
xdim = max(w, xdim)
ydim = max(h, ydim)
cropped_imgs = []
for img, center in zip(imgs, masks_centers):
if center is not None:
cropped_img = img[max(0, center[0]-ydim/2)
:min(img.shape[0], center[0]+ydim/2),
max(0, center[1]-xdim/2)
:min(img.shape[0], center[1]+xdim/2)]
inp_img = np.zeros((ydim, xdim))
inp_img[:cropped_img.shape[0],
:cropped_img.shape[1]] = cropped_img
cropped_imgs.append(inp_img)
else:
cropped_imgs.append(None)
fig = co.draw_oper.plot_utterances(frames=cropped_imgs,
frames_sync=sync,
ground_truth=ground_truth,
breakpoints= breakpoints,
labels=labels,
dataset_name=action,
*args, **kwargs)
if save:
if save_name is None:
save_name = 'Full' + action
fig.savefig(os.path.join(results_loc,
save_name + '.pdf'))
return fig
'''
categories_to_zoom=None,
#categories_to_zoom = self.dynamic_actions,
show_breaks=True, show_occ_tab=False,
show_zoomed_occ=True, show_im_examples=False,
show_fig_title=True,
examples_num=15
'''
def apply_to_training(
self, method, excluded_actions=None, *args, **kwargs):
'''
Apply a method to training data
'''
prev_root = ''
prev_action = ''
res = []
actions = (self.passive_actions +
self.dynamic_actions)
if excluded_actions is not None:
for action in excluded_actions:
actions.remove(action)
paths = os.listdir(co.CONST['actions_path'])
for action in actions:
if action not in paths:
actions.remove(action)
if not actions:
raise Exception('Badly given actions_path in config.yaml')
dirs = [os.path.join(co.CONST['actions_path'], action) for action in
actions]
for direc in dirs:
for root, dirs, _ in os.walk(direc):
separated_root = os.path.normpath(
root).split(
os.path.sep)
if root != prev_root and str.isdigit(
separated_root[-1]) and separated_root[
-2] != co.CONST['hnd_mk_fold_name']:
prev_root = root
if separated_root[-2] == co.CONST['mv_obj_fold_name']:
action = separated_root[-3]
action_path = (os.path.sep).join(separated_root[:-2])
else:
action = separated_root[-2]
if excluded_actions is not None:
if action in excluded_actions:
continue
if action != prev_action:
LOG.info('Processing action: ' + action)
res.append(method(action_path=action_path,
action_name=action,
*args, **kwargs))
prev_action = action
try:
return map(list, zip(*res))
except TypeError:
return res
def display_scores_and_time(self, save=False):
'''
Displays scores and elapsed time
'''
if self.online:
self.plot_result(np.array(self.scores),
labels=self.train_classes,
xlabel='Frames',
save=save)
LOG.info(self.name.title())
if self.test_ind is not None:
test_times = self.compute_testing_time(self.available_tests[
self.test_ind])
LOG.info('Mean Testing Times:\n\t' +str(test_times))
if not self.online:
self.testdata[self.test_ind]['TestTime'] = test_times
def process_single_sample(self, data, img_count,
derot_angle=None, derot_center=None):
if data is None:
self.scores.append(None)
return False, np.array([[None] *
len(self.train_classes)]).astype(
np.float64)
if not self.frames_preproc.update(data,
angle=derot_angle,
center=derot_center,
masks_needed=True,
img_count=self.img_count,
isderotated=False):
return False, np.array([None] * len(self.train_classes))
descriptors = [descriptor.extract() for
descriptor in self.features_extractors]
if not any([desc is None for desc in descriptors]):
for count in range(len(descriptors)):
if self.sparsecoded == 'Features':
descriptors[count] = (self.action_recog.actions.
coders[count].code(descriptors[count]))
self.buffer_operators[count].update_buffer_info(
self.img_count, samples=descriptors[count])
self.buffer_operators[count].add_buffer()
descriptors[count] = self.buffer_operators[count].buffer
if descriptors[count] is None:
return False, np.array([[None] *
len(self.train_classes)]).astype(
np.float64)
if self.sparsecoded == 'Buffer':
descriptors[count] = (self.action_recog.actions.
coders[count].code(descriptors[count]))
if self.ptpca:
descriptors[count] = self.buffer_operators[
count].perform_post_time_pca(
descriptors[count])
else:
return False, np.array([[None] *
len(self.train_classes)]).astype(
np.float64)
inp = np.hstack(tuple(descriptors))
try:
score = (self.unified_classifier.decide(inp))
except Exception as e:
raise
return True, np.array(score).reshape(1, -1)
def process_online_data(self, data, img_count=None,
derot_angle=None, derot_center=None,
just_scores=False):
'''
<data> is the frame with frame number <img_count> or increasing by one
relatively to the previous frame. Scores are filtered with a filter of
length <self.scores_filter_shape>. <self.std_small_filter_shape> is the shape
of the filter used to remove the temporal noise from the scores std.
<self.std_big_filter_shape> is the shape of the filter to compute the mean
of the scores std. Returns True if scores have been computed
'''
self.img_count += 1
self.mean_from += 1
# self.buffer_exists = self.buffer_exists[
# -self.std_big_filter_shape:]
if not self.action_type == 'Passive':
if not self.img_count or (img_count == 0):
self._buffer = []
self.mean_from = 0
self.buffer_exists = []
self.scores = []
self.scores_std_mean = []
self.scores_std = []
self.small_std_running_mean_vec = []
self.big_std_running_mean_vec = []
self.scores_running_mean_vec = []
self.act_inds = []
self.crossings = []
self.count_prev = self.img_count - 1
if img_count is not None:
self.scores += [None] * (img_count - self.img_count - 1)
self.mean_from = img_count - self.img_count + self.mean_from
self.img_count = img_count
elif not self.img_count:
self.scores = []
valid, score = self.process_single_sample(data, img_count,
derot_angle,
derot_center)
self.scores.append(score)
if not valid:
return valid, score
if not just_scores:
self.classify_online(score, self.img_count,
self.mean_from)
return True, np.array(score).reshape(1, -1)
@timeit
def classify_online(self, score, img_count, mean_from):
'''
To be used after scores from <online_processing_data> have been
computed. It is a convenience function to allow the modification of
the scores, if this is wanted, before performing classification
'''
if self.action_type == 'Passive':
self.scores_filter_shape = 3
if len(self.scores_running_mean_vec) < self.scores_filter_shape:
self.scores_running_mean_vec.append(score.ravel())
else:
self.scores_running_mean_vec = (self.scores_running_mean_vec[1:]
+ [score.ravel()])
# filter scores using a mean window
self.scores[-1] = np.mean(np.array(self.scores_running_mean_vec), axis=0)
if not self.action_type == 'Passive':
start_from = min(self.scores_filter_shape, mean_from)
score_std = np.std(self.scores[-1])
if len(self.small_std_running_mean_vec) < self.std_small_filter_shape:
self.small_std_running_mean_vec.append(score_std)
else:
self.small_std_running_mean_vec = (
self.small_std_running_mean_vec[1:] +
[score_std])
filtered_score_std = np.mean(self.small_std_running_mean_vec)
self.scores_std.append(filtered_score_std)
if len(self.big_std_running_mean_vec) < self.std_big_filter_shape:
self.big_std_running_mean_vec.append(filtered_score_std)
else:
self.big_std_running_mean_vec = (self.big_std_running_mean_vec[1:]
+ [filtered_score_std])
if mean_from >= self.std_big_filter_shape:
start_from = 0
else:
start_from = - mean_from
self.scores_std_mean.append(
np.mean(self.big_std_running_mean_vec[-start_from:]))
std_mean_diff = self.scores_std_mean[
-1] - self.scores_std[-1]
if (np.min(std_mean_diff) > co.CONST['action_separation_thres'] and not
self.on_action) or not self.recognized_classes:
self.crossings.append(img_count)
self.on_action = True
if self.recognized_classes is not None:
self.recognized_classes.add(length=img_count -
self.new_action_starts_count +
1)
LOG.info('Frame ' + str(img_count) + ': ' +
self.recognized_classes.name +
', starting from frame ' +
str(self.recognized_classes.start) +
' with length ' +
str(self.recognized_classes.length))
else:
self.recognized_classes = RecognitionVectorizer(
self.train_classes)
index = np.argmax(self.scores[-1])
self.max_filtered_score = self.scores[-1][index]
self.act_inds = [index]
self.new_action_starts_count = img_count
LOG.info('Frame ' + str(img_count) + ': ' +
self.recognized_classes.name)
self.saved_buffers_scores = []
return None
else:
if len(self.recognized_classes) > 0:
_arg = np.argmax(self.scores[-1])
if self.max_filtered_score < self.scores[
-1][_arg]:
self.max_filtered_score = self.scores[
-1][_arg]
self.recognized_classes[-1].add(index=_arg)
LOG.info('Frame ' + str(img_count) + ': ' +
self.recognized_classes[-1].name)
if std_mean_diff < co.CONST['action_separation_thres']:
self.on_action = False
self.saved_buffers_scores.append(score)
return None
else:
return None
else:
if np.max(self.scores[-1]) >= 0.6 or len(
self.recognized_classes) == 0:
self.recognized_classes.append(
self.scores[-1].argmax())
else:
self.recognized_classes.append(
self.recognized_classes[-1])
LOG.info('Pose detected:'
+ self.train_classes[self.recognized_classes[-1]])
return self.train_classes[self.recognized_classes[-1]]
def extract_actions(self, scores, method='CProb', tol=0.7,
filterr=True):
if filterr:
scores = co.noise_proc.masked_filter(scores,
self.scores_filter_shape)
extracted_actions = []
if method == 'CProb':
for count, score in enumerate(scores):
if not np.prod(np.isfinite(score)).astype(bool):
extracted_actions.append(np.nan)
continue
if (np.max(score) >= tol or len(
extracted_actions) == 0 or
np.isnan(extracted_actions[-1])):
extracted_actions.append(score.argmax())
else:
extracted_actions.append(
extracted_actions[-1])
return extracted_actions, None
elif method == 'CSTD':
fmask = np.prod(np.isfinite(scores), axis=1).astype(bool)
scores_std = np.zeros(scores.shape[0])
scores_std[:] = None
scores_std[fmask] = np.std(scores[fmask, :],
axis=1)
less_filtered_scores_std = co.noise_proc.masked_filter(
scores_std, self.std_small_filter_shape)
high_filtered_scores_std = co.noise_proc.masked_filter(
scores_std,
self.std_big_filter_shape)
positive = np.zeros(scores.shape[0])
positive[:] = None
positive[fmask] = ((high_filtered_scores_std -
less_filtered_scores_std).ravel()[fmask] > 0).astype(int)
# We are interested only in finding negative to positive zero crossings,
# because this is where std falls below its mean
neg_to_pos_zero_crossings = np.where(positive[1:] -
positive[:-1] ==
-1)[0]
crossings = neg_to_pos_zero_crossings
interesting_crossings = np.concatenate((np.array([0]),
neg_to_pos_zero_crossings,
np.array([scores.shape[0]])),
axis=0)
for cross1, cross2 in zip(interesting_crossings[
:-1], interesting_crossings[1:]):
act_scores = scores[cross1:cross2, :]
mask = fmask[cross1:cross2]
if not np.any(mask):
act = np.zeros(cross2 - cross1)
act[:] = None
extracted_actions.append(act)
continue
index = np.mean(
act_scores[mask, :], axis=0).argmax()
'''
index = np.median(
act_scores[mask, :], axis=0).argmax()
'''
act = index * np.ones(cross2 - cross1)
act[np.logical_not(mask)] = None
extracted_actions.append(act)
extracted_actions = np.concatenate(
tuple(extracted_actions), axis=0)
return extracted_actions, (less_filtered_scores_std,
high_filtered_scores_std,
crossings)
@timeit
def classify_offline(self, display=True,
save=True, compute_perform=True,
extraction_method=None, tol=0.7):
'''
To be used after offline have been computed. It is a convenience
function to allow the modification of the scores, if this is wanted,
before performing classification.
Process scores using stds as proposed by the paper
'''
if 'Sync' in self.classifiers_used:
if extraction_method is None:
extraction_method = 'CProb'
if not isinstance(extraction_method, list):
extraction_method = [extraction_method] * len(self.scores)
if not isinstance(tol, list):
tol = [tol] * len(self.scores)
self.recognized_classes = {}
for count, key in enumerate(self.scores):
(extracted_actions, more) = self.extract_actions(
self.scores[key], method=extraction_method[count],
tol=tol[count])
self.recognized_classes[key] = extracted_actions
else:
(self.recognized_classes,
more) = self.extract_actions(
self.scores, method=extraction_method)
if extraction_method == 'CSTD':
if self.test_ind is not None:
self.testdata[self.test_ind][
'Results'][
'LessFilteredScoresSTD'] = more[0]
self.testdata[self.test_ind][
'Results'][
'HighFilteredScoresSTD'] = more[1]
self.testdata[self.test_ind][
'Results'][
'Crossings'] = more[2]
self.less_filtered_scores_std = more[0]
self.high_filtered_scores_std = more[1]
self.crossings = more[2]
if self.test_ind is not None:
self.testdata[self.test_ind]['Results'][
'Actions'] = self.recognized_classes
return self.recognized_classes
def compute_performance_measures(
self, recognized_classes, ground_truths, act_namespaces,
utterances_annotation=None, save=True):
'''
Extract confusion matrix, accuracy and f scores from the given
<recognized_classes> predicted classes and <ground_truths> actual
classes. If <utterances_annotation> is given, metrics are
calculated (utterance level), else micro metrics are computed (frames
level)
'''
from sklearn import metrics
from scipy.linalg import block_diag
LOG.info('Computing performance measures for ' +
self.classifier_savename + ' with dataset:' +
self.testdataname)
y_trues = []
y_preds = []
utters = []
weights = []
confusion_matrices = []
f1_scores = []
existing_classes = []
accuracies = []
if not 'Sync' in self.classifiers_used:
recognized_classes = {self.action_type: recognized_classes}
ground_truths = {self.action_type: ground_truths}
act_namespaces = {self.action_type: act_namespaces}
if utterances_annotation is not None:
utterances_annotation = {
self.action_type: utterances_annotation}
if utterances_annotation is not None:
prefix = 'macro'
else:
prefix = 'micro'
undef_exists = False
undef_vec = []
for act_type in recognized_classes:
ground_truth = np.array(ground_truths[act_type]).ravel()
recognized_actions = np.array(recognized_classes[act_type])
act_names = act_namespaces[act_type]
fmask = np.isnan(ground_truth)
ground_truth[fmask] = -1
y_trues.append(ground_truth.astype(int))
recognized_actions[np.isnan(recognized_actions)] = -1
y_preds.append(np.array(recognized_actions))
y_preds[-1][np.isnan(y_preds[-1])] = -1
if utterances_annotation is not None:
utters.append(np.array(utterances_annotation[act_type]))
y_trues[-1], y_preds[-1] = co.macro_metrics.construct_vectors(
y_trues[-1], y_preds[-1], utters[-1])
weights.append(len(np.unique(ground_truth)))
fmask = y_trues[-1] != -1
y_trues[-1] = y_trues[-1][fmask]
y_preds[-1] = y_preds[-1][fmask]
flag_to_set_undef = np.sum(
y_preds[-1][:, None]
== np.unique(y_trues[-1])[None, :], axis=1) == 0
y_preds[-1][flag_to_set_undef] = -1
fsc = metrics.f1_score(y_trues[-1],
y_preds[-1],
average=None)
if -1 in y_preds[-1]:
fsc = fsc[1:]
f1_scores.append(np.atleast_2d(fsc))
accuracies.append(metrics.accuracy_score(y_trues[-1],
y_preds[-1]))
# now clean undefined from predicted too
conf_mat = metrics.confusion_matrix(
y_trues[-1], y_preds[-1])
if -1 in y_preds[-1]:
conf_mat = conf_mat[1:, :]
undef_vec.append(conf_mat[:,0])
conf_mat = conf_mat[:, 1:]
else:
undef_vec.append(np.zeros(conf_mat.shape[0]))
confusion_matrices.append(conf_mat)
classes = set(y_trues[-1].tolist() +
y_preds[-1].tolist())
classes.discard(-1)
classes = np.array(list(classes)).astype(int)
existing_classes += (np.array(
act_names)[classes]).tolist()
labels = existing_classes
labels_w_undef = (['Undefined'] + existing_classes if undef_exists
else existing_classes)
f1_scores = np.concatenate(f1_scores, axis=1)
actions_id = []
for clas in labels_w_undef:
actions_id.append(self.all_actions.index(clas) -1)
undef_vec = [vec for vec_list in undef_vec for vec in vec_list ]
confusion_matrix = block_diag(*tuple(confusion_matrices))
confusion_matrix = np.concatenate((confusion_matrix,
np.array(undef_vec).reshape(-1, 1)),
axis=1).astype(int)
accuracy = sum([accuracy * weight for accuracy, weight in
zip(accuracies, weights)]) / float(sum(weights))
if not self.online:
self.testdata[self.test_ind]['Accuracy'][
prefix.title()] = accuracy
self.testdata[self.test_ind]['PartialAccuracies'][
prefix.title()] = accuracies
self.testdata[self.test_ind]['FScores'][
prefix.title()] = [f1_scores, actions_id]
self.testdata[self.test_ind][
'ConfMat'][prefix.title()] = [confusion_matrix,
actions_id]
self.testdata[self.test_ind][
'Labels'][prefix.title()] = labels
LOG.info(prefix.title() + ' F1 Scores: \n' +
np.array2string(f1_scores))
LOG.info(
prefix.title() + ' Confusion Matrix: \n' +
np.array2string(
confusion_matrix))
if 'Sync' in self.classifiers_used:
LOG.info(prefix.title() + ' Partial Accuracies:' + str(accuracies))
LOG.info(prefix.title() + ' Accuracy: ' + str(accuracy))
LOG.info('Labels of actions:' + str(labels))
def write_metrics_to_file(self):
accuracies = self.testdata[self.test_ind]['Accuracy']
partial_accuracies = self.testdata[
self.test_ind]['PartialAccuracies']
if 'Sync' in self.classifiers_used:
acc_labels = (['Class.' + str(clas) for clas in
self.parameters['sub_classifiers']] +
['Total Mean'])
for cnt,acc_label in enumerate(acc_labels):
if 'mathregular' in acc_label:
import re
acc_labels[cnt] = re.sub('\\\\mathregular{(.*)}',
lambda x: x.group(1), acc_label)
ylabels = []
data = []
extra_locs = []
for key in partial_accuracies:
ylabels.append(key)
if not data:
data += [partial_accuracies[key], accuracies[key]]
extra_locs = ['right']
else:
data += [np.hstack((partial_accuracies[key],
accuracies[key]))]
extra_locs.append('bot')
with open(os.path.join(self.save_fold, 'sync_accuracy.tex'), 'w') as out:
out.write(co.latex.array_transcribe(data,
xlabels=acc_labels,
ylabels=ylabels,
sup_x_label='Accuracy',
extra_locs=extra_locs))
f1_scores = self.testdata[self.test_ind]['FScores']
for typ in f1_scores:
with open(os.path.join(self.save_fold, typ.title() +'_F1_Scores.tex'), 'w') as out:
out.write(co.latex.array_transcribe([f1_scores[typ][0],
np.atleast_2d(accuracies[typ])],
xlabels=np.concatenate((self.testdata[
self.test_ind]['Labels'][typ],
['Accuracy']), axis=0),
sup_x_label=typ.title() +
' Metrics',
extra_locs=['right']))
confmats = self.testdata[self.test_ind]['ConfMat']
for typ in confmats:
with open(os.path.join(self.save_fold,
typ.title()+'_Confusion_Matrix.tex'), 'w') as out:
ylabels = self.testdata[self.test_ind]['Labels'][typ]
xlabels = ylabels[:]
if confmats[typ][0].shape[0] != confmats[typ][0].shape[1]:
xlabels += ['Undefined']
out.write(co.latex.array_transcribe(confmats[typ][0],
ylabels=ylabels,
xlabels=xlabels,
sup_x_label='Predicted',
sup_y_label='Actual',
title=typ.title() +
' Metrics',
wrap=False))
def construct_classifiers_matrix(self):
'''
Constructs a table which shows most parameters of the trained
classifiers and saves it as a pdf inside Total Results folder
'''
from textwrap import TextWrapper
wrapper = TextWrapper(width=15, break_long_words=False,
break_on_hyphens=False, replace_whitespace=False)
all_parameters = [(self.trained_classifiers[name][2], self.classifiers_list[name])
for name in self.trained_classifiers if name in
self.classifiers_list]
all_parameters = sorted(all_parameters, key=lambda pair: pair[1])
params_rows = []
for parameters in all_parameters:
row = []
row.append(parameters[1])
row.append(parameters[0]['classifier'])
row.append('\n'.join(
parameters[0]['descriptors']))
row.append(parameters[0]['sparsecoded'])
if parameters[0]['sparsecoded']:
row.append('\n'.join(
['%d' % parameters[0]['sparse_params'][feature]
for feature in parameters[0]['descriptors']]))
else:
row.append('')
row.append(parameters[0]['passive'])
if (not parameters[0]['passive'] or
'Sync' in parameters[0]['classifier']):
'''
if parameters[0]['classifier']=='Double':
row.append('%d'%parameters[0]['classifier_params'][
'RDF_n_estimators'])
else:
row.append('')
'''
row.append('')
row.append(
str(parameters[0]['classifier_params']['SVM_kernel']))
try:
row.append('%d' % parameters[0]['dynamic_params'][
'buffer_size'])
except BaseException: row.append('')
try:
if parameters['testing_params'][
'post_scores_processing_method'] == 'CSTD':
row.append('%d' % parameters[0]['dynamic_params'][
'filter_window_size'])
except BaseException: row.append('')
try:
row.append(str(parameters[0]['PTPCA']))
except BaseException: row.append('')
if row[-1] != '' and row[-1] == 'True':
try:
row.append('%d' % parameters[0]['PTPCA_params'][
'PTPCA_components'])
except BaseException: row.append('')
else:
row.append('')
else:
row.append('%d' % parameters[0]['classifier_params'][
'RDF_n_estimators'])
[row.append('') for count in range(5)]
params_rows.append(row)
params_valids = np.tile(
(np.array(params_rows) != '')[..., None], (1, 1, 3))
params_valids = params_valids * 0.5
params_valids += 0.5
params_rows = [[wrapper.fill(el) if
isinstance(el, basestring) else el
for el in row] for row in params_rows]
params_col_names = ('Classifier', 'Type', 'Features', 'Sparse',
'Sparse Features\ndimension',
'Actions', 'Estimators', 'Kernel',
'Buffer size', 'Filter size', 'post PCA',
'post PCA\ncomponents')
all_results = [(self.classified_dict[item],
self.classifiers_list[item])
for item in self.classified_dict if item in
self.classifiers_list]
results_rows = []
for results in all_results:
row = []
row.append(str(results[1]))
mean = 0
for test in self.available_tests:
try:
row.append('%1.2f' % results[0][test][1][0])
except KeyError:
row.append('')
mean += results[0][test][1][0]
row.append('%1.2f' % (mean / float(len(results[0]))))
results_rows.append(row)
if results_rows:
results_col_names = ['Classifier'] + \
self.available_tests + ['Mean']
results_valids = np.tile(
(np.array(results_rows) != '')[..., None], (1, 1, 3))
results_rows = sorted(results_rows, key=lambda pair:
float(pair[-1]), reverse=True)
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import pyplot as plt
import datetime
#matplotlib.rcParams.update({'font.size': 22})
if self.save_fold is None:
save_fold = os.path.join(
co.CONST['results_fold'], 'Classification', 'Total')
co.makedir(save_fold)
filename = os.path.join(save_fold,
'matrices.pdf')
else:
filename = os.path.join(*self.save_fold.split(os.sep)[:-1] +
['Total', 'matrices.pdf'])
with PdfPages(filename) as pdf:
fig = plt.figure()
axes = fig.add_subplot(111)
params_table = co.table_oper.construct(axes, cellText=params_rows,
colLabels=params_col_names,
cellColours=params_valids,
cellLoc='center',
loc='center', usetex=True)
# params_table.auto_set_font_size(False)
params_table.scale(2, 2)
# params_table.set_fontsize(10)
co.table_oper.fit_cells_to_content(
fig, params_table, equal_height=True)
plt.axis('off')
pdf.savefig(
bbox_extra_artists=(
params_table,
),
bbox_inches='tight')
plt.close()
if results_rows:
fig = plt.figure()
axes = fig.add_subplot(111)
results_table = co.table_oper.construct(
axes,
cellText=results_rows,
colLabels=results_col_names,
cellColours=results_valids,
cellLoc='center',
loc='center')
co.table_oper.fit_cells_to_content(fig,
results_table,
equal_height=True)
results_table.scale(2, 2)
plt.axis('off')
pdf.savefig(
bbox_extra_artists=(
results_table,
),
bbox_inches='tight')
plt.close()
idd = pdf.infodict()
idd['Author'] = u'Vassilis Lemonidis'
idd['Subject'] = 'Unified Comparative View'
idd['Keywords'] = 'PdfPages multipage keywords author title subject'
idd['CreationDate'] = datetime.datetime.today()
def load_tests_mapping(self):
tests_catalog = co.file_oper.load_labeled_data(['Testing'],
fold_lev=1, just_catalog=True, include_all_catalog=
True)
return tests_catalog
def return_description(self, catalog, value):
try:
return catalog.keys()[catalog.values().index(value)]
except BaseException: LOG.warning('No such value inside catalog')
def load_all_test_instances(self, test_ind):
available_test_instances = {}
test_name = self.available_tests[test_ind]
import ast
loaded_instances, keys_list = co.file_oper.load_labeled_data(['Testing'],
fold_lev=1, all_inside=True)
for _id in loaded_instances:
loaded_instance = loaded_instances[_id]
if dict(keys_list[_id][0])['Test'] == test_name:
available_test_instances[_id] = loaded_instance
return available_test_instances
def extract_test_results_instances(self, test_ind, key,*keys):
if self.test_instances is None:
self.test_instances = self.load_all_test_instances(test_ind)
res = []
for entry in co.dict_oper.create_sorted_dict_view(self.test_instances):
if entry[1] is None:
res.append(None)
else:
res.append(co.dict_oper.lookup(entry[0], key,*keys))
return res
def correlate_with_ground_truth(self, save=True, display=False,
display_all=False, compute_perform=True,
utterances_inds=None):
'''
Plot results with title <title>
<display_all> if a plot of all the classifiers results is wanted
Do not classifiers_used this function if more than one classifiers are to be run in
parallel
'''
if self.parameters['testing_params']['online']:
recognized_classes = self.recognized_classes.recognition_vector
if isinstance(self.crossings, list):
self.crossings = np.array(self.crossings)
if self.test_ground_truth is not None and compute_perform:
self.compute_performance_measures(
self.recognized_classes,
ground_truths=self.test_ground_truth,
act_namespaces=self.train_classes,
save=save)
if utterances_inds is not None:
self.compute_performance_measures(
self.recognized_classes,
ground_truths=self.test_ground_truth,
utterances_annotation= utterances_inds,
act_namespaces=self.train_classes,
save=save)
else:
LOG.warning('Utterances Indices not passed to' +
' function. MacroMetrics won\'t be' +
' computed.')
if save and self.save_fold is not None:
self.write_metrics_to_file()
if save:
display = True
if display:
if display_all:
self.construct_classifiers_matrix()
iterat = []
iterat_name = []
for name in self.classifiers_list:
parameters = self.classified_dict[name][
self.testdataname][2]
recognized_actions = self.classified_dict[name][
self.testdataname][0]
if (parameters['action_type'] == self.action_type):
if 'Sync' in parameters['classifier']:
iterat.append(recognized_actions[self.action_type])
else:
iterat.append(recognized_actions)
iterat_name.append(int(self.classifiers_list[name]))
# sort iterat based on the index of classifier inside
# classifiers_list
iterat = [x for (_, x) in sorted(zip(iterat_name, iterat),
key=lambda pair: pair[0])]
# provide argsort using accuracy measures, to alter line width
higher_acc = sorted(range(len(iterat)), key=lambda
l: l[1][0], reverse=True)
else:
try:
iterat = [self.testdata[self.test_ind][
'Results']['Actions']]
available_ids = co.file_oper.load_labeled_data(
['Classifier'], just_catalog=True
)
if available_ids is not None:
try:
iterat_name = available_ids[str(
self.classifier_id)]
except KeyError:
iterat_name = str(len(available_ids))
else:
iterat_name = str(0)
higher_acc = [0]
if 'Sync' in self.classifiers_used:
new_iter = []
ref = 0
for key in iterat[0]:
new_iter.append(iterat[0][key])
new_iter[-1] = [item + ref for
item in new_iter[-1]]
ref += len(self.parameters['actions_params'][key])
iterat = new_iter
iterat_name = self.parameters['sub_classifiers']
higher_acc.append(1)
except KeyError as err:
LOG.warning(
str(err) + ' is missing from the tested datasets')
return False
plots = []
linewidths = []
labels = []
markers = []
markers_sizes = []
alphas = []
zorders = []
colors = []
xticks = None
width = 1
dec_q = 0.3
min_q = 0.2
from matplotlib.cm import get_cmap
available_colors = get_cmap('tab20b')
if self.crossings is not None:
xticks = self.crossings
expanded_xticks = np.zeros_like(self.test_ground_truth)
expanded_xticks[:] = None
expanded_xticks[xticks] = -1
plots.append(expanded_xticks)
alphas.append(1)
markers.append('o')
markers_sizes.append(5)
if 'Sync' in self.classifiers_used:
labels.append('Utterances\n'+
'Predicted\n'+
'break-\npoints\n'+
'by Cl_${dyn}$')
else:
labels.append('Utterances\n'+
'Predicted\n'+
'break-\npoints')
colors.append('green')
linewidths.append(1)
zorders.append(2)
for count in range(len(higher_acc)):
syncplots = []
plots.append(iterat[count])
if len(higher_acc) == 1:
labels.append('Predictions')
else:
labels.append('Class. ' +
str(iterat_name[count]) +
' Predictions')
markers.append(',')
markers_sizes.append(10)
linewidths.append(width)
colors.append(available_colors(count))
alphas.append(1)
zorders.append(3)
width -= dec_q
width = max(min_q, width)
if 'Sync' in self.classifiers_used:
yticks = []
for key in self.train_classes:
yticks += list(self.train_classes[key])
else:
yticks = self.train_classes
ylim = (-1, len(yticks) + 1)
fig, lgd, axes = self.plot_result(np.vstack(plots).T, labels=labels,
xticks_locs=xticks, ylim=ylim,
yticks_names=yticks,
markers=markers,
linewidths=linewidths,
alphas=alphas,
xlabel='Frames',
zorders=zorders,
markers_sizes= markers_sizes,
info='Classification Results',
save=False)
if self.test_breakpoints is not None:
if 'Sync' in self.classifiers_used:
tg_ref = 0
for key in (self.test_ground_truth):
self.draw_breakpoints(axes,
self.test_breakpoints[key],
yticks)
else:
self.draw_breakpoints(axes,
self.test_breakpoints, yticks)
if save:
save_info = 'Classification Results'
if self.crossings is not None:
save_info += ' with Crossings'
self.save_plot(fig, lgd, info=save_info)
return True
def draw_breakpoints(self, axes, breakpoints, yticks, lw=3,
zorder=2):
'''
Draws colored ground truth
'''
from matplotlib.cm import get_cmap
cmap = get_cmap('Spectral')
max_plotpoints_num = 0
for act in breakpoints:
max_plotpoints_num = max(max_plotpoints_num,
len(breakpoints[act][0]))
c_num = max_plotpoints_num
yticks = [ytick.lower() for ytick in yticks]
for act_cnt, act in enumerate(breakpoints):
drawn = 0
for cnt, (start, end) in enumerate(zip(breakpoints[act][0],
breakpoints[act][1])):
gest_dur = np.arange(int(start), int(end))
if act.lower() in yticks:
axes.plot(gest_dur, np.ones(gest_dur.size) *(
yticks.index(act.lower()) ),
color=cmap(cnt/float(c_num))
, linewidth=lw,
solid_capstyle="butt", zorder=zorder)
class RecognitionVectorizer(object):
'''
Class to hold classification classes
'''
def __init__(self, class_names):
self.name = ''
self.index = 0
self.start = 0
self.length = 0
self.names = class_names
self.recognition_vector = []
def add(self, index=None, start=None, length=None):
'''
Add Class with name, corresponding index in self.train_classes,
starting from start frame, with length length frames
'''
if index is not None:
self.index = int(index)
self.name = self.names[int(index)]
if start is not None:
self.start = start
self.recognition_vector.append(
[None] * (start - len(self.recognition_vector)))
if length is not None:
self.length = length
self.recognition_vector.append(
[self.index] * self.length)
def fake_online_testing(classifier, testname='actions', path=None):
'''
Immitate online testing for performance testing and debugging reasons
'''
if path is None:
path = os.path.join(co.CONST['test_' + testname], '0')
filenames = glob.glob(os.path.join(path, '*.png'))
sync = [int(filter(str.isdigit,
os.path.basename(filename)))
for filename in filenames]
[sync, filenames] = map(list, zip(*[[y, x] for (y, x) in
sorted(zip(sync, filenames),
key=lambda pair: pair[0])]))
txts = glob.glob(os.path.join(path, '*.txt'))
angles = []
centers = []
for txt in txts:
if 'angles' in txt:
with open(txt, 'r') as inpf:
angles += map(float, inpf)
elif 'centers' in txt:
with open(txt, 'r') as inpf:
for line in inpf:
center = [
float(num) for num
in line.split(' ')]
centers += [center]
for count, filename in enumerate(filenames):
img = cv2.imread(filename, -1)
# DEBUGGING
#cv2.imshow('test', (img % 255).astype(np.uint8))
# cv2.waitKey(10)
classifier.run_testing(
data=img,
img_count=sync[count],
online=True,
load=False,
derot_angle=angles[count],
derot_center=centers[count],
testdatapath=co.CONST['test_' + testname])
classifier.recognized_classes[-1].add(length=max(sync))
if len(classifier.scores_exist) > 1:
classifier.test_ground_truth = co.gd_oper.construct_ground_truth(
classifier.scores_exist, ground_truth_type=co.CONST['test_'
+ testname
+
'_ground_truth'],
classes_namespace=classifier.train_classes)
classifier.scores = np.array(
classifier.scores).squeeze()
classifier.scores_exist = np.array(classifier.scores_exist)
expanded_scores = np.zeros(
(len(classifier.scores_exist), classifier.scores.shape[1]))
expanded_scores[:] = np.NaN
expanded_scores[
classifier.scores_exist.astype(bool),
:] = classifier.scores
else:
expanded_scores = np.array(classifier.scores)
classifier.plot_result(expanded_scores,
labels=['%s' % classifier.train_classes[count]
for count in
range(expanded_scores.shape[1])],
info='Filtered Scores',
xlabel='Frames', save=True)
classifier.plot_result(np.concatenate((
classifier.filtered_scores_std,
classifier.filtered_scores_std_mean), axis=0).T,
colors=['r', 'g'],
labels=['STD', 'STD Mean'],
info='Filtered Scores Statistics',
xlabel='Frames', save=True)
def signal_handler(sig, frame):
'''
Signal handler for CTRL-C interrupt (SIGINT)
'''
LOG.info('\nGot SIGINT')
LOG.info('Exiting...')
loc = locals()
running_classifiers = [loc[key] for key in loc
if isinstance(loc[key], Classifier)
and loc[key].testing_initialized and
loc[key].online]
for classifier in running_classifiers:
classifier.display_scores_and_time()
if running_classifiers:
from matplotlib import pyplot as plt
plt.show()
sys.exit(0)
def construct_dynamic_actions_classifier(testname='test2', train=False,
test=True, visualize=True,
coders_retrain=False,
name='actions', sparsecoding_level=False,
sparse_dim_rat=None, test_against_all=False,
visualize_feat=False, kernel=None,
descriptors='GHOG', ptpca=False,
ptpca_components=1,
just_sparse=False,
debug=False,
classifiers_used='SVM',
action_type='Dynamic',
post_scores_processing_method='CSTD'):
'''
Constructs an SVM classifier with input 3DHOF and GHOG descriptors
'''
if sparsecoding_level:
if sparse_dim_rat is None:
sparse_dim_rat = co.CONST['sparse_dim_rat']
classifier = Classifier('INFO', action_type=action_type,
name=name, sparse_dim_rat=sparse_dim_rat,
sparsecoding_level=sparsecoding_level,
descriptors=descriptors,
kernel=kernel, ptpca=ptpca,
ptpca_components=ptpca_components,
classifiers_used=classifiers_used, post_scores_processing_method= post_scores_processing_method)
if debug:
classifier.debug = True
classifier.run_training(classifiers_retrain=train,
coders_retrain=coders_retrain,
visualize_feat=visualize_feat,
just_sparse=just_sparse,
# init_sc_traindata_num=5000,
init_sc_traindata_num=15000,
min_dict_iterations=20)
if test or visualize:
if test_against_all:
iterat = classifier.available_tests
else:
iterat = [testname]
for name in iterat:
if test:
classifier.run_testing(name,
ground_truth_type=os.path.join(
co.CONST['ground_truth_fold'],
name + '.csv'),
online=False, load=False)
else:
classifier.run_testing(name,
ground_truth_type=os.path.join(
co.CONST['ground_truth_fold'],
name + '.csv'),
online=False, load=False)
return classifier
def construct_passive_actions_classifier(testname='test2',
train=True, test=True, visualize=True,
test_against_all=False,
descriptors='3DXYPCA',
post_scores_processing_method='CProb',
for_app=False):
'''
Constructs a random forests passive_actions classifier with input 3DXYPCA descriptors
'''
classifier = Classifier('INFO', action_type='Passive',
name='actions', classifiers_used='RDF',
sparsecoding_level=False,
descriptors=descriptors,
post_scores_processing_method=
post_scores_processing_method, for_app=for_app)
classifier.run_training(classifiers_retrain=train,
max_act_samples=2000)
if test or visualize:
if test_against_all:
iterat = classifier.available_tests
else:
iterat = [testname]
for name in iterat:
if test:
classifier.run_testing(name,
ground_truth_type=os.path.join(
co.CONST['ground_truth_fold'],
name + '.csv'),
online=False, load=False)
else:
classifier.run_testing(name,
ground_truth_type=os.path.join(
co.CONST['ground_truth_fold'],
name + '.csv'),
online=False, load=False)
return classifier
def construct_total_statistics():
'''
Construct unified plots for all classifiers, tested on all tests
'''
classifier = Classifier()
classifier.action_type = 'Dynamic'
iterat = classifier.available_tests
classifier.scores_exist = None
classifier.recognized_classes = None
for test in iterat:
classifier.test_ground_truth = co.gd_oper.construct_ground_truth(
ground_truth_type=os.path.join(co.CONST['test_save_path'], test),
classes_namespace=classifier.dynamic_actions)
classifier.correlate_with_ground_truth(save=True,
display=True,
display_all=True,
compute_perform=True)
def main():
'''
Example Usage
'''
from matplotlib import pyplot as plt
testname = 'actions'
# construct_passive_actions_classifier(test)
# plt.show()
'''
TRAIN_ALL_SPARSE = construct_dynamic_actions_classifier(
train=[0],descriptors=['GHOG', 'ZHOF', '3DHOF', '3DXYPCA'],
sparsecoding_level=True,just_sparse=True, debug=False)
'''
'''
POSES_CLASSIFIER = construct_passive_actions_classifier(train=True,
test=True,
visualize=True,
test_against_all=True)
'''
ACTIONS_CLASSIFIER_SIMPLE = construct_dynamic_actions_classifier(
train=True,
test=True,
visualize=True,
test_against_all=True,
ptpca=False,
classifiers_used='RDF',
descriptors=['GHOG','ZHOF'],
post_scores_processing_method='CSTD')
exit()
'''
ACTIONS_CLASSIFIER_SPARSE = construct_dynamic_actions_classifier(train=True,
coders_retrain=False,
test=True,
visualize=True,
test_against_all=True,
sparsecoding_level='Features',
classifiers_used='RDF')
ACTIONS_CLASSIFIER_SIMPLE_POST_PCA = construct_dynamic_actions_classifier(
train=True,
test=True,
visualize=True,
test_against_all=True,
ptpca=True,
ptpca_components=2)
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['3DHOF'],ptpca=False,sparsecoding_level=False)
'''
'''
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['ZHOF'], ptpca=False, sparsecoding_level=False)
'''
'''
ACTIONS_CLASSIFIER_SPARSE_WITH_3DHOF = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', '3DHOF'], coders_retrain=False, sparsecoding_level=True,
kernel='linear')
ACTIONS_CLASSIFIER_SIMPLE_WITH_3DHOF_POST_PCA = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', '3DHOF'], ptpca=True, ptpca_components=4)
construct_dynamic_actions_classifier(
#debugging, train=True, test=True,
train=True, test=True,
visualize=True, test_against_all=True,
descriptors=['GHOG', '3DHOF'], ptpca=True, sparsecoding_level=True,
ptpca_components=2)
'''
'''
ACTIONS_CLASSIFIER_SIMPLE_WITH_3DHOF = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', '3DHOF'], kernel='linear')
'''
'''
ACTIONS_CLASSIFIER_SIMPLE_WITH_ZHOF = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', 'ZHOF'])
'''
'''
ACTIONS_CLASSIFIER_SIMPLE_WITH_ZHOF = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['3DXYPCA','GHOG','3DHOF','ZHOF'], classifiers_used='SVM')
'''
# Let's try RDF for dynamic actions
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', 'ZHOF'], ptpca=False, sparsecoding_level=False,
classifiers_used='RDF')
exit()
# Let's try RDF with all descriptors for dynamic actions
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', '3DHOF', '3DXYPCA'], ptpca=False, sparsecoding_level=False,
classifiers_used='RDF')
# Let's try RDF for all descriptors for all actions
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', '3DHOF', '3DXYPCA'], action_type='All', ptpca=False, sparsecoding_level=False,
classifiers_used='RDF')
# Let's try RDF with all descriptors for dynamic actions
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', 'ZHOF', '3DXYPCA'], action_type='Dynamic', ptpca=False, sparsecoding_level=False,
classifiers_used='RDF')
# Let's try RDF for all descriptors for all actions
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', 'ZHOF', '3DXYPCA'], action_type='All', ptpca=False, sparsecoding_level=False,
classifiers_used='RDF')
ACTIONS_CLASSIFIER_SPARSE_WITH_ZHOF = construct_dynamic_actions_classifier(
train=True,
test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', 'ZHOF'], coders_retrain=False, sparsecoding_level=True,
kernel='linear')
ACTIONS_CLASSIFIER_SIMPLE_WITH_ZHOF_POST_PCA = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', 'ZHOF'], ptpca=True, ptpca_components=4)
construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG', 'ZHOF'], ptpca=True,
sparsecoding_level=True, coders_retrain=False, ptpca_components=4)
'''
ACTIONS_CLASSIFIER_SPARSE_WITH_ZHOF_RBF = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG','ZHOF'], coders_retrain=False, sparsecoding_level=True,
kernel='rbf')
ACTIONS_CLASSIFIER_SIMPLE_WITH_ZHOF_RBF = construct_dynamic_actions_classifier(
train=True, test=True, visualize=True, test_against_all=True,
descriptors=['GHOG','ZHOF'], coders_retrain=False, sparsecoding_level=False,
kernel='rbf')
ACTIONS_CLASSIFIER_SIMPLE_RBF = construct_dynamic_actions_classifier(
train=False,
test=False,
visualize=False,
sparsecoding_level=False,
test_against_all=True,
kernel='rbf')
'''
# construct classifiers comparative table
tmp = Classifier(descriptors=[''])
tmp.construct_classifiers_matrix()
sys.exit(0)
# visualize_feat=True)
# visualize_feat=['Fingerwave in'])
LOG = logging.getLogger('__name__')
CH = logging.StreamHandler(sys.stderr)
CH.setFormatter(logging.Formatter(
'%(funcName)20s()(%(lineno)s)-%(levelname)s:%(message)s'))
LOG.handlers = []
LOG.addHandler(CH)
LOG.setLevel(logging.INFO)
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal_handler)
main()
|
import axios from 'axios';
import i18next from 'i18next';
import Backend from 'i18next-chained-backend';
import LocalStorageBackend from 'i18next-localstorage-backend';
import XHR from 'i18next-xhr-backend';
import LngDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';
import {
LANGUAGES,
URL_LOCALIZATION,
TIME_CACHE_LOCALIZATION,
VERSION_LOCALIZATION,
} from '../constants';
const URL_API_LOCALIZATION =
process.env.REACT_APP_API_LOCALIZATION || 'http://localhost:3005';
function loadLocales(url, options, callback) {
axios
.get(`${url}?v=${options.queryStringParams.v}`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(res => {
callback(res.data, { status: '200' });
})
.catch(err => {
callback(null, { status: '404', message: err.message });
});
}
export default i18next
.use(LngDetector)
.use(Backend)
.use(initReactI18next)
.init(
{
whitelist: Object.values(LANGUAGES),
fallbackLng: LANGUAGES.default,
// have a common namespace used around the full app
ns: 'translation',
defaultNS: 'translation',
debug: process.env.NODE_ENV === 'development',
backend: {
backends: [LocalStorageBackend, XHR],
backendOptions: [
{
expirationTime: TIME_CACHE_LOCALIZATION,
prefix: 'i18next_res_',
},
{
queryStringParams: { v: VERSION_LOCALIZATION },
parse: data => data,
loadPath: `${URL_API_LOCALIZATION}${URL_LOCALIZATION}`,
ajax: loadLocales,
},
],
},
},
err => {
if (err) return console.log('something went wrong loading', err);
}
);
|
import express from 'express';
const router = express.Router();
import { asyncHandler } from '../Middleware/asyncErrorHandler.js';
import { WebHookHandler } from '../Services/stripe/stripeWebhooksHanlder.js';
/* Webhook Routes */
router.post(
'/stripe-webhook',
express.raw({ type: 'application/json' }),
asyncHandler(WebHookHandler)
);
export default router;
|
import math
from bisect import bisect_left, bisect_right
import numpy as np
from metrics.metric import Metric
import concurrent.futures as cf
class ClassificationMetric(Metric):
def __init__(self, tolerance=0.1):
self.fn = []
self.fp = []
self.tp = []
self.tolerance = tolerance
def join(self, other):
self.fn.extend(other.fn)
self.fp.extend(other.fp)
self.tp.extend(other.tp)
return self
def match_annotations(self, true_samples, true_symbols, test_samples, sampling_frequency=360):
"""Tries to match two lists of (supposed) QRS positions.
Args:
true_samples: List of samples representing the actual QRS positions.
true_symbols: Annotation symbols for the samples in true_samples.
test_samples: List of samples representing the detected QRS positions.
tolerance: Maximum allowed distance between actual and detected QRS
position.
Returns:
Tuple (tp, fp, fn) whereas tp is a list of true positives characterized
as tripel (true_sample, test_sample, symbol), fp is a list of false
positives characterized as tuple (test_sample, symbol?), and fn is a
list of false negatives characterized as list of tuples (true_sample,
symbol).
:param sampling_frequency:
"""
self.match_classification_annotations(true_samples, true_symbols, test_samples,
self.tolerance * sampling_frequency)
def match_classification_annotations(self, true_samples, true_symbols, test_samples, tolerance):
tp, fp, fn = [], [], []
for true_sample, true_symbol in zip(true_samples, true_symbols):
matches = [test_sample
for test_sample in test_samples
if abs(test_sample - true_sample) <= tolerance]
matches.sort(key=lambda m: abs(m - true_sample))
if len(matches) == 0:
fn.append((true_sample, true_symbol))
if len(matches) > 0:
tp.append((true_sample, matches[0], true_symbol))
if len(matches) > 1:
fp.extend([(match, true_symbol) for match in matches[1:]])
for test_sample in test_samples:
matches = [true_sample
for true_sample in true_samples
if abs(true_sample - test_sample) <= tolerance]
if len(matches) == 0:
fp.append((test_sample, ''))
self.fn.extend(fn)
self.fp.extend(fp)
self.tp.extend(tp)
return tp, fp, fn
def compute(self):
raise NotImplementedError
class PositivePredictiveValue(ClassificationMetric):
__abbrev__ = "PPV"
def match_annotations(self, true_samples, true_symbols, test_samples, sampling_frequency=360):
super().match_annotations(true_samples, true_symbols, test_samples)
return self.compute()
def compute(self):
if len(self.tp) == 0 == len(self.fp):
return 0
return len(self.tp) / (len(self.fp) + len(self.tp))
class Sensitivity(ClassificationMetric):
__abbrev__ = "Sens"
def match_annotations(self, true_samples, true_symbols, test_samples, sampling_frequency=360):
super().match_annotations(true_samples, true_symbols, test_samples)
return self.compute()
def compute(self):
if len(self.tp) == 0 == len(self.fn):
return 0
return len(self.tp) / (len(self.fn) + len(self.tp))
class F1(ClassificationMetric):
__abbrev__ = "F1 Score"
def match_annotations(self, true_samples, true_symbols, test_samples, sampling_frequency=360):
super().match_annotations(true_samples, true_symbols, test_samples)
return self.compute()
def compute(self):
if len(self.tp) == 0 == len(self.fp) == len(self.fn):
return 0
return 2 * len(self.tp) / (2 * len(self.tp) + len(self.fn) + len(self.fp))
class RoCCurve(ClassificationMetric):
__abbrev__ = "RoC"
__parts__ = 10
def __init__(self, parts=__parts__):
super().__init__()
self.parts = parts
self.tp_by_tol = [0 for _ in range(parts)]
self.fp_by_tol = [0 for _ in range(parts)]
self.tn_by_tol = [0 for _ in range(parts)]
self.fn_by_tol = [0 for _ in range(parts)]
def join(self, other):
for p in range(self.parts):
self.tp_by_tol[p] += other.tp_by_tol[p]
self.fp_by_tol[p] += other.fp_by_tol[p]
self.tn_by_tol[p] += other.tn_by_tol[p]
self.fn_by_tol[p] += other.fn_by_tol[p]
return self
def match_annotations(self, true_samples, true_symbols, test_samples, sampling_frequency=360):
sf = sampling_frequency // 5
window_sizes = list(range(1, sf - (sf % self.parts), sf // self.parts))
confusion_values = map(self.match_classification_annotations,
list([true_samples] * len(window_sizes)),
list([true_symbols] * len(window_sizes)),
list([test_samples] * len(window_sizes)),
window_sizes)
for idx, cv in enumerate(confusion_values):
self.tp_by_tol[idx] += cv[0]
self.fp_by_tol[idx] += cv[1]
self.tn_by_tol[idx] += cv[2]
self.fn_by_tol[idx] += cv[3]
return self.compute()
def match_classification_annotations(self, true_samples, true_symbols, test_samples, tolerance):
recording_len = 2 * true_samples[-1] - true_samples[-2] if len(true_samples) > 1 else 2 * true_samples[-1]
if len(test_samples) == 0:
fn = len(true_samples) * (tolerance + 1)
return 0, 0, fn, recording_len - fn + 1
tp, fp, fn, tn = 0, 0, 0, 0
for true_beat in true_samples:
left_pred_idx = bisect_right(test_samples, true_beat) - 1
right_pred_idx = bisect_left(test_samples, true_beat)
left_pred_idx = max(left_pred_idx, 0)
right_pred_idx = min(right_pred_idx, len(test_samples) - 1)
left_dist_to_beat = abs(test_samples[left_pred_idx] - true_beat)
right_dist_to_beat = abs(test_samples[right_pred_idx] - true_beat)
closest_pred_idx = left_pred_idx if left_dist_to_beat < right_dist_to_beat else right_pred_idx
# was the beat found
if min(left_dist_to_beat, right_dist_to_beat) <= tolerance:
if left_pred_idx != right_pred_idx and left_dist_to_beat <= tolerance and right_dist_to_beat <= tolerance:
left_overlap = abs(test_samples[left_pred_idx] - (true_beat - tolerance - 1))
right_overlap = abs(test_samples[right_pred_idx] - (true_beat + tolerance + 1))
overlap = max(0, test_samples[left_pred_idx] + tolerance - (test_samples[right_pred_idx] - tolerance) - 2)
num_tp = left_overlap + right_overlap - overlap
tp += int(num_tp)
else:
num_tp = min(abs(test_samples[closest_pred_idx] - (true_beat - tolerance - 1)),
abs(test_samples[closest_pred_idx] - (true_beat + tolerance + 1)),
test_samples[closest_pred_idx] + 1)
tp += int(num_tp)
# are there some windows where no prediction lies
if left_pred_idx != right_pred_idx and left_dist_to_beat + right_dist_to_beat > tolerance:
num_fn = min(min(right_dist_to_beat, left_dist_to_beat) - 1, tolerance + 1)
fn += int(num_fn)
if left_pred_idx == right_pred_idx:
fn += min(left_dist_to_beat, tolerance + 1)
for pred_beat in test_samples:
next_beat_idx = bisect_right(true_samples, pred_beat)
previous_beat_idx = next_beat_idx - 1
previous_beat = true_samples[previous_beat_idx] if previous_beat_idx >= 0 else -1
if previous_beat == pred_beat:
continue
next_beat = true_samples[next_beat_idx] if next_beat_idx != len(true_samples) else previous_beat
if next_beat - pred_beat <= tolerance and pred_beat - previous_beat <= tolerance and next_beat != previous_beat:
continue
num_fp = min(abs(previous_beat - pred_beat),
abs(next_beat - pred_beat),
tolerance + 1,
recording_len - next_beat)
fp += int(num_fp)
num_tn = recording_len - tp - fp - fn + 1
if num_tn < 0:
print("error:", num_tn, true_samples, test_samples, tolerance)
tn += max(int(num_tn), 0)
return tp, fp, tn, fn
def compute(self):
metrics_per_tol = []
for tp, fp, tn, fn in zip(self.tp_by_tol, self.fp_by_tol, self.tn_by_tol, self.fn_by_tol):
metrics_per_tol.append(self.ppv_fpr(tp, fp, tn, fn))
return min(metrics_per_tol, key=self.distance_to_upper_left_corner)
def distance_to_upper_left_corner(self, x):
fi, se = x
return math.sqrt((1 - fi) ** 2 + se ** 2)
def ppv_fpr(self, tp, fp, tn, fn):
return tp / max(tp + fn, 0.00001), fp / max(fp + tn, 0.00001)
class PPVSpec(RoCCurve):
def compute(self):
metrics_per_tol = []
for tp, fp, tn, fn in zip(self.tp_by_tol, self.fp_by_tol, self.tn_by_tol, self.fn_by_tol):
metrics_per_tol.append(self.ppv_spec(tp, fp, tn, fn))
return min(metrics_per_tol, key=self.distance_to_upper_right_corner)
def distance_to_upper_right_corner(self, x):
fi, se = x
return math.sqrt((1 - fi) ** 2 + (1 - se) ** 2)
def ppv_spec(self, tp, fp, tn, fn):
return tp / max(tp + fn, 0.00001), tn / max(fp + tn, 0.00001)
class TP(RoCCurve):
__abbrev__ = "TP"
def compute(self):
return self.tp_by_tol
class FP(RoCCurve):
__abbrev__ = "FP"
def compute(self):
return self.fp_by_tol
class TN(RoCCurve):
__abbrev__ = "TN"
def compute(self):
return self.tn_by_tol
class FN(RoCCurve):
__abbrev__ = "FN"
def compute(self):
return self.fn_by_tol
|
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import abc
import platform
import time
from msal import TokenCache
import six
from six.moves.urllib_parse import urlparse
from azure.core.credentials import AccessToken
from .. import CredentialUnavailableError
from .._constants import KnownAuthorities
from .._internal import get_default_authority, normalize_authority, wrap_exceptions
from .._internal.persistent_cache import load_user_cache
try:
ABC = abc.ABC
except AttributeError: # Python 2.7, abc exists, but not ABC
ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()}) # type: ignore
try:
from typing import TYPE_CHECKING
except ImportError:
TYPE_CHECKING = False
if TYPE_CHECKING:
# pylint:disable=unused-import,ungrouped-imports
from typing import Any, Iterable, List, Mapping, Optional
from .._internal import AadClientBase
from azure.identity import AuthenticationRecord
CacheItem = Mapping[str, str]
MULTIPLE_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. Multiple accounts
were found in the cache. Use username and tenant id to disambiguate."""
MULTIPLE_MATCHING_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. Multiple accounts
matching the specified{}{} were found in the cache."""
NO_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache."""
NO_MATCHING_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. No account
matching the specified{}{} was found in the cache."""
NO_TOKEN = """Token acquisition failed for user '{}'. To fix, re-authenticate
through developer tooling supporting Azure single sign on"""
# build a dictionary {authority: {its known aliases}}, aliases taken from MSAL.NET's KnownMetadataProvider
KNOWN_ALIASES = {
alias: aliases # N.B. aliases includes alias itself
for aliases in (
frozenset((KnownAuthorities.AZURE_CHINA, "login.partner.microsoftonline.cn")),
frozenset((KnownAuthorities.AZURE_PUBLIC_CLOUD, "login.windows.net", "login.microsoft.com", "sts.windows.net")),
frozenset((KnownAuthorities.AZURE_GOVERNMENT, "login.usgovcloudapi.net")),
)
for alias in aliases
}
def _account_to_string(account):
username = account.get("username")
home_account_id = account.get("home_account_id", "").split(".")
tenant_id = home_account_id[-1] if len(home_account_id) == 2 else ""
return "(username: {}, tenant: {})".format(username, tenant_id)
def _filtered_accounts(accounts, username=None, tenant_id=None):
"""yield accounts matching username and/or tenant_id"""
filtered_accounts = []
for account in accounts:
if username and account.get("username") != username:
continue
if tenant_id:
try:
_, tenant = account["home_account_id"].split(".")
if tenant_id != tenant:
continue
except Exception: # pylint:disable=broad-except
continue
filtered_accounts.append(account)
return filtered_accounts
class SharedTokenCacheBase(ABC):
def __init__(self, username=None, **kwargs): # pylint:disable=unused-argument
# type: (Optional[str], **Any) -> None
self._auth_record = kwargs.pop("authentication_record", None) # type: Optional[AuthenticationRecord]
if self._auth_record:
# authenticate in the tenant that produced the record unless 'tenant_id' specifies another
authenticating_tenant = kwargs.pop("tenant_id", None) or self._auth_record.tenant_id
self._tenant_id = self._auth_record.tenant_id
self._authority = self._auth_record.authority
self._username = self._auth_record.username
self._environment_aliases = frozenset((self._authority,))
else:
authenticating_tenant = "organizations"
authority = kwargs.pop("authority", None)
self._authority = normalize_authority(authority) if authority else get_default_authority()
environment = urlparse(self._authority).netloc
self._environment_aliases = KNOWN_ALIASES.get(environment) or frozenset((environment,))
self._username = username
self._tenant_id = kwargs.pop("tenant_id", None)
self._cache = kwargs.pop("_cache", None)
self._client = None # type: Optional[AadClientBase]
self._client_kwargs = kwargs
self._client_kwargs["tenant_id"] = authenticating_tenant
self._initialized = False
def _initialize(self):
if self._initialized:
return
if not self._cache and self.supported():
allow_unencrypted = self._client_kwargs.get("allow_unencrypted_cache", False)
try:
self._cache = load_user_cache(allow_unencrypted)
except Exception: # pylint:disable=broad-except
pass
if self._cache:
self._client = self._get_auth_client(authority=self._authority, cache=self._cache, **self._client_kwargs)
self._initialized = True
@abc.abstractmethod
def _get_auth_client(self, **kwargs):
# type: (**Any) -> AadClientBase
pass
def _get_cache_items_for_authority(self, credential_type):
# type: (TokenCache.CredentialType) -> List[CacheItem]
"""yield cache items matching this credential's authority or one of its aliases"""
items = []
for item in self._cache.find(credential_type):
environment = item.get("environment")
if environment in self._environment_aliases:
items.append(item)
return items
def _get_accounts_having_matching_refresh_tokens(self):
# type: () -> Iterable[CacheItem]
"""returns an iterable of cached accounts which have a matching refresh token"""
refresh_tokens = self._get_cache_items_for_authority(TokenCache.CredentialType.REFRESH_TOKEN)
all_accounts = self._get_cache_items_for_authority(TokenCache.CredentialType.ACCOUNT)
accounts = {}
for refresh_token in refresh_tokens:
home_account_id = refresh_token.get("home_account_id")
if not home_account_id:
continue
for account in all_accounts:
# When the token has no family, msal.net falls back to matching client_id,
# which won't work for the shared cache because we don't know the IDs of
# all contributing apps. It should be unnecessary anyway because the
# apps should all belong to the family.
if home_account_id == account.get("home_account_id") and "family_id" in refresh_token:
accounts[account["home_account_id"]] = account
return accounts.values()
@wrap_exceptions
def _get_account(self, username=None, tenant_id=None):
# type: (Optional[str], Optional[str]) -> CacheItem
"""returns exactly one account which has a refresh token and matches username and/or tenant_id"""
accounts = self._get_accounts_having_matching_refresh_tokens()
if not accounts:
# cache is empty or contains no refresh token -> user needs to sign in
raise CredentialUnavailableError(message=NO_ACCOUNTS)
if self._auth_record:
for account in accounts:
if account.get("home_account_id") == self._auth_record.home_account_id:
return account
raise CredentialUnavailableError(
message="The cache contains no account matching the given AuthenticationRecord."
)
filtered_accounts = _filtered_accounts(accounts, username, tenant_id)
if len(filtered_accounts) == 1:
return filtered_accounts[0]
# no, or multiple, accounts after filtering -> choose the best error message
cached_accounts = ", ".join(_account_to_string(account) for account in accounts)
if username or tenant_id:
username_string = " username: {}".format(username) if username else ""
tenant_string = " tenant: {}".format(tenant_id) if tenant_id else ""
if filtered_accounts:
message = MULTIPLE_MATCHING_ACCOUNTS.format(username_string, tenant_string)
else:
message = NO_MATCHING_ACCOUNTS.format(username_string, tenant_string)
else:
message = MULTIPLE_ACCOUNTS.format(cached_accounts)
raise CredentialUnavailableError(message=message)
def _get_cached_access_token(self, scopes, account):
# type: (Iterable[str], CacheItem) -> Optional[AccessToken]
if "home_account_id" not in account:
return None
try:
cache_entries = self._cache.find(
TokenCache.CredentialType.ACCESS_TOKEN,
target=list(scopes),
query={"home_account_id": account["home_account_id"]},
)
for token in cache_entries:
expires_on = int(token["expires_on"])
if expires_on - 300 > int(time.time()):
return AccessToken(token["secret"], expires_on)
except Exception as ex: # pylint:disable=broad-except
message = "Error accessing cached data: {}".format(ex)
six.raise_from(CredentialUnavailableError(message=message), ex)
return None
def _get_refresh_tokens(self, account):
if "home_account_id" not in account:
return None
try:
cache_entries = self._cache.find(
TokenCache.CredentialType.REFRESH_TOKEN, query={"home_account_id": account["home_account_id"]}
)
return [token["secret"] for token in cache_entries if "secret" in token]
except Exception as ex: # pylint:disable=broad-except
message = "Error accessing cached data: {}".format(ex)
six.raise_from(CredentialUnavailableError(message=message), ex)
@staticmethod
def supported():
# type: () -> bool
"""Whether the shared token cache is supported on the current platform.
:rtype: bool
"""
return platform.system() in {"Darwin", "Linux", "Windows"}
|
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Dialog from 'material-ui/Dialog';
import IconButton from 'material-ui/IconButton';
import uniqueId from 'lodash/uniqueId';
import ArtistIcon from 'material-ui/svg-icons/hardware/headset';
import TitleIcon from 'material-ui/svg-icons/image/music-note';
import StartIcon from 'material-ui/svg-icons/av/play-arrow';
import EndIcon from 'material-ui/svg-icons/av/stop';
import SwapArtistTitleIcon from 'material-ui/svg-icons/action/swap-horiz';
import formatDuration from '../../../utils/formatDuration';
import Form from '../../Form';
import FormGroup from '../../Form/Group';
import Button from '../../Form/Button';
import TextField from '../../Form/TextField';
// naive HH:mm:ss → seconds
const parseDuration = str => str.split(':')
.map(part => parseInt(part.trim(), 10))
.reduce((duration, part) => (duration * 60) + part, 0);
@translate()
export default class EditMediaDialog extends React.Component {
static propTypes = {
t: PropTypes.func.isRequired,
open: PropTypes.bool,
media: PropTypes.object,
bodyClassName: PropTypes.string,
contentClassName: PropTypes.string,
titleClassName: PropTypes.string,
onEditedMedia: PropTypes.func.isRequired,
onCloseDialog: PropTypes.func.isRequired
};
state = {
errors: null,
artist: this.props.media.artist,
title: this.props.media.title,
start: formatDuration(this.props.media.start),
end: formatDuration(this.props.media.end)
};
labelStart = uniqueId('editmedia');
labelEnd = uniqueId('editmedia');
handleSubmit = (e) => {
e.preventDefault();
const { media, onEditedMedia, onCloseDialog } = this.props;
const { artist, title, start, end } = this.state;
const startSeconds = parseDuration(start);
const endSeconds = parseDuration(end);
const errors = [];
if (isNaN(startSeconds) || startSeconds < 0) {
errors.push('invalidStartTime');
}
if (isNaN(endSeconds) || endSeconds < 0) {
errors.push('invalidEndTime');
} else if (endSeconds < startSeconds) {
errors.push('endTimeBeforeStart');
} else if (endSeconds > media.duration) {
errors.push('endTimeAfterSongEnd');
}
if (errors.length > 0) {
this.setState({ errors });
return;
}
onEditedMedia({
artist,
title,
start: startSeconds,
end: endSeconds
});
onCloseDialog();
};
handleChangeArtist = (event) => {
this.setState({ artist: event.target.value });
};
handleChangeTitle = (event) => {
this.setState({ title: event.target.value });
};
handleChangeStart = (event) => {
this.setState({ start: event.target.value });
};
handleChangeEnd = (event) => {
this.setState({ end: event.target.value });
};
handleSwapArtistTitle = () => {
this.setState({
artist: this.state.title,
title: this.state.artist
});
};
render() {
const {
t,
open,
media,
onCloseDialog,
bodyClassName,
contentClassName,
titleClassName,
...props
} = this.props;
const {
errors,
artist,
title,
start,
end
} = this.state;
const baseTabIndex = 1000;
let content = null;
if (open) {
const artistInput = (
<TextField
className="EditMediaDialogGroup-field"
placeholder={t([ 'dialogs.editMedia.artistLabel', 'media.artist' ])}
value={artist}
onChange={this.handleChangeArtist}
icon={<ArtistIcon color="#9f9d9e" />}
tabIndex={baseTabIndex}
autoFocus
/>
);
const artistTitleLabel = (
<div className="EditMediaDialogGroup-label">
<IconButton onClick={this.handleSwapArtistTitle}>
<SwapArtistTitleIcon color="#9f9d9e" />
</IconButton>
</div>
);
const titleInput = (
<TextField
className="EditMediaDialogGroup-field"
placeholder={t([ 'dialogs.editMedia.titleLabel', 'media.title' ])}
value={title}
onChange={this.handleChangeTitle}
icon={<TitleIcon color="#9f9d9e" />}
tabIndex={baseTabIndex + 1}
/>
);
const fromLabel = (
<label htmlFor={this.labelStart} className="EditMediaDialogGroup-label">
{t('dialogs.editMedia.playFromLabel')}
</label>
);
const fromInput = (
<TextField
id={this.labelStart}
className="EditMediaDialogGroup-field"
placeholder="0:00"
value={start}
onChange={this.handleChangeStart}
icon={<StartIcon color="#9f9d9e" />}
tabIndex={baseTabIndex + 2}
/>
);
const toLabel = (
<label htmlFor={this.labelEnd} className="EditMediaDialogGroup-label">
{t('dialogs.editMedia.playToLabel')}
</label>
);
const toInput = (
<TextField
id={this.labelEnd}
className="EditMediaDialogGroup-field"
placeholder={formatDuration(media.duration)}
value={end}
onChange={this.handleChangeEnd}
icon={<EndIcon color="#9f9d9e" />}
tabIndex={baseTabIndex + 3}
/>
);
content = (
<Form className="EditMediaDialog" onSubmit={this.handleSubmit}>
{errors && errors.length > 0 && (
<FormGroup>
{errors.map(error => <div>{t(`dialogs.editMedia.errors.${error}`)}</div>)}
</FormGroup>
)}
<div className="EditMediaDialogForm">
<div className="EditMediaDialogForm-column">
<FormGroup className="EditMediaDialogGroup">
{artistInput}
</FormGroup>
<FormGroup className="EditMediaDialogGroup">
{fromLabel}
{fromInput}
</FormGroup>
</div>
<div className="EditMediaDialogForm-separator">
<FormGroup className="EditMediaDialogGroup">
{artistTitleLabel}
</FormGroup>
<FormGroup className="EditMediaDialogGroup">
{toLabel}
</FormGroup>
</div>
<div className="EditMediaDialogForm-column">
<FormGroup className="EditMediaDialogGroup">
{titleInput}
</FormGroup>
<FormGroup className="EditMediaDialogGroup">
{toInput}
</FormGroup>
</div>
</div>
<FormGroup className="FormGroup--noSpacing">
<Button className="EditMediaDialog-submit">
{t('dialogs.editMedia.save')}
</Button>
</FormGroup>
</Form>
);
}
return (
<Dialog
{...props}
contentClassName={cx('Dialog', contentClassName)}
bodyClassName={cx('Dialog-body', bodyClassName)}
titleClassName={cx('Dialog-title', titleClassName)}
title={t('dialogs.editMedia.title')}
open={open}
onRequestClose={onCloseDialog}
>
{content}
</Dialog>
);
}
}
|
import React from 'react';
import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router';
import { createStore } from 'redux';
import { reducer, generateInitialState } from 'app/intake/index';
export const IntakeProviders = ({ children }) => {
const store = createStore(reducer, { ...generateInitialState() });
return (
<Provider store={store}>
<MemoryRouter>{children}</MemoryRouter>
</Provider>
);
};
|
import { FETCH_POSTS, NEW_POST } from './types';
export const fetchPosts = () => dispatch => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(posts =>
dispatch({
type: FETCH_POSTS,
payload: posts
})
);
}
export const createPost = (postData) => dispatch => {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(res => res.json())
.then(post =>
dispatch({
type: NEW_POST,
payload: post
}))
};
|
// This tests that $setOnInsert works and allow setting the _id
t = db.update_setOnInsert;
db.setProfilingLevel( 2 );
function getLastOp() {
var cursor = db.system.profile.find( { ns : t.getFullName() , op : "update" } );
cursor = cursor.sort( { $natural : -1 } ).limit(1);
return cursor[0];
}
function dotest( useIndex ) {
t.drop();
if ( useIndex ) {
t.ensureIndex( { a : 1 } );
}
t.update( { _id: 5 }, { $inc : { x: 2 }, $setOnInsert : { a : 3 } }, true );
assert.docEq( { _id : 5, a: 3, x : 2 }, t.findOne() );
t.update( { _id: 5 }, { $set : { a : 4 } }, true );
t.update( { _id: 5 }, { $inc : { x: 2 }, $setOnInsert : { a : 3 } }, true );
assert.docEq( { _id : 5, a: 4, x : 4 }, t.findOne() );
op = getLastOp();
assert( op.fastmod );
}
dotest( false );
dotest( true );
// Cases for SERVER-9958 -- Allow _id $setOnInsert during insert (if upsert:true, and not doc found)
t.drop();
t.update( {_id: 1} , { $setOnInsert: { "_id.a": new Date() } } , true );
assert.gleError(db, function(gle) {
return "$setOnInsert _id.a - " + tojson(gle) + tojson(t.findOne()) } );
t.update( {"_id.a": 4} , { $setOnInsert: { "_id.b": 1 } } , true );
assert.gleError(db, function(gle) {
return "$setOnInsert _id.b - " + tojson(gle) + tojson(t.findOne()) } );
t.update( {"_id.a": 4} , { $setOnInsert: { "_id": {a:4, b:1} } } , true );
assert.gleError(db, function(gle) {
return "$setOnInsert _id 3 - " + tojson(gle) + tojson(t.findOne()) } );
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-20 13:24
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import role.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Courseware',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128)),
('pub_datetime', models.DateTimeField(auto_now_add=True)),
('file', models.FileField(upload_to=role.models.resource_file_path)),
],
options={
'db_table': 'role_courseware',
'verbose_name': '\u8bfe\u4ef6',
'verbose_name_plural': '\u8bfe\u4ef6',
},
),
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('number', models.IntegerField(blank=True, null=True, unique=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='StuToSub',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='role.Student')),
],
options={
'verbose_name': '\u5b66\u751f\u79d1\u76ee\u5173\u7cfb',
'verbose_name_plural': '\u5b66\u751f\u79d1\u76ee\u5173\u7cfb',
},
),
migrations.CreateModel(
name='Subject',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('number', models.IntegerField(unique=True)),
('name', models.CharField(max_length=32, unique=True)),
],
options={
'verbose_name': '\u79d1\u76ee',
'verbose_name_plural': '\u79d1\u76ee',
},
),
migrations.CreateModel(
name='Teacher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('number', models.IntegerField(blank=True, null=True, unique=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='subject',
name='teacher',
field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='role.Teacher'),
),
migrations.AddField(
model_name='stutosub',
name='subject',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='role.Subject'),
),
migrations.AddField(
model_name='courseware',
name='subject',
field=models.ManyToManyField(to='role.Subject'),
),
migrations.AddField(
model_name='courseware',
name='teacher',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='role.Teacher'),
),
]
|
import { InputTextField } from 'components/ReduxForm/TextInput/InputTextField'
// import { SelectField } from 'components/ReduxForm/Select/SelectField'
export const formFields = [
{
label: 'Razão Social/Nome',
name: 'socialReason',
type: 'text',
className: 'input',
// noValueError: 'Digite seu email para fazer login',
fieldType: InputTextField,
},
{
label: 'CNPJ/CPF',
name: 'CNPJ',
type: 'text',
className: 'lastInput',
// noValueError: 'Digite seu email para fazer login',
fieldType: InputTextField,
},
]
|
const CreateAccountSuccess = 'registration-create-account-success';
const CreateAccountFailure = 'registration-create-account-failure';
const CreateAccountWarning = 'registration-create-account-warning';
const CreateAccountStart = 'registration-create-account-start';
const CreateAccountInlineError = 'registration-create-account-inline-error';
const VisitLoginPage = 'registration-visit-login-page';
const LoginBlocked = 'registration-login-blocked';
export default {
CreateAccountSuccess,
CreateAccountFailure,
CreateAccountWarning,
CreateAccountStart,
CreateAccountInlineError,
VisitLoginPage,
LoginBlocked
};
|
/*!
* robust-admin-theme (https://pixinvent.com/bootstrap-admin-template/robust)
* Copyright 2018 PIXINVENT
* Licensed under the Themeforest Standard Licenses
*/
$(window).on("load",function(){var toBarTransform=c3.generate({bindto:"#to-bar",size:{height:400},color:{pattern:["#673AB7","#E91E63"]},data:{columns:[["data1",30,200,100,400,150,250],["data2",130,100,140,200,150,50]],type:"line"},grid:{y:{show:!0}}});setTimeout(function(){toBarTransform.transform("bar","data1")},1e3),setTimeout(function(){toBarTransform.transform("bar","data2")},2e3),setTimeout(function(){toBarTransform.transform("line")},3e3),setTimeout(function(){toBarTransform.transform("bar")},4e3),$(".menu-toggle").on("click",function(){toBarTransform.resize()})});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _jsxRuntime = require("react/jsx-runtime.js");
var _react = require("react");
var _useListen = _interopRequireDefault(require("../hooks/useListen"));
var _Atoms = _interopRequireDefault(require("./Atoms"));
//import PropTypes from "prop-types";
var ListDeletePane = function ListDeletePane(_ref) {
var store = _ref.store,
actionCompleted = _ref.actionCompleted,
forActionType = _ref.forActionType,
onDelete = _ref.onDelete,
msgOnNotSelect = _ref.msgOnNotSelect,
onClose = _ref.onClose;
var _useState = (0, _react.useState)(function () {
return store.getWatchGroups();
}),
groupOptions = _useState[0],
setGroupOptions = _useState[1],
_useState2 = (0, _react.useState)([]),
validationMessages = _useState2[0],
setValidationMessages = _useState2[1],
_refSelectGroupList = (0, _react.useRef)(),
_hClear = (0, _react.useCallback)(function () {
return setValidationMessages([]);
}, []),
_hDelete = (0, _react.useCallback)(function () {
var _refSelectGroupList$c = _refSelectGroupList.current.getValue(),
captionGroup = _refSelectGroupList$c.captionGroup,
captionList = _refSelectGroupList$c.captionList;
if (captionGroup && captionList) {
onDelete({
captionGroup: captionGroup,
captionList: captionList
});
} else {
var msg = [];
if (!captionGroup) {
msg.push(msgOnNotSelect('Group'));
}
if (!captionList) {
msg.push(msgOnNotSelect('List'));
}
setValidationMessages(msg);
}
}, []),
_primaryBt = (0, _react.useMemo)(function () {
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Atoms["default"].Button.Primary, {
caption: "Delete",
title: "Delete List",
onClick: _hDelete
});
}, [_hDelete]);
(0, _useListen["default"])(store, function (actionType, data) {
if (actionType === actionCompleted) {
if (data.forActionType === forActionType) {
_hClear();
}
setGroupOptions(store.getWatchGroups());
}
});
return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Atoms["default"].SelectGroupList, {
ref: _refSelectGroupList,
store: store,
groupCaption: "In Group:",
groupOptions: groupOptions,
listCaption: "List:"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Atoms["default"].ValidationMessages, {
validationMessages: validationMessages
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Atoms["default"].RowButtons, {
Primary: _primaryBt,
onClear: _hClear,
onClose: onClose
})]
});
};
/*
ListDeletePane.propTypes = {
store: PropTypes.shape({
listen: PropTypes.func,
getWatchGroups: PropTypes.func
}),
actionCompleted: PropTypes.string,
forActionType: PropTypes.string,
msgOnNotSelect: PropTypes.func,
onDelete: PropTypes.func,
onClose: PropTypes.func
}
*/
var _default = ListDeletePane;
exports["default"] = _default;
//# sourceMappingURL=ListDeletePane.js.map
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const config_1 = __importDefault(require("config"));
const path_1 = __importDefault(require("path"));
const mongoose_1 = __importDefault(require("mongoose"));
const app = express_1.default();
const a = { extended: true };
app.use(express_1.default.json(a));
if (process.env.NODE_ENV === 'production') {
app.use('/', express_1.default.static(path_1.default.join(__dirname, 'client', 'build')));
app.get('*', (req, res) => {
res.sendFile(path_1.default.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const PORT = config_1.default.get('port') || 5000;
const MONGOURI = config_1.default.get('mongoUri');
function start() {
return __awaiter(this, void 0, void 0, function* () {
try {
yield mongoose_1.default.connect(MONGOURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
}
catch (e) {
console.log('Server Error', e.message);
process.exit(1);
}
app.listen(PORT, () => {
console.log(`App has been started on port ${PORT}...`);
});
});
}
start();
|
const mongoose = require('mongoose');
const Site = mongoose.model('site');
class SiteController {
static getByHostName(hostName) {
return Site.findOne({
host_name: hostName
}).lean();
}
static add({ hostName, isWpSite }) {
return Site.findOneAndUpdate({
host_name: hostName
}, {
updated_at: new Date(),
is_wp_site: isWpSite,
$setOnInsert: {
created_at: new Date()
}
}, {
upsert: true
}).lean();
}
}
module.exports = SiteController;
|
sap.ui.define([
"sap/ui/test/Opa5",
"sap/ui/equipment/EquipmentCRUD/test/integration/pages/Common"
], function (Opa5, Common) {
"use strict";
var sViewName = "App",
sAppControl = "idAppControl";
Opa5.createPageObjects({
onTheAppPage: {
baseClass: Common,
actions: {
iWaitUntilTheBusyIndicatorIsGone: function () {
return this.waitFor({
id: sAppControl,
viewName: sViewName,
// inline-matcher directly as function
matchers: function (oRootView) {
// we set the view busy, so we need to query the parent of the app
return oRootView.getParent().getBusy() === false;
},
errorMessage: "The app is still busy."
});
}
},
assertions: {
iShouldSeeTheBusyIndicator: function () {
return this.waitFor({
id: sAppControl,
viewName: sViewName,
success: function (oRootView) {
// we set the view busy, so we need to query the parent of the app
Opa5.assert.ok(oRootView.getParent().getBusy(), "The app is busy");
},
errorMessage: "The app is not busy."
});
},
iShouldSeeTheMessageBox: function (sMessageBoxId) {
return this.waitFor({
id: sMessageBoxId,
success: function () {
Opa5.assert.ok(true, "the correct MessageBox was shown");
}
});
}
}
}
});
});
|
from flask_restful import Resource, reqparse
from models.user import UserModel
class UserRegister(Resource):
parser = reqparse.RequestParser()
parser.add_argument(
'username',
type=str,
required=True,
help="This field cannot be blank."
)
parser.add_argument(
'password',
type=str,
required=True,
help="This field cannot be blank."
)
def post(self):
''' If user with specific name exists, return with error.
If not, create that user according to the request data. '''
data = UserRegister.parser.parse_args()
if UserModel.find_by_username(data['username']):
return {"message": "Username already exists."}, 400
user = UserModel(**data)
user.save_to_db()
return {"message": "User created."}, 201
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Randomly assign oneself middle names in Fleep
Based on https://github.com/anroots/spotify-fleep-nowplaying
Author: ando@sqroot.eu 2016-05-25
Licence: MIT
Usage example (change Fleep display name every 30 seconds):
▶ ./fleep-name-updater.py --email=<fleep-email> --password='<fleep-password>' --sleep-duration=30 --prefix=Ando --suffix=Roots
Starting polling. Hit CTRL+C to stop.
[ok]: Ando "Mad" Roots
[ok]: Ando "The Silencer" Roots
[ok]: Ando "Dark" Roots
"""
import random
import requests
import json
import time
import click
import sys
# Set up CLI usage
@click.command()
@click.option('--email', prompt='Email', help='Your Fleep account email')
@click.option(
'--sleep-duration', default=60,
help='How many seconds to wait between status updates')
@click.option('--prefix', default='Ando', help='Name prefix (First Name)')
@click.option('--suffix', default='Roots', help='Name suffix (Last Name)')
@click.option('--password', prompt='Password', help='Your Fleep account password')
def main(email, password, sleep_duration, prefix, suffix):
# Login to Fleep
credentials = login(email, password)
if not credentials:
click.echo('Invalid credentials, unable to login.', err=True)
sys.exit(1)
click.echo('Starting polling. Hit CTRL+C to stop.')
while True:
new_name = "%s \"%s\" %s" % (prefix, get_middle_name(), suffix)
# Update display name on Fleep
if update_name(credentials, new_name):
click.echo("[ok]: %s" % new_name)
else:
click.echo('Fleep API responded with an error', err=True)
time.sleep(sleep_duration)
def login(email, password):
"""Login to Fleep, return session information"""
response = requests.post(
"https://fleep.io/api/account/login",
headers={"Content-Type": "application/json"},
data=json.dumps({"email": email, "password": password})
)
if response.status_code is not 200:
return False
data = response.json()
return {
'ticket': data["ticket"],
'token_id':response.cookies["token_id"],
'display_name': data['display_name']
}
def get_middle_name():
clever_names = [
'The Doctor',
'Annoyed',
'PHP',
'Mr-Know-It-All',
'Grumpy',
'Whichdoctor',
'Quick Shot',
'Security',
'Tokenizer',
'Punisher',
'Funny',
'Lannister',
'The Silencer',
'#kickban',
'The Janitor',
'The Gray',
'Who?',
'Gentleman',
'Azog',
'Dark',
'The Immutable',
'#oldschool',
'The Dark',
'<?var_dump()?>',
'Robert\'); DROP TABLE students;--',
'The Wizard',
'Clever',
'Creepy',
'Mad',
'Mad',
'Mad',
'Coder',
'/dev/sad',
'Sneaky',
'Sarcastic',
'Boolean',
'Rambling',
'Attractive',
'Quicksilver',
'Hacker',
'Cracker',
'Hodor',
'Father of Programs',
'HTTPS',
'Secretive',
'Tremors',
'Java'
]
return random.choice(clever_names)
def update_name(credentials, name):
"""Change display name in Fleep"""
response = requests.post(
"https://fleep.io/api/account/configure",
headers={"Content-Type": "application/json"},
cookies={"token_id": credentials['token_id']},
data=json.dumps({"display_name": name, "ticket": credentials['ticket']})
)
return response.status_code == 200
if __name__ == '__main__':
main()
|
const fs = require('fs-extra')
const path = require('path')
const config_api = require('./config');
const CONSTS = require('./consts')
const archiver = require('archiver');
const is_windows = process.platform === 'win32';
// replaces .webm with appropriate extension
function getTrueFileName(unfixed_path, type) {
let fixed_path = unfixed_path;
const new_ext = (type === 'audio' ? 'mp3' : 'mp4');
let unfixed_parts = unfixed_path.split('.');
const old_ext = unfixed_parts[unfixed_parts.length-1];
if (old_ext !== new_ext) {
unfixed_parts[unfixed_parts.length-1] = new_ext;
fixed_path = unfixed_parts.join('.');
}
return fixed_path;
}
async function getDownloadedFilesByType(basePath, type, full_metadata = false) {
// return empty array if the path doesn't exist
if (!(await fs.pathExists(basePath))) return [];
let files = [];
const ext = type === 'audio' ? 'mp3' : 'mp4';
var located_files = await recFindByExt(basePath, ext);
for (let i = 0; i < located_files.length; i++) {
let file = located_files[i];
var file_path = file.substring(basePath.includes('\\') ? basePath.length+1 : basePath.length, file.length);
var stats = await fs.stat(file);
var id = file_path.substring(0, file_path.length-4);
var jsonobj = await getJSONByType(type, id, basePath);
if (!jsonobj) continue;
if (full_metadata) {
jsonobj['id'] = id;
files.push(jsonobj);
continue;
}
var upload_date = jsonobj.upload_date;
upload_date = upload_date ? `${upload_date.substring(0, 4)}-${upload_date.substring(4, 6)}-${upload_date.substring(6, 8)}` : null;
var isaudio = type === 'audio';
var file_obj = new File(id, jsonobj.title, jsonobj.thumbnail, isaudio, jsonobj.duration, jsonobj.webpage_url, jsonobj.uploader,
stats.size, file, upload_date, jsonobj.description, jsonobj.view_count, jsonobj.height, jsonobj.abr);
files.push(file_obj);
}
return files;
}
async function createContainerZipFile(container_obj, container_file_objs) {
const container_files_to_download = [];
for (let i = 0; i < container_file_objs.length; i++) {
const container_file_obj = container_file_objs[i];
container_files_to_download.push(container_file_obj.path);
}
return await createZipFile(path.join('appdata', container_obj.name + '.zip'), container_files_to_download);
}
async function createZipFile(zip_file_path, file_paths) {
let output = fs.createWriteStream(zip_file_path);
var archive = archiver('zip', {
gzip: true,
zlib: { level: 9 } // Sets the compression level.
});
archive.on('error', function(err) {
logger.error(err);
throw err;
});
// pipe archive data to the output file
archive.pipe(output);
for (let file_path of file_paths) {
const file_name = path.parse(file_path).base;
archive.file(file_path, {name: file_name})
}
await archive.finalize();
// wait a tiny bit for the zip to reload in fs
await wait(100);
return zip_file_path;
}
function getJSONMp4(name, customPath, openReadPerms = false) {
var obj = null; // output
if (!customPath) customPath = config_api.getConfigItem('ytdl_video_folder_path');
var jsonPath = path.join(customPath, name + ".info.json");
var alternateJsonPath = path.join(customPath, name + ".mp4.info.json");
if (fs.existsSync(jsonPath))
{
obj = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
} else if (fs.existsSync(alternateJsonPath)) {
obj = JSON.parse(fs.readFileSync(alternateJsonPath, 'utf8'));
}
else obj = 0;
return obj;
}
function getJSONMp3(name, customPath, openReadPerms = false) {
var obj = null;
if (!customPath) customPath = config_api.getConfigItem('ytdl_audio_folder_path');
var jsonPath = path.join(customPath, name + ".info.json");
var alternateJsonPath = path.join(customPath, name + ".mp3.info.json");
if (fs.existsSync(jsonPath)) {
obj = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
}
else if (fs.existsSync(alternateJsonPath)) {
obj = JSON.parse(fs.readFileSync(alternateJsonPath, 'utf8'));
}
else
obj = 0;
return obj;
}
function getJSON(file_path, type) {
const ext = type === 'audio' ? '.mp3' : '.mp4';
let obj = null;
var jsonPath = removeFileExtension(file_path) + '.info.json';
var alternateJsonPath = removeFileExtension(file_path) + `${ext}.info.json`;
if (fs.existsSync(jsonPath))
{
obj = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
} else if (fs.existsSync(alternateJsonPath)) {
obj = JSON.parse(fs.readFileSync(alternateJsonPath, 'utf8'));
}
else obj = 0;
return obj;
}
function getJSONByType(type, name, customPath, openReadPerms = false) {
return type === 'audio' ? getJSONMp3(name, customPath, openReadPerms) : getJSONMp4(name, customPath, openReadPerms)
}
function getDownloadedThumbnail(name, type, customPath = null) {
if (!customPath) customPath = type === 'audio' ? config_api.getConfigItem('ytdl_audio_folder_path') : config_api.getConfigItem('ytdl_video_folder_path');
let jpgPath = path.join(customPath, name + '.jpg');
let webpPath = path.join(customPath, name + '.webp');
let pngPath = path.join(customPath, name + '.png');
if (fs.existsSync(jpgPath))
return jpgPath;
else if (fs.existsSync(webpPath))
return webpPath;
else if (fs.existsSync(pngPath))
return pngPath;
else
return null;
}
function getDownloadedThumbnail2(file_path, type) {
const file_path_no_extension = removeFileExtension(file_path);
let jpgPath = file_path_no_extension + '.jpg';
let webpPath = file_path_no_extension + '.webp';
let pngPath = file_path_no_extension + '.png';
if (fs.existsSync(jpgPath))
return jpgPath;
else if (fs.existsSync(webpPath))
return webpPath;
else if (fs.existsSync(pngPath))
return pngPath;
else
return null;
}
function getExpectedFileSize(input_info_jsons) {
// treat single videos as arrays to have the file sizes checked/added to. makes the code cleaner
const info_jsons = Array.isArray(input_info_jsons) ? input_info_jsons : [input_info_jsons];
let expected_filesize = 0;
info_jsons.forEach(info_json => {
if (info_json['filesize']) {
expected_filesize += info_json['filesize'];
return;
}
const formats = info_json['format_id'].split('+');
let individual_expected_filesize = 0;
formats.forEach(format_id => {
info_json.formats.forEach(available_format => {
if (available_format.format_id === format_id && available_format.filesize) {
individual_expected_filesize += available_format.filesize;
}
});
});
expected_filesize += individual_expected_filesize;
});
return expected_filesize;
}
function fixVideoMetadataPerms(name, type, customPath = null) {
if (is_windows) return;
if (!customPath) customPath = type === 'audio' ? config_api.getConfigItem('ytdl_audio_folder_path')
: config_api.getConfigItem('ytdl_video_folder_path');
const ext = type === 'audio' ? '.mp3' : '.mp4';
const files_to_fix = [
// JSONs
path.join(customPath, name + '.info.json'),
path.join(customPath, name + ext + '.info.json'),
// Thumbnails
path.join(customPath, name + '.webp'),
path.join(customPath, name + '.jpg')
];
for (const file of files_to_fix) {
if (!fs.existsSync(file)) continue;
fs.chmodSync(file, 0o644);
}
}
function fixVideoMetadataPerms2(file_path, type) {
if (is_windows) return;
const ext = type === 'audio' ? '.mp3' : '.mp4';
const file_path_no_extension = removeFileExtension(file_path);
const files_to_fix = [
// JSONs
file_path_no_extension + '.info.json',
file_path_no_extension + ext + '.info.json',
// Thumbnails
file_path_no_extension + '.webp',
file_path_no_extension + '.jpg'
];
for (const file of files_to_fix) {
if (!fs.existsSync(file)) continue;
fs.chmodSync(file, 0o644);
}
}
function deleteJSONFile(name, type, customPath = null) {
if (!customPath) customPath = type === 'audio' ? config_api.getConfigItem('ytdl_audio_folder_path')
: config_api.getConfigItem('ytdl_video_folder_path');
const ext = type === 'audio' ? '.mp3' : '.mp4';
let json_path = path.join(customPath, name + '.info.json');
let alternate_json_path = path.join(customPath, name + ext + '.info.json');
if (fs.existsSync(json_path)) fs.unlinkSync(json_path);
if (fs.existsSync(alternate_json_path)) fs.unlinkSync(alternate_json_path);
}
function deleteJSONFile2(file_path, type) {
const ext = type === 'audio' ? '.mp3' : '.mp4';
const file_path_no_extension = removeFileExtension(file_path);
let json_path = file_path_no_extension + '.info.json';
let alternate_json_path = file_path_no_extension + ext + '.info.json';
if (fs.existsSync(json_path)) fs.unlinkSync(json_path);
if (fs.existsSync(alternate_json_path)) fs.unlinkSync(alternate_json_path);
}
async function removeIDFromArchive(archive_path, id) {
let data = await fs.readFile(archive_path, {encoding: 'utf-8'});
if (!data) {
logger.error('Archive could not be found.');
return;
}
let dataArray = data.split('\n'); // convert file data in an array
const searchKeyword = id; // we are looking for a line, contains, key word id in the file
let lastIndex = -1; // let say, we have not found the keyword
for (let index=0; index<dataArray.length; index++) {
if (dataArray[index].includes(searchKeyword)) { // check if a line contains the id keyword
lastIndex = index; // found a line includes a id keyword
break;
}
}
const line = dataArray.splice(lastIndex, 1); // remove the keyword id from the data Array
// UPDATE FILE WITH NEW DATA
const updatedData = dataArray.join('\n');
await fs.writeFile(archive_path, updatedData);
if (line) return line;
if (err) throw err;
}
function durationStringToNumber(dur_str) {
if (typeof dur_str === 'number') return dur_str;
let num_sum = 0;
const dur_str_parts = dur_str.split(':');
for (let i = dur_str_parts.length-1; i >= 0; i--) {
num_sum += parseInt(dur_str_parts[i])*(60**(dur_str_parts.length-1-i));
}
return num_sum;
}
function getMatchingCategoryFiles(category, files) {
return files && files.filter(file => file.category && file.category.uid === category.uid);
}
function addUIDsToCategory(category, files) {
const files_that_match = getMatchingCategoryFiles(category, files);
category['uids'] = files_that_match.map(file => file.uid);
return files_that_match;
}
function getCurrentDownloader() {
const details_json = fs.readJSONSync(CONSTS.DETAILS_BIN_PATH);
return details_json['downloader'];
}
async function recFindByExt(base,ext,files,result)
{
files = files || (await fs.readdir(base))
result = result || []
for (const file of files) {
var newbase = path.join(base,file)
if ( (await fs.stat(newbase)).isDirectory() )
{
result = await recFindByExt(newbase,ext,await fs.readdir(newbase),result)
}
else
{
if ( file.substr(-1*(ext.length+1)) == '.' + ext )
{
result.push(newbase)
}
}
}
return result
}
function removeFileExtension(filename) {
const filename_parts = filename.split('.');
filename_parts.splice(filename_parts.length - 1);
return filename_parts.join('.');
}
/**
* setTimeout, but its a promise.
* @param {number} ms
*/
async function wait(ms) {
await new Promise(resolve => {
setTimeout(resolve, ms);
});
}
// objects
function File(id, title, thumbnailURL, isAudio, duration, url, uploader, size, path, upload_date, description, view_count, height, abr) {
this.id = id;
this.title = title;
this.thumbnailURL = thumbnailURL;
this.isAudio = isAudio;
this.duration = duration;
this.url = url;
this.uploader = uploader;
this.size = size;
this.path = path;
this.upload_date = upload_date;
this.description = description;
this.view_count = view_count;
this.height = height;
this.abr = abr;
}
module.exports = {
getJSONMp3: getJSONMp3,
getJSONMp4: getJSONMp4,
getJSON: getJSON,
getTrueFileName: getTrueFileName,
getDownloadedThumbnail: getDownloadedThumbnail,
getDownloadedThumbnail2: getDownloadedThumbnail2,
getExpectedFileSize: getExpectedFileSize,
fixVideoMetadataPerms: fixVideoMetadataPerms,
fixVideoMetadataPerms2: fixVideoMetadataPerms2,
deleteJSONFile: deleteJSONFile,
deleteJSONFile2: deleteJSONFile2,
removeIDFromArchive, removeIDFromArchive,
getDownloadedFilesByType: getDownloadedFilesByType,
createContainerZipFile: createContainerZipFile,
durationStringToNumber: durationStringToNumber,
getMatchingCategoryFiles: getMatchingCategoryFiles,
addUIDsToCategory: addUIDsToCategory,
getCurrentDownloader: getCurrentDownloader,
recFindByExt: recFindByExt,
removeFileExtension: removeFileExtension,
wait: wait,
File: File
}
|
import React, { PropTypes } from 'react';
import withStyles from '../../../../node_modules/isomorphic-style-loader/lib/withStyles';
import s from './Button.scss';
function Button({ buttonType, buttonText }) {
let buttonToDisplay;
if (buttonType === 'primary') {
buttonToDisplay = (<button type="button" className={s.primaryButton}>
{buttonText}</button>);
} else if (buttonType === 'info') {
buttonToDisplay = (<button type="button" className={s.infoButton}>
{buttonText}</button>);
} else if (buttonType === 'warning') {
buttonToDisplay = (<button type="button" className={s.warningButton} disabled="true">
{buttonText}</button>);
} else if (buttonType === 'default') {
buttonToDisplay = (<button type="button" className={s.defaultButton} disabled="true">
{buttonText}</button>);
}
return (
<div>
{buttonToDisplay}
</div>
);
}
Button.propTypes = {
buttonType: PropTypes.string.isRequired,
buttonText: PropTypes.string.isRequired,
};
export default withStyles(s)(Button);
|
var React = require("react");
function App(props) {
var arr = [1, 2, 3];
if (props.cond) {
arr.push(4);
} else {
arr.pop();
}
return (
<div>
<span x={arr} />
<span x={arr} />
</div>
);
}
App.getTrials = function(renderer, Root) {
let results = [];
renderer.update(<Root cond={true} />);
results.push(["abstract array length on prop (cond: true)", renderer.toJSON()]);
renderer.update(<Root cond={false} />);
results.push(["abstract array length on prop (cond: false)", renderer.toJSON()]);
return results;
};
if (this.__optimizeReactComponentTree) {
__optimizeReactComponentTree(App);
}
module.exports = App;
|
//
// Gathering log definers in a helper library
// Create logger is for logging outside the express middleware
// Express logger config defines express middleware logging levels
//
var bunyan = require('bunyan');
var config = require('../config/config.js');
//Logger for non middleware
exports.createLogger = function(){
switch (process.env.NODE_ENV) {
case 'development':
return bunyan.createLogger({
name: 'sMailandStuff',
stream: process.stdout,
level: config.appConfig.logLevel.development
});
case 'debug':
return bunyan.createLogger({
name: 'sMailandStuff',
stream: process.stdout,
level: config.appConfig.logLevel.debug
});
case 'production':
return bunyan.createLogger({
name: 'sMailandStuff',
stream: process.stdout,
level: config.appConfig.logLevel.production
});
case 'test':
return bunyan.createLogger({
name: 'sMailandStuff-test',
streams: [{
path: './test/log/test.log',
}],
level: config.appConfig.logLevel.development
});
default:
return bunyan.createLogger({
name: 'sMailandStuff',
stream: process.stdout,
level: config.appConfig.logLevel.development
});
}
};
//Environmental aware config for the middleware
exports.expressLoggerConfig = function() {
var log = module.exports.createLogger();
switch (process.env.NODE_ENV) {
case 'development':
log.info('Expresslogger - development');
return {name: 'DEVELOPMENT',
streams: [{
level: config.appConfig.logLevel.development,
stream: process.stdout
}],
excludes: ['req-headers', 'user-agent','res-headers','response-hrtime','req','res','body']
};
case 'production':
log.info('Expresslogger - production');
return {name: 'PRODUCTION',
streams: [{
level: config.appConfig.logLevel.production,
stream: process.stdout
}],
excludes: ['req-headers', 'user-agent','res-headers','response-hrtime','req','res']
};
case 'debug':
log.info('Expresslogger - debug');
return {name: 'DEBUG',
streams: [{
level: config.appConfig.logLevel.debug,
stream: process.stdout
}],
// excludes: ['req-headers', 'user-agent','res-headers','response-hrtime','req','res']
};
case 'test':
log.info('Expresslogger - test');
return {name: 'TEST',
streams: [{
level: config.appConfig.logLevel.development,
path: './test/log/test_express.log',
}],
// excludes: ['req-headers', 'user-agent','res-headers','response-hrtime','req','res']
};
default :
log.info('Expresslogger - default');
return {name: process.env.NODE_ENV,
streams: [{
level: 'warn',
stream: process.stdout
}],
excludes: ['req-headers', 'user-agent','res-headers','response-hrtime','req','res']
};
}
};
|
import React from 'react'
import PropTypes from 'prop-types'
import { DragHandleIcon } from '../Popup/styled'
export default function DragHandle (props) {
const { color, height, className } = props
return (
<DragHandleIcon color={color} height={height} className={className}>
<svg width='65px' height='7px' viewBox='0 0 32 7' version='1.1' xmlns='http://www.w3.org/2000/svg' >
<title>Drag icon</title>
<g stroke='none' strokeWidth='1' fill='none' fillRule='evenodd'>
<g id='2' transform='translate(-704.000000, -63.000000)' fill='#C1C1C1'>
<g id='Bottom-Sheet' transform='translate(0.000000, 59.000000)'>
<g id='sheet-actions' transform='translate(704.000000, 4.000000)'>
<g id='Drag-icon'>
<rect id='Rectangle' x='0' y='0' width='32' height='2' rx='1'></rect>
<rect id='Rectangle-Copy-4' x='0' y='5' width='32' height='2' rx='1'></rect>
</g>
</g>
</g>
</g>
</g>
</svg>
</DragHandleIcon>
)
}
DragHandle.defaultProps = {
color: 'grey',
height: '7px',
className: 'handle'
}
DragHandle.propTypes = {
color: PropTypes.string,
height: PropTypes.string,
className: PropTypes.string
}
|
this.wc=this.wc||{},this.wc.blocks=this.wc.blocks||{},this.wc.blocks.blocks=function(t){function e(e){for(var r,i,s=e[0],u=e[1],a=e[2],f=0,p=[];f<s.length;f++)i=s[f],Object.prototype.hasOwnProperty.call(o,i)&&o[i]&&p.push(o[i][0]),o[i]=0;for(r in u)Object.prototype.hasOwnProperty.call(u,r)&&(t[r]=u[r]);for(l&&l(e);p.length;)p.shift()();return c.push.apply(c,a||[]),n()}function n(){for(var t,e=0;e<c.length;e++){for(var n=c[e],r=!0,s=1;s<n.length;s++){var u=n[s];0!==o[u]&&(r=!1)}r&&(c.splice(e--,1),t=i(i.s=n[0]))}return t}var r={},o={19:0},c=[];function i(e){if(r[e])return r[e].exports;var n=r[e]={i:e,l:!1,exports:{}};return t[e].call(n.exports,n,n.exports,i),n.l=!0,n.exports}i.m=t,i.c=r,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)i.d(n,r,function(e){return t[e]}.bind(null,r));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="";var s=window.webpackWcBlocksJsonp=window.webpackWcBlocksJsonp||[],u=s.push.bind(s);s.push=e,s=s.slice();for(var a=0;a<s.length;a++)e(s[a]);var l=u;return c.push([929,0]),n()}({0:function(t,e){!function(){t.exports=this.wp.element}()},1:function(t,e){!function(){t.exports=this.wp.i18n}()},19:function(t,e){!function(){t.exports=this.wp.blocks}()},3:function(t,e){!function(){t.exports=this.wc.wcSettings}()},37:function(t,e){!function(){t.exports=this.wp.isShallowEqual}()},586:function(t,e){},587:function(t,e){},6:function(t,e){!function(){t.exports=this.React}()},64:function(t,e,n){"use strict";var r=n(9),o=n.n(r),c=n(31),i=n.n(c),s=n(6);n(2);function u(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}e.a=function(t){var e=t.srcElement,n=t.size,r=void 0===n?24:n,c=i()(t,["srcElement","size"]);return Object(s.isValidElement)(e)&&Object(s.cloneElement)(e,function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?u(Object(n),!0).forEach((function(e){o()(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}({width:r,height:r},c))}},7:function(t,e){!function(){t.exports=this.lodash}()},77:function(t,e){!function(){t.exports=this.wp.hooks}()},929:function(t,e,n){"use strict";n.r(e);var r=n(51),o=n.n(r),c=n(0),i=n(19),s=n(1),u=n(64),a=n(10),l=n.n(a),f=n(31),p=n.n(f),b=n(56),h=n(8),m=n.n(h),d=Object(c.createElement)((function(t){var e=t.className,n=t.height,r=t.width,o=p()(t,["className","height","width"]);return Object(c.createElement)(b.b,l()({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 245 145",className:m()("woo-icon",e),width:r,height:n},o),Object(c.createElement)("path",{fill:"#96588A",d:"M22.76 0h199.1a22.77 22.77 0 0 1 22.8 22.76v75.92a22.77 22.77 0 0 1-22.78 22.78h-71.41l9.77 24-43.13-24H22.76C10.1946 121.449.011 111.2654 0 98.7V22.76C.011 10.1946 10.1946.011 22.76 0z"}),Object(c.createElement)("path",{fill:"#FFF",fillRule:"nonzero",d:"M12.32 20.63a8.16 8.16 0 0 1 6.25-3.09c5.0733-.36 7.9867 2.0333 8.74 7.18 3.14 20.86 6.4933 38.5633 10.06 53.11l21.92-41.69c2-3.76 4.49-5.76 7.52-6 4.3867-.3067 7.13 2.49 8.23 8.39a186 186 0 0 0 9.47 34.23c2.62-25.38 7.0133-43.7133 13.18-55a7.73 7.73 0 0 1 6.6-4.43 8.8 8.8 0 0 1 6.32 2 7.75 7.75 0 0 1 3.05 5.74 8.52 8.52 0 0 1-1 4.77c-3.9 7.24-7.12 19.28-9.66 36.12-2.48 16.2533-3.3967 28.9633-2.75 38.13a12.25 12.25 0 0 1-1.16 6.56 6.32 6.32 0 0 1-5.33 3.53c-2.6667.18-5.3033-1.0567-7.91-3.71-9.2933-9.54-16.6567-23.7267-22.09-42.56C57.3 76.7167 52.48 86.3333 49.3 92.76c-5.86 11.3333-10.89 17.13-15.09 17.39-2.7333.1933-5.0667-2.0933-7-6.86-5.1-13.0933-10.5833-38.4033-16.45-75.93a8.56 8.56 0 0 1 1.56-6.73zM227.23 36.34a23.17 23.17 0 0 0-16-11.59 26.25 26.25 0 0 0-5.42-.58c-9.5867 0-17.41 5-23.47 15a53 53 0 0 0-7.78 28.16c0 7.7333 1.6167 14.3333 4.85 19.8a23.15 23.15 0 0 0 16 11.59 26.28 26.28 0 0 0 5.42.59c9.68 0 17.5033-5 23.47-15A53.89 53.89 0 0 0 232.08 56c0-7.7333-1.6167-14.2867-4.85-19.66zm-12.61 27.72c-1.3733 6.56-3.9167 11.5-7.63 14.82-2.9267 2.6667-5.6133 3.7433-8.06 3.23-2.4467-.5133-4.4033-2.6667-5.87-6.46a25.68 25.68 0 0 1-1.76-9.09 35.9 35.9 0 0 1 .73-7.34 33 33 0 0 1 5.28-11.88c3.3333-4.8933 6.8067-6.9467 10.42-6.16 2.44.4867 4.3933 2.64 5.86 6.46a25.68 25.68 0 0 1 1.76 9.12 35.73 35.73 0 0 1-.73 7.33v-.03zM164.57 36.34a23.2 23.2 0 0 0-16-11.59 26.42 26.42 0 0 0-5.43-.58c-9.5933 0-17.4167 5-23.47 15a53 53 0 0 0-7.78 28.16c0 7.7333 1.6133 14.3333 4.84 19.8a23.19 23.19 0 0 0 16 11.59 26.44 26.44 0 0 0 5.43.59c9.68 0 17.5033-5 23.47-15A53.88 53.88 0 0 0 169.4 56c0-7.7333-1.6133-14.2867-4.84-19.66h.01zm-12.61 27.72c-1.3667 6.56-3.91 11.5-7.63 14.82-2.93 2.64-5.63 3.72-8.07 3.23-2.44-.49-4.4-2.64-5.86-6.46a25.7 25.7 0 0 1-1.77-9.09 35.9 35.9 0 0 1 .74-7.34 33 33 0 0 1 5.28-11.88c3.3333-4.8933 6.8067-6.9467 10.42-6.16 2.44.4867 4.3933 2.64 5.86 6.46a25.91 25.91 0 0 1 1.76 9.12 35.73 35.73 0 0 1-.73 7.33v-.03z"}))}),null),w=Object(c.createElement)(b.b,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},Object(c.createElement)("path",{d:"M12 11a1 1 0 011 1 1 1 0 01-1 1 1 1 0 01-1-1 1 1 0 011-1M4.2 4.2c1.5-1.4 4.5-.8 7.8 1.4 3.3-2.2 6.4-2.8 7.8-1.4 1.4 1.5.8 4.5-1.4 7.8 2.2 3.3 2.8 6.4 1.4 7.8-1.4 1.4-4.6.8-7.8-1.4-3.3 2.2-6.3 2.8-7.8 1.4-1.4-1.4-.8-4.6 1.4-7.8-2.2-3.3-2.8-6.3-1.4-7.8m11.3 4.3a29 29 0 011.7 1.8c1.4-2 2-4 1.2-4.7-.8-.7-2.6-.2-4.7 1.2l1.8 1.7m-7 7a29 29 0 01-1.7-1.8c-1.4 2-2 4-1.2 4.7.8.7 2.6.2 4.7-1.2a29 29 0 01-1.8-1.7M5.6 5.6c-.7.8-.2 2.6 1.2 4.7a29 29 0 013.5-3.5c-2-1.4-4-2-4.7-1.2m4.3 8.5l2.1 2a28.1 28.1 0 004-4.1 28.1 28.1 0 00-4-4 28.1 28.1 0 00-4 4l1.9 2.1m8.5 4.3c.7-.8.2-2.6-1.2-4.7a29 29 0 01-3.5 3.5c2 1.4 4 2 4.7 1.2z"})),v=(n(586),n(587),n(22)),O=n.n(v),g=n(26),y=n.n(g),j=n(21),k=n.n(j),E=n(23),x=n.n(E),P=n(24),W=n.n(P),D=n(12),M=n.n(D),z=n(9),A=n.n(z),S=n(36),_=n(3),B=n(77);function C(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=M()(t);if(e){var o=M()(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return W()(this,n)}}var R=Object(S.b)((function(t){return function(e){x()(r,e);var n=C(r);function r(){var t;O()(this,r);for(var e=arguments.length,o=new Array(e),c=0;c<e;c++)o[c]=arguments[c];return t=n.call.apply(n,[this].concat(o)),A()(k()(t),"mounted",!1),t}return y()(r,[{key:"componentDidMount",value:function(){var t=this.props,e=t.block,n=t.setAttributes;e.name.startsWith("woocommerce/")&&n(this.getAttributesWithDefaults())}},{key:"componentDidUpdate",value:function(){this.props.block.name.startsWith("woocommerce/")&&!this.mounted&&(this.mounted=!0)}},{key:"getAttributesWithDefaults",value:function(){var t=Object(i.getBlockType)(this.props.block.name),e=this.props.attributes;return!this.mounted&&this.props.block.name.startsWith("woocommerce/")&&void 0!==t.attributes&&void 0!==t.defaults&&(e=Object.assign({},this.props.attributes||{}),Object.keys(t.attributes).map((function(n){return void 0===e[n]&&void 0!==t.defaults[n]&&(e[n]=t.defaults[n]),n}))),e}},{key:"render",value:function(){return Object(c.createElement)(t,l()({},this.props,{attributes:this.getAttributesWithDefaults()}))}}]),r}(c.Component)}),"withDefaultAttributes");Object(_.compareWithWpVersion)("5.3","<=")&&Object(B.addFilter)("editor.BlockListBlock","woocommerce-blocks/block-list-block",R);Object(B.addFilter)("blocks.getBlockAttributes","woocommerce-blocks/get-block-attributes",(function(t,e){return e.name.startsWith("woocommerce/")&&Object.keys(e.attributes).map((function(n){return void 0===t[n]&&void 0!==e.defaults&&void 0!==e.defaults[n]&&(t[n]=e.defaults[n]),n})),t})),Object(i.setCategories)([].concat(o()(Object(i.getCategories)().filter((function(t){var e=t.slug;return"woocommerce"!==e&&"woocommerce-product-elements"!==e}))),[{slug:"woocommerce",title:Object(s.__)("WooCommerce",'woocommerce'),icon:Object(c.createElement)(u.a,{srcElement:d})},{slug:"woocommerce-product-elements",title:Object(s.__)("WooCommerce Product Elements",'woocommerce'),icon:Object(c.createElement)(u.a,{srcElement:w,style:{fill:"#874FB9"}})}]))}});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _default = (0, _createSvgIcon.default)(_react.default.createElement(_react.default.Fragment, null, _react.default.createElement("path", {
fill: "none",
d: "M0 0h24v24H0V0z"
}), _react.default.createElement("g", null, _react.default.createElement("path", {
d: "M3 12c0 2.21.91 4.2 2.36 5.64L3 20h6v-6l-2.24 2.24C5.68 15.15 5 13.66 5 12c0-2.61 1.67-4.83 4-5.65V4.26C5.55 5.15 3 8.27 3 12zm8 5h2v-2h-2v2zM21 4h-6v6l2.24-2.24C18.32 8.85 19 10.34 19 12c0 2.61-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74 0-2.21-.91-4.2-2.36-5.64L21 4zm-10 9h2V7h-2v6z"
}))), 'SyncProblemTwoTone');
exports.default = _default;
|
'use strict';
var _ = require('lodash');
var $ = require('preconditions').singleton();
var Uuid = require('uuid');
var log = require('npmlog');
log.debug = log.verbose;
log.disableColor();
var EINRcore = {
'btc': require('EINRcore-lib'),
'bch': require('EINRcore-lib-cash'),
};
var Common = require('../common');
var Constants = Common.Constants,
Defaults = Common.Defaults,
Utils = Common.Utils;
var TxProposalLegacy = require('./txproposal_legacy');
var TxProposalAction = require('./txproposalaction');
function TxProposal() {};
TxProposal.create = function(opts) {
opts = opts || {};
$.checkArgument(Utils.checkValueInCollection(opts.coin, Constants.COINS));
$.checkArgument(Utils.checkValueInCollection(opts.network, Constants.NETWORKS));
var x = new TxProposal();
x.version = 3;
var now = Date.now();
x.createdOn = Math.floor(now / 1000);
x.id = opts.id || Uuid.v4();
x.walletId = opts.walletId;
x.creatorId = opts.creatorId;
x.coin = opts.coin;
x.network = opts.network;
x.message = opts.message;
x.payProUrl = opts.payProUrl;
x.changeAddress = opts.changeAddress;
x.outputs = _.map(opts.outputs, function(output) {
return _.pick(output, ['amount', 'toAddress', 'message', 'script']);
});
x.outputOrder = _.range(x.outputs.length + 1);
if (!opts.noShuffleOutputs) {
x.outputOrder = _.shuffle(x.outputOrder);
}
x.walletM = opts.walletM;
x.walletN = opts.walletN;
x.requiredSignatures = x.walletM;
x.requiredRejections = Math.min(x.walletM, x.walletN - x.walletM + 1),
x.status = 'temporary';
x.actions = [];
x.feeLevel = opts.feeLevel;
x.feePerKb = opts.feePerKb;
x.excludeUnconfirmedUtxos = opts.excludeUnconfirmedUtxos;
x.addressType = opts.addressType || (x.walletN > 1 ? Constants.SCRIPT_TYPES.P2SH : Constants.SCRIPT_TYPES.P2PKH);
$.checkState(Utils.checkValueInCollection(x.addressType, Constants.SCRIPT_TYPES));
x.customData = opts.customData;
x.amount = x.getTotalAmount();
x.setInputs(opts.inputs);
x.fee = opts.fee;
return x;
};
TxProposal.fromObj = function(obj) {
if (!(obj.version >= 3)) {
return TxProposalLegacy.fromObj(obj);
}
var x = new TxProposal();
x.version = obj.version;
x.createdOn = obj.createdOn;
x.id = obj.id;
x.walletId = obj.walletId;
x.creatorId = obj.creatorId;
x.coin = obj.coin || Defaults.COIN;
x.network = obj.network;
x.outputs = obj.outputs;
x.amount = obj.amount;
x.message = obj.message;
x.payProUrl = obj.payProUrl;
x.changeAddress = obj.changeAddress;
x.inputs = obj.inputs;
x.walletM = obj.walletM;
x.walletN = obj.walletN;
x.requiredSignatures = obj.requiredSignatures;
x.requiredRejections = obj.requiredRejections;
x.status = obj.status;
x.txid = obj.txid;
x.broadcastedOn = obj.broadcastedOn;
x.inputPaths = obj.inputPaths;
x.actions = _.map(obj.actions, function(action) {
return TxProposalAction.fromObj(action);
});
x.outputOrder = obj.outputOrder;
x.fee = obj.fee;
x.feeLevel = obj.feeLevel;
x.feePerKb = obj.feePerKb;
x.excludeUnconfirmedUtxos = obj.excludeUnconfirmedUtxos;
x.addressType = obj.addressType;
x.customData = obj.customData;
x.proposalSignature = obj.proposalSignature;
x.proposalSignaturePubKey = obj.proposalSignaturePubKey;
x.proposalSignaturePubKeySig = obj.proposalSignaturePubKeySig;
return x;
};
TxProposal.prototype.toObject = function() {
var x = _.cloneDeep(this);
x.isPending = this.isPending();
return x;
};
TxProposal.prototype.setInputs = function(inputs) {
this.inputs = inputs || [];
this.inputPaths = _.pluck(inputs, 'path') || [];
};
TxProposal.prototype._updateStatus = function() {
if (this.status != 'pending') return;
if (this.isRejected()) {
this.status = 'rejected';
} else if (this.isAccepted()) {
this.status = 'accepted';
}
};
TxProposal.prototype._buildTx = function() {
var self = this;
var t = new EINRcore[self.coin].Transaction();
$.checkState(Utils.checkValueInCollection(self.addressType, Constants.SCRIPT_TYPES));
switch (self.addressType) {
case Constants.SCRIPT_TYPES.P2SH:
_.each(self.inputs, function(i) {
$.checkState(i.publicKeys, 'Inputs should include public keys');
t.from(i, i.publicKeys, self.requiredSignatures);
});
break;
case Constants.SCRIPT_TYPES.P2PKH:
t.from(self.inputs);
break;
}
_.each(self.outputs, function(o) {
$.checkState(o.script || o.toAddress, 'Output should have either toAddress or script specified');
if (o.script) {
t.addOutput(new EINRcore[self.coin].Transaction.Output({
script: o.script,
satoshis: o.amount
}));
} else {
t.to(o.toAddress, o.amount);
}
});
t.fee(self.fee);
if (self.changeAddress) {
t.change(self.changeAddress.address);
}
// Shuffle outputs for improved privacy
if (t.outputs.length > 1) {
var outputOrder = _.reject(self.outputOrder, function(order) {
return order >= t.outputs.length;
});
$.checkState(t.outputs.length == outputOrder.length);
t.sortOutputs(function(outputs) {
return _.map(outputOrder, function(i) {
return outputs[i];
});
});
}
// Validate actual inputs vs outputs independently of EINRcore
var totalInputs = _.sum(t.inputs, 'output.satoshis');
var totalOutputs = _.sum(t.outputs, 'satoshis');
$.checkState(totalInputs > 0 && totalOutputs > 0 && totalInputs >= totalOutputs);
$.checkState(totalInputs - totalOutputs <= Defaults.MAX_TX_FEE);
return t;
};
TxProposal.prototype._getCurrentSignatures = function() {
var acceptedActions = _.filter(this.actions, {
type: 'accept'
});
return _.map(acceptedActions, function(x) {
return {
signatures: x.signatures,
xpub: x.xpub,
};
});
};
TxProposal.prototype.getEINRcoreTx = function() {
var self = this;
var t = this._buildTx();
var sigs = this._getCurrentSignatures();
_.each(sigs, function(x) {
self._addSignaturesToEINRcoreTx(t, x.signatures, x.xpub);
});
return t;
};
TxProposal.prototype.getRawTx = function() {
var t = this.getEINRcoreTx();
return t.uncheckedSerialize();
};
TxProposal.prototype.getEstimatedSizeForSingleInput = function() {
switch (this.addressType) {
case Constants.SCRIPT_TYPES.P2PKH:
return 147;
default:
case Constants.SCRIPT_TYPES.P2SH:
return this.requiredSignatures * 72 + this.walletN * 36 + 44;
}
};
TxProposal.prototype.getEstimatedSize = function() {
// Note: found empirically based on all multisig P2SH inputs and within m & n allowed limits.
var safetyMargin = 0.02;
var overhead = 4 + 4 + 9 + 9;
var inputSize = this.getEstimatedSizeForSingleInput();
var outputSize = 34;
var nbInputs = this.inputs.length;
var nbOutputs = (_.isArray(this.outputs) ? Math.max(1, this.outputs.length) : 1) + 1;
var size = overhead + inputSize * nbInputs + outputSize * nbOutputs;
return parseInt((size * (1 + safetyMargin)).toFixed(0));
};
TxProposal.prototype.getEstimatedFee = function() {
$.checkState(_.isNumber(this.feePerKb));
var fee = this.feePerKb * this.getEstimatedSize() / 1000;
return parseInt(fee.toFixed(0));
};
TxProposal.prototype.estimateFee = function() {
this.fee = this.getEstimatedFee();
};
/**
* getTotalAmount
*
* @return {Number} total amount of all outputs excluding change output
*/
TxProposal.prototype.getTotalAmount = function() {
return _.sum(this.outputs, 'amount');
};
/**
* getActors
*
* @return {String[]} copayerIds that performed actions in this proposal (accept / reject)
*/
TxProposal.prototype.getActors = function() {
return _.pluck(this.actions, 'copayerId');
};
/**
* getApprovers
*
* @return {String[]} copayerIds that approved the tx proposal (accept)
*/
TxProposal.prototype.getApprovers = function() {
return _.pluck(
_.filter(this.actions, {
type: 'accept'
}), 'copayerId');
};
/**
* getActionBy
*
* @param {String} copayerId
* @return {Object} type / createdOn
*/
TxProposal.prototype.getActionBy = function(copayerId) {
return _.find(this.actions, {
copayerId: copayerId
});
};
TxProposal.prototype.addAction = function(copayerId, type, comment, signatures, xpub) {
var action = TxProposalAction.create({
copayerId: copayerId,
type: type,
signatures: signatures,
xpub: xpub,
comment: comment,
});
this.actions.push(action);
this._updateStatus();
};
TxProposal.prototype._addSignaturesToEINRcoreTx = function(tx, signatures, xpub) {
var self = this;
var EINRcore = EINRcore[self.coin];
if (signatures.length != this.inputs.length)
throw new Error('Number of signatures does not match number of inputs');
var i = 0,
x = new EINRcore.HDPublicKey(xpub);
_.each(signatures, function(signatureHex) {
var input = self.inputs[i];
try {
var signature = EINRcore.crypto.Signature.fromString(signatureHex);
var pub = x.deriveChild(self.inputPaths[i]).publicKey;
var s = {
inputIndex: i,
signature: signature,
sigtype: EINRcore.crypto.Signature.SIGHASH_ALL | EINRcore.crypto.Signature.SIGHASH_FORKID,
publicKey: pub,
};
tx.inputs[i].addSignature(tx, s);
i++;
} catch (e) {};
});
if (i != tx.inputs.length)
throw new Error('Wrong signatures');
};
TxProposal.prototype.sign = function(copayerId, signatures, xpub) {
try {
// Tests signatures are OK
var tx = this.getEINRcoreTx();
this._addSignaturesToEINRcoreTx(tx, signatures, xpub);
this.addAction(copayerId, 'accept', null, signatures, xpub);
if (this.status == 'accepted') {
this.raw = tx.uncheckedSerialize();
this.txid = tx.id;
}
return true;
} catch (e) {
log.debug(e);
return false;
}
};
TxProposal.prototype.reject = function(copayerId, reason) {
this.addAction(copayerId, 'reject', reason);
};
TxProposal.prototype.isTemporary = function() {
return this.status == 'temporary';
};
TxProposal.prototype.isPending = function() {
return !_.contains(['temporary', 'broadcasted', 'rejected'], this.status);
};
TxProposal.prototype.isAccepted = function() {
var votes = _.countBy(this.actions, 'type');
return votes['accept'] >= this.requiredSignatures;
};
TxProposal.prototype.isRejected = function() {
var votes = _.countBy(this.actions, 'type');
return votes['reject'] >= this.requiredRejections;
};
TxProposal.prototype.isBroadcasted = function() {
return this.status == 'broadcasted';
};
TxProposal.prototype.setBroadcasted = function() {
$.checkState(this.txid);
this.status = 'broadcasted';
this.broadcastedOn = Math.floor(Date.now() / 1000);
};
module.exports = TxProposal;
|
# Generated by Django 2.0.2 on 2018-08-12 09:55
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0030_auto_20180811_1620'),
]
operations = [
migrations.CreateModel(
name='currentData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('data', models.FileField(upload_to='main/static/main/data')),
('dateRecorded', models.DateTimeField(default=datetime.datetime(2018, 8, 12, 12, 55, 33, 918461), verbose_name='Date')),
('name', models.CharField(max_length=200)),
('cropName', models.CharField(max_length=100, null=True, verbose_name='Crop Name')),
],
),
migrations.DeleteModel(
name='Crop_Seasons',
),
migrations.AlterField(
model_name='csv_data',
name='dateRecorded',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 12, 12, 55, 33, 914464), verbose_name='Date'),
),
migrations.AlterField(
model_name='expenses',
name='dateRecorded',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 12, 12, 55, 33, 917462), verbose_name='Date'),
),
migrations.AlterField(
model_name='farm_production',
name='dateRecorded',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 12, 12, 55, 33, 918461), verbose_name='Date'),
),
]
|
'use strict';
module.exports = function() {
return {
debounce: function(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
};
};
|
import Typography from '@material-ui/core/Typography'
import BrushIcon from '@material-ui/icons/BrushSharp'
import CategoryIcon from '@material-ui/icons/CategorySharp'
import ChevronLeftIcon from '@material-ui/icons/ChevronLeftSharp'
import ChevronRightIcon from '@material-ui/icons/ChevronRightSharp'
import DeviceHubIcon from '@material-ui/icons/DeviceHubSharp'
import GridOnIcon from '@material-ui/icons/GridOnSharp'
import PlayArrowIcon from '@material-ui/icons/PlayArrowSharp'
import RedoIcon from '@material-ui/icons/RedoSharp'
import SkipNextIcon from '@material-ui/icons/SkipNextSharp'
import SkipPreviousIcon from '@material-ui/icons/SkipPreviousSharp'
import StopIcon from '@material-ui/icons/StopSharp'
import UndoIcon from '@material-ui/icons/UndoSharp'
import ZoomInIcon from '@material-ui/icons/ZoomInSharp'
import ZoomOutIcon from '@material-ui/icons/ZoomOutSharp'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { connect } from 'react-redux'
import ReactTour from 'reactour'
import { bindActionCreators } from 'redux'
import { operations as tutorialOperations } from '../../ducks/tutorial'
const mapStateToProps = state => ({
isTourOpen: state.tutorial.visible,
})
const mapDispatchToProps = dispatch =>
bindActionCreators(tutorialOperations, dispatch)
const Tutorial = ({ isTourOpen, setTutorialVisibility }) => {
const { t } = useTranslation()
const closeTutorial = () => setTutorialVisibility(false)
const steps = [
{
content: (
<>
<Typography gutterBottom variant="body1">
{t('app.tutorial.step1.welcome')}
</Typography>
<Typography gutterBottom variant="h6">
{t('common.project_name')}
</Typography>
<Typography gutterBottom variant="body1">
{t('app.tutorial.step1.body')}
</Typography>
</>
),
selector: '#root',
},
{
content: (
<Typography gutterBottom variant="body1">
<Typography gutterBottom variant="h6">
{t('common.project_name')}
</Typography>
{t('app.tutorial.step2.body')}
</Typography>
),
selector: '#root',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step3.body')}
</Typography>
),
selector: '#interactive_editor',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step4.body')}
</Typography>
),
selector: '#editor_bar',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step5.first')} <strong>undo</strong> <RedoIcon />{' '}
{t('app.tutorial.step5.second')} <strong>redo</strong> <UndoIcon />{' '}
{t('app.tutorial.step5.third')}
</Typography>
),
selector: '#editor_bar_undo_redo_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step6.first')} <strong>zoom in</strong>{' '}
<ZoomInIcon /> {t('app.tutorial.step6.second')}{' '}
<strong>zoom out</strong> <ZoomOutIcon />{' '}
{t('app.tutorial.step6.third')}
</Typography>
),
selector: '#editor_bar_zoom_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step7.first')} <strong>grid</strong> <GridOnIcon />{' '}
{t('app.tutorial.step7.second')}
</Typography>
),
selector: '#editor_bar_grid_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step8.body')}
</Typography>
),
selector: '#editor_bar_editor_mode_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step9.first')} <strong>selector</strong>{' '}
<BrushIcon /> {t('app.tutorial.step9.second')} <strong>edit</strong>{' '}
{t('app.tutorial.step9.third')} <strong>delete</strong>{' '}
{t('app.tutorial.step9.fourth')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_editor_select_mode_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step10.first')} <strong>nodes</strong>{' '}
<CategoryIcon /> {t('app.tutorial.step10.second')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_editor_nodes_mode_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step11.first')} <strong>edges</strong>{' '}
<DeviceHubIcon /> {t('app.tutorial.step11.second')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_editor_edges_mode_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step13.body')}
</Typography>
),
selector: '#editor_bar_algorithm_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step14.first')} <strong>play</strong>{' '}
<PlayArrowIcon /> {t('app.tutorial.step14.second')}{' '}
<strong>stop</strong> <StopIcon /> {t('app.tutorial.step14.third')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_algorithm_play_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step15.first')} <strong>first step</strong>{' '}
<SkipPreviousIcon /> {t('app.tutorial.step15.second')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_algorithm_first_step_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step16.first')} <strong>back step</strong>{' '}
<ChevronLeftIcon /> {t('app.tutorial.step16.second')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_algorithm_back_step_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step17.first')} <strong>next step</strong>{' '}
<ChevronRightIcon /> {t('app.tutorial.step17.second')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_algorithm_next_step_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step18.first')} <strong>last step</strong>{' '}
<SkipNextIcon /> {t('app.tutorial.step18.second')}
</Typography>
),
position: 'bottom',
selector: '#editor_bar_algorithm_last_step_section',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step19.first')}{' '}
<strong>{t('app.appbar.menu.file')}</strong>{' '}
{t('app.tutorial.step19.second')}
</Typography>
),
selector: '#file_dropdown_menu',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step20.body')}
</Typography>
),
selector: '#google_signin_button',
},
{
content: (
<Typography gutterBottom variant="body1">
{t('app.tutorial.step21.first')}{' '}
<Typography gutterBottom variant="button">
{' '}
<strong>{t('app.appbar.menu.help')}</strong>
</Typography>{' '}
{t('app.tutorial.step21.second')}
</Typography>
),
selector: '#help_button',
},
{
content: (
<>
<Typography gutterBottom variant="body1">
<strong>{t('app.tutorial.step22.first')}</strong>
</Typography>
<Typography gutterBottom variant="body1">
<em>
{t('app.tutorial.step22.second')}{' '}
<Typography gutterBottom variant="button">
✗
</Typography>{' '}
{t('app.tutorial.step22.third')}
</em>
</Typography>
</>
),
selector: '#root',
},
]
return (
<ReactTour
disableDotsNavigation
disableInteraction
isOpen={isTourOpen}
showNavigation={false}
startAt={0}
steps={steps}
onRequestClose={closeTutorial}
/>
)
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Tutorial)
|
var Struct = require('structjs')
var Record = new Struct({
platformID: Struct.Uint16,
encodingID: Struct.Uint16,
languageID: Struct.Uint16,
nameID: Struct.Uint16,
length: Struct.Uint16.with({
$unpacked: function(value) {
return value / 2
},
$packing: function(value) {
return value * 2
}
}),
offset: Struct.Uint16,
string: Struct.String({
storage: true, size: 2,
length: Struct.Ref('length'),
offset: Struct.Ref('offset')
})
})
var Name = module.exports = new Struct({
format: Struct.Uint16,
count: Struct.Uint16,
stringOffset: Struct.Uint16,
records: Struct.Array(Record, Struct.Ref('count')),
names: Struct.Storage('records.string', Struct.Ref('stringOffset'))
})
Name.prototype.embed = function(charMap, trimNames) {
var postscriptName = null
for (var i = 0; i < this.records.length; ++i) {
var record = this.records[i]
if (trimNames && record.platformID !== 0) { // unicode
this.records.splice(i--, 1)
continue
}
switch (record.nameID) {
case 0: // copyright
case 2: // font subfamily name
case 5: // version string
case 7: // trademark
case 13: // license description
case 14: // license info URL
// preserve
break
case 1: // font family name
case 3: // unique font identifier
case 4: // full font name
case 6: // postscript name
record.string = "TTFJS+" + record.string
break
default:
this.records.splice(i--, 1)
break
}
}
}
|