file_path
stringlengths
11
219
num_changed_lines
int64
0
58.4k
code
stringlengths
0
3.52M
repo_name
stringclasses
25 values
commit_date
stringclasses
5 values
sha
stringclasses
25 values
numpy/lib/tests/test_packbits.py
178
from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import ( assert_array_equal, assert_equal, assert_raises, run_module_suite ) def test_packbits(): # Copied from the docstring. a = [[[1, 0, 1], [0, 1, 0]], [[1, 1, 0], [0, 0, 1]]] for dt in '?bBhHiIlLqQ': arr = np.array(a, dtype=dt) b = np.packbits(arr, axis=-1) assert_equal(b.dtype, np.uint8) assert_array_equal(b, np.array([[[160], [64]], [[192], [32]]])) assert_raises(TypeError, np.packbits, np.array(a, dtype=float)) def test_packbits_empty(): shapes = [ (0,), (10, 20, 0), (10, 0, 20), (0, 10, 20), (20, 0, 0), (0, 20, 0), (0, 0, 20), (0, 0, 0), ] for dt in '?bBhHiIlLqQ': for shape in shapes: a = np.empty(shape, dtype=dt) b = np.packbits(a) assert_equal(b.dtype, np.uint8) assert_equal(b.shape, (0,)) def test_packbits_empty_with_axis(): # Original shapes and lists of packed shapes for different axes. shapes = [ ((0,), [(0,)]), ((10, 20, 0), [(2, 20, 0), (10, 3, 0), (10, 20, 0)]), ((10, 0, 20), [(2, 0, 20), (10, 0, 20), (10, 0, 3)]), ((0, 10, 20), [(0, 10, 20), (0, 2, 20), (0, 10, 3)]), ((20, 0, 0), [(3, 0, 0), (20, 0, 0), (20, 0, 0)]), ((0, 20, 0), [(0, 20, 0), (0, 3, 0), (0, 20, 0)]), ((0, 0, 20), [(0, 0, 20), (0, 0, 20), (0, 0, 3)]), ((0, 0, 0), [(0, 0, 0), (0, 0, 0), (0, 0, 0)]), ] for dt in '?bBhHiIlLqQ': for in_shape, out_shapes in shapes: for ax, out_shape in enumerate(out_shapes): a = np.empty(in_shape, dtype=dt) b = np.packbits(a, axis=ax) assert_equal(b.dtype, np.uint8) assert_equal(b.shape, out_shape) def test_packbits_large(): # test data large enough for 16 byte vectorization a = np.array([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0]) a = a.repeat(3) for dtype in '?bBhHiIlLqQ': arr = np.array(a, dtype=dtype) b = np.packbits(arr, axis=None) assert_equal(b.dtype, np.uint8) r = [252, 127, 192, 3, 254, 7, 252, 0, 7, 31, 240, 0, 28, 1, 255, 252, 113, 248, 3, 255, 192, 28, 15, 192, 28, 126, 0, 224, 127, 255, 227, 142, 7, 31, 142, 63, 28, 126, 56, 227, 240, 0, 227, 128, 63, 224, 14, 56, 252, 112, 56, 255, 241, 248, 3, 240, 56, 224, 112, 63, 255, 255, 199, 224, 14, 0, 31, 143, 192, 3, 255, 199, 0, 1, 255, 224, 1, 255, 252, 126, 63, 0, 1, 192, 252, 14, 63, 0, 15, 199, 252, 113, 255, 3, 128, 56, 252, 14, 7, 0, 113, 255, 255, 142, 56, 227, 129, 248, 227, 129, 199, 31, 128] assert_array_equal(b, r) # equal for size being multiple of 8 assert_array_equal(np.unpackbits(b)[:-4], a) # check last byte of different remainders (16 byte vectorization) b = [np.packbits(arr[:-i], axis=None)[-1] for i in range(1, 16)] assert_array_equal(b, [128, 128, 128, 31, 30, 28, 24, 16, 0, 0, 0, 199, 198, 196, 192]) arr = arr.reshape(36, 25) b = np.packbits(arr, axis=0) assert_equal(b.dtype, np.uint8) assert_array_equal(b, [[190, 186, 178, 178, 150, 215, 87, 83, 83, 195, 199, 206, 204, 204, 140, 140, 136, 136, 8, 40, 105, 107, 75, 74, 88], [72, 216, 248, 241, 227, 195, 202, 90, 90, 83, 83, 119, 127, 109, 73, 64, 208, 244, 189, 45, 41, 104, 122, 90, 18], [113, 120, 248, 216, 152, 24, 60, 52, 182, 150, 150, 150, 146, 210, 210, 246, 255, 255, 223, 151, 21, 17, 17, 131, 163], [214, 210, 210, 64, 68, 5, 5, 1, 72, 88, 92, 92, 78, 110, 39, 181, 149, 220, 222, 218, 218, 202, 234, 170, 168], [0, 128, 128, 192, 80, 112, 48, 160, 160, 224, 240, 208, 144, 128, 160, 224, 240, 208, 144, 144, 176, 240, 224, 192, 128]]) b = np.packbits(arr, axis=1) assert_equal(b.dtype, np.uint8) assert_array_equal(b, [[252, 127, 192, 0], [ 7, 252, 15, 128], [240, 0, 28, 0], [255, 128, 0, 128], [192, 31, 255, 128], [142, 63, 0, 0], [255, 240, 7, 0], [ 7, 224, 14, 0], [126, 0, 224, 0], [255, 255, 199, 0], [ 56, 28, 126, 0], [113, 248, 227, 128], [227, 142, 63, 0], [ 0, 28, 112, 0], [ 15, 248, 3, 128], [ 28, 126, 56, 0], [ 56, 255, 241, 128], [240, 7, 224, 0], [227, 129, 192, 128], [255, 255, 254, 0], [126, 0, 224, 0], [ 3, 241, 248, 0], [ 0, 255, 241, 128], [128, 0, 255, 128], [224, 1, 255, 128], [248, 252, 126, 0], [ 0, 7, 3, 128], [224, 113, 248, 0], [ 0, 252, 127, 128], [142, 63, 224, 0], [224, 14, 63, 0], [ 7, 3, 128, 0], [113, 255, 255, 128], [ 28, 113, 199, 0], [ 7, 227, 142, 0], [ 14, 56, 252, 0]]) arr = arr.T.copy() b = np.packbits(arr, axis=0) assert_equal(b.dtype, np.uint8) assert_array_equal(b, [[252, 7, 240, 255, 192, 142, 255, 7, 126, 255, 56, 113, 227, 0, 15, 28, 56, 240, 227, 255, 126, 3, 0, 128, 224, 248, 0, 224, 0, 142, 224, 7, 113, 28, 7, 14], [127, 252, 0, 128, 31, 63, 240, 224, 0, 255, 28, 248, 142, 28, 248, 126, 255, 7, 129, 255, 0, 241, 255, 0, 1, 252, 7, 113, 252, 63, 14, 3, 255, 113, 227, 56], [192, 15, 28, 0, 255, 0, 7, 14, 224, 199, 126, 227, 63, 112, 3, 56, 241, 224, 192, 254, 224, 248, 241, 255, 255, 126, 3, 248, 127, 224, 63, 128, 255, 199, 142, 252], [0, 128, 0, 128, 128, 0, 0, 0, 0, 0, 0, 128, 0, 0, 128, 0, 128, 0, 128, 0, 0, 0, 128, 128, 128, 0, 128, 0, 128, 0, 0, 0, 128, 0, 0, 0]]) b = np.packbits(arr, axis=1) assert_equal(b.dtype, np.uint8) assert_array_equal(b, [[190, 72, 113, 214, 0], [186, 216, 120, 210, 128], [178, 248, 248, 210, 128], [178, 241, 216, 64, 192], [150, 227, 152, 68, 80], [215, 195, 24, 5, 112], [ 87, 202, 60, 5, 48], [ 83, 90, 52, 1, 160], [ 83, 90, 182, 72, 160], [195, 83, 150, 88, 224], [199, 83, 150, 92, 240], [206, 119, 150, 92, 208], [204, 127, 146, 78, 144], [204, 109, 210, 110, 128], [140, 73, 210, 39, 160], [140, 64, 246, 181, 224], [136, 208, 255, 149, 240], [136, 244, 255, 220, 208], [ 8, 189, 223, 222, 144], [ 40, 45, 151, 218, 144], [105, 41, 21, 218, 176], [107, 104, 17, 202, 240], [ 75, 122, 17, 234, 224], [ 74, 90, 131, 170, 192], [ 88, 18, 163, 168, 128]]) # result is the same if input is multiplied with a nonzero value for dtype in 'bBhHiIlLqQ': arr = np.array(a, dtype=dtype) rnd = np.random.randint(low=np.iinfo(dtype).min, high=np.iinfo(dtype).max, size=arr.size, dtype=dtype) rnd[rnd == 0] = 1 arr *= rnd.astype(dtype) b = np.packbits(arr, axis=-1) assert_array_equal(np.unpackbits(b)[:-4], a) assert_raises(TypeError, np.packbits, np.array(a, dtype=float)) def test_unpackbits(): # Copied from the docstring. a = np.array([[2], [7], [23]], dtype=np.uint8) b = np.unpackbits(a, axis=1) assert_equal(b.dtype, np.uint8) assert_array_equal(b, np.array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1]])) def test_unpackbits_empty(): a = np.empty((0,), dtype=np.uint8) b = np.unpackbits(a) assert_equal(b.dtype, np.uint8) assert_array_equal(b, np.empty((0,))) def test_unpackbits_empty_with_axis(): # Lists of packed shapes for different axes and unpacked shapes. shapes = [ ([(0,)], (0,)), ([(2, 24, 0), (16, 3, 0), (16, 24, 0)], (16, 24, 0)), ([(2, 0, 24), (16, 0, 24), (16, 0, 3)], (16, 0, 24)), ([(0, 16, 24), (0, 2, 24), (0, 16, 3)], (0, 16, 24)), ([(3, 0, 0), (24, 0, 0), (24, 0, 0)], (24, 0, 0)), ([(0, 24, 0), (0, 3, 0), (0, 24, 0)], (0, 24, 0)), ([(0, 0, 24), (0, 0, 24), (0, 0, 3)], (0, 0, 24)), ([(0, 0, 0), (0, 0, 0), (0, 0, 0)], (0, 0, 0)), ] for in_shapes, out_shape in shapes: for ax, in_shape in enumerate(in_shapes): a = np.empty(in_shape, dtype=np.uint8) b = np.unpackbits(a, axis=ax) assert_equal(b.dtype, np.uint8) assert_equal(b.shape, out_shape) def test_unpackbits_large(): # test all possible numbers via comparison to already tested packbits d = np.arange(277, dtype=np.uint8) assert_array_equal(np.packbits(np.unpackbits(d)), d) assert_array_equal(np.packbits(np.unpackbits(d[::2])), d[::2]) d = np.tile(d, (3, 1)) assert_array_equal(np.packbits(np.unpackbits(d, axis=1), axis=1), d) d = d.T.copy() assert_array_equal(np.packbits(np.unpackbits(d, axis=0), axis=0), d) if __name__ == "__main__": run_module_suite()
numpy_numpy
2017-01-24
c5e1773f0d77755e21d072eb106b8e51a672bfa8
wp-admin/js/customize-controls.min.js
2
!function(a,b){var c,d,e,f=wp.customize;f.Setting=f.Value.extend({initialize:function(a,b,c){var d=this;f.Value.prototype.initialize.call(d,b,c),d.id=a,d.transport=d.transport||"refresh",d._dirty=c.dirty||!1,d.notifications=new f.Values({defaultConstructor:f.Notification}),d.bind(d.preview)},preview:function(){var a,b=this;a=b.transport,"postMessage"!==a||f.state("previewerAlive").get()||(a="refresh"),"postMessage"===a?b.previewer.send("setting",[b.id,b()]):"refresh"===a&&b.previewer.refresh()},findControls:function(){var a=this,b=[];return f.control.each(function(c){_.each(c.settings,function(d){d.id===a.id&&b.push(c)})}),b}}),f._latestRevision=0,f._lastSavedRevision=0,f._latestSettingRevisions={},f.bind("change",function(a){f._latestRevision+=1,f._latestSettingRevisions[a.id]=f._latestRevision}),f.bind("ready",function(){f.bind("add",function(a){a._dirty&&(f._latestRevision+=1,f._latestSettingRevisions[a.id]=f._latestRevision)})}),f.dirtyValues=function(a){var b={};return f.each(function(c){var d;c._dirty&&(d=f._latestSettingRevisions[c.id],f.state("changesetStatus").get()&&a&&a.unsaved&&(_.isUndefined(d)||d<=f._lastSavedRevision)||(b[c.id]=c.get()))}),b},f.requestChangesetUpdate=function(a){var c,d,e,g={};return c=new b.Deferred,a&&_.extend(g,a),_.each(f.dirtyValues({unsaved:!0}),function(b,c){a&&null===a[c]||(g[c]=_.extend({},g[c]||{},{value:b}))}),_.isEmpty(g)?(c.resolve({}),c.promise()):(f.state("processing").set(f.state("processing").get()+1),c.always(function(){f.state("processing").set(f.state("processing").get()-1)}),f.trigger("changeset-save",g),e=f.previewer.query({excludeCustomizedSaved:!0}),delete e.customized,_.extend(e,{nonce:f.settings.nonce.save,customize_theme:f.settings.theme.stylesheet,customize_changeset_data:JSON.stringify(g)}),d=wp.ajax.post("customize_save",e),d.done(function(a){var b={};f._lastSavedRevision=Math.max(f._latestRevision,f._lastSavedRevision),f.state("changesetStatus").set(a.changeset_status),c.resolve(a),f.trigger("changeset-saved",a),a.setting_validities&&_.each(a.setting_validities,function(a,c){!0===a&&_.isObject(g[c])&&!_.isUndefined(g[c].value)&&(b[c]=g[c].value)}),f.previewer.send("changeset-saved",_.extend({},a,{saved_changeset_values:b}))}),d.fail(function(a){c.reject(a),f.trigger("changeset-error",a)}),d.always(function(a){a.setting_validities&&f._handleSettingValidities({settingValidities:a.setting_validities})}),c.promise())},f.utils.bubbleChildValueChanges=function(a,c){b.each(c,function(b,c){a[c].bind(function(b,c){a.parent&&b!==c&&a.parent.trigger("change",a)})})},d=function(a){var b,c,d,e;b=this,a=a||{},d=function(){var a;a=(b.extended(f.Panel)||b.extended(f.Section))&&b.expanded&&b.expanded()?b.contentContainer:b.container,e=a.find(".control-focus:first"),0===e.length&&(e=a.find("input, select, textarea, button, object, a[href], [tabindex]").filter(":visible").first()),e.focus()},a.completeCallback?(c=a.completeCallback,a.completeCallback=function(){d(),c()}):a.completeCallback=d,f.state("paneVisible").set(!0),b.expand?b.expand(a):a.completeCallback()},f.utils.prioritySort=function(a,b){return a.priority()===b.priority()&&"number"==typeof a.params.instanceNumber&&"number"==typeof b.params.instanceNumber?a.params.instanceNumber-b.params.instanceNumber:a.priority()-b.priority()},f.utils.isKeydownButNotEnterEvent=function(a){return"keydown"===a.type&&13!==a.which},f.utils.areElementListsEqual=function(a,c){var d=a.length===c.length&&-1===_.indexOf(_.map(_.zip(a,c),function(a){return b(a[0]).is(a[1])}),!1);return d},e=function(){var a,b,c;return a=document.createElement("div"),b={transition:"transitionend",OTransition:"oTransitionEnd",MozTransition:"transitionend",WebkitTransition:"webkitTransitionEnd"},c=_.find(_.keys(b),function(b){return!_.isUndefined(a.style[b])}),c?b[c]:null}(),c=f.Class.extend({defaultActiveArguments:{duration:"fast",completeCallback:b.noop},defaultExpandedArguments:{duration:"fast",completeCallback:b.noop},containerType:"container",defaults:{title:"",description:"",priority:100,type:"default",content:null,active:!0,instanceNumber:null},initialize:function(a,c){var d=this;d.id=a,c=c||{},c.params=_.defaults(c.params||{},d.defaults),b.extend(d,c),d.templateSelector="customize-"+d.containerType+"-"+d.params.type,d.container=b(d.params.content),0===d.container.length&&(d.container=b(d.getContainer())),d.headContainer=d.container,d.contentContainer=d.getContent(),d.container=d.container.add(d.contentContainer),d.deferred={embedded:new b.Deferred},d.priority=new f.Value,d.active=new f.Value,d.activeArgumentsQueue=[],d.expanded=new f.Value,d.expandedArgumentsQueue=[],d.active.bind(function(a){var c=d.activeArgumentsQueue.shift();c=b.extend({},d.defaultActiveArguments,c),a=a&&d.isContextuallyActive(),d.onChangeActive(a,c)}),d.expanded.bind(function(a){var c=d.expandedArgumentsQueue.shift();c=b.extend({},d.defaultExpandedArguments,c),d.onChangeExpanded(a,c)}),d.deferred.embedded.done(function(){d.attachEvents()}),f.utils.bubbleChildValueChanges(d,["priority","active"]),d.priority.set(d.params.priority),d.active.set(d.params.active),d.expanded.set(!1)},ready:function(){},_children:function(a,b){var c=this,d=[];return f[b].each(function(b){b[a].get()===c.id&&d.push(b)}),d.sort(f.utils.prioritySort),d},isContextuallyActive:function(){throw new Error("Container.isContextuallyActive() must be overridden in a subclass.")},onChangeActive:function(a,c){var d,e,g=this,h=g.headContainer;return c.unchanged?void(c.completeCallback&&c.completeCallback()):(d="resolved"===f.previewer.deferred.active.state()?c.duration:0,g.extended(f.Panel)&&(f.panel.each(function(a){a!==g&&a.expanded()&&(e=a,d=0)}),a||_.each(g.sections(),function(a){a.collapse({duration:0})})),void(b.contains(document,h)?a?h.stop(!0,!0).slideDown(d,c.completeCallback):g.expanded()?g.collapse({duration:d,completeCallback:function(){h.stop(!0,!0).slideUp(d,c.completeCallback)}}):h.stop(!0,!0).slideUp(d,c.completeCallback):(h.toggle(a),c.completeCallback&&c.completeCallback())))},_toggleActive:function(a,b){var c=this;return b=b||{},a&&this.active.get()||!a&&!this.active.get()?(b.unchanged=!0,c.onChangeActive(c.active.get(),b),!1):(b.unchanged=!1,this.activeArgumentsQueue.push(b),this.active.set(a),!0)},activate:function(a){return this._toggleActive(!0,a)},deactivate:function(a){return this._toggleActive(!1,a)},onChangeExpanded:function(){throw new Error("Must override with subclass.")},_toggleExpanded:function(a,b){var c,d=this;return b=b||{},c=b.completeCallback,!(a&&!d.active())&&(f.state("paneVisible").set(!0),b.completeCallback=function(){c&&c.apply(d,arguments),a?d.container.trigger("expanded"):d.container.trigger("collapsed")},a&&d.expanded.get()||!a&&!d.expanded.get()?(b.unchanged=!0,d.onChangeExpanded(d.expanded.get(),b),!1):(b.unchanged=!1,d.expandedArgumentsQueue.push(b),d.expanded.set(a),!0))},expand:function(a){return this._toggleExpanded(!0,a)},collapse:function(a){return this._toggleExpanded(!1,a)},_animateChangeExpanded:function(a){if(!e)return void(a&&a());var c,d,f=this,g=f.contentContainer,h=g.closest(".wp-full-overlay");c=h.add(g),(_.isUndefined(f.panel)||""===f.panel())&&(c=c.add("#customize-info, .customize-pane-parent")),d=function(f){2===f.eventPhase&&b(f.target).is(g)&&(g.off(e,d),c.removeClass("busy"),a&&a())},g.on(e,d),c.addClass("busy"),_.defer(function(){var a=g.closest(".wp-full-overlay-sidebar-content"),b=a.scrollTop(),c=g.data("previous-scrollTop")||0,d=f.expanded();d&&0<b?(g.css("top",b+"px"),g.data("previous-scrollTop",b)):!d&&0<b+c&&(g.css("top",c-b+"px"),a.scrollTop(c))})},focus:d,getContainer:function(){var a,c=this;return a=0!==b("#tmpl-"+c.templateSelector).length?wp.template(c.templateSelector):wp.template("customize-"+c.containerType+"-default"),a&&c.container?b.trim(a(c.params)):"<li></li>"},getContent:function(){var a=this,b=a.container,c=b.find(".accordion-section-content, .control-panel-content").first(),d="sub-"+b.attr("id"),e=d,f=b.attr("aria-owns");return f&&(e=e+" "+f),b.attr("aria-owns",e),c.detach().attr({id:d,"class":"customize-pane-child "+c.attr("class")+" "+b.attr("class")})}}),f.Section=c.extend({containerType:"section",defaults:{title:"",description:"",priority:100,type:"default",content:null,active:!0,instanceNumber:null,panel:null,customizeAction:""},initialize:function(a,d){var e=this;c.prototype.initialize.call(e,a,d),e.id=a,e.panel=new f.Value,e.panel.bind(function(a){b(e.headContainer).toggleClass("control-subsection",!!a)}),e.panel.set(e.params.panel||""),f.utils.bubbleChildValueChanges(e,["panel"]),e.embed(),e.deferred.embedded.done(function(){e.ready()})},embed:function(){var a,c=this,d=b("#customize-theme-controls");a=function(a){var e;a?f.panel(a,function(a){a.deferred.embedded.done(function(){e=a.contentContainer,c.headContainer.parent().is(e)||e.append(c.headContainer),c.contentContainer.parent().is(c.headContainer)||d.append(c.contentContainer),c.deferred.embedded.resolve()})}):(e=b(".customize-pane-parent"),c.headContainer.parent().is(e)||e.append(c.headContainer),c.contentContainer.parent().is(c.headContainer)||d.append(c.contentContainer),c.deferred.embedded.resolve())},c.panel.bind(a),a(c.panel.get())},attachEvents:function(){var a,b,c=this;c.container.hasClass("cannot-expand")||(c.container.find(".accordion-section-title, .customize-section-back").on("click keydown",function(a){f.utils.isKeydownButNotEnterEvent(a)||(a.preventDefault(),c.expanded()?c.collapse():c.expand())}),c.container.find(".customize-section-title .customize-help-toggle").on("click",function(){a=c.container.find(".section-meta"),a.hasClass("cannot-expand")||(b=a.find(".customize-section-description:first"),b.toggleClass("open"),b.slideToggle(),b.attr("aria-expanded",function(a,b){return"true"===b?"false":"true"}))}))},isContextuallyActive:function(){var a=this,b=a.controls(),c=0;return _(b).each(function(a){a.active()&&(c+=1)}),0!==c},controls:function(){return this._children("section","control")},onChangeExpanded:function(a,c){var d,e=this,g=e.headContainer.closest(".wp-full-overlay-sidebar-content"),h=e.contentContainer,i=e.headContainer.closest(".wp-full-overlay"),j=h.find(".customize-section-back"),k=e.headContainer.find(".accordion-section-title").first();a&&!h.hasClass("open")?(d=c.unchanged?c.completeCallback:b.proxy(function(){e._animateChangeExpanded(function(){k.attr("tabindex","-1"),j.attr("tabindex","0"),j.focus(),h.css("top",""),g.scrollTop(0),c.completeCallback&&c.completeCallback()}),h.addClass("open"),i.addClass("section-open"),f.state("expandedSection").set(e)},this),c.allowMultiple||f.section.each(function(a){a!==e&&a.collapse({duration:c.duration})}),e.panel()?f.panel(e.panel()).expand({duration:c.duration,completeCallback:d}):(f.panel.each(function(a){a.collapse()}),d())):!a&&h.hasClass("open")?(e._animateChangeExpanded(function(){j.attr("tabindex","-1"),k.attr("tabindex","0"),k.focus(),h.css("top",""),c.completeCallback&&c.completeCallback()}),h.removeClass("open"),i.removeClass("section-open"),e===f.state("expandedSection").get()&&f.state("expandedSection").set(!1)):c.completeCallback&&c.completeCallback()}}),f.ThemesSection=f.Section.extend({currentTheme:"",overlay:"",template:"",screenshotQueue:null,$window:b(window),initialize:function(){return this.$customizeSidebar=b(".wp-full-overlay-sidebar-content:first"),f.Section.prototype.initialize.apply(this,arguments)},ready:function(){var a=this;a.overlay=a.container.find(".theme-overlay"),a.template=wp.template("customize-themes-details-view"),a.container.on("keydown",function(b){a.overlay.find(".theme-wrap").is(":visible")&&(39===b.keyCode&&a.nextTheme(),37===b.keyCode&&a.previousTheme(),27===b.keyCode&&(a.closeDetails(),b.stopPropagation()))}),_.bindAll(this,"renderScreenshots")},isContextuallyActive:function(){return this.active()},attachEvents:function(){var a=this;a.container.find(".change-theme, .customize-theme").on("click keydown",function(b){f.utils.isKeydownButNotEnterEvent(b)||(b.preventDefault(),a.expanded()?a.collapse():a.expand())}),a.container.on("click keydown",".left",function(b){f.utils.isKeydownButNotEnterEvent(b)||(b.preventDefault(),a.previousTheme())}),a.container.on("click keydown",".right",function(b){f.utils.isKeydownButNotEnterEvent(b)||(b.preventDefault(),a.nextTheme())}),a.container.on("click keydown",".theme-backdrop, .close",function(b){f.utils.isKeydownButNotEnterEvent(b)||(b.preventDefault(),a.closeDetails())});var b=_.throttle(_.bind(a.renderScreenshots,this),100);a.container.on("input","#themes-filter",function(c){var d,e=c.currentTarget.value.toLowerCase().trim().replace("-"," "),f=a.controls();_.each(f,function(a){a.filter(e)}),b(),d=a.container.find("li.customize-control:visible").length,a.container.find(".theme-count").text(d)}),f.bind("ready",function(){_.each(a.controls().slice(0,3),function(a){var b,c=a.params.theme.screenshot[0];c&&(b=new Image,b.src=c)})})},onChangeExpanded:function(a,b){if(b.unchanged)return void(b.completeCallback&&b.completeCallback());var c=this,d=c.contentContainer,e=d.closest(".wp-full-overlay"),g=d.closest(".wp-full-overlay-sidebar-content"),h=d.find(".customize-theme"),i=c.headContainer.find(".change-theme");a&&!d.hasClass("current-panel")?(f.section.each(function(a){a!==c&&a.collapse({duration:b.duration})}),f.panel.each(function(a){a.collapse({duration:0})}),c._animateChangeExpanded(function(){i.attr("tabindex","-1"),h.attr("tabindex","0"),h.focus(),d.css("top",""),g.scrollTop(0),b.completeCallback&&b.completeCallback()}),e.addClass("in-themes-panel"),d.addClass("current-panel"),_.delay(c.renderScreenshots,10),c.$customizeSidebar.on("scroll.customize-themes-section",_.throttle(c.renderScreenshots,300))):!a&&d.hasClass("current-panel")&&(c._animateChangeExpanded(function(){i.attr("tabindex","0"),h.attr("tabindex","-1"),i.focus(),d.css("top",""),b.completeCallback&&b.completeCallback()}),e.removeClass("in-themes-panel"),d.removeClass("current-panel"),c.$customizeSidebar.off("scroll.customize-themes-section"))},renderScreenshots:function(){var a=this;null===a.screenshotQueue&&(a.screenshotQueue=a.controls()),a.screenshotQueue.length&&(a.screenshotQueue=_.filter(a.screenshotQueue,function(b){var c=b.container.find(".theme-screenshot"),d=c.find("img");if(!d.length)return!1;if(d.is(":hidden"))return!0;var e=a.$window.scrollTop(),f=e+a.$window.height(),g=d.offset().top,h=c.height(),i=g+h,j=3*h,k=i>=e-j&&g<=f+j;return k&&b.container.trigger("render-screenshot"),!k}))},nextTheme:function(){var a=this;a.getNextTheme()&&a.showDetails(a.getNextTheme(),function(){a.overlay.find(".right").focus()})},getNextTheme:function(){var a,b;return a=f.control("theme_"+this.currentTheme),b=a.container.next("li.customize-control-theme"),!!b.length&&(b=b[0].id.replace("customize-control-",""),a=f.control(b),a.params.theme)},previousTheme:function(){var a=this;a.getPreviousTheme()&&a.showDetails(a.getPreviousTheme(),function(){a.overlay.find(".left").focus()})},getPreviousTheme:function(){var a,b;return a=f.control("theme_"+this.currentTheme),b=a.container.prev("li.customize-control-theme"),!!b.length&&(b=b[0].id.replace("customize-control-",""),a=f.control(b),a.params.theme)},updateLimits:function(){this.getNextTheme()||this.overlay.find(".right").addClass("disabled"),this.getPreviousTheme()||this.overlay.find(".left").addClass("disabled")},loadThemePreview:function(a){var c,d,e,g=b.Deferred();return e=document.createElement("a"),e.href=location.href,e.search=b.param(_.extend(f.utils.parseQueryString(e.search.substr(1)),{theme:a,changeset_uuid:f.settings.changeset.uuid})),d=b(".wp-full-overlay"),d.addClass("customize-loading"),c=function(){var a;f.state("processing").get()>0||(f.state("processing").unbind(c),a=f.requestChangesetUpdate(),a.done(function(){b(window).off("beforeunload.customize-confirm"),top.location.href=e.href,g.resolve()}),a.fail(function(){d.removeClass("customize-loading"),g.reject()}))},0===f.state("processing").get()?c():f.state("processing").bind(c),g.promise()},showDetails:function(a,c){var d,e=this;c=c||function(){},e.currentTheme=a.id,e.overlay.html(e.template(a)).fadeIn("fast").focus(),b("body").addClass("modal-open"),e.containFocus(e.overlay),e.updateLimits(),d=e.overlay.find(".inactive-theme > a"),d.on("click",function(b){b.preventDefault(),d.hasClass("disabled")||(d.addClass("disabled"),e.loadThemePreview(a.id).fail(function(){d.removeClass("disabled")}))}),c()},closeDetails:function(){b("body").removeClass("modal-open"),this.overlay.fadeOut("fast"),f.control("theme_"+this.currentTheme).focus()},containFocus:function(a){var c;a.on("keydown",function(d){if(9===d.keyCode)return c=b(":tabbable",a),c.last()[0]!==d.target||d.shiftKey?c.first()[0]===d.target&&d.shiftKey?(c.last().focus(),!1):void 0:(c.first().focus(),!1)})}}),f.Panel=c.extend({containerType:"panel",initialize:function(a,b){var d=this;c.prototype.initialize.call(d,a,b),d.embed(),d.deferred.embedded.done(function(){d.ready()})},embed:function(){var a=this,c=b("#customize-theme-controls"),d=b(".customize-pane-parent");a.headContainer.parent().is(d)||d.append(a.headContainer),a.contentContainer.parent().is(a.headContainer)||(c.append(a.contentContainer),a.renderContent()),a.deferred.embedded.resolve()},attachEvents:function(){var a,c=this;c.headContainer.find(".accordion-section-title").on("click keydown",function(a){f.utils.isKeydownButNotEnterEvent(a)||(a.preventDefault(),c.expanded()||c.expand())}),c.container.find(".customize-panel-back").on("click keydown",function(a){f.utils.isKeydownButNotEnterEvent(a)||(a.preventDefault(),c.expanded()&&c.collapse())}),a=c.container.find(".panel-meta:first"),a.find("> .accordion-section-title .customize-help-toggle").on("click keydown",function(d){if(!f.utils.isKeydownButNotEnterEvent(d)&&(d.preventDefault(),!a.hasClass("cannot-expand"))){var e=a.find(".customize-panel-description:first");a.hasClass("open")?(a.toggleClass("open"),e.slideUp(c.defaultExpandedArguments.duration),b(this).attr("aria-expanded",!1)):(e.slideDown(c.defaultExpandedArguments.duration),a.toggleClass("open"),b(this).attr("aria-expanded",!0))}})},sections:function(){return this._children("panel","section")},isContextuallyActive:function(){var a=this,b=a.sections(),c=0;return _(b).each(function(a){a.active()&&a.isContextuallyActive()&&(c+=1)}),0!==c},onChangeExpanded:function(a,b){if(b.unchanged)return void(b.completeCallback&&b.completeCallback());var c=this,d=c.contentContainer,e=d.closest(".wp-full-overlay"),g=d.closest(".wp-full-overlay-sidebar-content"),h=c.headContainer.find(".accordion-section-title"),i=d.find(".customize-panel-back");a&&!d.hasClass("current-panel")?(f.section.each(function(a){c.id!==a.panel()&&a.collapse({duration:0})}),f.panel.each(function(a){c!==a&&a.collapse({duration:0})}),c._animateChangeExpanded(function(){h.attr("tabindex","-1"),i.attr("tabindex","0"),i.focus(),d.css("top",""),g.scrollTop(0),b.completeCallback&&b.completeCallback()}),e.addClass("in-sub-panel"),d.addClass("current-panel"),f.state("expandedPanel").set(c)):!a&&d.hasClass("current-panel")&&(c._animateChangeExpanded(function(){h.attr("tabindex","0"),i.attr("tabindex","-1"),h.focus(),d.css("top",""),b.completeCallback&&b.completeCallback()}),e.removeClass("in-sub-panel"),d.removeClass("current-panel"),c===f.state("expandedPanel").get()&&f.state("expandedPanel").set(!1))},renderContent:function(){var a,c=this;a=0!==b("#tmpl-"+c.templateSelector+"-content").length?wp.template(c.templateSelector+"-content"):wp.template("customize-panel-default-content"),a&&c.headContainer&&c.contentContainer.html(a(c.params))}}),f.Control=f.Class.extend({defaultActiveArguments:{duration:"fast",completeCallback:b.noop},initialize:function(a,c){var d,e,g,h=this;h.params={},b.extend(h,c||{}),h.id=a,h.selector="#customize-control-"+a.replace(/\]/g,"").replace(/\[/g,"-"),h.templateSelector="customize-control-"+h.params.type+"-content",h.container=b(h.params.content?h.params.content:h.selector),h.deferred={embedded:new b.Deferred},h.section=new f.Value,h.priority=new f.Value,h.active=new f.Value,h.activeArgumentsQueue=[],h.notifications=new f.Values({defaultConstructor:f.Notification}),h.elements=[],d=h.container.find("[data-customize-setting-link]"),e={},d.each(function(){var a,c=b(this);if(c.is(":radio")){if(a=c.prop("name"),e[a])return;e[a]=!0,c=d.filter('[name="'+a+'"]')}f(c.data("customizeSettingLink"),function(a){var b=new f.Element(c);h.elements.push(b),b.sync(a),b.set(a())})}),h.active.bind(function(a){var c=h.activeArgumentsQueue.shift();c=b.extend({},h.defaultActiveArguments,c),h.onChangeActive(a,c)}),h.section.set(h.params.section),h.priority.set(isNaN(h.params.priority)?10:h.params.priority),h.active.set(h.params.active),f.utils.bubbleChildValueChanges(h,["section","priority","active"]),g=b.map(h.params.settings,function(a){return a}),0===g.length?(h.setting=null,h.settings={},h.embed()):f.apply(f,g.concat(function(){var a;h.settings={};for(a in h.params.settings)h.settings[a]=f(h.params.settings[a]);h.setting=h.settings["default"]||null,_.each(h.settings,function(a){a.notifications.bind("add",function(b){var c,d,e;d=a.id+":"+b.code,e=_.extend({},b,{setting:a.id}),c=new f.Notification(d,e),h.notifications.add(c.code,c)}),a.notifications.bind("remove",function(b){h.notifications.remove(a.id+":"+b.code)})}),h.embed()})),h.deferred.embedded.done(function(){var a=_.debounce(function(){h.renderNotifications()});h.notifications.bind("add",function(b){wp.a11y.speak(b.message,"assertive"),a()}),h.notifications.bind("remove",a),h.renderNotifications(),h.ready()})},embed:function(){var a,b=this;a=function(a){var c;a&&f.section(a,function(a){a.deferred.embedded.done(function(){c=a.contentContainer.is("ul")?a.contentContainer:a.contentContainer.find("ul:first"),b.container.parent().is(c)||(c.append(b.container),b.renderContent()),b.deferred.embedded.resolve()})})},b.section.bind(a),a(b.section.get())},ready:function(){var a,c=this;"dropdown-pages"===c.params.type&&c.params.allow_addition&&(a=c.container.find(".new-content-item"),a.hide(),c.container.on("click",".add-new-toggle",function(c){b(c.currentTarget).slideUp(180),a.slideDown(180),a.find(".create-item-input").focus()}),c.container.on("click",".add-content",function(){c.addNewPage()}),c.container.on("keyup",".create-item-input",function(a){13===a.which&&c.addNewPage()}))},getNotificationsContainerElement:function(){var a,c,d=this;return c=d.container.find(".customize-control-notifications-container:first"),c.length?c:(c=b('<div class="customize-control-notifications-container"></div>'),d.container.hasClass("customize-control-nav_menu_item")?d.container.find(".menu-item-settings:first").prepend(c):d.container.hasClass("customize-control-widget_form")?d.container.find(".widget-inside:first").prepend(c):(a=d.container.find(".customize-control-title"),a.length?a.after(c):d.container.prepend(c)),c)},renderNotifications:function(){var a,c,d=this,e=!1;a=d.getNotificationsContainerElement(),a&&a.length&&(c=[],d.notifications.each(function(a){c.push(a),"error"===a.type&&(e=!0)}),0===c.length?a.stop().slideUp("fast"):a.stop().slideDown("fast",null,function(){b(this).css("height","auto")}),d.notificationsTemplate||(d.notificationsTemplate=wp.template("customize-control-notifications")),d.container.toggleClass("has-notifications",0!==c.length),d.container.toggleClass("has-error",e),a.empty().append(b.trim(d.notificationsTemplate({notifications:c,altNotice:Boolean(d.altNotice)}))))},expand:function(a){f.section(this.section()).expand(a)},focus:d,onChangeActive:function(a,c){return c.unchanged?void(c.completeCallback&&c.completeCallback()):void(b.contains(document,this.container[0])?a?this.container.slideDown(c.duration,c.completeCallback):this.container.slideUp(c.duration,c.completeCallback):(this.container.toggle(a),c.completeCallback&&c.completeCallback()))},toggle:function(a){return this.onChangeActive(a,this.defaultActiveArguments)},activate:c.prototype.activate,deactivate:c.prototype.deactivate,_toggleActive:c.prototype._toggleActive,dropdownInit:function(){var a=this,b=this.container.find(".dropdown-status"),c=this.params,d=!1,e=function(a){"string"==typeof a&&c.statuses&&c.statuses[a]?b.html(c.statuses[a]).show():b.hide()};this.container.on("click keydown",".dropdown",function(b){f.utils.isKeydownButNotEnterEvent(b)||(b.preventDefault(),d||a.container.toggleClass("open"),a.container.hasClass("open")&&a.container.parent().parent().find("li.library-selected").focus(),d=!0,setTimeout(function(){d=!1},400))}),this.setting.bind(e),e(this.setting())},renderContent:function(){var a,c=this;0!==b("#tmpl-"+c.templateSelector).length&&(a=wp.template(c.templateSelector),a&&c.container&&c.container.html(a(c.params)))},addNewPage:function(){var a,c,d,e,g,h,i=this;if("dropdown-pages"===i.params.type&&i.params.allow_addition&&f.Menus){if(c=i.container.find(".add-new-toggle"),d=i.container.find(".new-content-item"),e=i.container.find(".create-item-input"),g=e.val(),h=i.container.find("select"),!g)return void e.addClass("invalid");e.removeClass("invalid"),e.attr("disabled","disabled"),a=f.Menus.insertAutoDraftPost({post_title:g,post_type:"page"}),a.done(function(a){var e,j,k;e=new f.Menus.AvailableItemModel({id:"post-"+a.post_id,title:g,type:"page",type_label:f.Menus.data.l10n.page_label,object:"post_type",object_id:a.post_id,url:a.url}),f.Menus.availableMenuItemsPanel.collection.add(e),j=b("#available-menu-items-post_type-page").find(".available-menu-items-list"),k=wp.template("available-menu-item"),j.prepend(k(e.attributes)),h.focus(),i.setting.set(String(a.post_id)),d.slideUp(180),c.slideDown(180)}),a.always(function(){e.val("").removeAttr("disabled")})}}}),f.ColorControl=f.Control.extend({ready:function(){var a,b=this,c="hue"===this.params.mode,d=!1;c?(a=this.container.find(".color-picker-hue"),a.val(b.setting()).wpColorPicker({change:function(a,c){d=!0,b.setting(c.color.h()),d=!1}})):(a=this.container.find(".color-picker-hex"),a.val(b.setting()).wpColorPicker({change:function(){d=!0,b.setting.set(a.wpColorPicker("color")),d=!1},clear:function(){d=!0,b.setting.set(""),d=!1}})),b.setting.bind(function(b){d||(a.val(b),a.wpColorPicker("color",b))}),b.container.on("keydown",function(c){var d;27===c.which&&(d=b.container.find(".wp-picker-container"),d.hasClass("wp-picker-active")&&(a.wpColorPicker("close"),b.container.find(".wp-color-result").focus(),c.stopPropagation()))})}}),f.MediaControl=f.Control.extend({ready:function(){function a(a){var d=b.Deferred();c.extended(f.UploadControl)?d.resolve():(a=parseInt(a,10),_.isNaN(a)||a<=0?(delete c.params.attachment,d.resolve()):c.params.attachment&&c.params.attachment.id===a&&d.resolve()),"pending"===d.state()&&wp.media.attachment(a).fetch().done(function(){c.params.attachment=this.attributes,d.resolve(),wp.customize.previewer.send(c.setting.id+"-attachment-data",this.attributes)}),d.done(function(){c.renderContent()})}var c=this;_.bindAll(c,"restoreDefault","removeFile","openFrame","select","pausePlayer"),c.container.on("click keydown",".upload-button",c.openFrame),c.container.on("click keydown",".upload-button",c.pausePlayer),c.container.on("click keydown",".thumbnail-image img",c.openFrame),c.container.on("click keydown",".default-button",c.restoreDefault),c.container.on("click keydown",".remove-button",c.pausePlayer),c.container.on("click keydown",".remove-button",c.removeFile),c.container.on("click keydown",".remove-button",c.cleanupPlayer),f.section(c.section()).container.on("expanded",function(){c.player&&c.player.setControlsSize()}).on("collapsed",function(){c.pausePlayer()}),a(c.setting()),c.setting.bind(a)},pausePlayer:function(){this.player&&this.player.pause()},cleanupPlayer:function(){this.player&&wp.media.mixin.removePlayer(this.player)},openFrame:function(a){f.utils.isKeydownButNotEnterEvent(a)||(a.preventDefault(),this.frame||this.initFrame(),this.frame.open())},initFrame:function(){this.frame=wp.media({button:{text:this.params.button_labels.frame_button},states:[new wp.media.controller.Library({title:this.params.button_labels.frame_title,library:wp.media.query({type:this.params.mime_type}),multiple:!1,date:!1})]}),this.frame.on("select",this.select)},select:function(){var a,b=this.frame.state().get("selection").first().toJSON(),c=window._wpmejsSettings||{};this.params.attachment=b,this.setting(b.id),a=this.container.find("audio, video").get(0),a?this.player=new MediaElementPlayer(a,c):this.cleanupPlayer()},restoreDefault:function(a){f.utils.isKeydownButNotEnterEvent(a)||(a.preventDefault(),this.params.attachment=this.params.defaultAttachment,this.setting(this.params.defaultAttachment.url))},removeFile:function(a){f.utils.isKeydownButNotEnterEvent(a)||(a.preventDefault(),this.params.attachment={},this.setting(""),this.renderContent())}}),f.UploadControl=f.MediaControl.extend({select:function(){var a,b=this.frame.state().get("selection").first().toJSON(),c=window._wpmejsSettings||{};this.params.attachment=b,this.setting(b.url),a=this.container.find("audio, video").get(0),a?this.player=new MediaElementPlayer(a,c):this.cleanupPlayer()},success:function(){},removerVisibility:function(){}}),f.ImageControl=f.UploadControl.extend({thumbnailSrc:function(){}}),f.BackgroundControl=f.UploadControl.extend({ready:function(){f.UploadControl.prototype.ready.apply(this,arguments)},select:function(){f.UploadControl.prototype.select.apply(this,arguments),wp.ajax.post("custom-background-add",{nonce:_wpCustomizeBackground.nonces.add,wp_customize:"on",customize_theme:f.settings.theme.stylesheet,attachment_id:this.params.attachment.id})}}),f.BackgroundPositionControl=f.Control.extend({ready:function(){var a,c=this;c.container.on("change",'input[name="background-position"]',function(){var a=b(this).val().split(" ");c.settings.x(a[0]),c.settings.y(a[1])}),a=_.debounce(function(){var a,b,d,e;a=c.settings.x.get(),b=c.settings.y.get(),e=String(a)+" "+String(b),d=c.container.find('input[name="background-position"][value="'+e+'"]'),d.click()}),c.settings.x.bind(a),c.settings.y.bind(a),a()}}),f.CroppedImageControl=f.MediaControl.extend({openFrame:function(a){f.utils.isKeydownButNotEnterEvent(a)||(this.initFrame(),this.frame.setState("library").open())},initFrame:function(){var a=_wpMediaViewsL10n;this.frame=wp.media({button:{text:a.select,close:!1},states:[new wp.media.controller.Library({title:this.params.button_labels.frame_title,library:wp.media.query({type:"image"}),multiple:!1,date:!1,priority:20,suggestedWidth:this.params.width,suggestedHeight:this.params.height}),new wp.media.controller.CustomizeImageCropper({imgSelectOptions:this.calculateImageSelectOptions,control:this})]}),this.frame.on("select",this.onSelect,this),this.frame.on("cropped",this.onCropped,this),this.frame.on("skippedcrop",this.onSkippedCrop,this)},onSelect:function(){var a=this.frame.state().get("selection").first().toJSON();this.params.width!==a.width||this.params.height!==a.height||this.params.flex_width||this.params.flex_height?this.frame.setState("cropper"):(this.setImageFromAttachment(a),this.frame.close())},onCropped:function(a){this.setImageFromAttachment(a)},calculateImageSelectOptions:function(a,b){var c,d,e,f=b.get("control"),g=!!parseInt(f.params.flex_width,10),h=!!parseInt(f.params.flex_height,10),i=a.get("width"),j=a.get("height"),k=parseInt(f.params.width,10),l=parseInt(f.params.height,10),m=k/l,n=k,o=l;return b.set("canSkipCrop",!f.mustBeCropped(g,h,k,l,i,j)),i/j>m?(l=j,k=l*m):(k=i,l=k/m),c=(i-k)/2,d=(j-l)/2,e={handles:!0,keys:!0,instance:!0,persistent:!0,imageWidth:i,imageHeight:j,minWidth:n>k?k:n,minHeight:o>l?l:o,x1:c,y1:d,x2:k+c,y2:l+d},h===!1&&g===!1&&(e.aspectRatio=k+":"+l),!0===h&&(delete e.minHeight,e.maxWidth=i),!0===g&&(delete e.minWidth,e.maxHeight=j),e},mustBeCropped:function(a,b,c,d,e,f){return(!0!==a||!0!==b)&&((!0!==a||d!==f)&&((!0!==b||c!==e)&&((c!==e||d!==f)&&!(e<=c))))},onSkippedCrop:function(){var a=this.frame.state().get("selection").first().toJSON();this.setImageFromAttachment(a)},setImageFromAttachment:function(a){this.params.attachment=a,this.setting(a.id)}}),f.SiteIconControl=f.CroppedImageControl.extend({ initFrame:function(){var a=_wpMediaViewsL10n;this.frame=wp.media({button:{text:a.select,close:!1},states:[new wp.media.controller.Library({title:this.params.button_labels.frame_title,library:wp.media.query({type:"image"}),multiple:!1,date:!1,priority:20,suggestedWidth:this.params.width,suggestedHeight:this.params.height}),new wp.media.controller.SiteIconCropper({imgSelectOptions:this.calculateImageSelectOptions,control:this})]}),this.frame.on("select",this.onSelect,this),this.frame.on("cropped",this.onCropped,this),this.frame.on("skippedcrop",this.onSkippedCrop,this)},onSelect:function(){var a=this.frame.state().get("selection").first().toJSON(),b=this;this.params.width!==a.width||this.params.height!==a.height||this.params.flex_width||this.params.flex_height?this.frame.setState("cropper"):wp.ajax.post("crop-image",{nonce:a.nonces.edit,id:a.id,context:"site-icon",cropDetails:{x1:0,y1:0,width:this.params.width,height:this.params.height,dst_width:this.params.width,dst_height:this.params.height}}).done(function(a){b.setImageFromAttachment(a),b.frame.close()}).fail(function(){b.frame.trigger("content:error:crop")})},setImageFromAttachment:function(a){var c,d,e=["site_icon-32","thumbnail","full"];_.each(e,function(b){d||_.isUndefined(a.sizes[b])||(d=a.sizes[b])}),this.params.attachment=a,this.setting(a.id),d&&(c=b('link[rel="icon"][sizes="32x32"]'),c.attr("href",d.url))},removeFile:function(a){f.utils.isKeydownButNotEnterEvent(a)||(a.preventDefault(),this.params.attachment={},this.setting(""),this.renderContent(),b('link[rel="icon"][sizes="32x32"]').attr("href","/favicon.ico"))}}),f.HeaderControl=f.Control.extend({ready:function(){this.btnRemove=b("#customize-control-header_image .actions .remove"),this.btnNew=b("#customize-control-header_image .actions .new"),_.bindAll(this,"openMedia","removeImage"),this.btnNew.on("click",this.openMedia),this.btnRemove.on("click",this.removeImage),f.HeaderTool.currentHeader=this.getInitialHeaderImage(),new f.HeaderTool.CurrentView({model:f.HeaderTool.currentHeader,el:"#customize-control-header_image .current .container"}),new f.HeaderTool.ChoiceListView({collection:f.HeaderTool.UploadsList=new f.HeaderTool.ChoiceList,el:"#customize-control-header_image .choices .uploaded .list"}),new f.HeaderTool.ChoiceListView({collection:f.HeaderTool.DefaultsList=new f.HeaderTool.DefaultsList,el:"#customize-control-header_image .choices .default .list"}),f.HeaderTool.combinedList=f.HeaderTool.CombinedList=new f.HeaderTool.CombinedList([f.HeaderTool.UploadsList,f.HeaderTool.DefaultsList]),wp.media.controller.Cropper.prototype.defaults.doCropArgs.wp_customize="on",wp.media.controller.Cropper.prototype.defaults.doCropArgs.customize_theme=f.settings.theme.stylesheet},getInitialHeaderImage:function(){if(!f.get().header_image||!f.get().header_image_data||_.contains(["remove-header","random-default-image","random-uploaded-image"],f.get().header_image))return new f.HeaderTool.ImageModel;var a=_.find(_wpCustomizeHeader.uploads,function(a){return a.attachment_id===f.get().header_image_data.attachment_id});return a||(a={url:f.get().header_image,thumbnail_url:f.get().header_image,attachment_id:f.get().header_image_data.attachment_id}),new f.HeaderTool.ImageModel({header:a,choice:a.url.split("/").pop()})},calculateImageSelectOptions:function(a,b){var c,d,e,g,h,i,j=parseInt(_wpCustomizeHeader.data.width,10),k=parseInt(_wpCustomizeHeader.data.height,10),l=!!parseInt(_wpCustomizeHeader.data["flex-width"],10),m=!!parseInt(_wpCustomizeHeader.data["flex-height"],10);return h=a.get("width"),g=a.get("height"),this.headerImage=new f.HeaderTool.ImageModel,this.headerImage.set({themeWidth:j,themeHeight:k,themeFlexWidth:l,themeFlexHeight:m,imageWidth:h,imageHeight:g}),b.set("canSkipCrop",!this.headerImage.shouldBeCropped()),c=j/k,d=h,e=g,d/e>c?(k=e,j=k*c):(j=d,k=j/c),i={handles:!0,keys:!0,instance:!0,persistent:!0,imageWidth:h,imageHeight:g,x1:0,y1:0,x2:j,y2:k},m===!1&&l===!1&&(i.aspectRatio=j+":"+k),m===!1&&(i.maxHeight=k),l===!1&&(i.maxWidth=j),i},openMedia:function(a){var b=_wpMediaViewsL10n;a.preventDefault(),this.frame=wp.media({button:{text:b.selectAndCrop,close:!1},states:[new wp.media.controller.Library({title:b.chooseImage,library:wp.media.query({type:"image"}),multiple:!1,date:!1,priority:20,suggestedWidth:_wpCustomizeHeader.data.width,suggestedHeight:_wpCustomizeHeader.data.height}),new wp.media.controller.Cropper({imgSelectOptions:this.calculateImageSelectOptions})]}),this.frame.on("select",this.onSelect,this),this.frame.on("cropped",this.onCropped,this),this.frame.on("skippedcrop",this.onSkippedCrop,this),this.frame.open()},onSelect:function(){this.frame.setState("cropper")},onCropped:function(a){var b=a.url,c=a.attachment_id,d=a.width,e=a.height;this.setImageFromURL(b,c,d,e)},onSkippedCrop:function(a){var b=a.get("url"),c=a.get("width"),d=a.get("height");this.setImageFromURL(b,a.id,c,d)},setImageFromURL:function(a,b,c,d){var e,g={};g.url=a,g.thumbnail_url=a,g.timestamp=_.now(),b&&(g.attachment_id=b),c&&(g.width=c),d&&(g.height=d),e=new f.HeaderTool.ImageModel({header:g,choice:a.split("/").pop()}),f.HeaderTool.UploadsList.add(e),f.HeaderTool.currentHeader.set(e.toJSON()),e.save(),e.importImage()},removeImage:function(){f.HeaderTool.currentHeader.trigger("hide"),f.HeaderTool.CombinedList.trigger("control:removeImage")}}),f.ThemeControl=f.Control.extend({touchDrag:!1,isRendered:!1,renderContent:function(){var a=this,b=arguments;f.section(a.section(),function(c){c.expanded()?(f.Control.prototype.renderContent.apply(a,b),a.isRendered=!0):c.expanded.bind(function(c){c&&!a.isRendered&&(f.Control.prototype.renderContent.apply(a,b),a.isRendered=!0)})})},ready:function(){var a=this;a.container.on("touchmove",".theme",function(){a.touchDrag=!0}),a.container.on("click keydown touchend",".theme",function(c){if(!f.utils.isKeydownButNotEnterEvent(c))return a.touchDrag===!0?a.touchDrag=!1:void(b(c.target).is(".theme-actions .button")||f.section(a.section()).loadThemePreview(a.params.theme.id))}),a.container.on("click keydown",".theme-actions .theme-details",function(b){f.utils.isKeydownButNotEnterEvent(b)||(b.preventDefault(),f.section(a.section()).showDetails(a.params.theme))}),a.container.on("render-screenshot",function(){var a=b(this).find("img"),c=a.data("src");c&&a.attr("src",c)})},filter:function(a){var b=this,c=b.params.theme.name+" "+b.params.theme.description+" "+b.params.theme.tags+" "+b.params.theme.author;c=c.toLowerCase().replace("-"," "),-1!==c.search(a)?b.activate():b.deactivate()}}),f.defaultConstructor=f.Setting,f.control=new f.Values({defaultConstructor:f.Control}),f.section=new f.Values({defaultConstructor:f.Section}),f.panel=new f.Values({defaultConstructor:f.Panel}),f.PreviewFrame=f.Messenger.extend({sensitivity:null,initialize:function(a,c){var d=b.Deferred();d.promise(this),this.container=a.container,b.extend(a,{channel:f.PreviewFrame.uuid()}),f.Messenger.prototype.initialize.call(this,a,c),this.add("previewUrl",a.previewUrl),this.query=b.extend(a.query||{},{customize_messenger_channel:this.channel()}),this.run(d)},run:function(a){var c,d,e,g=this,h=!1,i=!1,j=null,k="{}"!==g.query.customized;g._ready&&g.unbind("ready",g._ready),g._ready=function(b){i=!0,j=b,g.container.addClass("iframe-ready"),b&&h&&a.resolveWith(g,[b])},g.bind("ready",g._ready),c=document.createElement("a"),c.href=g.previewUrl(),d=_.extend(f.utils.parseQueryString(c.search.substr(1)),{customize_changeset_uuid:g.query.customize_changeset_uuid,customize_theme:g.query.customize_theme,customize_messenger_channel:g.query.customize_messenger_channel}),c.search=b.param(d),g.iframe=b("<iframe />",{title:f.l10n.previewIframeTitle,name:"customize-"+g.channel()}),g.iframe.attr("onmousewheel",""),k?g.iframe.attr("data-src",c.href):g.iframe.attr("src",c.href),g.iframe.appendTo(g.container),g.targetWindow(g.iframe[0].contentWindow),k&&(e=b("<form>",{action:c.href,target:g.iframe.attr("name"),method:"post",hidden:"hidden"}),e.append(b("<input>",{type:"hidden",name:"_method",value:"GET"})),_.each(g.query,function(a,c){e.append(b("<input>",{type:"hidden",name:c,value:a}))}),g.container.append(e),e.submit(),e.remove()),g.bind("iframe-loading-error",function(b){return g.iframe.remove(),0===b?void g.login(a):-1===b?void a.rejectWith(g,["cheatin"]):void a.rejectWith(g,["request failure"])}),g.iframe.one("load",function(){h=!0,i?a.resolveWith(g,[j]):setTimeout(function(){a.rejectWith(g,["ready timeout"])},g.sensitivity)})},login:function(a){var c,d=this;return c=function(){a.rejectWith(d,["logged out"])},this.triedLogin?c():void b.get(f.settings.url.ajax,{action:"logged-in"}).fail(c).done(function(e){var g;"1"!==e&&c(),g=b("<iframe />",{src:d.previewUrl(),title:f.l10n.previewIframeTitle}).hide(),g.appendTo(d.container),g.on("load",function(){d.triedLogin=!0,g.remove(),d.run(a)})})},destroy:function(){f.Messenger.prototype.destroy.call(this),this.iframe&&this.iframe.remove(),delete this.iframe,delete this.targetWindow}}),function(){var a=0;f.PreviewFrame.uuid=function(){return"preview-"+String(a++)}}(),f.setDocumentTitle=function(a){var b,c;b=f.settings.documentTitleTmpl,c=b.replace("%s",a),document.title=c,f.trigger("title",c)},f.Previewer=f.Messenger.extend({refreshBuffer:null,initialize:function(a,c){var d=this,e=document.createElement("a");b.extend(d,c||{}),d.deferred={active:b.Deferred()},d.refresh=_.debounce(function(a){return function(){var b,c;b=function(){return 0===f.state("processing").get()},b()?a.call(d):(c=function(){b()&&(a.call(d),f.state("processing").unbind(c))},f.state("processing").bind(c))}}(d.refresh),d.refreshBuffer),d.container=f.ensure(a.container),d.allowedUrls=a.allowedUrls,a.url=window.location.href,f.Messenger.prototype.initialize.call(d,a),e.href=d.origin(),d.add("scheme",e.protocol.replace(/:$/,"")),d.add("previewUrl",a.previewUrl).setter(function(a){var c,e,g,h=null,i=[];return c=document.createElement("a"),c.href=a,/\/wp-(admin|includes|content)(\/|$)/.test(c.pathname)?null:(c.search.length>1&&(e=f.utils.parseQueryString(c.search.substr(1)),delete e.customize_changeset_uuid,delete e.customize_theme,delete e.customize_messenger_channel,_.isEmpty(e)?c.search="":c.search=b.param(e)),i.push(c),d.scheme.get()+":"!==c.protocol&&(c=document.createElement("a"),c.href=i[0].href,c.protocol=d.scheme.get()+":",i.unshift(c)),g=document.createElement("a"),_.find(i,function(a){return!_.isUndefined(_.find(d.allowedUrls,function(b){if(g.href=b,c.protocol===g.protocol&&c.host===g.host&&0===c.pathname.indexOf(g.pathname.replace(/\/$/,"")))return h=a.href,!0}))}),h)}),d.bind("ready",d.ready),d.deferred.active.done(_.bind(d.keepPreviewAlive,d)),d.bind("synced",function(){d.send("active")}),d.previewUrl.bind(d.refresh),d.scroll=0,d.bind("scroll",function(a){d.scroll=a}),d.bind("url",function(a){var b,c=!1;d.scroll=0,b=function(){c=!0},d.previewUrl.bind(b),d.previewUrl.set(a),d.previewUrl.unbind(b),c||d.refresh()}),d.bind("documentTitle",function(a){f.setDocumentTitle(a)})},ready:function(a){var b,c=this,d={};d.settings=f.get(),d["settings-modified-while-loading"]=c.settingsModifiedWhileLoading,("resolved"!==c.deferred.active.state()||c.loading)&&(d.scroll=c.scroll),d["edit-shortcut-visibility"]=f.state("editShortcutVisibility").get(),c.send("sync",d),a.currentUrl&&(c.previewUrl.unbind(c.refresh),c.previewUrl.set(a.currentUrl),c.previewUrl.bind(c.refresh)),b={panel:a.activePanels,section:a.activeSections,control:a.activeControls},_(b).each(function(a,b){f[b].each(function(c,d){var e=_.isUndefined(f.settings[b+"s"][d]);e&&_.isUndefined(a[d])||(a[d]?c.activate():c.deactivate())})}),a.settingValidities&&f._handleSettingValidities({settingValidities:a.settingValidities,focusInvalidControl:!1})},keepPreviewAlive:function(){var a,b,c,d,e=this;d=function(){b=setTimeout(c,f.settings.timeouts.keepAliveCheck)},a=function(){f.state("previewerAlive").set(!0),clearTimeout(b),d()},c=function(){f.state("previewerAlive").set(!1)},d(),e.bind("ready",a),e.bind("keep-alive",a)},query:function(){},abort:function(){this.loading&&(this.loading.destroy(),delete this.loading)},refresh:function(){var a,b=this;b.send("loading-initiated"),b.abort(),b.loading=new f.PreviewFrame({url:b.url(),previewUrl:b.previewUrl(),query:b.query({excludeCustomizedSaved:!0})||{},container:b.container}),b.settingsModifiedWhileLoading={},a=function(a){b.settingsModifiedWhileLoading[a.id]=!0},f.bind("change",a),b.loading.always(function(){f.unbind("change",a)}),b.loading.done(function(a){var c,d=this;b.preview=d,b.targetWindow(d.targetWindow()),b.channel(d.channel()),c=function(){d.unbind("synced",c),b._previousPreview&&b._previousPreview.destroy(),b._previousPreview=b.preview,b.deferred.active.resolve(),delete b.loading},d.bind("synced",c),b.trigger("ready",a)}),b.loading.fail(function(a){b.send("loading-failed"),"logged out"===a&&(b.preview&&(b.preview.destroy(),delete b.preview),b.login().done(b.refresh)),"cheatin"===a&&b.cheatin()})},login:function(){var a,c,d,e=this;return this._login?this._login:(a=b.Deferred(),this._login=a.promise(),c=new f.Messenger({channel:"login",url:f.settings.url.login}),d=b("<iframe />",{src:f.settings.url.login,title:f.l10n.loginIframeTitle}).appendTo(this.container),c.targetWindow(d[0].contentWindow),c.bind("login",function(){var b=e.refreshNonces();b.always(function(){d.remove(),c.destroy(),delete e._login}),b.done(function(){a.resolve()}),b.fail(function(){e.cheatin(),a.reject()})}),this._login)},cheatin:function(){b(document.body).empty().addClass("cheatin").append("<h1>"+f.l10n.cheatin+"</h1><p>"+f.l10n.notAllowed+"</p>")},refreshNonces:function(){var a,c=b.Deferred();return c.promise(),a=wp.ajax.post("customize_refresh_nonces",{wp_customize:"on",customize_theme:f.settings.theme.stylesheet}),a.done(function(a){f.trigger("nonce-refresh",a),c.resolve()}),a.fail(function(){c.reject()}),c}}),f.settingConstructor={},f.controlConstructor={color:f.ColorControl,media:f.MediaControl,upload:f.UploadControl,image:f.ImageControl,cropped_image:f.CroppedImageControl,site_icon:f.SiteIconControl,header:f.HeaderControl,background:f.BackgroundControl,background_position:f.BackgroundPositionControl,theme:f.ThemeControl},f.panelConstructor={},f.sectionConstructor={themes:f.ThemesSection},f._handleSettingValidities=function(a){var b,c=[],d=!1;_.each(a.settingValidities,function(a,b){var d=f(b);d&&(_.isObject(a)&&_.each(a,function(a,b){var e,g,h=!1;e=new f.Notification(b,_.extend({fromServer:!0},a)),g=d.notifications(e.code),g&&(h=e.type!==g.type||e.message!==g.message||!_.isEqual(e.data,g.data)),h&&d.notifications.remove(b),d.notifications.has(e.code)||d.notifications.add(b,e),c.push(d.id)}),d.notifications.each(function(b){"error"!==b.type||!0!==a&&a[b.code]||d.notifications.remove(b.code)}))}),a.focusInvalidControl&&(b=f.findControlsForSettings(c),_(_.values(b)).find(function(a){return _(a).find(function(a){var b=a.section()&&f.section.has(a.section())&&f.section(a.section()).expanded();return b&&a.expanded&&(b=a.expanded()),b&&(a.focus(),d=!0),d})}),d||_.isEmpty(b)||_.values(b)[0][0].focus())},f.findControlsForSettings=function(a){var b,c={};return _.each(_.unique(a),function(a){var d=f(a);d&&(b=d.findControls(),b&&b.length>0&&(c[a]=b))}),c},f.reflowPaneContents=_.bind(function(){var a,c,d,e=[],g=!1;document.activeElement&&(c=b(document.activeElement)),f.panel.each(function(b){var c=b.sections(),d=_.pluck(c,"headContainer");e.push(b),a=b.contentContainer.is("ul")?b.contentContainer:b.contentContainer.find("ul:first"),f.utils.areElementListsEqual(d,a.children("[id]"))||(_(c).each(function(b){a.append(b.headContainer)}),g=!0)}),f.section.each(function(b){var c=b.controls(),d=_.pluck(c,"container");b.panel()||e.push(b),a=b.contentContainer.is("ul")?b.contentContainer:b.contentContainer.find("ul:first"),f.utils.areElementListsEqual(d,a.children("[id]"))||(_(c).each(function(b){a.append(b.container)}),g=!0)}),e.sort(f.utils.prioritySort),d=_.pluck(e,"headContainer"),a=b("#customize-theme-controls .customize-pane-parent"),f.utils.areElementListsEqual(d,a.children())||(_(e).each(function(b){a.append(b.headContainer)}),g=!0),f.panel.each(function(a){var b=a.active();a.active.callbacks.fireWith(a.active,[b,b])}),f.section.each(function(a){var b=a.active();a.active.callbacks.fireWith(a.active,[b,b])}),g&&c&&c.focus(),f.trigger("pane-contents-reflowed")},f),b(function(){if(f.settings=window._wpCustomizeSettings,f.l10n=window._wpCustomizeControlsL10n,f.settings&&b.support.postMessage&&(b.support.cors||!f.settings.isCrossDomain)){null===f.PreviewFrame.prototype.sensitivity&&(f.PreviewFrame.prototype.sensitivity=f.settings.timeouts.previewFrameSensitivity),null===f.Previewer.prototype.refreshBuffer&&(f.Previewer.prototype.refreshBuffer=f.settings.timeouts.windowRefresh);var a,c=b(document.body),d=c.children(".wp-full-overlay"),e=b("#customize-info .panel-title.site-title"),g=b(".customize-controls-close"),h=b("#save"),i=b("#customize-footer-actions");b("#customize-controls").on("keydown",function(a){var c=13===a.which,d=b(a.target);c&&(d.is("input:not([type=button])")||d.is("select"))&&a.preventDefault()}),b(".customize-info").find("> .accordion-section-title .customize-help-toggle").on("click",function(){var a=b(this).closest(".accordion-section"),c=a.find(".customize-panel-description:first");a.hasClass("cannot-expand")||(a.hasClass("open")?(a.toggleClass("open"),c.slideUp(f.Panel.prototype.defaultExpandedArguments.duration),b(this).attr("aria-expanded",!1)):(c.slideDown(f.Panel.prototype.defaultExpandedArguments.duration),a.toggleClass("open"),b(this).attr("aria-expanded",!0)))}),f.previewer=new f.Previewer({container:"#customize-preview",form:"#customize-controls",previewUrl:f.settings.url.preview,allowedUrls:f.settings.url.allowed},{nonce:f.settings.nonce,query:function(a){var b={wp_customize:"on",customize_theme:f.settings.theme.stylesheet,nonce:this.nonce.preview,customize_changeset_uuid:f.settings.changeset.uuid};return b.customized=JSON.stringify(f.dirtyValues({unsaved:a&&a.excludeCustomizedSaved})),b},save:function(c){function d(a){n[a.id]=!0}var e,g,i,j=this,k=b.Deferred(),l="publish",m=f.state("processing"),n={},o=[];return c&&c.status&&(l=c.status),f.state("saving").get()&&(k.reject("already_saving"),k.promise()),f.state("saving").set(!0),f.bind("change",d),g=function(){var e,g,m={},p=f._latestRevision;return f.each(function(a){a.notifications.each(function(b){"error"!==b.type||b.fromServer||(o.push(a.id),m[a.id]||(m[a.id]={}),m[a.id][b.code]=b)})}),i=f.findControlsForSettings(o),_.isEmpty(i)?(g=b.extend(j.query({excludeCustomizedSaved:!1}),{nonce:j.nonce.save,customize_changeset_status:l}),c&&c.date&&(g.customize_changeset_date=c.date),c&&c.title&&(g.customize_changeset_title=c.title),e=wp.ajax.post("customize_save",g),h.prop("disabled",!0),f.trigger("save",e),e.always(function(){f.state("saving").set(!1),h.prop("disabled",!1),f.unbind("change",d)}),e.fail(function(a){"0"===a?a="not_logged_in":"-1"===a&&(a="invalid_nonce"),"invalid_nonce"===a?j.cheatin():"not_logged_in"===a&&(j.preview.iframe.hide(),j.login().done(function(){j.save(),j.preview.iframe.show()})),a.setting_validities&&f._handleSettingValidities({settingValidities:a.setting_validities,focusInvalidControl:!0}),k.rejectWith(j,[a]),f.trigger("error",a)}),void e.done(function(b){j.send("saved",b),f.state("changesetStatus").set(b.changeset_status),"publish"===b.changeset_status&&(f.each(function(a){a._dirty&&(_.isUndefined(f._latestSettingRevisions[a.id])||f._latestSettingRevisions[a.id]<=p)&&(a._dirty=!1)}),f.state("changesetStatus").set(""),f.settings.changeset.uuid=b.next_changeset_uuid,a.send("changeset-uuid",f.settings.changeset.uuid)),b.setting_validities&&f._handleSettingValidities({settingValidities:b.setting_validities,focusInvalidControl:!0}),k.resolveWith(j,[b]),f.trigger("saved",b),_.isEmpty(n)||f.state("saved").set(!1)})):(_.values(i)[0][0].focus(),f.unbind("change",d),k.rejectWith(j,[{setting_invalidities:m}]),f.state("saving").set(!1),k.promise())},0===m()?g():(e=function(){0===m()&&(f.state.unbind("change",e),g())},f.state.bind("change",e)),k.promise()}}),f.previewer.bind("nonce",function(a){b.extend(this.nonce,a)}),f.bind("nonce-refresh",function(a){b.extend(f.settings.nonce,a),b.extend(f.previewer.nonce,a),f.previewer.send("nonce-refresh",a)}),b.each(f.settings.settings,function(a,b){var c,d=f.settingConstructor[b.type]||f.Setting;c=new d(a,b.value,{transport:b.transport,previewer:f.previewer,dirty:!!b.dirty}),f.add(a,c)}),b.each(f.settings.panels,function(a,b){var c,d=f.panelConstructor[b.type]||f.Panel;c=new d(a,{params:b}),f.panel.add(a,c)}),b.each(f.settings.sections,function(a,b){var c,d=f.sectionConstructor[b.type]||f.Section;c=new d(a,{params:b}),f.section.add(a,c)}),b.each(f.settings.controls,function(a,b){var c,d=f.controlConstructor[b.type]||f.Control;c=new d(a,{params:b,previewer:f.previewer}),f.control.add(a,c)}),_.each(["panel","section","control"],function(a){var b=f.settings.autofocus[a];b&&f[a](b,function(a){a.deferred.embedded.done(function(){f.previewer.deferred.active.done(function(){a.focus()})})})}),f.bind("ready",f.reflowPaneContents),b([f.panel,f.section,f.control]).each(function(a,b){var c=_.debounce(f.reflowPaneContents,f.settings.timeouts.reflowPaneContents);b.bind("add",c),b.bind("change",c),b.bind("remove",c)}),function(){var a,d=new f.Values,e=d.create("saved"),i=d.create("saving"),j=d.create("activated"),k=d.create("processing"),l=d.create("paneVisible"),m=d.create("expandedPanel"),n=d.create("expandedSection"),o=d.create("changesetStatus"),p=d.create("previewerAlive"),q=d.create("editShortcutVisibility");d.bind("change",function(){var a;j()?""===o.get()&&e()?(h.val(f.l10n.saved),g.find(".screen-reader-text").text(f.l10n.close)):(h.val(f.l10n.save),g.find(".screen-reader-text").text(f.l10n.cancel)):(h.val(f.l10n.activate),g.find(".screen-reader-text").text(f.l10n.cancel)),a=!i()&&(!j()||!e()||""!==o()&&"publish"!==o()),h.prop("disabled",!a)}),o(f.settings.changeset.status),e(!0),""===o()&&f.each(function(a){a._dirty&&e(!1)}),i(!1),j(f.settings.theme.active),k(0),l(!0),m(!1),n(!1),p(!0),q("visible"),f.bind("change",function(){d("saved").get()&&(d("saved").set(!1),a(!0))}),i.bind(function(a){c.toggleClass("saving",a)}),f.bind("saved",function(a){d("saved").set(!0),"publish"===a.changeset_status&&d("activated").set(!0)}),j.bind(function(a){a&&f.trigger("activated")}),a=function(a){var c,d;if(c=document.createElement("a"),c.href=location.href,d=f.utils.parseQueryString(c.search.substr(1)),a){if(d.changeset_uuid===f.settings.changeset.uuid)return;d.changeset_uuid=f.settings.changeset.uuid}else{if(!d.changeset_uuid)return;delete d.changeset_uuid}c.search=b.param(d),history.replaceState({},document.title,c.href)},history.replaceState&&o.bind(function(b){a(""!==b&&"publish"!==b)}),f.state=d}(),f.previewer.previewUrl()?f.previewer.refresh():f.previewer.previewUrl(f.settings.url.home),h.click(function(a){f.previewer.save(),a.preventDefault()}).keydown(function(a){9!==a.which&&(13===a.which&&f.previewer.save(),a.preventDefault())}),g.keydown(function(a){9!==a.which&&(13===a.which&&this.click(),a.preventDefault())}),b(".collapse-sidebar").on("click",function(){f.state("paneVisible").set(!f.state("paneVisible").get())}),f.state("paneVisible").bind(function(a){d.toggleClass("preview-only",!a),d.toggleClass("expanded",a),d.toggleClass("collapsed",!a),a?b(".collapse-sidebar").attr({"aria-expanded":"true","aria-label":f.l10n.collapseSidebar}):b(".collapse-sidebar").attr({"aria-expanded":"false","aria-label":f.l10n.expandSidebar})}),b("body").on("keydown",function(a){var c,d=[],e=[],g=[];27===a.which&&(b(a.target).is("body")||b.contains(b("#customize-controls")[0],a.target))&&(f.control.each(function(a){a.expanded&&a.expanded()&&_.isFunction(a.collapse)&&d.push(a)}),f.section.each(function(a){a.expanded()&&e.push(a)}),f.panel.each(function(a){a.expanded()&&g.push(a)}),d.length>0&&0===e.length&&(d.length=0),c=d[0]||e[0]||g[0],c&&(c.collapse(),a.preventDefault()))}),b(".customize-controls-preview-toggle").on("click",function(){f.state("paneVisible").set(!f.state("paneVisible").get())}),function(){var a,c,d,e,g,h,i,j=b(".wp-full-overlay-sidebar-content");a=function(a){var b,g=a,i=f.state("expandedSection").get(),j=f.state("expandedPanel").get();if(h&&h.element&&d(h.element),!g)if(!i&&j&&j.contentContainer)g=j;else{if(j||!i||!i.contentContainer)return void(h=!1);g=i}b=g.contentContainer.find(".customize-section-title, .panel-meta").first(),b.length?(h={instance:g,element:b,parent:b.closest(".customize-pane-child"),height:c(b)},i&&e(h.element,h.parent)):h=!1},f.state("expandedSection").bind(a),f.state("expandedPanel").bind(a),j.on("scroll",_.throttle(function(){if(h){var a=j.scrollTop(),b=!i||a<=i;i=a,g(h,a,b)}},8)),d=function(a){a.hasClass("is-sticky")&&a.removeClass("is-sticky").addClass("maybe-sticky is-in-view").css("top",j.scrollTop()+"px")},e=function(a,b){a.removeClass("maybe-sticky is-in-view").css({width:"",top:""}),b.css("padding-top","")},c=function(a){var b=a.data("height");return b||(b=a.outerHeight(),a.data("height",b)),b},g=function(a,b,c){var d=a.element,e=a.parent,f=a.height,g=parseInt(d.css("top"),10),h=d.hasClass("maybe-sticky"),i=d.hasClass("is-sticky"),j=d.hasClass("is-in-view");if(!c)return i&&(g=b,d.removeClass("is-sticky").css({top:g+"px",width:""})),void(j&&b>g+f&&(d.removeClass("is-in-view"),e.css("padding-top","")));if(!h&&b>=f)h=!0,d.addClass("maybe-sticky");else if(0===b)return d.removeClass("maybe-sticky is-in-view is-sticky").css({top:"",width:""}),void e.css("padding-top","");j&&!i?g>=b&&d.addClass("is-sticky").css({top:"",width:e.outerWidth()+"px"}):h&&!j&&(d.addClass("is-in-view").css("top",b-f+"px"),e.css("padding-top",f+"px"))}}(),f.previewedDevice=new f.Value,f.bind("ready",function(){_.find(f.settings.previewableDevices,function(a,b){if(!0===a["default"])return f.previewedDevice.set(b),!0})}),i.find(".devices button").on("click",function(a){f.previewedDevice.set(b(a.currentTarget).data("device"))}),f.previewedDevice.bind(function(a){var c=b(".wp-full-overlay"),d="";i.find(".devices button").removeClass("active").attr("aria-pressed",!1),i.find(".devices .preview-"+a).addClass("active").attr("aria-pressed",!0),b.each(f.settings.previewableDevices,function(a){d+=" preview-"+a}),c.removeClass(d).addClass("preview-"+a)}),e.length&&f("blogname",function(a){var c=function(){e.text(b.trim(a())||f.l10n.untitledBlogName)};a.bind(c),c()}),a=new f.Messenger({url:f.settings.url.parent,channel:"loader"}),a.bind("back",function(){g.on("click.customize-controls-close",function(b){b.preventDefault(),a.send("close")})}),b(window).on("beforeunload.customize-confirm",function(){if(!f.state("saved")())return setTimeout(function(){d.removeClass("customize-loading")},1),f.l10n.saveAlert}),b.each(["saved","change"],function(b,c){f.bind(c,function(){a.send(c)})}),f.bind("title",function(b){a.send("title",b)}),a.send("changeset-uuid",f.settings.changeset.uuid),a.send("ready"),b.each({background_image:{controls:["background_preset","background_position","background_size","background_repeat","background_attachment"],callback:function(a){return!!a}},show_on_front:{controls:["page_on_front","page_for_posts"],callback:function(a){return"page"===a}},header_textcolor:{controls:["header_textcolor"],callback:function(a){return"blank"!==a}}},function(a,c){f(a,function(a){b.each(c.controls,function(b,d){f.control(d,function(b){var d=function(a){b.container.toggle(c.callback(a))};d(a.get()),a.bind(d)})})})}),f.control("background_preset",function(a){var b,c,d,e,g,h;b={"default":[!1,!1,!1,!1],fill:[!0,!1,!1,!1],fit:[!0,!1,!0,!1],repeat:[!0,!1,!1,!0],custom:[!0,!0,!0,!0]},c=[_wpCustomizeBackground.defaults["default-position-x"],_wpCustomizeBackground.defaults["default-position-y"],_wpCustomizeBackground.defaults["default-size"],_wpCustomizeBackground.defaults["default-repeat"],_wpCustomizeBackground.defaults["default-attachment"]],d={"default":c,fill:["left","top","cover","no-repeat","fixed"],fit:["left","top","contain","no-repeat","fixed"],repeat:["left","top","auto","repeat","scroll"]},e=function(a){_.each(["background_position","background_size","background_repeat","background_attachment"],function(c,d){var e=f.control(c);e&&e.container.toggle(b[a][d])})},g=function(a){_.each(["background_position_x","background_position_y","background_size","background_repeat","background_attachment"],function(b,c){var e=f(b);e&&e.set(d[a][c])})},h=a.setting.get(),e(h),a.setting.bind("change",function(a){e(a),"custom"!==a&&g(a)})}),f.control("background_repeat",function(a){a.elements[0].unsync(f("background_repeat")),a.element=new f.Element(a.container.find("input")),a.element.set("no-repeat"!==a.setting()),a.element.bind(function(b){a.setting.set(b?"repeat":"no-repeat")}),a.setting.bind(function(b){a.element.set("no-repeat"!==b)})}),f.control("background_attachment",function(a){a.elements[0].unsync(f("background_attachment")),a.element=new f.Element(a.container.find("input")),a.element.set("fixed"!==a.setting()),a.element.bind(function(b){a.setting.set(b?"scroll":"fixed")}),a.setting.bind(function(b){a.element.set("fixed"!==b)})}),f.control("display_header_text",function(a){var b="";a.elements[0].unsync(f("header_textcolor")),a.element=new f.Element(a.container.find("input")),a.element.set("blank"!==a.setting()),a.element.bind(function(c){c||(b=f("header_textcolor").get()),a.setting.set(c?b:"blank")}),a.setting.bind(function(b){a.element.set("blank"!==b)})}),f("show_on_front","page_on_front",function(a,b){var c=function(){"page"===a()&&parseInt(b(),10)>0&&f.previewer.previewUrl.set(f.settings.url.home)};a.bind(c),b.bind(c)}),f("page_for_posts",function(a){a.bind(function(a){a=parseInt(a,10),a>0&&f.previewer.previewUrl.set(f.settings.url.home+"?page_id="+a)})}),f.control("custom_css",function(a){a.deferred.embedded.done(function(){var b=a.container.find("textarea"),c=b[0];b.on("blur",function(){b.data("next-tab-blurs",!1)}),b.on("keydown",function(a){var d,e,f,g=9,h=27;return h===a.keyCode?void(b.data("next-tab-blurs")||(b.data("next-tab-blurs",!0),a.stopPropagation())):void(g!==a.keyCode||a.ctrlKey||a.altKey||a.shiftKey||b.data("next-tab-blurs")||(d=c.selectionStart,e=c.selectionEnd,f=c.value,d>=0&&(c.value=f.substring(0,d).concat("\t",f.substring(e)),b.selectionStart=c.selectionEnd=d+1),a.stopPropagation(),a.preventDefault()))})})}),f.control("header_video",function(a){a.deferred.embedded.done(function(){var b=function(){var b,c=f.section(a.section());c&&(b=c.container.find(".header-video-not-currently-previewable:first"),a.active.get()?b.stop().slideUp("fast"):b.stop().slideDown("fast"))};b(),a.active.bind(b)})}),f.previewer.bind("selective-refresh-setting-validities",function(a){f._handleSettingValidities({settingValidities:a,focusInvalidControl:!1})}),f.previewer.bind("focus-control-for-setting",function(a){var b=[];f.control.each(function(c){var d=_.pluck(c.settings,"id");-1!==_.indexOf(d,a)&&b.push(c)}),b.length&&(b.sort(function(a,b){return a.priority()-b.priority()}),b[0].focus())}),f.previewer.bind("refresh",function(){f.previewer.refresh()}),f.state("paneVisible").bind(function(a){var c;c=window.matchMedia?window.matchMedia("screen and ( max-width: 640px )").matches:b(window).width()<=640,f.state("editShortcutVisibility").set(a||c?"visible":"hidden")}),window.matchMedia&&window.matchMedia("screen and ( max-width: 640px )").addListener(function(){var a=f.state("paneVisible");a.callbacks.fireWith(a,[a.get(),a.get()])}),f.previewer.bind("edit-shortcut-visibility",function(a){f.state("editShortcutVisibility").set(a)}),f.state("editShortcutVisibility").bind(function(a){f.previewer.send("edit-shortcut-visibility",a)}),function(){var a,c,d,e=!1;c=function(){e||(e=!0,f.requestChangesetUpdate().always(function(){e=!1})),d()},d=function(){clearTimeout(a),a=setTimeout(function(){c()},f.settings.timeouts.changesetAutoSave)},d(),b(window).on("blur.wp-customize-changeset-update",function(){c()}),b(window).on("beforeunload.wp-customize-changeset-update",function(){c()})}(),f.trigger("ready"); }})}(wp,jQuery);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/css/customize-nav-menus-rtl.min.css
1
#customize-theme-controls #accordion-section-menu_locations{position:relative;margin-bottom:15px}#customize-theme-controls #accordion-section-menu_locations>.accordion-section-title{border-bottom-color:#ddd}.menu-in-location,.menu-in-locations{display:block;font-weight:600;font-size:10px}#customize-controls .control-section .accordion-section-title:focus .menu-in-location,#customize-controls .control-section .accordion-section-title:hover .menu-in-location,#customize-controls .theme-location-set{color:#555}.customize-control-nav_menu_location .edit-menu{margin-right:6px;vertical-align:middle;line-height:28px;color:#0073aa;text-decoration:underline}.customize-control-nav_menu_location .edit-menu:active,.customize-control-nav_menu_location .edit-menu:hover{color:#00a0d2}.customize-control-nav_menu_location .edit-menu:focus{color:#124964}.wp-customizer .menu-item-bar .menu-item-handle,.wp-customizer .menu-item-settings,.wp-customizer .menu-item-settings .description-thin{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.wp-customizer .menu-item-bar{margin:0}.wp-customizer .menu-item-bar .menu-item-handle{width:100%;background:#fff}.wp-customizer .menu-item-handle .item-title{margin-left:0}.wp-customizer .menu-item-handle .item-type{padding:1px 5px 0 21px;float:left;text-align:left}.wp-customizer .menu-item-handle:hover{z-index:8}.customize-control-nav_menu_item.has-notifications .menu-item-handle{border-right:4px solid #00a0d2}.wp-customizer .menu-item-settings{max-width:100%;overflow:hidden;z-index:8;padding:10px;background:#eee;border:1px solid #999;border-top:none}.wp-customizer .menu-item-settings .description-thin{width:100%;height:auto;margin:0 0 8px}.wp-customizer .menu-item-settings input[type=text]{width:100%}.wp-customizer .menu-item-settings .submitbox{margin:0;padding:0}.wp-customizer .menu-item-settings .link-to-original{padding:5px 0;border:none;font-style:normal;margin:0;width:100%}.wp-customizer .menu-item .submitbox .submitdelete{float:right;margin:6px 0 0;padding:0;cursor:pointer}.menu-item-reorder-nav{display:none;background-color:#fff;position:absolute;top:0;left:0}.menus-move-left:before{content:"\f345"}.menus-move-right:before{content:"\f341"}.reordering .menu-item .item-controls,.reordering .menu-item .item-type{display:none}.reordering .menu-item-reorder-nav{display:block}.customize-control input.menu-name-field{width:100%;margin:12px 0}.wp-customizer .menu-item .item-edit{position:absolute;left:-19px;top:2px;display:block;width:30px;height:38px;margin-left:0!important;-webkit-box-shadow:none;box-shadow:none;outline:0;overflow:hidden;cursor:pointer}.wp-customizer .menu-item.menu-item-edit-active .item-edit .toggle-indicator:after{content:"\f142"}.wp-customizer .menu-item-settings p.description{font-style:normal}.wp-customizer .menu-settings dl{margin:12px 0 0;padding:0}.wp-customizer .menu-settings .checkbox-input{margin-top:8px}.wp-customizer .menu-settings .menu-theme-locations{border-top:1px solid #ccc}.wp-customizer .menu-settings{margin-top:36px;border-top:none}.menu-settings .customize-control-checkbox label{line-height:1}.menu-settings .customize-control.customize-control-checkbox{margin-bottom:8px}.customize-control-menu{margin-top:4px}#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle{color:#555}.customize-screen-options-toggle{background:0 0;border:none;color:#555;cursor:pointer;margin:0;padding:20px;position:absolute;left:0;top:30px}#customize-controls .customize-info .customize-help-toggle{padding:20px}#customize-controls .customize-info .customize-help-toggle:before{padding:4px}#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle:active,#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle:focus,#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle:hover,.active-menu-screen-options .customize-screen-options-toggle,.customize-screen-options-toggle:active,.customize-screen-options-toggle:focus,.customize-screen-options-toggle:hover{color:#0073aa}#customize-controls .customize-info .customize-help-toggle:focus,.customize-screen-options-toggle:focus{outline:0}.customize-screen-options-toggle:before{-moz-osx-font-smoothing:grayscale;border:none;content:"\f111";display:block;font:18px/1 dashicons;padding:5px;text-align:center;text-decoration:none!important;text-indent:0;right:6px;position:absolute;top:6px}#customize-controls .customize-info .customize-help-toggle:focus:before,.customize-screen-options-toggle:focus:before{-webkit-border-radius:100%;border-radius:100%}.wp-customizer #screen-options-wrap{display:none;background:#fff;border-top:1px solid #ddd;padding:4px 15px 15px}.wp-customizer .metabox-prefs label{display:block;padding-left:0;line-height:30px}.wp-customizer .toggle-indicator{display:inline-block;font-size:20px;line-height:1;text-indent:-1px}.rtl .wp-customizer .toggle-indicator{text-indent:1px}.wp-customizer .toggle-indicator:after{content:"\f140";speak:none;vertical-align:top;-webkit-border-radius:50%;border-radius:50%;color:#72777c;font:400 20px/1 dashicons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-decoration:none!important}.control-section-nav_menu .field-css-classes,.control-section-nav_menu .field-description,.control-section-nav_menu .field-link-target,.control-section-nav_menu .field-title-attribute,.control-section-nav_menu .field-xfn{display:none}.control-section-nav_menu.field-css-classes-active .field-css-classes,.control-section-nav_menu.field-description-active .field-description,.control-section-nav_menu.field-link-target-active .field-link-target,.control-section-nav_menu.field-title-attribute-active .field-title-attribute,.control-section-nav_menu.field-xfn-active .field-xfn{display:block}.menu-item-depth-0{margin-right:0}.menu-item-depth-1{margin-right:20px}.menu-item-depth-2{margin-right:40px}.menu-item-depth-3{margin-right:60px}.menu-item-depth-4{margin-right:80px}.menu-item-depth-5{margin-right:100px}.menu-item-depth-6{margin-right:120px}.menu-item-depth-7{margin-right:140px}.menu-item-depth-8{margin-right:160px}.menu-item-depth-9{margin-right:180px}.menu-item-depth-10{margin-right:200px}.menu-item-depth-11{margin-right:220px}.menu-item-depth-0>.menu-item-bar{margin-left:0}.menu-item-depth-1>.menu-item-bar{margin-left:20px}.menu-item-depth-2>.menu-item-bar{margin-left:40px}.menu-item-depth-3>.menu-item-bar{margin-left:60px}.menu-item-depth-4>.menu-item-bar{margin-left:80px}.menu-item-depth-5>.menu-item-bar{margin-left:100px}.menu-item-depth-6>.menu-item-bar{margin-left:120px}.menu-item-depth-7>.menu-item-bar{margin-left:140px}.menu-item-depth-8>.menu-item-bar{margin-left:160px}.menu-item-depth-9>.menu-item-bar{margin-left:180px}.menu-item-depth-10>.menu-item-bar{margin-left:200px}.menu-item-depth-11>.menu-item-bar{margin-left:220px}.menu-item-depth-0 .menu-item-transport{margin-right:0}.menu-item-depth-1 .menu-item-transport{margin-right:-20px}.menu-item-depth-3 .menu-item-transport{margin-right:-60px}.menu-item-depth-4 .menu-item-transport{margin-right:-80px}.menu-item-depth-2 .menu-item-transport{margin-right:-40px}.menu-item-depth-5 .menu-item-transport{margin-right:-100px}.menu-item-depth-6 .menu-item-transport{margin-right:-120px}.menu-item-depth-7 .menu-item-transport{margin-right:-140px}.menu-item-depth-8 .menu-item-transport{margin-right:-160px}.menu-item-depth-9 .menu-item-transport{margin-right:-180px}.menu-item-depth-10 .menu-item-transport{margin-right:-200px}.menu-item-depth-11 .menu-item-transport{margin-right:-220px}.reordering .menu-item-depth-0{margin-right:0}.reordering .menu-item-depth-1{margin-right:15px}.reordering .menu-item-depth-2{margin-right:30px}.reordering .menu-item-depth-3{margin-right:45px}.reordering .menu-item-depth-4{margin-right:60px}.reordering .menu-item-depth-5{margin-right:75px}.reordering .menu-item-depth-6{margin-right:90px}.reordering .menu-item-depth-7{margin-right:105px}.reordering .menu-item-depth-8{margin-right:120px}.reordering .menu-item-depth-9{margin-right:135px}.reordering .menu-item-depth-10{margin-right:150px}.reordering .menu-item-depth-11{margin-right:165px}.reordering .menu-item-depth-0>.menu-item-bar{margin-left:0}.reordering .menu-item-depth-1>.menu-item-bar{margin-left:15px}.reordering .menu-item-depth-2>.menu-item-bar{margin-left:30px}.reordering .menu-item-depth-3>.menu-item-bar{margin-left:45px}.reordering .menu-item-depth-4>.menu-item-bar{margin-left:60px}.reordering .menu-item-depth-5>.menu-item-bar{margin-left:75px}.reordering .menu-item-depth-6>.menu-item-bar{margin-left:90px}.reordering .menu-item-depth-7>.menu-item-bar{margin-left:105px}.reordering .menu-item-depth-8>.menu-item-bar{margin-left:120px}.reordering .menu-item-depth-9>.menu-item-bar{margin-left:135px}.reordering .menu-item-depth-10>.menu-item-bar{margin-left:150px}.reordering .menu-item-depth-11>.menu-item-bar{margin-left:165px}.control-section-nav_menu.menu .menu-item-edit-active{margin-right:0}.control-section-nav_menu.menu .menu-item-edit-active .menu-item-bar{margin-left:0}.control-section-nav_menu.menu .sortable-placeholder{margin-top:0;margin-bottom:1px;max-width:-webkit-calc(100% - 2px);max-width:calc(100% - 2px);float:right;display:list-item;border-color:#a0a5aa}.menu-item-transport li.customize-control{float:none}.control-section-nav_menu.menu ul.menu-item-transport .menu-item-bar{margin-top:0}.adding-menu-items .control-section{opacity:.4}.adding-menu-items .control-panel.control-section,.adding-menu-items .control-section.open{opacity:1}.menu-item-bar .item-delete{color:#a00;position:absolute;top:2px;left:-19px;width:30px;height:38px;cursor:pointer;display:none}.menu-item-bar .item-delete:before{content:"\f335";position:absolute;top:9px;right:5px;-webkit-border-radius:50%;border-radius:50%;font:400 20px/1 dashicons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ie8 .menu-item-bar .item-delete:before{top:-10px}.menu-item-bar .item-delete:focus,.menu-item-bar .item-delete:hover{-webkit-box-shadow:none;box-shadow:none;outline:0;color:red}.adding-menu-items .menu-item-bar .item-edit{display:none}.adding-menu-items .menu-item-bar .item-delete{display:block}#available-menu-items.opening{overflow-y:hidden}#available-menu-items #available-menu-items-search.open{height:100%;border-bottom:none}#available-menu-items .accordion-section-title{border-right:none;border-left:none;background:#fff;-webkit-transition:background-color .15s;transition:background-color .15s;-webkit-user-select:auto;-moz-user-select:auto;-ms-user-select:auto;user-select:auto}#available-menu-items #available-menu-items-search .accordion-section-title,#available-menu-items .open .accordion-section-title{background:#eee}#available-menu-items .accordion-section-title:after{content:none!important}#available-menu-items .accordion-section-title:hover .toggle-indicator:after,#available-menu-items .button-link:focus .toggle-indicator:after,#available-menu-items .button-link:hover .toggle-indicator:after{color:#23282d}#available-menu-items .open .accordion-section-title .toggle-indicator:after{content:"\f142";color:#23282d}#available-menu-items .available-menu-items-list{overflow-y:auto;max-height:200px;background:0 0}#available-menu-items .accordion-section-title button{display:block;width:28px;height:35px;position:absolute;top:5px;left:5px;-webkit-box-shadow:none;box-shadow:none;outline:0;cursor:pointer}#available-menu-items .accordion-section-title .no-items,#available-menu-items .cannot-expand .accordion-section-title .spinner,#available-menu-items .cannot-expand .accordion-section-title>button{display:none}#available-menu-items-search.cannot-expand .accordion-section-title .spinner{display:block}#available-menu-items .cannot-expand .accordion-section-title .no-items{float:left;color:#555d66;font-weight:400;margin-right:5px}#available-menu-items .accordion-section-content{max-height:290px;margin:0;padding:0;position:relative;background:0 0}#available-menu-items .accordion-section-content .available-menu-items-list{margin:0 0 45px;padding:1px 15px 15px}#available-menu-items .accordion-section-content .available-menu-items-list:only-child{margin-bottom:0}#new-custom-menu-item .accordion-section-content{padding:0 15px 15px}#available-menu-items .menu-item-tpl{margin:0}#available-menu-items .new-content-item .create-item-input.invalid,#available-menu-items .new-content-item .create-item-input.invalid:focus,#custom-menu-item-name.invalid,#custom-menu-item-url.invalid,.menu-name-field.invalid,.menu-name-field.invalid:focus{border:1px solid red}#available-menu-items .menu-item-handle .item-type{padding-left:0}#available-menu-items .menu-item-handle .item-title{padding-right:20px}#available-menu-items .menu-item-handle{cursor:pointer;-webkit-box-shadow:none;box-shadow:none;margin-top:-1px}#available-menu-items .menu-item-handle:hover{z-index:1}#available-menu-items .item-title h4{padding:0 0 5px;font-size:14px}#available-menu-items .item-add{position:absolute;top:1px;right:1px;color:#82878c;width:30px;height:38px;-webkit-box-shadow:none;box-shadow:none;outline:0;cursor:pointer}#available-menu-items .menu-item-handle .item-add:focus{color:#23282d}#available-menu-items .item-add:before{content:"\f543";position:relative;right:2px;top:3px;display:inline-block;height:20px;-webkit-border-radius:50%;border-radius:50%;font:400 20px/1.05 dashicons}#available-menu-items .menu-item-handle.item-added .item-add:focus,#available-menu-items .menu-item-handle.item-added .item-title,#available-menu-items .menu-item-handle.item-added .item-type,#available-menu-items .menu-item-handle.item-added:hover .item-add{color:#82878c}#available-menu-items .menu-item-handle.item-added .item-add:before{content:"\f147"}#available-menu-items .accordion-section-title.loading .spinner,#available-menu-items-search.loading .accordion-section-title .spinner{visibility:visible;margin:0 20px}#available-menu-items-search .spinner{position:absolute;top:20px;left:21px;margin:0!important}#available-menu-items #available-menu-items-search .accordion-section-content{position:absolute;right:0;top:60px;bottom:0;max-height:none;width:100%;padding:1px 15px 15px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#available-menu-items-search .nothing-found{margin-top:-1px}#available-menu-items-search .accordion-section-title:after{display:none}#available-menu-items-search .accordion-section-content:empty{min-height:0;padding:0}#available-menu-items-search.loading .accordion-section-content div{opacity:.5}#available-menu-items-search.loading.loading-more .accordion-section-content div{opacity:1}#customize-preview{-webkit-transition:all .2s;transition:all .2s}body.adding-menu-items #available-menu-items{right:0;visibility:visible}body.adding-menu-items .wp-full-overlay-main{right:300px}body.adding-menu-items #customize-preview{opacity:.4}body.adding-menu-items #customize-preview iframe{pointer-events:none}.menu-item-handle .spinner{display:none;float:right;margin:0 0 0 8px}.nav-menu-inserted-item-loading .spinner{display:block}.nav-menu-inserted-item-loading .menu-item-handle .item-type{padding:0 8px 0 0}.added-menu-item .menu-item-handle.loading,.nav-menu-inserted-item-loading .menu-item-handle{padding:10px 8px 10px 15px;cursor:default;opacity:.5;background:#fff;color:#727773}.added-menu-item .menu-item-handle{-webkit-transition-property:opacity,background,color;transition-property:opacity,background,color;-webkit-transition-duration:1.25s;transition-duration:1.25s;-webkit-transition-timing-function:cubic-bezier(.25,-2.5,.75,8);transition-timing-function:cubic-bezier(.25,-2.5,.75,8)}#customize-theme-controls .control-panel-content .control-section-nav_menu:nth-last-child(2) .accordion-section-title{border-bottom-color:#ddd}#accordion-section-add_menu{margin:15px 12px;overflow:hidden}.new-menu-section-content{display:none;padding:15px 0 0;clear:both}#accordion-section-add_menu .accordion-section-title{padding-right:45px}#accordion-section-add_menu .accordion-section-title:before{font:400 20px/1 dashicons;position:absolute;top:12px;right:14px;content:"\f132"}#create-new-menu-submit{float:left;margin:0 0 12px}.menu-delete-item{float:right;padding:1em 0;width:100%}li.assigned-to-menu-location .menu-delete-item{display:none}li.assigned-to-menu-location .add-new-menu-item{margin-bottom:1em}.menu-delete{color:#a00;cursor:pointer;text-decoration:underline}.menu-delete:focus,.menu-delete:hover{color:red}.menu-item-handle{margin-top:-1px}.ui-sortable-disabled .menu-item-handle{cursor:default}.menu-item-handle:hover{position:relative;z-index:10;color:#0073aa}#available-menu-items .menu-item-handle:hover .item-add,.menu-item-handle:hover .item-edit,.menu-item-handle:hover .item-type{color:#0073aa}.menu-item-edit-active .menu-item-handle{border-color:#999;border-bottom:none}.customize-control-nav_menu_item{margin-bottom:0}.customize-control-nav_menu{margin-top:12px}#available-menu-items .item-add:focus:before,#customize-controls .customize-info .customize-help-toggle:focus:before,.customize-screen-options-toggle:focus:before,.menu-delete:focus,.menu-item-bar .item-delete:focus:before,.wp-customizer .menu-item .submitbox .submitdelete:focus,.wp-customizer button:focus .toggle-indicator:after{-webkit-box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8);box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8)}@media screen and (max-width:782px){#available-menu-items #available-menu-items-search .accordion-section-content{top:63px}}@media screen and (max-width:640px){#available-menu-items #available-menu-items-search .accordion-section-content{top:130px}}
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/js/customize-nav-menus.min.js
2
!function(a,b,c){"use strict";function d(a){return"nav_menu_item["+a+"]"}function e(b){return b=b||"",b=c("<div>").text(b).html(),b=c.trim(b),b||a.Menus.data.l10n.unnamed}wpNavMenu.originalInit=wpNavMenu.init,wpNavMenu.options.menuItemDepthPerLevel=20,wpNavMenu.options.sortableItems="> .customize-control-nav_menu_item",wpNavMenu.options.targetTolerance=10,wpNavMenu.init=function(){this.jQueryExtensions()},a.Menus=a.Menus||{},a.Menus.data={itemTypes:[],l10n:{},settingTransport:"refresh",phpIntMax:0,defaultSettingValues:{nav_menu:{},nav_menu_item:{}},locationSlugMappedToName:{}},"undefined"!=typeof _wpCustomizeNavMenusSettings&&c.extend(a.Menus.data,_wpCustomizeNavMenusSettings),a.Menus.generatePlaceholderAutoIncrementId=function(){return-Math.ceil(a.Menus.data.phpIntMax*Math.random())},a.Menus.AvailableItemModel=Backbone.Model.extend(c.extend({id:null},a.Menus.data.defaultSettingValues.nav_menu_item)),a.Menus.AvailableItemCollection=Backbone.Collection.extend({model:a.Menus.AvailableItemModel,sort_key:"order",comparator:function(a){return-a.get(this.sort_key)},sortByField:function(a){this.sort_key=a,this.sort()}}),a.Menus.availableMenuItems=new a.Menus.AvailableItemCollection(a.Menus.data.availableMenuItems),a.Menus.insertAutoDraftPost=function(d){var e,f=c.Deferred();return e=b.ajax.post("customize-nav-menus-insert-auto-draft",{"customize-menus-nonce":a.settings.nonce["customize-menus"],wp_customize:"on",params:d}),e.done(function(b){b.post_id&&(a("nav_menus_created_posts").set(a("nav_menus_created_posts").get().concat([b.post_id])),"page"===d.post_type&&(a.section.has("static_front_page")&&a.section("static_front_page").activate(),a.control.each(function(a){var c;"dropdown-pages"===a.params.type&&(c=a.container.find('select[name^="_customize-dropdown-pages-"]'),c.append(new Option(d.post_title,b.post_id)))})),f.resolve(b))}),e.fail(function(a){var b=a||"";"undefined"!=typeof a.message&&(b=a.message),console.error(b),f.rejectWith(b)}),f.promise()},a.Menus.AvailableMenuItemsPanelView=b.Backbone.View.extend({el:"#available-menu-items",events:{"input #menu-items-search":"debounceSearch","keyup #menu-items-search":"debounceSearch","focus .menu-item-tpl":"focus","click .menu-item-tpl":"_submit","click #custom-menu-item-submit":"_submitLink","keypress #custom-menu-item-name":"_submitLink","click .new-content-item .add-content":"_submitNew","keypress .create-item-input":"_submitNew",keydown:"keyboardAccessible"},selected:null,currentMenuControl:null,debounceSearch:null,$search:null,$clearResults:null,searchTerm:"",rendered:!1,pages:{},sectionContent:"",loading:!1,addingNew:!1,initialize:function(){var b=this;a.panel.has("nav_menus")&&(this.$search=c("#menu-items-search"),this.$clearResults=this.$el.find(".clear-results"),this.sectionContent=this.$el.find(".available-menu-items-list"),this.debounceSearch=_.debounce(b.search,500),_.bindAll(this,"close"),c("#customize-controls, .customize-section-back").on("click keydown",function(a){var d=c(a.target).is(".item-delete, .item-delete *"),e=c(a.target).is(".add-new-menu-item, .add-new-menu-item *");!c("body").hasClass("adding-menu-items")||d||e||b.close()}),this.$clearResults.on("click",function(){b.$search.val("").focus().trigger("keyup")}),this.$el.on("input","#custom-menu-item-name.invalid, #custom-menu-item-url.invalid",function(){c(this).removeClass("invalid")}),a.panel("nav_menus").container.bind("expanded",function(){b.rendered||(b.initList(),b.rendered=!0)}),this.sectionContent.scroll(function(){var a=b.$el.find(".accordion-section.open .available-menu-items-list").prop("scrollHeight"),d=b.$el.find(".accordion-section.open").height();if(!b.loading&&c(this).scrollTop()>.75*a-d){var e=c(this).data("type"),f=c(this).data("object");"search"===e?b.searchTerm&&b.doSearch(b.pages.search):b.loadItems([{type:e,object:f}])}}),a.previewer.bind("url",this.close),b.delegateEvents())},search:function(a){var b=c("#available-menu-items-search"),d=c("#available-menu-items .accordion-section").not(b);a&&this.searchTerm!==a.target.value&&(""===a.target.value||b.hasClass("open")?""===a.target.value&&(b.removeClass("open"),d.show(),this.$clearResults.removeClass("is-visible")):(d.fadeOut(100),b.find(".accordion-section-content").slideDown("fast"),b.addClass("open"),this.$clearResults.addClass("is-visible")),this.searchTerm=a.target.value,this.pages.search=1,this.doSearch(1))},doSearch:function(d){var e,f=this,g=c("#available-menu-items-search"),h=g.find(".accordion-section-content"),i=b.template("available-menu-item");if(f.currentRequest&&f.currentRequest.abort(),!(d<0)){if(d>1)g.addClass("loading-more"),h.attr("aria-busy","true"),b.a11y.speak(a.Menus.data.l10n.itemsLoadingMore);else if(""===f.searchTerm)return h.html(""),void b.a11y.speak("");g.addClass("loading"),f.loading=!0,e=a.previewer.query({excludeCustomizedSaved:!0}),_.extend(e,{"customize-menus-nonce":a.settings.nonce["customize-menus"],wp_customize:"on",search:f.searchTerm,page:d}),f.currentRequest=b.ajax.post("search-available-menu-items-customizer",e),f.currentRequest.done(function(c){var e;1===d&&h.empty(),g.removeClass("loading loading-more"),h.attr("aria-busy","false"),g.addClass("open"),f.loading=!1,e=new a.Menus.AvailableItemCollection(c.items),f.collection.add(e.models),e.each(function(a){h.append(i(a.attributes))}),20>e.length?f.pages.search=-1:f.pages.search=f.pages.search+1,e&&d>1?b.a11y.speak(a.Menus.data.l10n.itemsFoundMore.replace("%d",e.length)):e&&1===d&&b.a11y.speak(a.Menus.data.l10n.itemsFound.replace("%d",e.length))}),f.currentRequest.fail(function(a){a.message&&(h.empty().append(c('<li class="nothing-found"></li>').text(a.message)),b.a11y.speak(a.message)),f.pages.search=-1}),f.currentRequest.always(function(){g.removeClass("loading loading-more"),h.attr("aria-busy","false"),f.loading=!1,f.currentRequest=null})}},initList:function(){var b=this;_.each(a.Menus.data.itemTypes,function(a){b.pages[a.type+":"+a.object]=0}),b.loadItems(a.Menus.data.itemTypes)},loadItems:function(d,e){var f,g,h,i,j=this,k=[],l={};i=b.template("available-menu-item"),f=_.isString(d)&&_.isString(e)?[{type:d,object:e}]:d,_.each(f,function(a){var b,d=a.type+":"+a.object;-1!==j.pages[d]&&(b=c("#available-menu-items-"+a.type+"-"+a.object),b.find(".accordion-section-title").addClass("loading"),l[d]=b,k.push({object:a.object,type:a.type,page:j.pages[d]}))}),0!==k.length&&(j.loading=!0,g=a.previewer.query({excludeCustomizedSaved:!0}),_.extend(g,{"customize-menus-nonce":a.settings.nonce["customize-menus"],wp_customize:"on",item_types:k}),h=b.ajax.post("load-available-menu-items-customizer",g),h.done(function(b){var c;_.each(b.items,function(b,d){return 0===b.length?(0===j.pages[d]&&l[d].find(".accordion-section-title").addClass("cannot-expand").removeClass("loading").find(".accordion-section-title > button").prop("tabIndex",-1),void(j.pages[d]=-1)):("post_type:page"!==d||l[d].hasClass("open")||l[d].find(".accordion-section-title > button").click(),b=new a.Menus.AvailableItemCollection(b),j.collection.add(b.models),c=l[d].find(".available-menu-items-list"),b.each(function(a){c.append(i(a.attributes))}),void(j.pages[d]+=1))})}),h.fail(function(a){"undefined"!=typeof console&&console.error&&console.error(a)}),h.always(function(){_.each(l,function(a){a.find(".accordion-section-title").removeClass("loading")}),j.loading=!1}))},itemSectionHeight:function(){var a,b,c,d,e;c=window.innerHeight,a=this.$el.find(".accordion-section:not( #available-menu-items-search ) .accordion-section-content"),b=this.$el.find('.accordion-section:not( #available-menu-items-search ) .available-menu-items-list:not(":only-child")'),d=46*(1+a.length)+14,e=c-d,120<e&&290>e&&(a.css("max-height",e),b.css("max-height",e-60))},select:function(a){this.selected=c(a),this.selected.siblings(".menu-item-tpl").removeClass("selected"),this.selected.addClass("selected")},focus:function(a){this.select(c(a.currentTarget))},_submit:function(a){"keypress"===a.type&&13!==a.which&&32!==a.which||this.submit(c(a.currentTarget))},submit:function(a){var b,d;a||(a=this.selected),a&&this.currentMenuControl&&(this.select(a),b=c(this.selected).data("menu-item-id"),d=this.collection.findWhere({id:b}),d&&(this.currentMenuControl.addItemToMenu(d.attributes),c(a).find(".menu-item-handle").addClass("item-added")))},_submitLink:function(a){"keypress"===a.type&&13!==a.which||this.submitLink()},submitLink:function(){var b,d=c("#custom-menu-item-name"),e=c("#custom-menu-item-url");if(this.currentMenuControl){if(""===d.val())return void d.addClass("invalid");if(""===e.val()||"http://"===e.val())return void e.addClass("invalid");b={title:d.val(),url:e.val(),type:"custom",type_label:a.Menus.data.l10n.custom_label,object:"custom"},this.currentMenuControl.addItemToMenu(b),e.val("http://"),d.val("")}},_submitNew:function(a){var b;"keypress"===a.type&&13!==a.which||this.addingNew||(b=c(a.target).closest(".accordion-section"),this.submitNew(b))},submitNew:function(d){var e,f=this,g=d.find(".create-item-input"),h=g.val(),i=d.find(".available-menu-items-list"),j=i.data("type"),k=i.data("object"),l=i.data("type_label");if(this.currentMenuControl&&"post_type"===j){if(""===c.trim(g.val()))return g.addClass("invalid"),void g.focus();g.removeClass("invalid"),d.find(".accordion-section-title").addClass("loading"),f.addingNew=!0,g.attr("disabled","disabled"),e=a.Menus.insertAutoDraftPost({post_title:h,post_type:k}),e.done(function(e){var h,i,m;h=new a.Menus.AvailableItemModel({id:"post-"+e.post_id,title:g.val(),type:j,type_label:l,object:k,object_id:e.post_id,url:e.url}),f.currentMenuControl.addItemToMenu(h.attributes),a.Menus.availableMenuItemsPanel.collection.add(h),i=d.find(".available-menu-items-list"),m=c(b.template("available-menu-item")(h.attributes)),m.find(".menu-item-handle:first").addClass("item-added"),i.prepend(m),i.scrollTop(),g.val("").removeAttr("disabled"),f.addingNew=!1,d.find(".accordion-section-title").removeClass("loading")})}},open:function(a){var b,d=this;this.currentMenuControl=a,this.itemSectionHeight(),c("body").addClass("adding-menu-items"),b=function(){d.close(),c(this).off("click",b)},c("#customize-preview").on("click",b),_(this.currentMenuControl.getMenuItemControls()).each(function(a){a.collapseForm()}),this.$el.find(".selected").removeClass("selected"),this.$search.focus()},close:function(a){a=a||{},a.returnFocus&&this.currentMenuControl&&this.currentMenuControl.container.find(".add-new-menu-item").focus(),this.currentMenuControl=null,this.selected=null,c("body").removeClass("adding-menu-items"),c("#available-menu-items .menu-item-handle.item-added").removeClass("item-added"),this.$search.val("")},keyboardAccessible:function(a){var b=13===a.which,d=27===a.which,e=9===a.which&&a.shiftKey,f=c(a.target).is(this.$search);b&&!this.$search.val()||(f&&e?(this.currentMenuControl.container.find(".add-new-menu-item").focus(),a.preventDefault()):d&&this.close({returnFocus:!0}))}}),a.Menus.MenusPanel=a.Panel.extend({attachEvents:function(){a.Panel.prototype.attachEvents.call(this);var b=this,d=b.container.find(".panel-meta"),e=d.find(".customize-help-toggle"),f=d.find(".customize-panel-description"),g=c("#screen-options-wrap"),h=d.find(".customize-screen-options-toggle");h.on("click keydown",function(b){if(!a.utils.isKeydownButNotEnterEvent(b))return b.preventDefault(),f.not(":hidden")&&(f.slideUp("fast"),e.attr("aria-expanded","false")),"true"===h.attr("aria-expanded")?(h.attr("aria-expanded","false"),d.removeClass("open"),d.removeClass("active-menu-screen-options"),g.slideUp("fast")):(h.attr("aria-expanded","true"),d.addClass("open"),d.addClass("active-menu-screen-options"),g.slideDown("fast")),!1}),e.on("click keydown",function(b){a.utils.isKeydownButNotEnterEvent(b)||(b.preventDefault(),"true"===h.attr("aria-expanded")&&(h.attr("aria-expanded","false"),e.attr("aria-expanded","true"),d.addClass("open"),d.removeClass("active-menu-screen-options"),g.slideUp("fast"),f.slideDown("fast")))})},ready:function(){var a=this;a.container.find(".hide-column-tog").click(function(){a.saveManageColumnsState()})},saveManageColumnsState:_.debounce(function(){var a=this;a._updateHiddenColumnsRequest&&a._updateHiddenColumnsRequest.abort(),a._updateHiddenColumnsRequest=b.ajax.post("hidden-columns",{hidden:a.hidden(),screenoptionnonce:c("#screenoptionnonce").val(),page:"nav-menus"}),a._updateHiddenColumnsRequest.always(function(){a._updateHiddenColumnsRequest=null})},2e3),checked:function(){},unchecked:function(){},hidden:function(){return c(".hide-column-tog").not(":checked").map(function(){var a=this.id;return a.substring(0,a.length-5)}).get().join(",")}}),a.Menus.MenuSection=a.Section.extend({initialize:function(b,d){var e=this;a.Section.prototype.initialize.call(e,b,d),e.deferred.initSortables=c.Deferred()},ready:function(){var b,d,e=this;if("undefined"==typeof e.params.menu_id)throw new Error("params.menu_id was not defined");e.active.validate=function(){return!!a.has(e.id)&&!!a(e.id).get()},e.populateControls(),e.navMenuLocationSettings={},e.assignedLocations=new a.Value([]),a.each(function(a,b){var c=b.match(/^nav_menu_locations\[(.+?)]/);c&&(e.navMenuLocationSettings[c[1]]=a,a.bind(function(){e.refreshAssignedLocations()}))}),e.assignedLocations.bind(function(a){e.updateAssignedLocationsInSectionTitle(a)}),e.refreshAssignedLocations(),a.bind("pane-contents-reflowed",function(){e.contentContainer.parent().length&&(e.container.find(".menu-item .menu-item-reorder-nav button").attr({tabindex:"0","aria-hidden":"false"}),e.container.find(".menu-item.move-up-disabled .menus-move-up").attr({tabindex:"-1","aria-hidden":"true"}),e.container.find(".menu-item.move-down-disabled .menus-move-down").attr({tabindex:"-1","aria-hidden":"true"}),e.container.find(".menu-item.move-left-disabled .menus-move-left").attr({tabindex:"-1","aria-hidden":"true"}),e.container.find(".menu-item.move-right-disabled .menus-move-right").attr({tabindex:"-1","aria-hidden":"true"}))}),d=function(){var a="field-"+c(this).val()+"-active";e.contentContainer.toggleClass(a,c(this).prop("checked"))},b=a.panel("nav_menus").contentContainer.find(".metabox-prefs:first").find(".hide-column-tog"),b.each(d),b.on("click",d)},populateControls:function(){var b,c,d,e,f,g=this;b=g.id+"[name]",e=a.control(b),e||(e=new a.controlConstructor.nav_menu_name(b,{params:{type:"nav_menu_name",content:'<li id="customize-control-'+g.id.replace("[","-").replace("]","")+'-name" class="customize-control customize-control-nav_menu_name"></li>',label:a.Menus.data.l10n.menuNameLabel,active:!0,section:g.id,priority:0,settings:{"default":g.id}}}),a.control.add(e.id,e),e.active.set(!0)),d=a.control(g.id),d||(d=new a.controlConstructor.nav_menu(g.id,{params:{type:"nav_menu",content:'<li id="customize-control-'+g.id.replace("[","-").replace("]","")+'" class="customize-control customize-control-nav_menu"></li>',section:g.id,priority:998,active:!0,settings:{"default":g.id},menu_id:g.params.menu_id}}),a.control.add(d.id,d),d.active.set(!0)),c=g.id+"[auto_add]",f=a.control(c),f||(f=new a.controlConstructor.nav_menu_auto_add(c,{params:{type:"nav_menu_auto_add",content:'<li id="customize-control-'+g.id.replace("[","-").replace("]","")+'-auto-add" class="customize-control customize-control-nav_menu_auto_add"></li>',label:"",active:!0,section:g.id,priority:999,settings:{"default":g.id}}}),a.control.add(f.id,f),f.active.set(!0))},refreshAssignedLocations:function(){var a=this,b=a.params.menu_id,c=[];_.each(a.navMenuLocationSettings,function(a,d){a()===b&&c.push(d)}),a.assignedLocations.set(c)},updateAssignedLocationsInSectionTitle:function(b){var d,e=this;d=e.container.find(".accordion-section-title:first"),d.find(".menu-in-location").remove(),_.each(b,function(b){var e,f;e=c('<span class="menu-in-location"></span>'),f=a.Menus.data.locationSlugMappedToName[b],e.text(a.Menus.data.l10n.menuLocation.replace("%s",f)),d.append(e)}),e.container.toggleClass("assigned-to-menu-location",0!==b.length)},onChangeExpanded:function(b,d){var e,f=this;b&&(wpNavMenu.menuList=f.contentContainer,wpNavMenu.targetList=wpNavMenu.menuList,c("#menu-to-edit").removeAttr("id"),wpNavMenu.menuList.attr("id","menu-to-edit").addClass("menu"),_.each(a.section(f.id).controls(),function(a){"nav_menu_item"===a.params.type&&a.actuallyEmbed()}),d.completeCallback&&(e=d.completeCallback),d.completeCallback=function(){"resolved"!==f.deferred.initSortables.state()&&(wpNavMenu.initSortables(),f.deferred.initSortables.resolve(wpNavMenu.menuList),a.control("nav_menu["+String(f.params.menu_id)+"]").reflowMenuItems()),_.isFunction(e)&&e()}),a.Section.prototype.onChangeExpanded.call(f,b,d)}}),a.Menus.NewMenuSection=a.Section.extend({attachEvents:function(){var a=this;this.container.on("click",".add-menu-toggle",function(){a.expanded()?a.collapse():a.expand()})},onChangeExpanded:function(a){var b=this,c=b.container.find(".add-menu-toggle"),d=b.contentContainer,e=b.headContainer.closest(".wp-full-overlay-sidebar-content");a?(c.addClass("open"),c.attr("aria-expanded","true"),d.slideDown("fast",function(){e.scrollTop(e.height())})):(c.removeClass("open"),c.attr("aria-expanded","false"),d.slideUp("fast"),d.find(".menu-name-field").removeClass("invalid"))},getContent:function(){return this.container.find("ul:first")}}),a.Menus.MenuLocationControl=a.Control.extend({initialize:function(b,c){var d=this,e=b.match(/^nav_menu_locations\[(.+?)]/);d.themeLocation=e[1],a.Control.prototype.initialize.call(d,b,c)},ready:function(){var b=this,c=/^nav_menu\[(-?\d+)]/;b.setting.validate=function(a){return""===a?0:parseInt(a,10)},b.container.find(".edit-menu").on("click",function(){var c=b.setting();a.section("nav_menu["+c+"]").focus()}),b.setting.bind("change",function(){0===b.setting()?b.container.find(".edit-menu").addClass("hidden"):b.container.find(".edit-menu").removeClass("hidden")}),a.bind("add",function(a){var d,f,g=a.id.match(c);g&&!1!==a()&&(f=g[1],d=new Option(e(a().name),f),b.container.find("select").append(d))}),a.bind("remove",function(a){var d,e=a.id.match(c);e&&(d=parseInt(e[1],10),b.setting()===d&&b.setting.set(""),b.container.find("option[value="+d+"]").remove())}),a.bind("change",function(a){var d,f=a.id.match(c);f&&(d=parseInt(f[1],10),!1===a()?(b.setting()===d&&b.setting.set(""),b.container.find("option[value="+d+"]").remove()):b.container.find("option[value="+d+"]").text(e(a().name)))})}}),a.Menus.MenuItemControl=a.Control.extend({initialize:function(b,d){var e=this;e.expanded=new a.Value(!1),e.expandedArgumentsQueue=[],e.expanded.bind(function(a){var b=e.expandedArgumentsQueue.shift();b=c.extend({},e.defaultExpandedArguments,b),e.onChangeExpanded(a,b)}),a.Control.prototype.initialize.call(e,b,d),e.active.validate=function(){var b,c=a.section(e.section());return b=!!c&&c.active()}},embed:function(){var b,c=this,d=c.section();d&&(b=a.section(d),(b&&b.expanded()||a.settings.autofocus.control===c.id)&&c.actuallyEmbed())},actuallyEmbed:function(){var a=this;"resolved"!==a.deferred.embedded.state()&&(a.renderContent(),a.deferred.embedded.resolve())},ready:function(){if("undefined"==typeof this.params.menu_item_id)throw new Error("params.menu_item_id was not defined");this._setupControlToggle(),this._setupReorderUI(),this._setupUpdateUI(),this._setupRemoveUI(),this._setupLinksUI(),this._setupTitleUI()},_setupControlToggle:function(){var b=this;this.container.find(".menu-item-handle").on("click",function(c){c.preventDefault(),c.stopPropagation(),a.Menus.availableMenuItemsPanel.close();var d=b.getMenuControl();d.isReordering||d.isSorting||b.toggleForm()})},_setupReorderUI:function(){var a,d,e=this;a=b.template("menu-item-reorder-nav"),e.container.find(".item-controls").after(a),d=e.container.find(".menu-item-reorder-nav"),d.find(".menus-move-up, .menus-move-down, .menus-move-left, .menus-move-right").on("click",function(){var a=c(this);a.focus();var b=a.is(".menus-move-up"),d=a.is(".menus-move-down"),f=a.is(".menus-move-left"),g=a.is(".menus-move-right");b?e.moveUp():d?e.moveDown():f?e.moveLeft():g&&e.moveRight(),a.focus()})},_setupUpdateUI:function(){var b=this,c=b.setting();b.elements={},b.elements.url=new a.Element(b.container.find(".edit-menu-item-url")),b.elements.title=new a.Element(b.container.find(".edit-menu-item-title")),b.elements.attr_title=new a.Element(b.container.find(".edit-menu-item-attr-title")),b.elements.target=new a.Element(b.container.find(".edit-menu-item-target")),b.elements.classes=new a.Element(b.container.find(".edit-menu-item-classes")),b.elements.xfn=new a.Element(b.container.find(".edit-menu-item-xfn")),b.elements.description=new a.Element(b.container.find(".edit-menu-item-description")),_.each(b.elements,function(a,d){a.bind(function(c){a.element.is("input[type=checkbox]")&&(c=c?a.element.val():"");var e=b.setting();e&&e[d]!==c&&(e=_.clone(e),e[d]=c,b.setting.set(e))}),c&&("classes"!==d&&"xfn"!==d||!_.isArray(c[d])?a.set(c[d]):a.set(c[d].join(" ")))}),b.setting.bind(function(c,d){var e,f=b.params.menu_item_id,g=[],h=[];!1===c?(e=a.control("nav_menu["+String(d.nav_menu_term_id)+"]"),b.container.remove(),_.each(e.getMenuItemControls(),function(a){d.menu_item_parent===a.setting().menu_item_parent&&a.setting().position>d.position?g.push(a):a.setting().menu_item_parent===f&&h.push(a)}),_.each(g,function(a){var b=_.clone(a.setting());b.position+=h.length,a.setting.set(b)}),_.each(h,function(a,b){var c=_.clone(a.setting());c.position=d.position+b,c.menu_item_parent=d.menu_item_parent,a.setting.set(c)}),e.debouncedReflowMenuItems()):(_.each(c,function(a,d){b.elements[d]&&b.elements[d].set(c[d])}),b.container.find(".menu-item-data-parent-id").val(c.menu_item_parent),c.position===d.position&&c.menu_item_parent===d.menu_item_parent||b.getMenuControl().debouncedReflowMenuItems())})},_setupRemoveUI:function(){var d,e=this;d=e.container.find(".item-delete"),d.on("click",function(){var d,f,g,h=!0;c("body").hasClass("adding-menu-items")||(h=!1),f=e.container.nextAll(".customize-control-nav_menu_item:visible").first(),g=e.container.prevAll(".customize-control-nav_menu_item:visible").first(),d=f.length?f.find(!1===h?".item-edit":".item-delete").first():g.length?g.find(!1===h?".item-edit":".item-delete").first():e.container.nextAll(".customize-control-nav_menu").find(".add-new-menu-item").first(),e.container.slideUp(function(){e.setting.set(!1),b.a11y.speak(a.Menus.data.l10n.itemDeleted),d.focus()})})},_setupLinksUI:function(){var b;b=this.container.find("a.original-link"),b.on("click",function(b){b.preventDefault(),a.previewer.previewUrl(b.target.toString())})},_setupTitleUI:function(){var b,d=this;d.container.find(".edit-menu-item-title").on("blur",function(){c(this).val(c.trim(c(this).val()))}),b=d.container.find(".menu-item-title"),d.setting.bind(function(d){var e,f;d&&(e=c.trim(d.title),f=e||d.original_title||a.Menus.data.l10n.untitled,d._invalid&&(f=a.Menus.data.l10n.invalidTitleTpl.replace("%s",f)),e||d.original_title?b.text(f).removeClass("no-title"):b.text(f).addClass("no-title"))})},getDepth:function(){var b=this,c=b.setting(),d=0;if(!c)return 0;for(;c&&c.menu_item_parent&&(d+=1,b=a.control("nav_menu_item["+c.menu_item_parent+"]"));)c=b.setting();return d},renderContent:function(){var b,c=this,d=c.setting();c.params.title=d.title||"",c.params.depth=c.getDepth(),c.container.data("item-depth",c.params.depth),b=["menu-item","menu-item-depth-"+String(c.params.depth),"menu-item-"+d.object,"menu-item-edit-inactive"],d._invalid?(b.push("menu-item-invalid"),c.params.title=a.Menus.data.l10n.invalidTitleTpl.replace("%s",c.params.title)):"draft"===d.status&&(b.push("pending"),c.params.title=a.Menus.data.pendingTitleTpl.replace("%s",c.params.title)),c.params.el_classes=b.join(" "),c.params.item_type_label=d.type_label,c.params.item_type=d.type,c.params.url=d.url,c.params.target=d.target,c.params.attr_title=d.attr_title,c.params.classes=_.isArray(d.classes)?d.classes.join(" "):d.classes,c.params.attr_title=d.attr_title,c.params.xfn=d.xfn,c.params.description=d.description,c.params.parent=d.menu_item_parent,c.params.original_title=d.original_title||"",c.container.addClass(c.params.el_classes),a.Control.prototype.renderContent.call(c)},getMenuControl:function(){var b=this,c=b.setting();return c&&c.nav_menu_term_id?a.control("nav_menu["+c.nav_menu_term_id+"]"):null},expandControlSection:function(){var a=this.container.closest(".accordion-section");a.hasClass("open")||a.find(".accordion-section-title:first").trigger("click")},_toggleExpanded:a.Section.prototype._toggleExpanded,expand:a.Section.prototype.expand,expandForm:function(a){this.expand(a)},collapse:a.Section.prototype.collapse,collapseForm:function(a){this.collapse(a)},toggleForm:function(a,b){"undefined"==typeof a&&(a=!this.expanded()),a?this.expand(b):this.collapse(b)},onChangeExpanded:function(b,c){var d,e,f,g=this;return d=this.container,e=d.find(".menu-item-settings:first"),"undefined"==typeof b&&(b=!e.is(":visible")),e.is(":visible")===b?void(c&&c.completeCallback&&c.completeCallback()):void(b?(a.control.each(function(a){g.params.type===a.params.type&&g!==a&&a.collapseForm()}),f=function(){d.removeClass("menu-item-edit-inactive").addClass("menu-item-edit-active"),g.container.trigger("expanded"),c&&c.completeCallback&&c.completeCallback()},d.find(".item-edit").attr("aria-expanded","true"),e.slideDown("fast",f),g.container.trigger("expand")):(f=function(){d.addClass("menu-item-edit-inactive").removeClass("menu-item-edit-active"),g.container.trigger("collapsed"),c&&c.completeCallback&&c.completeCallback()},g.container.trigger("collapse"),d.find(".item-edit").attr("aria-expanded","false"),e.slideUp("fast",f)))},focus:function(b){b=b||{};var c,d=this,e=b.completeCallback;c=function(){d.expandControlSection(),b.completeCallback=function(){var a;a=d.container.find(".menu-item-settings").find("input, select, textarea, button, object, a[href], [tabindex]").filter(":visible"),a.first().focus(),e&&e()},d.expandForm(b)},a.section.has(d.section())?a.section(d.section()).expand({completeCallback:c}):c()},moveUp:function(){this._changePosition(-1),b.a11y.speak(a.Menus.data.l10n.movedUp)},moveDown:function(){this._changePosition(1),b.a11y.speak(a.Menus.data.l10n.movedDown)},moveLeft:function(){this._changeDepth(-1),b.a11y.speak(a.Menus.data.l10n.movedLeft)},moveRight:function(){this._changeDepth(1),b.a11y.speak(a.Menus.data.l10n.movedRight)},_changePosition:function(a){var b,d,e=this,f=_.clone(e.setting()),g=[];if(1!==a&&-1!==a)throw new Error("Offset changes by 1 are only supported.");if(e.setting()){if(_(e.getMenuControl().getMenuItemControls()).each(function(a){a.setting().menu_item_parent===f.menu_item_parent&&g.push(a.setting)}),g.sort(function(a,b){return a().position-b().position}),d=_.indexOf(g,e.setting),-1===d)throw new Error("Expected setting to be among siblings.");0===d&&a<0||d===g.length-1&&a>0||(b=g[d+a],b&&b.set(c.extend(_.clone(b()),{position:f.position})),f.position+=a,e.setting.set(f))}},_changeDepth:function(b){if(1!==b&&-1!==b)throw new Error("Offset changes by 1 are only supported.");var d,e,f,g=this,h=_.clone(g.setting()),i=[];if(_(g.getMenuControl().getMenuItemControls()).each(function(a){a.setting().menu_item_parent===h.menu_item_parent&&i.push(a)}),i.sort(function(a,b){return a.setting().position-b.setting().position}),d=_.indexOf(i,g),-1===d)throw new Error("Expected control to be among siblings.");if(-1===b){if(!h.menu_item_parent)return;f=a.control("nav_menu_item["+h.menu_item_parent+"]"),_(i).chain().slice(d).each(function(a,b){a.setting.set(c.extend({},a.setting(),{menu_item_parent:g.params.menu_item_id,position:b}))}),_(g.getMenuControl().getMenuItemControls()).each(function(a){var b,d;d=a.setting().menu_item_parent===f.setting().menu_item_parent&&a.setting().position>f.setting().position,d&&(b=_.clone(a.setting()),a.setting.set(c.extend(b,{position:b.position+1})))}),h.position=f.setting().position+1,h.menu_item_parent=f.setting().menu_item_parent,g.setting.set(h)}else if(1===b){if(0===d)return;e=i[d-1],h.menu_item_parent=e.params.menu_item_id,h.position=0,_(g.getMenuControl().getMenuItemControls()).each(function(a){a.setting().menu_item_parent===h.menu_item_parent&&(h.position=Math.max(h.position,a.setting().position))}),h.position+=1,g.setting.set(h)}}}),a.Menus.MenuNameControl=a.Control.extend({ready:function(){var b=this,c=b.setting();b.active.validate=function(){var c,d=a.section(b.section());return c=!!d&&d.active()},b.nameElement=new a.Element(b.container.find(".menu-name-field")),b.nameElement.bind(function(a){var c=b.setting();c&&c.name!==a&&(c=_.clone(c),c.name=a,b.setting.set(c))}),c&&b.nameElement.set(c.name),b.setting.bind(function(a){a&&b.nameElement.set(a.name)})}}),a.Menus.MenuAutoAddControl=a.Control.extend({ready:function(){var b=this,c=b.setting();b.active.validate=function(){var c,d=a.section(b.section());return c=!!d&&d.active()},b.autoAddElement=new a.Element(b.container.find("input[type=checkbox].auto_add")),b.autoAddElement.bind(function(a){var c=b.setting();c&&c.name!==a&&(c=_.clone(c),c.auto_add=a,b.setting.set(c))}),c&&b.autoAddElement.set(c.auto_add),b.setting.bind(function(a){a&&b.autoAddElement.set(a.auto_add)})}}),a.Menus.MenuControl=a.Control.extend({ready:function(){var b,d,f,g=this,h=a.section(g.section()),i=g.params.menu_id,j=g.setting();if("undefined"==typeof this.params.menu_id)throw new Error("params.menu_id was not defined");g.active.validate=function(){var a;return a=!!h&&h.active()},g.$controlSection=h.headContainer,g.$sectionContent=g.container.closest(".accordion-section-content"),this._setupModel(),a.section(g.section(),function(a){a.deferred.initSortables.done(function(a){g._setupSortable(a)})}),this._setupAddition(),this._setupLocations(),this._setupTitle(),j&&(b=e(j.name),a.control.each(function(c){c.extended(a.controlConstructor.widget_form)&&"nav_menu"===c.params.widget_id_base&&(c.container.find(".nav-menu-widget-form-controls:first").show(),c.container.find(".nav-menu-widget-no-menus-message:first").hide(),f=c.container.find("select"),0===f.find("option[value="+String(i)+"]").length&&f.append(new Option(b,i)))}),d=c("#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )"),d.find(".nav-menu-widget-form-controls:first").show(),d.find(".nav-menu-widget-no-menus-message:first").hide(),f=d.find(".widget-inside select:first"),0===f.find("option[value="+String(i)+"]").length&&f.append(new Option(b,i)))},_setupModel:function(){var b=this,c=b.params.menu_id;b.setting.bind(function(d){var f;!1===d?b._handleDeletion():(f=e(d.name),a.control.each(function(b){if(b.extended(a.controlConstructor.widget_form)&&"nav_menu"===b.params.widget_id_base){var d=b.container.find("select");d.find("option[value="+String(c)+"]").text(f)}}))}),b.container.find(".menu-delete").on("click",function(a){a.stopPropagation(),a.preventDefault(),b.setting.set(!1)})},_setupSortable:function(b){var c=this;if(!b.is(c.$sectionContent))throw new Error("Unexpected menuList.");b.on("sortstart",function(){c.isSorting=!0}),b.on("sortstop",function(){setTimeout(function(){var b=c.$sectionContent.sortable("toArray"),d=[],e=0,f=10;c.isSorting=!1,c.$sectionContent.scrollLeft(0),_.each(b,function(b){var c,e,f;f=b.match(/^customize-control-nav_menu_item-(-?\d+)$/,""),f&&(c=parseInt(f[1],10),e=a.control("nav_menu_item["+String(c)+"]"),e&&d.push(e))}),_.each(d,function(a){if(!1!==a.setting()){var b=_.clone(a.setting());e+=1,f+=1,b.position=e,a.priority(f),b.menu_item_parent=parseInt(a.container.find(".menu-item-data-parent-id").val(),10),b.menu_item_parent||(b.menu_item_parent=0),a.setting.set(b)}})})}),c.isReordering=!1,this.container.find(".reorder-toggle").on("click",function(){c.toggleReordering(!c.isReordering)})},_setupAddition:function(){var b=this;this.container.find(".add-new-menu-item").on("click",function(d){b.$sectionContent.hasClass("reordering")||(c("body").hasClass("adding-menu-items")?(c(this).attr("aria-expanded","false"),a.Menus.availableMenuItemsPanel.close(),d.stopPropagation()):(c(this).attr("aria-expanded","true"),a.Menus.availableMenuItemsPanel.open(b)))})},_handleDeletion:function(){var d,e,f,g=this,h=g.params.menu_id,i=0; d=a.section(g.section()),e=function(){d.container.remove(),a.section.remove(d.id)},d&&d.expanded()?d.collapse({completeCallback:function(){e(),b.a11y.speak(a.Menus.data.l10n.menuDeleted),a.panel("nav_menus").focus()}}):e(),a.each(function(a){/^nav_menu\[/.test(a.id)&&!1!==a()&&(i+=1)}),a.control.each(function(b){if(b.extended(a.controlConstructor.widget_form)&&"nav_menu"===b.params.widget_id_base){var c=b.container.find("select");c.val()===String(h)&&c.prop("selectedIndex",0).trigger("change"),b.container.find(".nav-menu-widget-form-controls:first").toggle(0!==i),b.container.find(".nav-menu-widget-no-menus-message:first").toggle(0===i),b.container.find("option[value="+String(h)+"]").remove()}}),f=c("#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )"),f.find(".nav-menu-widget-form-controls:first").toggle(0!==i),f.find(".nav-menu-widget-no-menus-message:first").toggle(0===i),f.find("option[value="+String(h)+"]").remove()},_setupLocations:function(){var b=this;b.container.find(".assigned-menu-location").each(function(){var d,f,g=c(this),h=g.find("input[type=checkbox]"),i=a("nav_menu_locations["+h.data("location-id")+"]");f=function(b){var c=a("nav_menu["+String(b)+"]");b&&c&&c()?g.find(".theme-location-set").show().find("span").text(e(c().name)):g.find(".theme-location-set").hide()},d=new a.Element(h),d.set(i.get()===b.params.menu_id),h.on("change",function(){i.set(this.checked?b.params.menu_id:0)}),i.bind(function(a){d.set(a===b.params.menu_id),f(a)}),f(i.get())})},_setupTitle:function(){var b=this;b.setting.bind(function(d){if(d){var f=a.section(b.section()),g=b.params.menu_id,h=f.headContainer.find(".accordion-section-title"),i=f.contentContainer.find(".customize-section-title h3"),j=f.headContainer.find(".menu-in-location"),k=i.find(".customize-action"),l=e(d.name);h.text(l),j.length&&j.appendTo(h),i.text(l),k.length&&k.prependTo(i),a.control.each(function(a){/^nav_menu_locations\[/.test(a.id)&&a.container.find("option[value="+g+"]").text(l)}),f.contentContainer.find(".customize-control-checkbox input").each(function(){c(this).prop("checked")&&c(".current-menu-location-name-"+c(this).data("location-id")).text(l)})}})},toggleReordering:function(c){var d=this.container.find(".add-new-menu-item"),e=this.container.find(".reorder-toggle"),f=this.$sectionContent.find(".item-title");c=Boolean(c),c!==this.$sectionContent.hasClass("reordering")&&(this.isReordering=c,this.$sectionContent.toggleClass("reordering",c),this.$sectionContent.sortable(this.isReordering?"disable":"enable"),this.isReordering?(d.attr({tabindex:"-1","aria-hidden":"true"}),e.attr("aria-label",a.Menus.data.l10n.reorderLabelOff),b.a11y.speak(a.Menus.data.l10n.reorderModeOn),f.attr("aria-hidden","false")):(d.removeAttr("tabindex aria-hidden"),e.attr("aria-label",a.Menus.data.l10n.reorderLabelOn),b.a11y.speak(a.Menus.data.l10n.reorderModeOff),f.attr("aria-hidden","true")),c&&_(this.getMenuItemControls()).each(function(a){a.collapseForm()}))},getMenuItemControls:function(){var b=this,c=[],d=b.params.menu_id;return a.control.each(function(a){"nav_menu_item"===a.params.type&&a.setting()&&d===a.setting().nav_menu_term_id&&c.push(a)}),c},reflowMenuItems:function(){var a,b=this,c=b.getMenuItemControls();a=function(b){var c=[],d=b.currentParent;_.each(b.menuItemControls,function(a){d===a.setting().menu_item_parent&&c.push(a)}),c.sort(function(a,b){return a.setting().position-b.setting().position}),_.each(c,function(c){b.currentAbsolutePosition+=1,c.priority.set(b.currentAbsolutePosition),c.container.hasClass("menu-item-depth-"+String(b.currentDepth))||(_.each(c.container.prop("className").match(/menu-item-depth-\d+/g),function(a){c.container.removeClass(a)}),c.container.addClass("menu-item-depth-"+String(b.currentDepth))),c.container.data("item-depth",b.currentDepth),b.currentDepth+=1,b.currentParent=c.params.menu_item_id,a(b),b.currentDepth-=1,b.currentParent=d}),c.length&&(_(c).each(function(a){a.container.removeClass("move-up-disabled move-down-disabled move-left-disabled move-right-disabled"),0===b.currentDepth?a.container.addClass("move-left-disabled"):10===b.currentDepth&&a.container.addClass("move-right-disabled")}),c[0].container.addClass("move-up-disabled").addClass("move-right-disabled").toggleClass("move-down-disabled",1===c.length),c[c.length-1].container.addClass("move-down-disabled").toggleClass("move-up-disabled",1===c.length))},a({menuItemControls:c,currentParent:0,currentDepth:0,currentAbsolutePosition:0}),b.container.find(".reorder-toggle").toggle(c.length>1)},debouncedReflowMenuItems:_.debounce(function(){this.reflowMenuItems.apply(this,arguments)},0),addItemToMenu:function(d){var e,f,g,h,i,j=this,k=0,l=10;return _.each(j.getMenuItemControls(),function(a){!1!==a.setting()&&(l=Math.max(l,a.priority()),0===a.setting().menu_item_parent&&(k=Math.max(k,a.setting().position)))}),k+=1,l+=1,d=c.extend({},a.Menus.data.defaultSettingValues.nav_menu_item,d,{nav_menu_term_id:j.params.menu_id,original_title:d.title,position:k}),delete d.id,i=a.Menus.generatePlaceholderAutoIncrementId(),e="nav_menu_item["+String(i)+"]",f={type:"nav_menu_item",transport:a.Menus.data.settingTransport,previewer:a.previewer},g=a.create(e,e,{},f),g.set(d),h=new a.controlConstructor.nav_menu_item(e,{params:{type:"nav_menu_item",content:'<li id="customize-control-nav_menu_item-'+String(i)+'" class="customize-control customize-control-nav_menu_item"></li>',section:j.id,priority:l,active:!0,settings:{"default":e},menu_item_id:i},previewer:a.previewer}),a.control.add(e,h),g.preview(),j.debouncedReflowMenuItems(),b.a11y.speak(a.Menus.data.l10n.itemAdded),h}}),a.Menus.NewMenuControl=a.Control.extend({ready:function(){this._bindHandlers()},_bindHandlers:function(){var a=this,b=c("#customize-control-new_menu_name input"),d=c("#create-new-menu-submit");b.on("keydown",function(b){13===b.which&&a.submit()}),d.on("click",function(b){a.submit(),b.stopPropagation(),b.preventDefault()})},submit:function(){var d,f,g=this,h=g.container.closest(".accordion-section-new-menu"),i=h.find(".menu-name-field").first(),j=i.val(),k=a.Menus.generatePlaceholderAutoIncrementId();return j?(f="nav_menu["+String(k)+"]",a.create(f,f,{},{type:"nav_menu",transport:a.Menus.data.settingTransport,previewer:a.previewer}),a(f).set(c.extend({},a.Menus.data.defaultSettingValues.nav_menu,{name:j})),d=new a.Menus.MenuSection(f,{params:{id:f,panel:"nav_menus",title:e(j),customizeAction:a.Menus.data.l10n.customizingMenus,type:"nav_menu",priority:10,menu_id:k}}),a.section.add(f,d),i.val(""),i.removeClass("invalid"),b.a11y.speak(a.Menus.data.l10n.menuAdded),void a.section(f).focus()):(i.addClass("invalid"),void i.focus())}}),c.extend(a.controlConstructor,{nav_menu_location:a.Menus.MenuLocationControl,nav_menu_item:a.Menus.MenuItemControl,nav_menu:a.Menus.MenuControl,nav_menu_name:a.Menus.MenuNameControl,nav_menu_auto_add:a.Menus.MenuAutoAddControl,new_menu:a.Menus.NewMenuControl}),c.extend(a.panelConstructor,{nav_menus:a.Menus.MenusPanel}),c.extend(a.sectionConstructor,{nav_menu:a.Menus.MenuSection,new_menu:a.Menus.NewMenuSection}),a.bind("ready",function(){a.Menus.availableMenuItemsPanel=new a.Menus.AvailableMenuItemsPanelView({collection:a.Menus.availableMenuItems}),a.bind("saved",function(b){(b.nav_menu_updates||b.nav_menu_item_updates)&&a.Menus.applySavedData(b)}),a.state("changesetStatus").bind(function(b){"publish"===b&&(a("nav_menus_created_posts")._value=[])}),a.previewer.bind("focus-nav-menu-item-control",a.Menus.focusMenuItemControl)}),a.Menus.applySavedData=function(d){var e={},f={};_(d.nav_menu_updates).each(function(d){var f,g,h,i,j,k,l,m,n,o,p,q;if("inserted"===d.status){if(!d.previous_term_id)throw new Error("Expected previous_term_id");if(!d.term_id)throw new Error("Expected term_id");if(f="nav_menu["+String(d.previous_term_id)+"]",!a.has(f))throw new Error("Expected setting to exist: "+f);if(i=a(f),!a.section.has(f))throw new Error("Expected control to exist: "+f);if(m=a.section(f),l=i.get(),!l)throw new Error("Did not expect setting to be empty (deleted).");l=c.extend(_.clone(l),d.saved_value),e[d.previous_term_id]=d.term_id,g="nav_menu["+String(d.term_id)+"]",j=a.create(g,g,l,{type:"nav_menu",transport:a.Menus.data.settingTransport,previewer:a.previewer}),m.expanded()&&m.collapse(),n=new a.Menus.MenuSection(g,{params:{id:g,panel:"nav_menus",title:l.name,customizeAction:a.Menus.data.l10n.customizingMenus,type:"nav_menu",priority:m.priority.get(),active:!0,menu_id:d.term_id}}),a.section.add(g,n),a.control.each(function(b){if(b.extended(a.controlConstructor.widget_form)&&"nav_menu"===b.params.widget_id_base){var c,e,f;c=b.container.find("select"),e=c.find("option[value="+String(d.previous_term_id)+"]"),f=c.find("option[value="+String(d.term_id)+"]"),f.prop("selected",e.prop("selected")),e.remove()}}),i.callbacks.disable(),i.set(!1),i.preview(),j.preview(),i._dirty=!1,m.container.remove(),a.section.remove(f),q=0,a.each(function(a){/^nav_menu\[/.test(a.id)&&!1!==a()&&(q+=1)}),p=c("#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )"),p.find(".nav-menu-widget-form-controls:first").toggle(0!==q),p.find(".nav-menu-widget-no-menus-message:first").toggle(0===q),p.find("option[value="+String(d.previous_term_id)+"]").remove(),b.customize.control.each(function(a){/^nav_menu_locations\[/.test(a.id)&&a.container.find("option[value="+String(d.previous_term_id)+"]").remove()}),a.each(function(b){var c=a.state("saved").get();/^nav_menu_locations\[/.test(b.id)&&b.get()===d.previous_term_id&&(b.set(d.term_id),b._dirty=!1,a.state("saved").set(c),b.preview())}),m.expanded.get()&&n.expand()}else if("updated"===d.status){if(h="nav_menu["+String(d.term_id)+"]",!a.has(h))throw new Error("Expected setting to exist: "+h);k=a(h),_.isEqual(d.saved_value,k.get())||(o=a.state("saved").get(),k.set(d.saved_value),k._dirty=!1,a.state("saved").set(o))}}),_(d.nav_menu_item_updates).each(function(a){a.previous_post_id&&(f[a.previous_post_id]=a.post_id)}),_(d.nav_menu_item_updates).each(function(b){var c,d,g,h,i,j,k;if("inserted"===b.status){if(!b.previous_post_id)throw new Error("Expected previous_post_id");if(!b.post_id)throw new Error("Expected post_id");if(c="nav_menu_item["+String(b.previous_post_id)+"]",!a.has(c))throw new Error("Expected setting to exist: "+c);if(g=a(c),!a.control.has(c))throw new Error("Expected control to exist: "+c);if(j=a.control(c),i=g.get(),!i)throw new Error("Did not expect setting to be empty (deleted).");if(i=_.clone(i),i.menu_item_parent<0){if(!f[i.menu_item_parent])throw new Error("inserted ID for menu_item_parent not available");i.menu_item_parent=f[i.menu_item_parent]}e[i.nav_menu_term_id]&&(i.nav_menu_term_id=e[i.nav_menu_term_id]),d="nav_menu_item["+String(b.post_id)+"]",h=a.create(d,d,i,{type:"nav_menu_item",transport:a.Menus.data.settingTransport,previewer:a.previewer}),k=new a.controlConstructor.nav_menu_item(d,{params:{type:"nav_menu_item",content:'<li id="customize-control-nav_menu_item-'+String(b.post_id)+'" class="customize-control customize-control-nav_menu_item"></li>',menu_id:b.post_id,section:"nav_menu["+String(i.nav_menu_term_id)+"]",priority:j.priority.get(),active:!0,settings:{"default":d},menu_item_id:b.post_id},previewer:a.previewer}),j.container.remove(),a.control.remove(c),a.control.add(d,k),g.callbacks.disable(),g.set(!1),g.preview(),h.preview(),g._dirty=!1,k.container.toggleClass("menu-item-edit-inactive",j.container.hasClass("menu-item-edit-inactive"))}}),_.each(d.widget_nav_menu_updates,function(b,c){var d=a(c);d&&(d._value=b,d.preview())})},a.Menus.focusMenuItemControl=function(b){var c=a.Menus.getMenuItemControl(b);c&&c.focus()},a.Menus.getMenuControl=function(b){return a.control("nav_menu["+b+"]")},a.Menus.getMenuItemControl=function(b){return a.control(d(b))}}(wp.customize,wp,jQuery);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/js/updates.min.js
2
!function(a,b,c){var d=a(document);b=b||{},b.updates={},b.updates.ajaxNonce=c.ajax_nonce,b.updates.l10n=c.l10n,b.updates.searchTerm="",b.updates.shouldRequestFilesystemCredentials=!1,b.updates.filesystemCredentials={ftp:{host:"",username:"",password:"",connectionType:""},ssh:{publicKey:"",privateKey:""},available:!1},b.updates.ajaxLocked=!1,b.updates.adminNotice=b.template("wp-updates-admin-notice"),b.updates.queue=[],b.updates.$elToReturnFocusToFromCredentialsModal=void 0,b.updates.addAdminNotice=function(c){var e,f=a(c.selector);delete c.selector,e=b.updates.adminNotice(c),f.length||(f=a("#"+c.id)),f.length?f.replaceWith(e):a(".wrap").find("> h1").after(e),d.trigger("wp-updates-notice-added")},b.updates.ajax=function(c,d){var e={};return b.updates.ajaxLocked?(b.updates.queue.push({action:c,data:d}),a.Deferred()):(b.updates.ajaxLocked=!0,d.success&&(e.success=d.success,delete d.success),d.error&&(e.error=d.error,delete d.error),e.data=_.extend(d,{action:c,_ajax_nonce:b.updates.ajaxNonce,username:b.updates.filesystemCredentials.ftp.username,password:b.updates.filesystemCredentials.ftp.password,hostname:b.updates.filesystemCredentials.ftp.hostname,connection_type:b.updates.filesystemCredentials.ftp.connectionType,public_key:b.updates.filesystemCredentials.ssh.publicKey,private_key:b.updates.filesystemCredentials.ssh.privateKey}),b.ajax.send(e).always(b.updates.ajaxAlways))},b.updates.ajaxAlways=function(c){c.errorCode&&"unable_to_connect_to_filesystem"===c.errorCode||(b.updates.ajaxLocked=!1,b.updates.queueChecker()),"undefined"!=typeof c.debug&&window.console&&window.console.log&&_.map(c.debug,function(b){window.console.log(a("<p />").html(b).text())})},b.updates.refreshCount=function(){var b,d=a("#wp-admin-bar-updates"),e=a('a[href="update-core.php"] .update-plugins'),f=a('a[href="plugins.php"] .update-plugins'),g=a('a[href="themes.php"] .update-plugins');d.find(".ab-item").removeAttr("title"),d.find(".ab-label").text(c.totals.counts.total),0===c.totals.counts.total&&d.find(".ab-label").parents("li").remove(),e.each(function(a,b){b.className=b.className.replace(/count-\d+/,"count-"+c.totals.counts.total)}),c.totals.counts.total>0?e.find(".update-count").text(c.totals.counts.total):e.remove(),f.each(function(a,b){b.className=b.className.replace(/count-\d+/,"count-"+c.totals.counts.plugins)}),c.totals.counts.total>0?f.find(".plugin-count").text(c.totals.counts.plugins):f.remove(),g.each(function(a,b){b.className=b.className.replace(/count-\d+/,"count-"+c.totals.counts.themes)}),c.totals.counts.total>0?g.find(".theme-count").text(c.totals.counts.themes):g.remove(),"plugins"===pagenow||"plugins-network"===pagenow?b=c.totals.counts.plugins:"themes"!==pagenow&&"themes-network"!==pagenow||(b=c.totals.counts.themes),b>0?a(".subsubsub .upgrade .count").text("("+b+")"):a(".subsubsub .upgrade").remove()},b.updates.decrementCount=function(a){c.totals.counts.total=Math.max(--c.totals.counts.total,0),"plugin"===a?c.totals.counts.plugins=Math.max(--c.totals.counts.plugins,0):"theme"===a&&(c.totals.counts.themes=Math.max(--c.totals.counts.themes,0)),b.updates.refreshCount(a)},b.updates.updatePlugin=function(c){var e,f,g,h;return c=_.extend({success:b.updates.updatePluginSuccess,error:b.updates.updatePluginError},c),"plugins"===pagenow||"plugins-network"===pagenow?(e=a('tr[data-plugin="'+c.plugin+'"]'),g=e.find(".update-message").removeClass("notice-error").addClass("updating-message notice-warning").find("p"),h=b.updates.l10n.updatingLabel.replace("%s",e.find(".plugin-title strong").text())):"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||(f=a(".plugin-card-"+c.slug),g=f.find(".update-now").addClass("updating-message"),h=b.updates.l10n.updatingLabel.replace("%s",g.data("name")),f.removeClass("plugin-card-update-failed").find(".notice.notice-error").remove()),g.html()!==b.updates.l10n.updating&&g.data("originaltext",g.html()),g.attr("aria-label",h).text(b.updates.l10n.updating),d.trigger("wp-plugin-updating",c),b.updates.ajax("update-plugin",c)},b.updates.updatePluginSuccess=function(c){var e,f,g;"plugins"===pagenow||"plugins-network"===pagenow?(e=a('tr[data-plugin="'+c.plugin+'"]').removeClass("update").addClass("updated"),f=e.find(".update-message").removeClass("updating-message notice-warning").addClass("updated-message notice-success").find("p"),g=e.find(".plugin-version-author-uri").html().replace(c.oldVersion,c.newVersion),e.find(".plugin-version-author-uri").html(g)):"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||(f=a(".plugin-card-"+c.slug).find(".update-now").removeClass("updating-message").addClass("button-disabled updated-message")),f.attr("aria-label",b.updates.l10n.updatedLabel.replace("%s",c.pluginName)).text(b.updates.l10n.updated),b.a11y.speak(b.updates.l10n.updatedMsg,"polite"),b.updates.decrementCount("plugin"),d.trigger("wp-plugin-update-success",c)},b.updates.updatePluginError=function(c){var e,f,g;b.updates.isValidResponse(c,"update")&&(b.updates.maybeHandleCredentialError(c,"update-plugin")||(g=b.updates.l10n.updateFailed.replace("%s",c.errorMessage),"plugins"===pagenow||"plugins-network"===pagenow?(f=c.plugin?a('tr[data-plugin="'+c.plugin+'"]').find(".update-message"):a('tr[data-slug="'+c.slug+'"]').find(".update-message"),f.removeClass("updating-message notice-warning").addClass("notice-error").find("p").html(g),c.pluginName?f.find("p").attr("aria-label",b.updates.l10n.updateFailedLabel.replace("%s",c.pluginName)):f.find("p").removeAttr("aria-label")):"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||(e=a(".plugin-card-"+c.slug).addClass("plugin-card-update-failed").append(b.updates.adminNotice({className:"update-message notice-error notice-alt is-dismissible",message:g})),e.find(".update-now").text(b.updates.l10n.updateFailedShort).removeClass("updating-message"),c.pluginName?e.find(".update-now").attr("aria-label",b.updates.l10n.updateFailedLabel.replace("%s",c.pluginName)):e.find(".update-now").removeAttr("aria-label"),e.on("click",".notice.is-dismissible .notice-dismiss",function(){setTimeout(function(){e.removeClass("plugin-card-update-failed").find(".column-name a").focus(),e.find(".update-now").attr("aria-label",!1).text(b.updates.l10n.updateNow)},200)})),b.a11y.speak(g,"assertive"),d.trigger("wp-plugin-update-error",c)))},b.updates.installPlugin=function(c){var e=a(".plugin-card-"+c.slug),f=e.find(".install-now");return c=_.extend({success:b.updates.installPluginSuccess,error:b.updates.installPluginError},c),"import"===pagenow&&(f=a('[data-slug="'+c.slug+'"]')),f.html()!==b.updates.l10n.installing&&f.data("originaltext",f.html()),f.addClass("updating-message").attr("aria-label",b.updates.l10n.pluginInstallingLabel.replace("%s",f.data("name"))).text(b.updates.l10n.installing),b.a11y.speak(b.updates.l10n.installingMsg,"polite"),e.removeClass("plugin-card-install-failed").find(".notice.notice-error").remove(),d.trigger("wp-plugin-installing",c),b.updates.ajax("install-plugin",c)},b.updates.installPluginSuccess=function(c){var e=a(".plugin-card-"+c.slug).find(".install-now");e.removeClass("updating-message").addClass("updated-message installed button-disabled").attr("aria-label",b.updates.l10n.pluginInstalledLabel.replace("%s",c.pluginName)).text(b.updates.l10n.installed),b.a11y.speak(b.updates.l10n.installedMsg,"polite"),d.trigger("wp-plugin-install-success",c),c.activateUrl&&setTimeout(function(){e.removeClass("install-now installed button-disabled updated-message").addClass("activate-now button-primary").attr("href",c.activateUrl).attr("aria-label",b.updates.l10n.activatePluginLabel.replace("%s",c.pluginName)).text(b.updates.l10n.activatePlugin)},1e3)},b.updates.installPluginError=function(c){var e,f=a(".plugin-card-"+c.slug),g=f.find(".install-now");b.updates.isValidResponse(c,"install")&&(b.updates.maybeHandleCredentialError(c,"install-plugin")||(e=b.updates.l10n.installFailed.replace("%s",c.errorMessage),f.addClass("plugin-card-update-failed").append('<div class="notice notice-error notice-alt is-dismissible"><p>'+e+"</p></div>"),f.on("click",".notice.is-dismissible .notice-dismiss",function(){setTimeout(function(){f.removeClass("plugin-card-update-failed").find(".column-name a").focus()},200)}),g.removeClass("updating-message").addClass("button-disabled").attr("aria-label",b.updates.l10n.pluginInstallFailedLabel.replace("%s",g.data("name"))).text(b.updates.l10n.installFailedShort),b.a11y.speak(e,"assertive"),d.trigger("wp-plugin-install-error",c)))},b.updates.installImporterSuccess=function(c){b.updates.addAdminNotice({id:"install-success",className:"notice-success is-dismissible",message:b.updates.l10n.importerInstalledMsg.replace("%s",c.activateUrl+"&from=import")}),a('[data-slug="'+c.slug+'"]').removeClass("install-now updating-message").addClass("activate-now").attr({href:c.activateUrl+"&from=import","aria-label":b.updates.l10n.activateImporterLabel.replace("%s",c.pluginName)}).text(b.updates.l10n.activateImporter),b.a11y.speak(b.updates.l10n.installedMsg,"polite"),d.trigger("wp-importer-install-success",c)},b.updates.installImporterError=function(c){var e=b.updates.l10n.installFailed.replace("%s",c.errorMessage),f=a('[data-slug="'+c.slug+'"]'),g=f.data("name");b.updates.isValidResponse(c,"install")&&(b.updates.maybeHandleCredentialError(c,"install-plugin")||(b.updates.addAdminNotice({id:c.errorCode,className:"notice-error is-dismissible",message:e}),f.removeClass("updating-message").text(b.updates.l10n.installNow).attr("aria-label",b.updates.l10n.installNowLabel.replace("%s",g)),b.a11y.speak(e,"assertive"),d.trigger("wp-importer-install-error",c)))},b.updates.deletePlugin=function(c){var e=a('[data-plugin="'+c.plugin+'"]').find(".row-actions a.delete");return c=_.extend({success:b.updates.deletePluginSuccess,error:b.updates.deletePluginError},c),e.html()!==b.updates.l10n.deleting&&e.data("originaltext",e.html()).text(b.updates.l10n.deleting),b.a11y.speak(b.updates.l10n.deleting,"polite"),d.trigger("wp-plugin-deleting",c),b.updates.ajax("delete-plugin",c)},b.updates.deletePluginSuccess=function(e){a('[data-plugin="'+e.plugin+'"]').css({backgroundColor:"#faafaa"}).fadeOut(350,function(){var d=a("#bulk-action-form"),f=a(".subsubsub"),g=a(this),h=d.find("thead th:not(.hidden), thead td").length,i=b.template("item-deleted-row"),j=c.plugins;g.hasClass("plugin-update-tr")||g.after(i({slug:e.slug,plugin:e.plugin,colspan:h,name:e.pluginName})),g.remove(),-1!==_.indexOf(j.upgrade,e.plugin)&&(j.upgrade=_.without(j.upgrade,e.plugin),b.updates.decrementCount("plugin")),-1!==_.indexOf(j.inactive,e.plugin)&&(j.inactive=_.without(j.inactive,e.plugin),j.inactive.length?f.find(".inactive .count").text("("+j.inactive.length+")"):f.find(".inactive").remove()),-1!==_.indexOf(j.active,e.plugin)&&(j.active=_.without(j.active,e.plugin),j.active.length?f.find(".active .count").text("("+j.active.length+")"):f.find(".active").remove()),-1!==_.indexOf(j.recently_activated,e.plugin)&&(j.recently_activated=_.without(j.recently_activated,e.plugin),j.recently_activated.length?f.find(".recently_activated .count").text("("+j.recently_activated.length+")"):f.find(".recently_activated").remove()),j.all=_.without(j.all,e.plugin),j.all.length?f.find(".all .count").text("("+j.all.length+")"):(d.find(".tablenav").css({visibility:"hidden"}),f.find(".all").remove(),d.find("tr.no-items").length||d.find("#the-list").append('<tr class="no-items"><td class="colspanchange" colspan="'+h+'">'+b.updates.l10n.noPlugins+"</td></tr>"))}),b.a11y.speak(b.updates.l10n.deleted,"polite"),d.trigger("wp-plugin-delete-success",e)},b.updates.deletePluginError=function(c){var e,f,g=b.template("item-update-row"),h=b.updates.adminNotice({className:"update-message notice-error notice-alt",message:c.errorMessage});c.plugin?(e=a('tr.inactive[data-plugin="'+c.plugin+'"]'),f=e.siblings('[data-plugin="'+c.plugin+'"]')):(e=a('tr.inactive[data-slug="'+c.slug+'"]'),f=e.siblings('[data-slug="'+c.slug+'"]')),b.updates.isValidResponse(c,"delete")&&(b.updates.maybeHandleCredentialError(c,"delete-plugin")||(f.length?(f.find(".notice-error").remove(),f.find(".plugin-update").append(h)):e.addClass("update").after(g({slug:c.slug,plugin:c.plugin||c.slug,colspan:a("#bulk-action-form").find("thead th:not(.hidden), thead td").length,content:h})),d.trigger("wp-plugin-delete-error",c)))},b.updates.updateTheme=function(c){var e;return c=_.extend({success:b.updates.updateThemeSuccess,error:b.updates.updateThemeError},c),"themes-network"===pagenow?e=a('[data-slug="'+c.slug+'"]').find(".update-message").removeClass("notice-error").addClass("updating-message notice-warning").find("p"):(e=a("#update-theme").closest(".notice").removeClass("notice-large"),e.find("h3").remove(),e=e.add(a('[data-slug="'+c.slug+'"]').find(".update-message")),e=e.addClass("updating-message").find("p")),e.html()!==b.updates.l10n.updating&&e.data("originaltext",e.html()),b.a11y.speak(b.updates.l10n.updatingMsg,"polite"),e.text(b.updates.l10n.updating),d.trigger("wp-theme-updating",c),b.updates.ajax("update-theme",c)},b.updates.updateThemeSuccess=function(c){var e,f,g=a("body.modal-open").length,h=a('[data-slug="'+c.slug+'"]'),i={className:"updated-message notice-success notice-alt",message:b.updates.l10n.updated};"themes-network"===pagenow?(e=h.find(".update-message"),f=h.find(".theme-version-author-uri").html().replace(c.oldVersion,c.newVersion),h.find(".theme-version-author-uri").html(f)):(e=a(".theme-info .notice").add(h.find(".update-message")),g?a(".load-customize:visible").focus():h.find(".load-customize").focus()),b.updates.addAdminNotice(_.extend({selector:e},i)),b.a11y.speak(b.updates.l10n.updatedMsg,"polite"),b.updates.decrementCount("theme"),d.trigger("wp-theme-update-success",c),g&&a(".theme-info .theme-author").after(b.updates.adminNotice(i))},b.updates.updateThemeError=function(c){var e,f=a('[data-slug="'+c.slug+'"]'),g=b.updates.l10n.updateFailed.replace("%s",c.errorMessage);b.updates.isValidResponse(c,"update")&&(b.updates.maybeHandleCredentialError(c,"update-theme")||("themes-network"===pagenow?e=f.find(".update-message "):(e=a(".theme-info .notice").add(f.find(".notice")),a("body.modal-open").length?a(".load-customize:visible").focus():f.find(".load-customize").focus()),b.updates.addAdminNotice({selector:e,className:"update-message notice-error notice-alt is-dismissible",message:g}),b.a11y.speak(g,"polite"),d.trigger("wp-theme-update-error",c)))},b.updates.installTheme=function(c){var e=a('.theme-install[data-slug="'+c.slug+'"]');return c=_.extend({success:b.updates.installThemeSuccess,error:b.updates.installThemeError},c),e.addClass("updating-message"),e.parents(".theme").addClass("focus"),e.html()!==b.updates.l10n.installing&&e.data("originaltext",e.html()),e.text(b.updates.l10n.installing).attr("aria-label",b.updates.l10n.themeInstallingLabel.replace("%s",e.data("name"))),b.a11y.speak(b.updates.l10n.installingMsg,"polite"),a('.install-theme-info, [data-slug="'+c.slug+'"]').removeClass("theme-install-failed").find(".notice.notice-error").remove(),d.trigger("wp-theme-installing",c),b.updates.ajax("install-theme",c)},b.updates.installThemeSuccess=function(c){var e,f=a(".wp-full-overlay-header, [data-slug="+c.slug+"]");d.trigger("wp-theme-install-success",c),e=f.find(".button-primary").removeClass("updating-message").addClass("updated-message disabled").attr("aria-label",b.updates.l10n.themeInstalledLabel.replace("%s",c.themeName)).text(b.updates.l10n.installed),b.a11y.speak(b.updates.l10n.installedMsg,"polite"),setTimeout(function(){c.activateUrl&&e.attr("href",c.activateUrl).removeClass("theme-install updated-message disabled").addClass("activate").attr("aria-label",b.updates.l10n.activateThemeLabel.replace("%s",c.themeName)).text(b.updates.l10n.activateTheme),c.customizeUrl&&e.siblings(".preview").replaceWith(function(){return a("<a>").attr("href",c.customizeUrl).addClass("button load-customize").text(b.updates.l10n.livePreview)})},1e3)},b.updates.installThemeError=function(c){var e,f,g=b.updates.l10n.installFailed.replace("%s",c.errorMessage),h=b.updates.adminNotice({className:"update-message notice-error notice-alt",message:g});b.updates.isValidResponse(c,"install")&&(b.updates.maybeHandleCredentialError(c,"install-theme")||(d.find("body").hasClass("full-overlay-active")?(f=a('.theme-install[data-slug="'+c.slug+'"]'),e=a(".install-theme-info").prepend(h)):(e=a('[data-slug="'+c.slug+'"]').removeClass("focus").addClass("theme-install-failed").append(h),f=e.find(".theme-install")),f.removeClass("updating-message").attr("aria-label",b.updates.l10n.themeInstallFailedLabel.replace("%s",f.data("name"))).text(b.updates.l10n.installFailedShort),b.a11y.speak(g,"assertive"),d.trigger("wp-theme-install-error",c)))},b.updates.deleteTheme=function(c){var e;return"themes"===pagenow?e=a(".theme-actions .delete-theme"):"themes-network"===pagenow&&(e=a('[data-slug="'+c.slug+'"]').find(".row-actions a.delete")),c=_.extend({success:b.updates.deleteThemeSuccess,error:b.updates.deleteThemeError},c),e&&e.html()!==b.updates.l10n.deleting&&e.data("originaltext",e.html()).text(b.updates.l10n.deleting),b.a11y.speak(b.updates.l10n.deleting,"polite"),a(".theme-info .update-message").remove(),d.trigger("wp-theme-deleting",c),b.updates.ajax("delete-theme",c)},b.updates.deleteThemeSuccess=function(e){var f=a('[data-slug="'+e.slug+'"]');"themes-network"===pagenow&&f.css({backgroundColor:"#faafaa"}).fadeOut(350,function(){var d=a(".subsubsub"),f=a(this),g=c.themes,h=b.template("item-deleted-row");f.hasClass("plugin-update-tr")||f.after(h({slug:e.slug,colspan:a("#bulk-action-form").find("thead th:not(.hidden), thead td").length,name:f.find(".theme-title strong").text()})),f.remove(),f.hasClass("update")&&(g.upgrade--,b.updates.decrementCount("theme")),f.hasClass("inactive")&&(g.disabled--,g.disabled?d.find(".disabled .count").text("("+g.disabled+")"):d.find(".disabled").remove()),d.find(".all .count").text("("+--g.all+")")}),b.a11y.speak(b.updates.l10n.deleted,"polite"),d.trigger("wp-theme-delete-success",e)},b.updates.deleteThemeError=function(c){var e=a('tr.inactive[data-slug="'+c.slug+'"]'),f=a(".theme-actions .delete-theme"),g=b.template("item-update-row"),h=e.siblings("#"+c.slug+"-update"),i=b.updates.l10n.deleteFailed.replace("%s",c.errorMessage),j=b.updates.adminNotice({className:"update-message notice-error notice-alt",message:i});b.updates.maybeHandleCredentialError(c,"delete-theme")||("themes-network"===pagenow?h.length?(h.find(".notice-error").remove(),h.find(".plugin-update").append(j)):e.addClass("update").after(g({slug:c.slug,colspan:a("#bulk-action-form").find("thead th:not(.hidden), thead td").length,content:j})):a(".theme-info .theme-description").before(j),f.html(f.data("originaltext")),b.a11y.speak(i,"assertive"),d.trigger("wp-theme-delete-error",c))},b.updates._addCallbacks=function(a,c){return"import"===pagenow&&"install-plugin"===c&&(a.success=b.updates.installImporterSuccess,a.error=b.updates.installImporterError),a},b.updates.queueChecker=function(){var a;if(!b.updates.ajaxLocked&&b.updates.queue.length)switch(a=b.updates.queue.shift(),a.action){case"install-plugin":b.updates.installPlugin(a.data);break;case"update-plugin":b.updates.updatePlugin(a.data);break;case"delete-plugin":b.updates.deletePlugin(a.data);break;case"install-theme":b.updates.installTheme(a.data);break;case"update-theme":b.updates.updateTheme(a.data);break;case"delete-theme":b.updates.deleteTheme(a.data)}},b.updates.requestFilesystemCredentials=function(c){!1===b.updates.filesystemCredentials.available&&(c&&!b.updates.$elToReturnFocusToFromCredentialsModal&&(b.updates.$elToReturnFocusToFromCredentialsModal=a(c.target)),b.updates.ajaxLocked=!0,b.updates.requestForCredentialsModalOpen())},b.updates.maybeRequestFilesystemCredentials=function(a){b.updates.shouldRequestFilesystemCredentials&&!b.updates.ajaxLocked&&b.updates.requestFilesystemCredentials(a)},b.updates.keydown=function(c){27===c.keyCode?b.updates.requestForCredentialsModalCancel():9===c.keyCode&&("upgrade"!==c.target.id||c.shiftKey?"hostname"===c.target.id&&c.shiftKey&&(a("#upgrade").focus(),c.preventDefault()):(a("#hostname").focus(),c.preventDefault()))},b.updates.requestForCredentialsModalOpen=function(){var c=a("#request-filesystem-credentials-dialog");a("body").addClass("modal-open"),c.show(),c.find("input:enabled:first").focus(),c.on("keydown",b.updates.keydown)},b.updates.requestForCredentialsModalClose=function(){a("#request-filesystem-credentials-dialog").hide(),a("body").removeClass("modal-open"),b.updates.$elToReturnFocusToFromCredentialsModal&&b.updates.$elToReturnFocusToFromCredentialsModal.focus()},b.updates.requestForCredentialsModalCancel=function(){(b.updates.ajaxLocked||b.updates.queue.length)&&(_.each(b.updates.queue,function(a){d.trigger("credential-modal-cancel",a)}),b.updates.ajaxLocked=!1,b.updates.queue=[],b.updates.requestForCredentialsModalClose())},b.updates.showErrorInCredentialsForm=function(b){var c=a("#request-filesystem-credentials-form");c.find(".notice").remove(),c.find("#request-filesystem-credentials-title").after('<div class="notice notice-alt notice-error"><p>'+b+"</p></div>")},b.updates.credentialError=function(a,c){a=b.updates._addCallbacks(a,c),b.updates.queue.unshift({action:c,data:a}),b.updates.filesystemCredentials.available=!1,b.updates.showErrorInCredentialsForm(a.errorMessage),b.updates.requestFilesystemCredentials()},b.updates.maybeHandleCredentialError=function(a,c){return!(!b.updates.shouldRequestFilesystemCredentials||!a.errorCode||"unable_to_connect_to_filesystem"!==a.errorCode)&&(b.updates.credentialError(a,c),!0)},b.updates.isValidResponse=function(c,d){var e,f=b.updates.l10n.unknownError;if(_.isObject(c)&&!_.isFunction(c.always))return!0;switch(_.isString(c)&&"-1"===c?f=b.updates.l10n.nonceError:_.isString(c)?f=c:"undefined"!=typeof c.readyState&&0===c.readyState?f=b.updates.l10n.connectionError:_.isString(c.responseText)&&""!==c.responseText?f=c.responseText:_.isString(c.statusText)&&(f=c.statusText),d){case"update":e=b.updates.l10n.updateFailed;break;case"install":e=b.updates.l10n.installFailed;break;case"delete":e=b.updates.l10n.deleteFailed}return f=f.replace(/<[\/a-z][^<>]*>/gi,""),e=e.replace("%s",f),b.updates.addAdminNotice({id:"unknown_error",className:"notice-error is-dismissible",message:_.escape(e)}),b.updates.ajaxLocked=!1,b.updates.queue=[],a(".button.updating-message").removeClass("updating-message").removeAttr("aria-label").prop("disabled",!0).text(b.updates.l10n.updateFailedShort),a(".updating-message:not(.button):not(.thickbox)").removeClass("updating-message notice-warning").addClass("notice-error").find("p").removeAttr("aria-label").text(e),b.a11y.speak(e,"assertive"),!1},b.updates.beforeunload=function(){if(b.updates.ajaxLocked)return b.updates.l10n.beforeunload},a(function(){var e=a("#plugin-filter"),f=a("#bulk-action-form"),g=a("#request-filesystem-credentials-form"),h=a("#request-filesystem-credentials-dialog"),i=a(".plugins-php .wp-filter-search"),j=a(".plugin-install-php .wp-filter-search");c=_.extend(c,window._wpUpdatesItemCounts||{}),c.totals&&b.updates.refreshCount(),b.updates.shouldRequestFilesystemCredentials=h.length>0,h.on("submit","form",function(c){c.preventDefault(),b.updates.filesystemCredentials.ftp.hostname=a("#hostname").val(),b.updates.filesystemCredentials.ftp.username=a("#username").val(),b.updates.filesystemCredentials.ftp.password=a("#password").val(),b.updates.filesystemCredentials.ftp.connectionType=a('input[name="connection_type"]:checked').val(),b.updates.filesystemCredentials.ssh.publicKey=a("#public_key").val(),b.updates.filesystemCredentials.ssh.privateKey=a("#private_key").val(),b.updates.filesystemCredentials.available=!0,b.updates.ajaxLocked=!1,b.updates.queueChecker(),b.updates.requestForCredentialsModalClose()}),h.on("click",'[data-js-action="close"], .notification-dialog-background',b.updates.requestForCredentialsModalCancel),g.on("change",'input[name="connection_type"]',function(){a("#ssh-keys").toggleClass("hidden","ssh"!==a(this).val())}).change(),d.on("credential-modal-cancel",function(c,d){var e,f,g=a(".updating-message");"import"===pagenow?g.removeClass("updating-message"):"plugins"===pagenow||"plugins-network"===pagenow?"update-plugin"===d.action?e=a('tr[data-plugin="'+d.data.plugin+'"]').find(".update-message"):"delete-plugin"===d.action&&(e=a('[data-plugin="'+d.data.plugin+'"]').find(".row-actions a.delete")):"themes"===pagenow||"themes-network"===pagenow?"update-theme"===d.action?e=a('[data-slug="'+d.data.slug+'"]').find(".update-message"):"delete-theme"===d.action&&"themes-network"===pagenow?e=a('[data-slug="'+d.data.slug+'"]').find(".row-actions a.delete"):"delete-theme"===d.action&&"themes"===pagenow&&(e=a(".theme-actions .delete-theme")):e=g,e&&e.hasClass("updating-message")&&(f=e.data("originaltext"),"undefined"==typeof f&&(f=a("<p>").html(e.find("p").data("originaltext"))),e.removeClass("updating-message").html(f),"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||("update-plugin"===d.action?e.attr("aria-label",b.updates.l10n.updateNowLabel.replace("%s",e.data("name"))):"install-plugin"===d.action&&e.attr("aria-label",b.updates.l10n.installNowLabel.replace("%s",e.data("name"))))),b.a11y.speak(b.updates.l10n.updateCancel,"polite")}),f.on("click","[data-plugin] .update-link",function(c){var d=a(c.target),e=d.parents("tr");c.preventDefault(),d.hasClass("updating-message")||d.hasClass("button-disabled")||(b.updates.maybeRequestFilesystemCredentials(c),b.updates.$elToReturnFocusToFromCredentialsModal=e.find(".check-column input"),b.updates.updatePlugin({plugin:e.data("plugin"),slug:e.data("slug")}))}),e.on("click",".update-now",function(c){var d=a(c.target);c.preventDefault(),d.hasClass("updating-message")||d.hasClass("button-disabled")||(b.updates.maybeRequestFilesystemCredentials(c),b.updates.updatePlugin({plugin:d.data("plugin"),slug:d.data("slug")}))}),e.on("click",".install-now",function(c){var e=a(c.target);c.preventDefault(),e.hasClass("updating-message")||e.hasClass("button-disabled")||(b.updates.shouldRequestFilesystemCredentials&&!b.updates.ajaxLocked&&(b.updates.requestFilesystemCredentials(c),d.on("credential-modal-cancel",function(){var c=a(".install-now.updating-message");c.removeClass("updating-message").text(b.updates.l10n.installNow),b.a11y.speak(b.updates.l10n.updateCancel,"polite")})),b.updates.installPlugin({slug:e.data("slug")}))}),d.on("click",".importer-item .install-now",function(c){var e=a(c.target),f=a(this).data("name");c.preventDefault(),e.hasClass("updating-message")||(b.updates.shouldRequestFilesystemCredentials&&!b.updates.ajaxLocked&&(b.updates.requestFilesystemCredentials(c),d.on("credential-modal-cancel",function(){e.removeClass("updating-message").text(b.updates.l10n.installNow).attr("aria-label",b.updates.l10n.installNowLabel.replace("%s",f)),b.a11y.speak(b.updates.l10n.updateCancel,"polite")})),b.updates.installPlugin({slug:e.data("slug"),pagenow:pagenow,success:b.updates.installImporterSuccess,error:b.updates.installImporterError}))}),f.on("click","[data-plugin] a.delete",function(c){var d=a(c.target).parents("tr");c.preventDefault(),window.confirm(b.updates.l10n.aysDeleteUninstall.replace("%s",d.find(".plugin-title strong").text()))&&(b.updates.maybeRequestFilesystemCredentials(c),b.updates.deletePlugin({plugin:d.data("plugin"),slug:d.data("slug")}))}),d.on("click",".themes-php.network-admin .update-link",function(c){var d=a(c.target),e=d.parents("tr");c.preventDefault(),d.hasClass("updating-message")||d.hasClass("button-disabled")||(b.updates.maybeRequestFilesystemCredentials(c),b.updates.$elToReturnFocusToFromCredentialsModal=e.find(".check-column input"),b.updates.updateTheme({slug:e.data("slug")}))}),d.on("click",".themes-php.network-admin a.delete",function(c){var d=a(c.target).parents("tr");c.preventDefault(),window.confirm(b.updates.l10n.aysDelete.replace("%s",d.find(".theme-title strong").text()))&&(b.updates.maybeRequestFilesystemCredentials(c),b.updates.deleteTheme({slug:d.data("slug")}))}),f.on("click",'[type="submit"]',function(c){var e,g,h=a(c.target).siblings("select").val(),i=f.find('input[name="checked[]"]:checked'),j=0,k=0,l=[];switch(pagenow){case"plugins":case"plugins-network":e="plugin";break;case"themes-network":e="theme";break;default:return}if(!i.length)return c.preventDefault(),a("html, body").animate({scrollTop:0}),b.updates.addAdminNotice({id:"no-items-selected",className:"notice-error is-dismissible",message:b.updates.l10n.noItemsSelected});switch(h){case"update-selected":g=h.replace("selected",e);break;case"delete-selected":if(!window.confirm("plugin"===e?b.updates.l10n.aysBulkDelete:b.updates.l10n.aysBulkDeleteThemes))return void c.preventDefault();g=h.replace("selected",e);break;default:return}b.updates.maybeRequestFilesystemCredentials(c),c.preventDefault(),f.find('.manage-column [type="checkbox"]').prop("checked",!1),d.trigger("wp-"+e+"-bulk-"+h,i),i.each(function(c,d){var e=a(d),f=e.parents("tr");return"update-selected"!==h||f.hasClass("update")&&!f.find("notice-error").length?void b.updates.queue.push({action:g,data:{plugin:f.data("plugin"),slug:f.data("slug")}}):void e.prop("checked",!1)}),d.on("wp-plugin-update-success wp-plugin-update-error wp-theme-update-success wp-theme-update-error",function(c,d){var e,f,g=a('[data-slug="'+d.slug+'"]');"wp-"+d.update+"-update-success"===c.type?j++:(f=d.pluginName?d.pluginName:g.find(".column-primary strong").text(),k++,l.push(f+": "+d.errorMessage)),g.find('input[name="checked[]"]:checked').prop("checked",!1),b.updates.adminNotice=b.template("wp-bulk-updates-admin-notice"),b.updates.addAdminNotice({id:"bulk-action-notice",className:"bulk-action-notice",successes:j,errors:k,errorMessages:l,type:d.update}),e=a("#bulk-action-notice").on("click","button",function(){a(this).toggleClass("bulk-action-errors-collapsed").attr("aria-expanded",!a(this).hasClass("bulk-action-errors-collapsed")),e.find(".bulk-action-errors").toggleClass("hidden")}),k>0&&!b.updates.queue.length&&a("html, body").animate({scrollTop:0})}),d.on("wp-updates-notice-added",function(){b.updates.adminNotice=b.template("wp-updates-admin-notice")}),b.updates.queueChecker()}),j.length&&j.attr("aria-describedby","live-search-desc"),j.on("keyup input",_.debounce(function(c,d){var f,g,h=a(".plugin-install-search");f={_ajax_nonce:b.updates.ajaxNonce,s:c.target.value,tab:"search",type:a("#typeselector").val(),pagenow:pagenow},g=location.href.split("?")[0]+"?"+a.param(_.omit(f,["_ajax_nonce","pagenow"])),"keyup"===c.type&&27===c.which&&(c.target.value=""),b.updates.searchTerm===f.s&&"typechange"!==d||(e.empty(),b.updates.searchTerm=f.s,window.history&&window.history.replaceState&&window.history.replaceState(null,"",g),h.length||(h=a('<li class="plugin-install-search" />').append(a("<a />",{"class":"current",href:g,text:b.updates.l10n.searchResultsLabel})),a(".wp-filter .filter-links .current").removeClass("current").parents(".filter-links").prepend(h),e.prev("p").remove(),a(".plugins-popular-tags-wrapper").remove()),"undefined"!=typeof b.updates.searchRequest&&b.updates.searchRequest.abort(),a("body").addClass("loading-content"),b.updates.searchRequest=b.ajax.post("search-install-plugins",f).done(function(c){a("body").removeClass("loading-content"),e.append(c.items),delete b.updates.searchRequest,0===c.count?b.a11y.speak(b.updates.l10n.noPluginsFound):b.a11y.speak(b.updates.l10n.pluginsFound.replace("%d",c.count))}))},500)),i.length&&i.attr("aria-describedby","live-search-desc"),i.on("keyup input",_.debounce(function(c){var d,e={_ajax_nonce:b.updates.ajaxNonce,s:c.target.value,pagenow:pagenow,plugin_status:"all"};"keyup"===c.type&&27===c.which&&(c.target.value=""),b.updates.searchTerm!==e.s&&(b.updates.searchTerm=e.s,d=_.object(_.compact(_.map(location.search.slice(1).split("&"),function(a){if(a)return a.split("=")}))),e.plugin_status=d.plugin_status||"all",window.history&&window.history.replaceState&&window.history.replaceState(null,"",location.href.split("?")[0]+"?s="+e.s+"&plugin_status="+e.plugin_status), "undefined"!=typeof b.updates.searchRequest&&b.updates.searchRequest.abort(),f.empty(),a("body").addClass("loading-content"),a(".subsubsub .current").removeClass("current"),b.updates.searchRequest=b.ajax.post("search-plugins",e).done(function(c){var d=a("<span />").addClass("subtitle").html(b.updates.l10n.searchResults.replace("%s",_.escape(e.s))),g=a(".wrap .subtitle");e.s.length?g.length?g.replaceWith(d):a(".wp-header-end").before(d):(g.remove(),a(".subsubsub ."+e.plugin_status+" a").addClass("current")),a("body").removeClass("loading-content"),f.append(c.items),delete b.updates.searchRequest,0===c.count?b.a11y.speak(b.updates.l10n.noPluginsFound):b.a11y.speak(b.updates.l10n.pluginsFound.replace("%d",c.count))}))},500)),d.on("submit",".search-plugins",function(b){b.preventDefault(),a("input.wp-filter-search").trigger("input")}),a("#typeselector").on("change",function(){var b=a('input[name="s"]');b.val().length&&b.trigger("input","typechange")}),a("#plugin_update_from_iframe").on("click",function(b){var c,d=window.parent===window?null:window.parent;a.support.postMessage=!!window.postMessage,!1!==a.support.postMessage&&null!==d&&-1===window.parent.location.pathname.indexOf("update-core.php")&&(b.preventDefault(),c={action:"update-plugin",data:{plugin:a(this).data("plugin"),slug:a(this).data("slug")}},d.postMessage(JSON.stringify(c),window.location.origin))}),a("#plugin_install_from_iframe").on("click",function(b){var c,d=window.parent===window?null:window.parent;a.support.postMessage=!!window.postMessage,!1!==a.support.postMessage&&null!==d&&-1===window.parent.location.pathname.indexOf("index.php")&&(b.preventDefault(),c={action:"install-plugin",data:{slug:a(this).data("slug")}},d.postMessage(JSON.stringify(c),window.location.origin))}),a(window).on("message",function(c){var d,e=c.originalEvent,f=document.location.protocol+"//"+document.location.hostname;if(e.origin===f){try{d=a.parseJSON(e.data)}catch(g){return}if("undefined"!=typeof d.action)switch(d.action){case"decrementUpdateCount":b.updates.decrementCount(d.upgradeType);break;case"install-plugin":case"update-plugin":window.tb_remove(),d.data=b.updates._addCallbacks(d.data,d.action),b.updates.queue.push(d),b.updates.queueChecker()}}}),a(window).on("beforeunload",b.updates.beforeunload)})}(jQuery,window.wp,window._wpUpdatesSettings);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/css/edit-rtl.min.css
1
#pending,#poststuff #titlewrap{border:0;padding:0}#pending,#poststuff #post-body{padding:0}#editable-post-name-full,body.post-new-php .submitbox .submitdelete{display:none}#edit-slug-box .cancel,.submitbox .submit a:hover{text-decoration:underline}#titlediv,#wp-content-editor-container,.postbox,form#tags-filter{position:relative}#poststuff{padding-top:10px;min-width:763px}#poststuff .postbox-container{width:100%}#poststuff #post-body.columns-2{margin-left:300px}#show-comments{overflow:hidden}#save-action .spinner,#show-comments a{float:right}#show-comments .spinner{float:none;margin-top:0}#lost-connection-notice .spinner{visibility:visible;float:right;margin:0 0 0 5px}#titlediv label{cursor:text}#titlediv div.inside{margin:0}#titlediv #title{padding:3px 8px;font-size:1.7em;line-height:100%;height:1.7em;width:100%;outline:0;margin:0 0 3px;background-color:#fff}#titlediv #title-prompt-text{color:#72777c;position:absolute;font-size:1.7em;padding:11px 10px}input#link_description,input#link_url{width:98%}#pending{background:100% none;font-size:11px;margin-top:-1px}#comment-link-box,#edit-slug-box{line-height:24px;min-height:25px;margin-top:5px;padding:0 10px;color:#666}#edit-slug-box .cancel{margin-left:10px;padding:0;font-size:11px;color:#0073aa}#comment-link-box{margin:5px 0;padding:0 5px}#editable-post-name{font-weight:600}#editable-post-name input{font-size:13px;font-weight:400;height:24px;margin:0;width:16em}.postarea h3 label{float:right}.submitbox .submit input{margin-bottom:8px;margin-left:4px;padding:6px}#post-status-select{margin-top:3px}#post-body #normal-sortables{min-height:50px}.postbox{min-width:255px;border:1px solid #e5e5e5;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.04);box-shadow:0 1px 1px rgba(0,0,0,.04);background:#fff}#trackback_url{width:99%}#normal-sortables .postbox .submit{background:0 0;border:0;float:left;padding:0 12px;margin:0}.category-add input[type=text],.category-add select{width:100%;max-width:260px;vertical-align:baseline}#side-sortables .category-add input[type=text],#side-sortables .category-add select{margin:0 0 1em}#side-sortables .add-menu-item-tabs li,.wp-tab-bar li,ul.category-tabs li{display:inline;line-height:1.35em}.no-js .category-tabs li.hide-if-no-js{display:none}#side-sortables .add-menu-item-tabs a,.category-tabs a,.wp-tab-bar a{text-decoration:none}#post-body ul.add-menu-item-tabs li.tabs a,#post-body ul.category-tabs li.tabs a,#side-sortables .add-menu-item-tabs .tabs a,#side-sortables .category-tabs .tabs a,.wp-tab-bar .wp-tab-active a{color:#32373c}.category-tabs{margin:8px 0 5px}#category-adder h4{margin:0}.taxonomy-add-new{display:inline-block;margin:10px 0;font-weight:600}#side-sortables .add-menu-item-tabs,.wp-tab-bar{margin-bottom:3px}#normal-sortables .postbox #replyrow .submit{float:none;margin:0;padding:5px 7px 10px;overflow:hidden}#side-sortables .submitbox .submit .preview,#side-sortables .submitbox .submit a.preview:hover,#side-sortables .submitbox .submit input{border:0}ul.add-menu-item-tabs,ul.category-tabs,ul.wp-tab-bar{margin-top:12px}ul.add-menu-item-tabs li,ul.category-tabs li{border:1px solid transparent;position:relative}.wp-tab-active,ul.add-menu-item-tabs li.tabs,ul.category-tabs li.tabs{border:1px solid #ddd;border-bottom-color:#fdfdfd;background-color:#fdfdfd}ul.add-menu-item-tabs li,ul.category-tabs li,ul.wp-tab-bar li{padding:3px 5px 6px}#set-post-thumbnail{display:inline-block;max-width:100%}.ui-tabs-hide,.wp-editor-expand #content-resize-handle,.wp-hidden-children .wp-hidden-child{display:none}#postimagediv .inside img{max-width:100%;height:auto;width:auto;vertical-align:top;background-image:-webkit-linear-gradient(-45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4),-webkit-linear-gradient(-45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4);background-image:linear-gradient(-45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4),linear-gradient(-45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4);background-position:100% 0,10px 10px;-webkit-background-size:20px 20px;background-size:20px 20px}#post-body .tagsdiv #newtag{margin-left:5px;width:16em}#side-sortables input#post_password{width:94%}#side-sortables .tagsdiv #newtag{width:68%}#post-status-info{width:100%;border-spacing:0;border:1px solid #e5e5e5;border-top:none;background-color:#f7f7f7;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.04);box-shadow:0 1px 1px rgba(0,0,0,.04);z-index:999}#post-status-info td{font-size:12px}.autosave-info{padding:2px 10px;text-align:left}#editorcontent #post-status-info{border:none}#content-resize-handle{background:url(../images/resize.gif) right bottom no-repeat;width:12px;cursor:row-resize}.rtl #content-resize-handle{background-image:url(../images/resize-rtl.gif);background-position:left bottom}#postdivrich #content{resize:none}#wp-word-count{display:block;padding:2px 10px}.wp-editor-expand #wp-content-editor-tools{z-index:1000;border-bottom:1px solid #e5e5e5}.wp-editor-expand #wp-content-editor-container{-webkit-box-shadow:none;box-shadow:none;margin-top:-1px;border-bottom:0 none}.wp-editor-expand div.mce-statusbar{z-index:1}.wp-editor-expand #post-status-info{border-top:1px solid #e5e5e5}.wp-editor-expand div.mce-toolbar-grp{z-index:999}.mce-fullscreen #wp-content-wrap .mce-edit-area,.mce-fullscreen #wp-content-wrap .mce-menubar,.mce-fullscreen #wp-content-wrap .mce-statusbar,.mce-fullscreen #wp-content-wrap .mce-toolbar-grp{position:static!important;width:auto!important;padding:0!important}.mce-fullscreen #wp-content-wrap .mce-statusbar{visibility:visible!important}.mce-fullscreen #wp-content-wrap .mce-tinymce .mce-wp-dfw,.mce-fullscreen #wp-content-wrap .mce-wp-dfw,.post-php.mce-fullscreen #wpadminbar{display:none}#wp-content-editor-tools{background-color:#f1f1f1;padding-top:20px}#poststuff #post-body.columns-2 #side-sortables{width:280px}#timestampdiv select{height:21px;line-height:14px;padding:0;vertical-align:top;font-size:12px}#aa,#hh,#jj,#mn{padding:1px;font-size:12px}#hh,#jj,#mn{width:2em}#aa{width:3.4em}.curtime #timestamp{padding:2px 0 1px;display:inline!important;height:auto!important}#post-body #visibility:before,#post-body .misc-pub-post-status:before,#post-body .misc-pub-revisions:before,.curtime #timestamp:before,span.wp-media-buttons-icon:before{color:#82878c}#post-body #visibility:before,#post-body .misc-pub-post-status:before,#post-body .misc-pub-revisions:before,.curtime #timestamp:before{font:400 20px/1 dashicons;speak:none;display:inline-block;margin-right:-1px;padding-left:3px;vertical-align:top;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}#post-body .misc-pub-post-status:before{content:"\f173"}#post-body #visibility:before{content:"\f177"}.curtime #timestamp:before{content:"\f145";position:relative;top:-1px}#post-body .misc-pub-revisions:before{content:"\f321"}#timestampdiv{padding-top:5px;line-height:23px}#timestampdiv p{margin:8px 0 6px}#timestampdiv input{border-width:1px;border-style:solid}.notification-dialog{position:fixed;top:30%;max-height:70%;right:50%;width:450px;margin-right:-225px;background:#fff;-webkit-box-shadow:0 3px 6px rgba(0,0,0,.3);box-shadow:0 3px 6px rgba(0,0,0,.3);line-height:1.5;z-index:1000005;overflow-y:auto}.notification-dialog-background{position:fixed;top:0;right:0;left:0;bottom:0;background:#000;opacity:.7;filter:alpha(opacity=70);z-index:1000000}#post-lock-dialog .post-locked-message,#post-lock-dialog .post-taken-over{margin:25px}#post-lock-dialog .post-locked-message a.button{margin-left:10px}#post-lock-dialog .post-locked-avatar{float:right;margin:0 0 20px 20px}#post-lock-dialog .wp-tab-first{outline:0}#post-lock-dialog .locked-saving img{float:right;margin-left:3px}#post-lock-dialog.saved .locked-saved,#post-lock-dialog.saving .locked-saving{display:inline}#excerpt{display:block;margin:12px 0 0;height:4em;width:100%}.tagchecklist{margin-right:14px;font-size:12px;overflow:auto}.tagchecklist br{display:none}.tagchecklist strong{margin-right:-8px;position:absolute}.tagchecklist>span{float:right;margin-left:25px;font-size:13px;line-height:1.8em;cursor:default;max-width:100%;overflow:hidden;text-overflow:ellipsis}.tagchecklist .ntdelbutton{position:absolute;width:24px;height:24px;border:none;margin:0 -19px 0 0;padding:0;background:0 0;cursor:pointer;text-indent:0}#poststuff .stuffbox>h3,#poststuff h2,#poststuff h3.hndle{font-size:14px;padding:8px 12px;margin:0;line-height:1.4}#poststuff .inside{margin:6px 0 0}#poststuff .inside #page_template,#poststuff .inside #parent_id{max-width:100%}.ie8 #poststuff .inside #page_template,.ie8 #poststuff .inside #parent_id{width:250px}.post-attributes-label-wrapper{margin-bottom:.5em}.post-attributes-label{vertical-align:baseline;font-weight:600}#post-visibility-select{line-height:1.5em;margin-top:3px}#linksubmitdiv .inside,#poststuff #submitdiv .inside{margin:0;padding:0}#post-body-content,.edit-form-section{margin-bottom:20px}#postcustomstuff thead th{padding:5px 8px 8px;background-color:#f1f1f1}#postcustom #postcustomstuff .submit{border:0;float:none;padding:0 8px 8px}#side-sortables #postcustom #postcustomstuff .submit{margin:0;padding:0}#side-sortables #postcustom #postcustomstuff #the-list textarea{height:85px}#side-sortables #postcustom #postcustomstuff td.left input,#side-sortables #postcustom #postcustomstuff td.left select,#side-sortables #postcustomstuff #newmetaleft a{margin:3px 3px 0}#postcustomstuff table{margin:0;width:100%;border:1px solid #ddd;border-spacing:0;background-color:#f9f9f9}#postcustomstuff tr{vertical-align:top}#postcustomstuff table input,#postcustomstuff table select,#postcustomstuff table textarea{width:96%;margin:8px}#side-sortables #postcustomstuff table input,#side-sortables #postcustomstuff table select,#side-sortables #postcustomstuff table textarea{margin:3px}#postcustomstuff td.left,#postcustomstuff th.left{width:38%}#postcustomstuff .submit input{margin:0;width:auto}#postcustomstuff #newmetaleft a{display:inline-block;margin:0 8px 8px;text-decoration:none}.no-js #postcustomstuff #enternew{display:none}#post-body-content .compat-attachment-fields{margin-bottom:20px}.compat-attachment-fields th{padding-top:5px;padding-left:10px}#select-featured-image{padding:4px 0;overflow:hidden}#select-featured-image img{max-width:100%;height:auto;margin-bottom:10px}#select-featured-image a{float:right;clear:both}#select-featured-image .remove{display:none;margin-top:10px}.js #select-featured-image.has-featured-image .remove{display:inline-block}.no-js #select-featured-image .choose{display:none}.post-state-format{overflow:hidden;display:inline-block;vertical-align:middle;height:20px;width:20px;margin-left:5px;margin-top:-4px}.post-state-format:before{display:block;height:20px;width:20px;font:400 20px/1 dashicons!important;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.post-format-icon:before,.post-state-format:before{color:#ddd;-webkit-transition:all .1s ease-in-out;transition:all .1s ease-in-out}a.post-format-icon:hover:before,a.post-state-format:hover:before{color:#00a0d2}#post-formats-select{line-height:2em}#post-formats-select .post-format-icon:before{top:5px}input.post-format{margin-top:1px}label.post-format-icon{margin-right:0;padding:2px 0}.post-format-icon:before{position:relative;display:inline-block;margin-left:7px;font:400 20px/1 dashicons;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.post-format-icon.post-format-standard:before,.post-state-format.post-format-standard:before,a.post-state-format.format-standard:before{content:"\f109"}.post-format-icon.post-format-image:before,.post-state-format.post-format-image:before,a.post-state-format.format-image:before{content:"\f128"}.post-format-icon.post-format-gallery:before,.post-state-format.post-format-gallery:before,a.post-state-format.format-gallery:before{content:"\f161"}.post-format-icon.post-format-audio:before,.post-state-format.post-format-audio:before,a.post-state-format.format-audio:before{content:"\f127"}.post-format-icon.post-format-video:before,.post-state-format.post-format-video:before,a.post-state-format.format-video:before{content:"\f126"}.post-format-icon.post-format-chat:before,.post-state-format.post-format-chat:before,a.post-state-format.format-chat:before{content:"\f125"}.post-format-icon.post-format-status:before,.post-state-format.post-format-status:before,a.post-state-format.format-status:before{content:"\f130"}.post-format-icon.post-format-aside:before,.post-state-format.post-format-aside:before,a.post-state-format.format-aside:before{content:"\f123"}.post-format-icon.post-format-quote:before,.post-state-format.post-format-quote:before,a.post-state-format.format-quote:before{content:"\f122"}.post-format-icon.post-format-link:before,.post-state-format.post-format-link:before,a.post-state-format.format-link:before{content:"\f103"}.category-adder{margin-right:120px;padding:4px 0}.category-adder h4{margin:0 0 8px}#side-sortables .category-adder{margin:0}.categorydiv div.tabs-panel,.customlinkdiv div.tabs-panel,.posttypediv div.tabs-panel,.taxonomydiv div.tabs-panel,.wp-tab-panel{min-height:42px;max-height:200px;overflow:auto;padding:0 .9em;border:1px solid #ddd;background-color:#fdfdfd}div.tabs-panel-active{display:block}div.tabs-panel-inactive{display:none}#front-page-warning,#front-static-pages ul,.categorydiv ul.categorychecklist ul,.customlinkdiv ul.categorychecklist ul,.inline-editor ul.cat-checklist ul,.posttypediv ul.categorychecklist ul,.taxonomydiv ul.categorychecklist ul,ul.export-filters{margin-right:18px}ul.categorychecklist li{margin:0;padding:0;line-height:22px;word-wrap:break-word}.categorydiv .tabs-panel,.customlinkdiv .tabs-panel,.posttypediv .tabs-panel,.taxonomydiv .tabs-panel{border-width:3px;border-style:solid}.form-wrap label{display:block;padding:2px 0}.form-field input[type=text],.form-field input[type=password],.form-field input[type=email],.form-field input[type=number],.form-field input[type=search],.form-field input[type=tel],.form-field input[type=url],.form-field textarea{border-style:solid;border-width:1px;width:95%}.form-wrap p,p.description{margin:2px 0 5px;color:#666}.form-wrap p,p.description,p.help,span.description{font-size:13px;font-style:italic}.form-wrap .form-field{margin:1em 0;padding:0}.form-wrap .form-field #parent{max-width:100%}.col-wrap h2{margin:12px 0;font-size:1.1em}.col-wrap p.submit{margin-top:-10px}.edit-term-notes{margin-top:2em}#poststuff .tagsdiv .howto{margin:0 0 6px}.ajaxtag .newtag{position:relative}.tagsdiv .newtag{width:180px}.tagsdiv .the-tags{display:block;height:60px;margin:0 auto;overflow:auto;width:260px}.tagcloud-link.button-link{color:#0073aa;text-decoration:underline}.tagcloud-link.button-link:hover{color:#00a0d2}.tagcloud-link.button-link:focus{color:#124964;-webkit-box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8);box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8)}#post-body-content .tagsdiv .the-tags{margin:0 5px}p.popular-tags{border:none;line-height:2em;padding:8px 12px 12px;text-align:justify}p.popular-tags a{padding:0 3px}.tagcloud{width:97%;margin:0 0 40px;text-align:justify}.tagcloud h2{margin:2px 0 12px}.ac_results{display:none;margin:-1px 0 0;padding:0;list-style:none;position:absolute;z-index:10000;border:1px solid #5b9dd9;background-color:#fff}.wp-customizer .ac_results{z-index:500000}.ac_results li{margin:0;padding:5px 10px;white-space:nowrap;text-align:right}.ac_over .ac_match,.ac_results .ac_over{background-color:#0073aa;color:#fff;cursor:pointer}.ac_match{text-decoration:underline}.comment-php .wp-editor-area{height:200px}.comment-ays td,.comment-ays th{padding:10px 15px}.comment-ays .comment-content ul{list-style:outside;margin-right:2em}.comment-ays .comment-content a[href]:after{content:'(' attr(href) ')';display:inline-block;padding:0 4px;color:#72777C;font-size:13px;word-break:break-all}.comment-ays .comment-content p.edit-comment{margin-top:10px}.comment-ays .comment-content p.edit-comment a[href]:after{content:'';padding:0}#comment-status-radio label,.links-table td,.links-table th{padding:5px 0}.comment-ays-submit .button-cancel{margin-right:1em}.spam-undo-inside,.trash-undo-inside{margin:1px 0 1px 8px;line-height:16px}.spam-undo-inside .avatar,.trash-undo-inside .avatar{height:20px;width:20px;margin-left:8px;vertical-align:middle}.stuffbox .editcomment{clear:none}#comment-status-radio p{margin:3px 0 5px}#comment-status-radio input{margin:2px 0 5px 3px;vertical-align:middle}table.links-table{width:100%;border-spacing:0}.links-table th{font-weight:400;text-align:right;vertical-align:top;min-width:80px;width:20%;word-wrap:break-word}.links-table td label{margin-left:8px}.links-table td input[type=text],.links-table td textarea{width:100%}.links-table #link_rel{max-width:280px}#qt_content_dfw,#wp-content-wrap .mce-wp-dfw{display:none}.wp-editor-expand #qt_content_dfw,.wp-editor-expand #wp-content-wrap .mce-wp-dfw{display:inline-block}.focus-on #screen-meta,.focus-on #screen-meta-links,.focus-on #wp-toolbar,.focus-on #wpfooter,.focus-on .page-title-action,.focus-on .postbox-container>*,.focus-on .update-nag,.focus-on .wrap>h1,.focus-on div.error,.focus-on div.notice,.focus-on div.updated{opacity:0;-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:opacity;transition-property:opacity;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out}.focus-on #wp-toolbar{opacity:.3}.focus-off #screen-meta,.focus-off #screen-meta-links,.focus-off #wp-toolbar,.focus-off #wpfooter,.focus-off .page-title-action,.focus-off .postbox-container>*,.focus-off .update-nag,.focus-off .wrap>h1,.focus-off div.error,.focus-off div.notice,.focus-off div.updated{opacity:1;-webkit-transition-duration:.2s;transition-duration:.2s;-webkit-transition-property:opacity;transition-property:opacity;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out}.focus-off #wp-toolbar{-webkit-transform:translate(0,0)}.focus-on #adminmenuback,.focus-on #adminmenuwrap{-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;transition-property:transform;transition-property:transform,-webkit-transform;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out;-webkit-transform:translateX(100%);-ms-transform:translateX(100%);transform:translateX(100%)}.focus-off #adminmenuback,.focus-off #adminmenuwrap{-webkit-transform:translateX(0);-ms-transform:translateX(0);transform:translateX(0);-webkit-transition-duration:.2s;transition-duration:.2s;-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;transition-property:transform;transition-property:transform,-webkit-transform;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out}@media print,(-webkit-min-device-pixel-ratio:1.25),(min-resolution:120dpi){#content-resize-handle,#post-body .wp_themeSkin .mceStatusbar a.mceResize{background:url(../images/resize-2x.gif) right bottom no-repeat;-webkit-background-size:11px 11px;background-size:11px 11px}.rtl #content-resize-handle,.rtl #post-body .wp_themeSkin .mceStatusbar a.mceResize{background-image:url(../images/resize-rtl-2x.gif);background-position:left bottom}}@media only screen and (max-width:850px){#poststuff{min-width:0}#wpbody-content #poststuff #post-body{margin:0}#wpbody-content #post-body.columns-2 #postbox-container-1{margin-left:0;width:100%}#poststuff #postbox-container-1 #side-sortables:empty,#poststuff #postbox-container-1 .empty-container{border:0;height:0;min-height:0}#poststuff #post-body.columns-2 #side-sortables{min-height:0;width:auto}.columns-prefs,.screen-layout{display:none}}@media screen and (max-width:782px){#post-body-content{min-width:0}#titlediv #title-prompt-text{padding:10px}#poststuff .stuffbox>h3,#poststuff h2,#poststuff h3.hndle{padding:12px}.post-format-options{padding-left:0}.post-format-options a{margin-left:5px;margin-bottom:5px;min-width:52px}.post-format-options .post-format-title{font-size:11px}.post-format-options a div{height:28px;width:28px}.post-format-options a div:before{font-size:26px!important}#post-visibility-select{line-height:280%}.wp-core-ui .save-post-visibility,.wp-core-ui .save-timestamp{vertical-align:middle;margin-left:15px}.timestamp-wrap select#mm{display:block;width:100%;margin-bottom:10px}.timestamp-wrap #aa,.timestamp-wrap #hh,.timestamp-wrap #jj,.timestamp-wrap #mn{padding:12px 3px;font-size:14px;margin-bottom:5px;width:auto;text-align:center}ul.category-tabs{margin:30px 0 15px}.tagsdiv .newtag,ul.categorychecklist li{margin-bottom:15px}ul.category-tabs li.tabs{padding:15px}ul.categorychecklist ul{margin-top:15px}.category-add input[type=text],.category-add select{max-width:none;margin-bottom:15px}.tagsdiv .newtag{width:100%;height:auto}.tagchecklist{margin:25px 10px}.tagchecklist>span{font-size:16px;line-height:1.4}#commentstatusdiv p{line-height:2.8}.mceToolbar *{white-space:normal!important}.mceToolbar td,.mceToolbar tr{float:right!important}.wp_themeSkin a.mceButton{width:30px;height:30px}.wp_themeSkin .mceButton .mceIcon{margin-top:5px;margin-right:5px}.wp_themeSkin .mceSplitButton{margin-top:1px}.wp_themeSkin .mceSplitButton td a.mceAction{padding:6px 6px 6px 3px}.wp_themeSkin .mceSplitButton td a.mceOpen,.wp_themeSkin .mceSplitButtonEnabled:hover td a.mceOpen{padding-top:6px;padding-bottom:6px;background-position:1px 6px}.wp_themeSkin table.mceListBox{margin:5px}div.quicktags-toolbar input{padding:10px 20px}button.wp-switch-editor{font-size:16px;line-height:1em;margin:7px 7px 0 0;padding:8px 12px}#wp-content-media-buttons a{font-size:14px;padding:6px 10px}.wp-media-buttons span.jetpack-contact-form-icon,.wp-media-buttons span.wp-media-buttons-icon{width:22px!important;margin-right:-2px!important}.wp-media-buttons #insert-jetpack-contact-form span.jetpack-contact-form-icon:before,.wp-media-buttons .add_media span.wp-media-buttons-icon:before{font-size:20px!important}#content_wp_fullscreen{display:none}.misc-pub-section{padding:20px 10px}.misc-pub-section>a{float:left;font-size:16px}#delete-action,#publishing-action{line-height:47px}#publishing-action .spinner{float:none;margin-top:-2px}.comment-ays td,.comment-ays th{padding-bottom:0}.comment-ays td{padding-top:6px}.links-table #link_rel{max-width:none}.links-table td,.links-table th{padding:10px 0}}
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/css/edit.min.css
1
#pending,#poststuff #titlewrap{border:0;padding:0}#pending,#poststuff #post-body{padding:0}#editable-post-name-full,body.post-new-php .submitbox .submitdelete{display:none}#edit-slug-box .cancel,.submitbox .submit a:hover{text-decoration:underline}#titlediv,#wp-content-editor-container,.postbox,form#tags-filter{position:relative}#poststuff{padding-top:10px;min-width:763px}#poststuff .postbox-container{width:100%}#poststuff #post-body.columns-2{margin-right:300px}#show-comments{overflow:hidden}#save-action .spinner,#show-comments a{float:left}#show-comments .spinner{float:none;margin-top:0}#lost-connection-notice .spinner{visibility:visible;float:left;margin:0 5px 0 0}#titlediv label{cursor:text}#titlediv div.inside{margin:0}#titlediv #title{padding:3px 8px;font-size:1.7em;line-height:100%;height:1.7em;width:100%;outline:0;margin:0 0 3px;background-color:#fff}#titlediv #title-prompt-text{color:#72777c;position:absolute;font-size:1.7em;padding:11px 10px}input#link_description,input#link_url{width:98%}#pending{background:0 none;font-size:11px;margin-top:-1px}#comment-link-box,#edit-slug-box{line-height:24px;min-height:25px;margin-top:5px;padding:0 10px;color:#666}#edit-slug-box .cancel{margin-right:10px;padding:0;font-size:11px;color:#0073aa}#comment-link-box{margin:5px 0;padding:0 5px}#editable-post-name{font-weight:600}#editable-post-name input{font-size:13px;font-weight:400;height:24px;margin:0;width:16em}.postarea h3 label{float:left}.submitbox .submit input{margin-bottom:8px;margin-right:4px;padding:6px}#post-status-select{margin-top:3px}#post-body #normal-sortables{min-height:50px}.postbox{min-width:255px;border:1px solid #e5e5e5;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.04);box-shadow:0 1px 1px rgba(0,0,0,.04);background:#fff}#trackback_url{width:99%}#normal-sortables .postbox .submit{background:0 0;border:0;float:right;padding:0 12px;margin:0}.category-add input[type=text],.category-add select{width:100%;max-width:260px;vertical-align:baseline}#side-sortables .category-add input[type=text],#side-sortables .category-add select{margin:0 0 1em}#side-sortables .add-menu-item-tabs li,.wp-tab-bar li,ul.category-tabs li{display:inline;line-height:1.35em}.no-js .category-tabs li.hide-if-no-js{display:none}#side-sortables .add-menu-item-tabs a,.category-tabs a,.wp-tab-bar a{text-decoration:none}#post-body ul.add-menu-item-tabs li.tabs a,#post-body ul.category-tabs li.tabs a,#side-sortables .add-menu-item-tabs .tabs a,#side-sortables .category-tabs .tabs a,.wp-tab-bar .wp-tab-active a{color:#32373c}.category-tabs{margin:8px 0 5px}#category-adder h4{margin:0}.taxonomy-add-new{display:inline-block;margin:10px 0;font-weight:600}#side-sortables .add-menu-item-tabs,.wp-tab-bar{margin-bottom:3px}#normal-sortables .postbox #replyrow .submit{float:none;margin:0;padding:5px 7px 10px;overflow:hidden}#side-sortables .submitbox .submit .preview,#side-sortables .submitbox .submit a.preview:hover,#side-sortables .submitbox .submit input{border:0}ul.add-menu-item-tabs,ul.category-tabs,ul.wp-tab-bar{margin-top:12px}ul.add-menu-item-tabs li,ul.category-tabs li{border:1px solid transparent;position:relative}.wp-tab-active,ul.add-menu-item-tabs li.tabs,ul.category-tabs li.tabs{border:1px solid #ddd;border-bottom-color:#fdfdfd;background-color:#fdfdfd}ul.add-menu-item-tabs li,ul.category-tabs li,ul.wp-tab-bar li{padding:3px 5px 6px}#set-post-thumbnail{display:inline-block;max-width:100%}.ui-tabs-hide,.wp-editor-expand #content-resize-handle,.wp-hidden-children .wp-hidden-child{display:none}#postimagediv .inside img{max-width:100%;height:auto;width:auto;vertical-align:top;background-image:-webkit-linear-gradient(45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4),-webkit-linear-gradient(45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4);background-image:linear-gradient(45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4),linear-gradient(45deg,#c4c4c4 25%,transparent 25%,transparent 75%,#c4c4c4 75%,#c4c4c4);background-position:0 0,10px 10px;-webkit-background-size:20px 20px;background-size:20px 20px}#post-body .tagsdiv #newtag{margin-right:5px;width:16em}#side-sortables input#post_password{width:94%}#side-sortables .tagsdiv #newtag{width:68%}#post-status-info{width:100%;border-spacing:0;border:1px solid #e5e5e5;border-top:none;background-color:#f7f7f7;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.04);box-shadow:0 1px 1px rgba(0,0,0,.04);z-index:999}#post-status-info td{font-size:12px}.autosave-info{padding:2px 10px;text-align:right}#editorcontent #post-status-info{border:none}#content-resize-handle{background:url(../images/resize.gif) right bottom no-repeat;width:12px;cursor:row-resize}.rtl #content-resize-handle{background-image:url(../images/resize-rtl.gif);background-position:left bottom}#postdivrich #content{resize:none}#wp-word-count{display:block;padding:2px 10px}.wp-editor-expand #wp-content-editor-tools{z-index:1000;border-bottom:1px solid #e5e5e5}.wp-editor-expand #wp-content-editor-container{-webkit-box-shadow:none;box-shadow:none;margin-top:-1px;border-bottom:0 none}.wp-editor-expand div.mce-statusbar{z-index:1}.wp-editor-expand #post-status-info{border-top:1px solid #e5e5e5}.wp-editor-expand div.mce-toolbar-grp{z-index:999}.mce-fullscreen #wp-content-wrap .mce-edit-area,.mce-fullscreen #wp-content-wrap .mce-menubar,.mce-fullscreen #wp-content-wrap .mce-statusbar,.mce-fullscreen #wp-content-wrap .mce-toolbar-grp{position:static!important;width:auto!important;padding:0!important}.mce-fullscreen #wp-content-wrap .mce-statusbar{visibility:visible!important}.mce-fullscreen #wp-content-wrap .mce-tinymce .mce-wp-dfw,.mce-fullscreen #wp-content-wrap .mce-wp-dfw,.post-php.mce-fullscreen #wpadminbar{display:none}#wp-content-editor-tools{background-color:#f1f1f1;padding-top:20px}#poststuff #post-body.columns-2 #side-sortables{width:280px}#timestampdiv select{height:21px;line-height:14px;padding:0;vertical-align:top;font-size:12px}#aa,#hh,#jj,#mn{padding:1px;font-size:12px}#hh,#jj,#mn{width:2em}#aa{width:3.4em}.curtime #timestamp{padding:2px 0 1px;display:inline!important;height:auto!important}#post-body #visibility:before,#post-body .misc-pub-post-status:before,#post-body .misc-pub-revisions:before,.curtime #timestamp:before,span.wp-media-buttons-icon:before{color:#82878c}#post-body #visibility:before,#post-body .misc-pub-post-status:before,#post-body .misc-pub-revisions:before,.curtime #timestamp:before{font:400 20px/1 dashicons;speak:none;display:inline-block;margin-left:-1px;padding-right:3px;vertical-align:top;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}#post-body .misc-pub-post-status:before{content:"\f173"}#post-body #visibility:before{content:"\f177"}.curtime #timestamp:before{content:"\f145";position:relative;top:-1px}#post-body .misc-pub-revisions:before{content:"\f321"}#timestampdiv{padding-top:5px;line-height:23px}#timestampdiv p{margin:8px 0 6px}#timestampdiv input{border-width:1px;border-style:solid}.notification-dialog{position:fixed;top:30%;max-height:70%;left:50%;width:450px;margin-left:-225px;background:#fff;-webkit-box-shadow:0 3px 6px rgba(0,0,0,.3);box-shadow:0 3px 6px rgba(0,0,0,.3);line-height:1.5;z-index:1000005;overflow-y:auto}.notification-dialog-background{position:fixed;top:0;left:0;right:0;bottom:0;background:#000;opacity:.7;filter:alpha(opacity=70);z-index:1000000}#post-lock-dialog .post-locked-message,#post-lock-dialog .post-taken-over{margin:25px}#post-lock-dialog .post-locked-message a.button{margin-right:10px}#post-lock-dialog .post-locked-avatar{float:left;margin:0 20px 20px 0}#post-lock-dialog .wp-tab-first{outline:0}#post-lock-dialog .locked-saving img{float:left;margin-right:3px}#post-lock-dialog.saved .locked-saved,#post-lock-dialog.saving .locked-saving{display:inline}#excerpt{display:block;margin:12px 0 0;height:4em;width:100%}.tagchecklist{margin-left:14px;font-size:12px;overflow:auto}.tagchecklist br{display:none}.tagchecklist strong{margin-left:-8px;position:absolute}.tagchecklist>span{float:left;margin-right:25px;font-size:13px;line-height:1.8em;cursor:default;max-width:100%;overflow:hidden;text-overflow:ellipsis}.tagchecklist .ntdelbutton{position:absolute;width:24px;height:24px;border:none;margin:0 0 0 -19px;padding:0;background:0 0;cursor:pointer;text-indent:0}#poststuff .stuffbox>h3,#poststuff h2,#poststuff h3.hndle{font-size:14px;padding:8px 12px;margin:0;line-height:1.4}#poststuff .inside{margin:6px 0 0}#poststuff .inside #page_template,#poststuff .inside #parent_id{max-width:100%}.ie8 #poststuff .inside #page_template,.ie8 #poststuff .inside #parent_id{width:250px}.post-attributes-label-wrapper{margin-bottom:.5em}.post-attributes-label{vertical-align:baseline;font-weight:600}#post-visibility-select{line-height:1.5em;margin-top:3px}#linksubmitdiv .inside,#poststuff #submitdiv .inside{margin:0;padding:0}#post-body-content,.edit-form-section{margin-bottom:20px}#postcustomstuff thead th{padding:5px 8px 8px;background-color:#f1f1f1}#postcustom #postcustomstuff .submit{border:0;float:none;padding:0 8px 8px}#side-sortables #postcustom #postcustomstuff .submit{margin:0;padding:0}#side-sortables #postcustom #postcustomstuff #the-list textarea{height:85px}#side-sortables #postcustom #postcustomstuff td.left input,#side-sortables #postcustom #postcustomstuff td.left select,#side-sortables #postcustomstuff #newmetaleft a{margin:3px 3px 0}#postcustomstuff table{margin:0;width:100%;border:1px solid #ddd;border-spacing:0;background-color:#f9f9f9}#postcustomstuff tr{vertical-align:top}#postcustomstuff table input,#postcustomstuff table select,#postcustomstuff table textarea{width:96%;margin:8px}#side-sortables #postcustomstuff table input,#side-sortables #postcustomstuff table select,#side-sortables #postcustomstuff table textarea{margin:3px}#postcustomstuff td.left,#postcustomstuff th.left{width:38%}#postcustomstuff .submit input{margin:0;width:auto}#postcustomstuff #newmetaleft a{display:inline-block;margin:0 8px 8px;text-decoration:none}.no-js #postcustomstuff #enternew{display:none}#post-body-content .compat-attachment-fields{margin-bottom:20px}.compat-attachment-fields th{padding-top:5px;padding-right:10px}#select-featured-image{padding:4px 0;overflow:hidden}#select-featured-image img{max-width:100%;height:auto;margin-bottom:10px}#select-featured-image a{float:left;clear:both}#select-featured-image .remove{display:none;margin-top:10px}.js #select-featured-image.has-featured-image .remove{display:inline-block}.no-js #select-featured-image .choose{display:none}.post-state-format{overflow:hidden;display:inline-block;vertical-align:middle;height:20px;width:20px;margin-right:5px;margin-top:-4px}.post-state-format:before{display:block;height:20px;width:20px;font:400 20px/1 dashicons!important;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.post-format-icon:before,.post-state-format:before{color:#ddd;-webkit-transition:all .1s ease-in-out;transition:all .1s ease-in-out}a.post-format-icon:hover:before,a.post-state-format:hover:before{color:#00a0d2}#post-formats-select{line-height:2em}#post-formats-select .post-format-icon:before{top:5px}input.post-format{margin-top:1px}label.post-format-icon{margin-left:0;padding:2px 0}.post-format-icon:before{position:relative;display:inline-block;margin-right:7px;font:400 20px/1 dashicons;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.post-format-icon.post-format-standard:before,.post-state-format.post-format-standard:before,a.post-state-format.format-standard:before{content:"\f109"}.post-format-icon.post-format-image:before,.post-state-format.post-format-image:before,a.post-state-format.format-image:before{content:"\f128"}.post-format-icon.post-format-gallery:before,.post-state-format.post-format-gallery:before,a.post-state-format.format-gallery:before{content:"\f161"}.post-format-icon.post-format-audio:before,.post-state-format.post-format-audio:before,a.post-state-format.format-audio:before{content:"\f127"}.post-format-icon.post-format-video:before,.post-state-format.post-format-video:before,a.post-state-format.format-video:before{content:"\f126"}.post-format-icon.post-format-chat:before,.post-state-format.post-format-chat:before,a.post-state-format.format-chat:before{content:"\f125"}.post-format-icon.post-format-status:before,.post-state-format.post-format-status:before,a.post-state-format.format-status:before{content:"\f130"}.post-format-icon.post-format-aside:before,.post-state-format.post-format-aside:before,a.post-state-format.format-aside:before{content:"\f123"}.post-format-icon.post-format-quote:before,.post-state-format.post-format-quote:before,a.post-state-format.format-quote:before{content:"\f122"}.post-format-icon.post-format-link:before,.post-state-format.post-format-link:before,a.post-state-format.format-link:before{content:"\f103"}.category-adder{margin-left:120px;padding:4px 0}.category-adder h4{margin:0 0 8px}#side-sortables .category-adder{margin:0}.categorydiv div.tabs-panel,.customlinkdiv div.tabs-panel,.posttypediv div.tabs-panel,.taxonomydiv div.tabs-panel,.wp-tab-panel{min-height:42px;max-height:200px;overflow:auto;padding:0 .9em;border:1px solid #ddd;background-color:#fdfdfd}div.tabs-panel-active{display:block}div.tabs-panel-inactive{display:none}#front-page-warning,#front-static-pages ul,.categorydiv ul.categorychecklist ul,.customlinkdiv ul.categorychecklist ul,.inline-editor ul.cat-checklist ul,.posttypediv ul.categorychecklist ul,.taxonomydiv ul.categorychecklist ul,ul.export-filters{margin-left:18px}ul.categorychecklist li{margin:0;padding:0;line-height:22px;word-wrap:break-word}.categorydiv .tabs-panel,.customlinkdiv .tabs-panel,.posttypediv .tabs-panel,.taxonomydiv .tabs-panel{border-width:3px;border-style:solid}.form-wrap label{display:block;padding:2px 0}.form-field input[type=text],.form-field input[type=password],.form-field input[type=email],.form-field input[type=number],.form-field input[type=search],.form-field input[type=tel],.form-field input[type=url],.form-field textarea{border-style:solid;border-width:1px;width:95%}.form-wrap p,p.description{margin:2px 0 5px;color:#666}.form-wrap p,p.description,p.help,span.description{font-size:13px;font-style:italic}.form-wrap .form-field{margin:1em 0;padding:0}.form-wrap .form-field #parent{max-width:100%}.col-wrap h2{margin:12px 0;font-size:1.1em}.col-wrap p.submit{margin-top:-10px}.edit-term-notes{margin-top:2em}#poststuff .tagsdiv .howto{margin:0 0 6px}.ajaxtag .newtag{position:relative}.tagsdiv .newtag{width:180px}.tagsdiv .the-tags{display:block;height:60px;margin:0 auto;overflow:auto;width:260px}.tagcloud-link.button-link{color:#0073aa;text-decoration:underline}.tagcloud-link.button-link:hover{color:#00a0d2}.tagcloud-link.button-link:focus{color:#124964;-webkit-box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8);box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8)}#post-body-content .tagsdiv .the-tags{margin:0 5px}p.popular-tags{border:none;line-height:2em;padding:8px 12px 12px;text-align:justify}p.popular-tags a{padding:0 3px}.tagcloud{width:97%;margin:0 0 40px;text-align:justify}.tagcloud h2{margin:2px 0 12px}.ac_results{display:none;margin:-1px 0 0;padding:0;list-style:none;position:absolute;z-index:10000;border:1px solid #5b9dd9;background-color:#fff}.wp-customizer .ac_results{z-index:500000}.ac_results li{margin:0;padding:5px 10px;white-space:nowrap;text-align:left}.ac_over .ac_match,.ac_results .ac_over{background-color:#0073aa;color:#fff;cursor:pointer}.ac_match{text-decoration:underline}.comment-php .wp-editor-area{height:200px}.comment-ays td,.comment-ays th{padding:10px 15px}.comment-ays .comment-content ul{list-style:outside;margin-left:2em}.comment-ays .comment-content a[href]:after{content:'(' attr(href) ')';display:inline-block;padding:0 4px;color:#72777C;font-size:13px;word-break:break-all}.comment-ays .comment-content p.edit-comment{margin-top:10px}.comment-ays .comment-content p.edit-comment a[href]:after{content:'';padding:0}#comment-status-radio label,.links-table td,.links-table th{padding:5px 0}.comment-ays-submit .button-cancel{margin-left:1em}.spam-undo-inside,.trash-undo-inside{margin:1px 8px 1px 0;line-height:16px}.spam-undo-inside .avatar,.trash-undo-inside .avatar{height:20px;width:20px;margin-right:8px;vertical-align:middle}.stuffbox .editcomment{clear:none}#comment-status-radio p{margin:3px 0 5px}#comment-status-radio input{margin:2px 3px 5px 0;vertical-align:middle}table.links-table{width:100%;border-spacing:0}.links-table th{font-weight:400;text-align:left;vertical-align:top;min-width:80px;width:20%;word-wrap:break-word}.links-table td label{margin-right:8px}.links-table td input[type=text],.links-table td textarea{width:100%}.links-table #link_rel{max-width:280px}#qt_content_dfw,#wp-content-wrap .mce-wp-dfw{display:none}.wp-editor-expand #qt_content_dfw,.wp-editor-expand #wp-content-wrap .mce-wp-dfw{display:inline-block}.focus-on #screen-meta,.focus-on #screen-meta-links,.focus-on #wp-toolbar,.focus-on #wpfooter,.focus-on .page-title-action,.focus-on .postbox-container>*,.focus-on .update-nag,.focus-on .wrap>h1,.focus-on div.error,.focus-on div.notice,.focus-on div.updated{opacity:0;-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:opacity;transition-property:opacity;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out}.focus-on #wp-toolbar{opacity:.3}.focus-off #screen-meta,.focus-off #screen-meta-links,.focus-off #wp-toolbar,.focus-off #wpfooter,.focus-off .page-title-action,.focus-off .postbox-container>*,.focus-off .update-nag,.focus-off .wrap>h1,.focus-off div.error,.focus-off div.notice,.focus-off div.updated{opacity:1;-webkit-transition-duration:.2s;transition-duration:.2s;-webkit-transition-property:opacity;transition-property:opacity;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out}.focus-off #wp-toolbar{-webkit-transform:translate(0,0)}.focus-on #adminmenuback,.focus-on #adminmenuwrap{-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;transition-property:transform;transition-property:transform,-webkit-transform;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out;-webkit-transform:translateX(-100%);-ms-transform:translateX(-100%);transform:translateX(-100%)}.focus-off #adminmenuback,.focus-off #adminmenuwrap{-webkit-transform:translateX(0);-ms-transform:translateX(0);transform:translateX(0);-webkit-transition-duration:.2s;transition-duration:.2s;-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;transition-property:transform;transition-property:transform,-webkit-transform;-webkit-transition-timing-function:ease-in-out;transition-timing-function:ease-in-out}@media print,(-webkit-min-device-pixel-ratio:1.25),(min-resolution:120dpi){#content-resize-handle,#post-body .wp_themeSkin .mceStatusbar a.mceResize{background:url(../images/resize-2x.gif) right bottom no-repeat;-webkit-background-size:11px 11px;background-size:11px 11px}.rtl #content-resize-handle,.rtl #post-body .wp_themeSkin .mceStatusbar a.mceResize{background-image:url(../images/resize-rtl-2x.gif);background-position:left bottom}}@media only screen and (max-width:850px){#poststuff{min-width:0}#wpbody-content #poststuff #post-body{margin:0}#wpbody-content #post-body.columns-2 #postbox-container-1{margin-right:0;width:100%}#poststuff #postbox-container-1 #side-sortables:empty,#poststuff #postbox-container-1 .empty-container{border:0;height:0;min-height:0}#poststuff #post-body.columns-2 #side-sortables{min-height:0;width:auto}.columns-prefs,.screen-layout{display:none}}@media screen and (max-width:782px){#post-body-content{min-width:0}#titlediv #title-prompt-text{padding:10px}#poststuff .stuffbox>h3,#poststuff h2,#poststuff h3.hndle{padding:12px}.post-format-options{padding-right:0}.post-format-options a{margin-right:5px;margin-bottom:5px;min-width:52px}.post-format-options .post-format-title{font-size:11px}.post-format-options a div{height:28px;width:28px}.post-format-options a div:before{font-size:26px!important}#post-visibility-select{line-height:280%}.wp-core-ui .save-post-visibility,.wp-core-ui .save-timestamp{vertical-align:middle;margin-right:15px}.timestamp-wrap select#mm{display:block;width:100%;margin-bottom:10px}.timestamp-wrap #aa,.timestamp-wrap #hh,.timestamp-wrap #jj,.timestamp-wrap #mn{padding:12px 3px;font-size:14px;margin-bottom:5px;width:auto;text-align:center}ul.category-tabs{margin:30px 0 15px}.tagsdiv .newtag,ul.categorychecklist li{margin-bottom:15px}ul.category-tabs li.tabs{padding:15px}ul.categorychecklist ul{margin-top:15px}.category-add input[type=text],.category-add select{max-width:none;margin-bottom:15px}.tagsdiv .newtag{width:100%;height:auto}.tagchecklist{margin:25px 10px}.tagchecklist>span{font-size:16px;line-height:1.4}#commentstatusdiv p{line-height:2.8}.mceToolbar *{white-space:normal!important}.mceToolbar td,.mceToolbar tr{float:left!important}.wp_themeSkin a.mceButton{width:30px;height:30px}.wp_themeSkin .mceButton .mceIcon{margin-top:5px;margin-left:5px}.wp_themeSkin .mceSplitButton{margin-top:1px}.wp_themeSkin .mceSplitButton td a.mceAction{padding:6px 3px 6px 6px}.wp_themeSkin .mceSplitButton td a.mceOpen,.wp_themeSkin .mceSplitButtonEnabled:hover td a.mceOpen{padding-top:6px;padding-bottom:6px;background-position:1px 6px}.wp_themeSkin table.mceListBox{margin:5px}div.quicktags-toolbar input{padding:10px 20px}button.wp-switch-editor{font-size:16px;line-height:1em;margin:7px 0 0 7px;padding:8px 12px}#wp-content-media-buttons a{font-size:14px;padding:6px 10px}.wp-media-buttons span.jetpack-contact-form-icon,.wp-media-buttons span.wp-media-buttons-icon{width:22px!important;margin-left:-2px!important}.wp-media-buttons #insert-jetpack-contact-form span.jetpack-contact-form-icon:before,.wp-media-buttons .add_media span.wp-media-buttons-icon:before{font-size:20px!important}#content_wp_fullscreen{display:none}.misc-pub-section{padding:20px 10px}.misc-pub-section>a{float:right;font-size:16px}#delete-action,#publishing-action{line-height:47px}#publishing-action .spinner{float:none;margin-top:-2px}.comment-ays td,.comment-ays th{padding-bottom:0}.comment-ays td{padding-top:6px}.links-table #link_rel{max-width:none}.links-table td,.links-table th{padding:10px 0}}
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/css/customize-nav-menus.min.css
1
#customize-theme-controls #accordion-section-menu_locations{position:relative;margin-bottom:15px}#customize-theme-controls #accordion-section-menu_locations>.accordion-section-title{border-bottom-color:#ddd}.menu-in-location,.menu-in-locations{display:block;font-weight:600;font-size:10px}#customize-controls .control-section .accordion-section-title:focus .menu-in-location,#customize-controls .control-section .accordion-section-title:hover .menu-in-location,#customize-controls .theme-location-set{color:#555}.customize-control-nav_menu_location .edit-menu{margin-left:6px;vertical-align:middle;line-height:28px;color:#0073aa;text-decoration:underline}.customize-control-nav_menu_location .edit-menu:active,.customize-control-nav_menu_location .edit-menu:hover{color:#00a0d2}.customize-control-nav_menu_location .edit-menu:focus{color:#124964}.wp-customizer .menu-item-bar .menu-item-handle,.wp-customizer .menu-item-settings,.wp-customizer .menu-item-settings .description-thin{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.wp-customizer .menu-item-bar{margin:0}.wp-customizer .menu-item-bar .menu-item-handle{width:100%;background:#fff}.wp-customizer .menu-item-handle .item-title{margin-right:0}.wp-customizer .menu-item-handle .item-type{padding:1px 21px 0 5px;float:right;text-align:right}.wp-customizer .menu-item-handle:hover{z-index:8}.customize-control-nav_menu_item.has-notifications .menu-item-handle{border-left:4px solid #00a0d2}.wp-customizer .menu-item-settings{max-width:100%;overflow:hidden;z-index:8;padding:10px;background:#eee;border:1px solid #999;border-top:none}.wp-customizer .menu-item-settings .description-thin{width:100%;height:auto;margin:0 0 8px}.wp-customizer .menu-item-settings input[type=text]{width:100%}.wp-customizer .menu-item-settings .submitbox{margin:0;padding:0}.wp-customizer .menu-item-settings .link-to-original{padding:5px 0;border:none;font-style:normal;margin:0;width:100%}.wp-customizer .menu-item .submitbox .submitdelete{float:left;margin:6px 0 0;padding:0;cursor:pointer}.menu-item-reorder-nav{display:none;background-color:#fff;position:absolute;top:0;right:0}.menus-move-left:before{content:"\f341"}.menus-move-right:before{content:"\f345"}.reordering .menu-item .item-controls,.reordering .menu-item .item-type{display:none}.reordering .menu-item-reorder-nav{display:block}.customize-control input.menu-name-field{width:100%;margin:12px 0}.wp-customizer .menu-item .item-edit{position:absolute;right:-19px;top:2px;display:block;width:30px;height:38px;margin-right:0!important;-webkit-box-shadow:none;box-shadow:none;outline:0;overflow:hidden;cursor:pointer}.wp-customizer .menu-item.menu-item-edit-active .item-edit .toggle-indicator:after{content:"\f142"}.wp-customizer .menu-item-settings p.description{font-style:normal}.wp-customizer .menu-settings dl{margin:12px 0 0;padding:0}.wp-customizer .menu-settings .checkbox-input{margin-top:8px}.wp-customizer .menu-settings .menu-theme-locations{border-top:1px solid #ccc}.wp-customizer .menu-settings{margin-top:36px;border-top:none}.menu-settings .customize-control-checkbox label{line-height:1}.menu-settings .customize-control.customize-control-checkbox{margin-bottom:8px}.customize-control-menu{margin-top:4px}#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle{color:#555}.customize-screen-options-toggle{background:0 0;border:none;color:#555;cursor:pointer;margin:0;padding:20px;position:absolute;right:0;top:30px}#customize-controls .customize-info .customize-help-toggle{padding:20px}#customize-controls .customize-info .customize-help-toggle:before{padding:4px}#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle:active,#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle:focus,#customize-controls .customize-info.open.active-menu-screen-options .customize-help-toggle:hover,.active-menu-screen-options .customize-screen-options-toggle,.customize-screen-options-toggle:active,.customize-screen-options-toggle:focus,.customize-screen-options-toggle:hover{color:#0073aa}#customize-controls .customize-info .customize-help-toggle:focus,.customize-screen-options-toggle:focus{outline:0}.customize-screen-options-toggle:before{-moz-osx-font-smoothing:grayscale;border:none;content:"\f111";display:block;font:18px/1 dashicons;padding:5px;text-align:center;text-decoration:none!important;text-indent:0;left:6px;position:absolute;top:6px}#customize-controls .customize-info .customize-help-toggle:focus:before,.customize-screen-options-toggle:focus:before{-webkit-border-radius:100%;border-radius:100%}.wp-customizer #screen-options-wrap{display:none;background:#fff;border-top:1px solid #ddd;padding:4px 15px 15px}.wp-customizer .metabox-prefs label{display:block;padding-right:0;line-height:30px}.wp-customizer .toggle-indicator{display:inline-block;font-size:20px;line-height:1;text-indent:-1px}.rtl .wp-customizer .toggle-indicator{text-indent:1px}.wp-customizer .toggle-indicator:after{content:"\f140";speak:none;vertical-align:top;-webkit-border-radius:50%;border-radius:50%;color:#72777c;font:400 20px/1 dashicons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-decoration:none!important}.control-section-nav_menu .field-css-classes,.control-section-nav_menu .field-description,.control-section-nav_menu .field-link-target,.control-section-nav_menu .field-title-attribute,.control-section-nav_menu .field-xfn{display:none}.control-section-nav_menu.field-css-classes-active .field-css-classes,.control-section-nav_menu.field-description-active .field-description,.control-section-nav_menu.field-link-target-active .field-link-target,.control-section-nav_menu.field-title-attribute-active .field-title-attribute,.control-section-nav_menu.field-xfn-active .field-xfn{display:block}.menu-item-depth-0{margin-left:0}.menu-item-depth-1{margin-left:20px}.menu-item-depth-2{margin-left:40px}.menu-item-depth-3{margin-left:60px}.menu-item-depth-4{margin-left:80px}.menu-item-depth-5{margin-left:100px}.menu-item-depth-6{margin-left:120px}.menu-item-depth-7{margin-left:140px}.menu-item-depth-8{margin-left:160px}.menu-item-depth-9{margin-left:180px}.menu-item-depth-10{margin-left:200px}.menu-item-depth-11{margin-left:220px}.menu-item-depth-0>.menu-item-bar{margin-right:0}.menu-item-depth-1>.menu-item-bar{margin-right:20px}.menu-item-depth-2>.menu-item-bar{margin-right:40px}.menu-item-depth-3>.menu-item-bar{margin-right:60px}.menu-item-depth-4>.menu-item-bar{margin-right:80px}.menu-item-depth-5>.menu-item-bar{margin-right:100px}.menu-item-depth-6>.menu-item-bar{margin-right:120px}.menu-item-depth-7>.menu-item-bar{margin-right:140px}.menu-item-depth-8>.menu-item-bar{margin-right:160px}.menu-item-depth-9>.menu-item-bar{margin-right:180px}.menu-item-depth-10>.menu-item-bar{margin-right:200px}.menu-item-depth-11>.menu-item-bar{margin-right:220px}.menu-item-depth-0 .menu-item-transport{margin-left:0}.menu-item-depth-1 .menu-item-transport{margin-left:-20px}.menu-item-depth-3 .menu-item-transport{margin-left:-60px}.menu-item-depth-4 .menu-item-transport{margin-left:-80px}.menu-item-depth-2 .menu-item-transport{margin-left:-40px}.menu-item-depth-5 .menu-item-transport{margin-left:-100px}.menu-item-depth-6 .menu-item-transport{margin-left:-120px}.menu-item-depth-7 .menu-item-transport{margin-left:-140px}.menu-item-depth-8 .menu-item-transport{margin-left:-160px}.menu-item-depth-9 .menu-item-transport{margin-left:-180px}.menu-item-depth-10 .menu-item-transport{margin-left:-200px}.menu-item-depth-11 .menu-item-transport{margin-left:-220px}.reordering .menu-item-depth-0{margin-left:0}.reordering .menu-item-depth-1{margin-left:15px}.reordering .menu-item-depth-2{margin-left:30px}.reordering .menu-item-depth-3{margin-left:45px}.reordering .menu-item-depth-4{margin-left:60px}.reordering .menu-item-depth-5{margin-left:75px}.reordering .menu-item-depth-6{margin-left:90px}.reordering .menu-item-depth-7{margin-left:105px}.reordering .menu-item-depth-8{margin-left:120px}.reordering .menu-item-depth-9{margin-left:135px}.reordering .menu-item-depth-10{margin-left:150px}.reordering .menu-item-depth-11{margin-left:165px}.reordering .menu-item-depth-0>.menu-item-bar{margin-right:0}.reordering .menu-item-depth-1>.menu-item-bar{margin-right:15px}.reordering .menu-item-depth-2>.menu-item-bar{margin-right:30px}.reordering .menu-item-depth-3>.menu-item-bar{margin-right:45px}.reordering .menu-item-depth-4>.menu-item-bar{margin-right:60px}.reordering .menu-item-depth-5>.menu-item-bar{margin-right:75px}.reordering .menu-item-depth-6>.menu-item-bar{margin-right:90px}.reordering .menu-item-depth-7>.menu-item-bar{margin-right:105px}.reordering .menu-item-depth-8>.menu-item-bar{margin-right:120px}.reordering .menu-item-depth-9>.menu-item-bar{margin-right:135px}.reordering .menu-item-depth-10>.menu-item-bar{margin-right:150px}.reordering .menu-item-depth-11>.menu-item-bar{margin-right:165px}.control-section-nav_menu.menu .menu-item-edit-active{margin-left:0}.control-section-nav_menu.menu .menu-item-edit-active .menu-item-bar{margin-right:0}.control-section-nav_menu.menu .sortable-placeholder{margin-top:0;margin-bottom:1px;max-width:-webkit-calc(100% - 2px);max-width:calc(100% - 2px);float:left;display:list-item;border-color:#a0a5aa}.menu-item-transport li.customize-control{float:none}.control-section-nav_menu.menu ul.menu-item-transport .menu-item-bar{margin-top:0}.adding-menu-items .control-section{opacity:.4}.adding-menu-items .control-panel.control-section,.adding-menu-items .control-section.open{opacity:1}.menu-item-bar .item-delete{color:#a00;position:absolute;top:2px;right:-19px;width:30px;height:38px;cursor:pointer;display:none}.menu-item-bar .item-delete:before{content:"\f335";position:absolute;top:9px;left:5px;-webkit-border-radius:50%;border-radius:50%;font:400 20px/1 dashicons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ie8 .menu-item-bar .item-delete:before{top:-10px}.menu-item-bar .item-delete:focus,.menu-item-bar .item-delete:hover{-webkit-box-shadow:none;box-shadow:none;outline:0;color:red}.adding-menu-items .menu-item-bar .item-edit{display:none}.adding-menu-items .menu-item-bar .item-delete{display:block}#available-menu-items.opening{overflow-y:hidden}#available-menu-items #available-menu-items-search.open{height:100%;border-bottom:none}#available-menu-items .accordion-section-title{border-left:none;border-right:none;background:#fff;-webkit-transition:background-color .15s;transition:background-color .15s;-webkit-user-select:auto;-moz-user-select:auto;-ms-user-select:auto;user-select:auto}#available-menu-items #available-menu-items-search .accordion-section-title,#available-menu-items .open .accordion-section-title{background:#eee}#available-menu-items .accordion-section-title:after{content:none!important}#available-menu-items .accordion-section-title:hover .toggle-indicator:after,#available-menu-items .button-link:focus .toggle-indicator:after,#available-menu-items .button-link:hover .toggle-indicator:after{color:#23282d}#available-menu-items .open .accordion-section-title .toggle-indicator:after{content:"\f142";color:#23282d}#available-menu-items .available-menu-items-list{overflow-y:auto;max-height:200px;background:0 0}#available-menu-items .accordion-section-title button{display:block;width:28px;height:35px;position:absolute;top:5px;right:5px;-webkit-box-shadow:none;box-shadow:none;outline:0;cursor:pointer}#available-menu-items .accordion-section-title .no-items,#available-menu-items .cannot-expand .accordion-section-title .spinner,#available-menu-items .cannot-expand .accordion-section-title>button{display:none}#available-menu-items-search.cannot-expand .accordion-section-title .spinner{display:block}#available-menu-items .cannot-expand .accordion-section-title .no-items{float:right;color:#555d66;font-weight:400;margin-left:5px}#available-menu-items .accordion-section-content{max-height:290px;margin:0;padding:0;position:relative;background:0 0}#available-menu-items .accordion-section-content .available-menu-items-list{margin:0 0 45px;padding:1px 15px 15px}#available-menu-items .accordion-section-content .available-menu-items-list:only-child{margin-bottom:0}#new-custom-menu-item .accordion-section-content{padding:0 15px 15px}#available-menu-items .menu-item-tpl{margin:0}#available-menu-items .new-content-item .create-item-input.invalid,#available-menu-items .new-content-item .create-item-input.invalid:focus,#custom-menu-item-name.invalid,#custom-menu-item-url.invalid,.menu-name-field.invalid,.menu-name-field.invalid:focus{border:1px solid red}#available-menu-items .menu-item-handle .item-type{padding-right:0}#available-menu-items .menu-item-handle .item-title{padding-left:20px}#available-menu-items .menu-item-handle{cursor:pointer;-webkit-box-shadow:none;box-shadow:none;margin-top:-1px}#available-menu-items .menu-item-handle:hover{z-index:1}#available-menu-items .item-title h4{padding:0 0 5px;font-size:14px}#available-menu-items .item-add{position:absolute;top:1px;left:1px;color:#82878c;width:30px;height:38px;-webkit-box-shadow:none;box-shadow:none;outline:0;cursor:pointer}#available-menu-items .menu-item-handle .item-add:focus{color:#23282d}#available-menu-items .item-add:before{content:"\f543";position:relative;left:2px;top:3px;display:inline-block;height:20px;-webkit-border-radius:50%;border-radius:50%;font:400 20px/1.05 dashicons}#available-menu-items .menu-item-handle.item-added .item-add:focus,#available-menu-items .menu-item-handle.item-added .item-title,#available-menu-items .menu-item-handle.item-added .item-type,#available-menu-items .menu-item-handle.item-added:hover .item-add{color:#82878c}#available-menu-items .menu-item-handle.item-added .item-add:before{content:"\f147"}#available-menu-items .accordion-section-title.loading .spinner,#available-menu-items-search.loading .accordion-section-title .spinner{visibility:visible;margin:0 20px}#available-menu-items-search .spinner{position:absolute;top:20px;right:21px;margin:0!important}#available-menu-items #available-menu-items-search .accordion-section-content{position:absolute;left:0;top:60px;bottom:0;max-height:none;width:100%;padding:1px 15px 15px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#available-menu-items-search .nothing-found{margin-top:-1px}#available-menu-items-search .accordion-section-title:after{display:none}#available-menu-items-search .accordion-section-content:empty{min-height:0;padding:0}#available-menu-items-search.loading .accordion-section-content div{opacity:.5}#available-menu-items-search.loading.loading-more .accordion-section-content div{opacity:1}#customize-preview{-webkit-transition:all .2s;transition:all .2s}body.adding-menu-items #available-menu-items{left:0;visibility:visible}body.adding-menu-items .wp-full-overlay-main{left:300px}body.adding-menu-items #customize-preview{opacity:.4}body.adding-menu-items #customize-preview iframe{pointer-events:none}.menu-item-handle .spinner{display:none;float:left;margin:0 8px 0 0}.nav-menu-inserted-item-loading .spinner{display:block}.nav-menu-inserted-item-loading .menu-item-handle .item-type{padding:0 0 0 8px}.added-menu-item .menu-item-handle.loading,.nav-menu-inserted-item-loading .menu-item-handle{padding:10px 15px 10px 8px;cursor:default;opacity:.5;background:#fff;color:#727773}.added-menu-item .menu-item-handle{-webkit-transition-property:opacity,background,color;transition-property:opacity,background,color;-webkit-transition-duration:1.25s;transition-duration:1.25s;-webkit-transition-timing-function:cubic-bezier(.25,-2.5,.75,8);transition-timing-function:cubic-bezier(.25,-2.5,.75,8)}#customize-theme-controls .control-panel-content .control-section-nav_menu:nth-last-child(2) .accordion-section-title{border-bottom-color:#ddd}#accordion-section-add_menu{margin:15px 12px;overflow:hidden}.new-menu-section-content{display:none;padding:15px 0 0;clear:both}#accordion-section-add_menu .accordion-section-title{padding-left:45px}#accordion-section-add_menu .accordion-section-title:before{font:400 20px/1 dashicons;position:absolute;top:12px;left:14px;content:"\f132"}#create-new-menu-submit{float:right;margin:0 0 12px}.menu-delete-item{float:left;padding:1em 0;width:100%}li.assigned-to-menu-location .menu-delete-item{display:none}li.assigned-to-menu-location .add-new-menu-item{margin-bottom:1em}.menu-delete{color:#a00;cursor:pointer;text-decoration:underline}.menu-delete:focus,.menu-delete:hover{color:red}.menu-item-handle{margin-top:-1px}.ui-sortable-disabled .menu-item-handle{cursor:default}.menu-item-handle:hover{position:relative;z-index:10;color:#0073aa}#available-menu-items .menu-item-handle:hover .item-add,.menu-item-handle:hover .item-edit,.menu-item-handle:hover .item-type{color:#0073aa}.menu-item-edit-active .menu-item-handle{border-color:#999;border-bottom:none}.customize-control-nav_menu_item{margin-bottom:0}.customize-control-nav_menu{margin-top:12px}#available-menu-items .item-add:focus:before,#customize-controls .customize-info .customize-help-toggle:focus:before,.customize-screen-options-toggle:focus:before,.menu-delete:focus,.menu-item-bar .item-delete:focus:before,.wp-customizer .menu-item .submitbox .submitdelete:focus,.wp-customizer button:focus .toggle-indicator:after{-webkit-box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8);box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8)}@media screen and (max-width:782px){#available-menu-items #available-menu-items-search .accordion-section-content{top:63px}}@media screen and (max-width:640px){#available-menu-items #available-menu-items-search .accordion-section-content{top:130px}}
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/js/editor.min.js
1
!function(a){function b(){function b(){!i&&window.tinymce&&(i=window.tinymce,j=i.$,j(document).on("click",function(a){var b,c,e=j(a.target);e.hasClass("wp-switch-editor")&&(b=e.attr("data-wp-editor-id"),c=e.hasClass("switch-tmce")?"tmce":"html",d(b,c))}))}function c(a){var b=j(".mce-toolbar-grp",a.getContainer())[0],c=b&&b.clientHeight;return c&&c>10&&c<200?parseInt(c,10):30}function d(a,b){a=a||"content",b=b||"toggle";var d,e,f,g=i.get(a),h=j("#wp-"+a+"-wrap"),k=j("#"+a),l=k[0];if("toggle"===b&&(b=g&&!g.isHidden()?"html":"tmce"),"tmce"===b||"tinymce"===b){if(g&&!g.isHidden())return!1;"undefined"!=typeof window.QTags&&window.QTags.closeAllTags(a),d=parseInt(l.style.height,10)||0,g?(g.show(),!i.Env.iOS&&d&&(e=c(g),d=d-e+14,d>50&&d<5e3&&g.theme.resizeTo(null,d))):i.init(window.tinyMCEPreInit.mceInit[a]),h.removeClass("html-active").addClass("tmce-active"),k.attr("aria-hidden",!0),window.setUserSetting("editor","tinymce")}else if("html"===b){if(g&&g.isHidden())return!1;g?(i.Env.iOS||(f=g.iframeElement,d=f?parseInt(f.style.height,10):0,d&&(e=c(g),d=d+e-14,d>50&&d<5e3&&(l.style.height=d+"px"))),g.hide()):k.css({display:"",visibility:""}),h.removeClass("tmce-active").addClass("html-active"),k.attr("aria-hidden",!1),window.setUserSetting("editor","html")}}function e(a){var b="blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure",c=b+"|div|p",d=b+"|pre",e=!1,f=!1,g=[];return a?(a.indexOf("<script")===-1&&a.indexOf("<style")===-1||(a=a.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g,function(a){return g.push(a),"<wp-preserve>"})),a.indexOf("<pre")!==-1&&(e=!0,a=a.replace(/<pre[^>]*>[\s\S]+?<\/pre>/g,function(a){return a=a.replace(/<br ?\/?>(\r\n|\n)?/g,"<wp-line-break>"),a=a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g,"<wp-line-break>"),a.replace(/\r?\n/g,"<wp-line-break>")})),a.indexOf("[caption")!==-1&&(f=!0,a=a.replace(/\[caption[\s\S]+?\[\/caption\]/g,function(a){return a.replace(/<br([^>]*)>/g,"<wp-temp-br$1>").replace(/[\r\n\t]+/,"")})),a=a.replace(new RegExp("\\s*</("+c+")>\\s*","g"),"</$1>\n"),a=a.replace(new RegExp("\\s*<((?:"+c+")(?: [^>]*)?)>","g"),"\n<$1>"),a=a.replace(/(<p [^>]+>.*?)<\/p>/g,"$1</p#>"),a=a.replace(/<div( [^>]*)?>\s*<p>/gi,"<div$1>\n\n"),a=a.replace(/\s*<p>/gi,""),a=a.replace(/\s*<\/p>\s*/gi,"\n\n"),a=a.replace(/\n[\s\u00a0]+\n/g,"\n\n"),a=a.replace(/\s*<br ?\/?>\s*/gi,"\n"),a=a.replace(/\s*<div/g,"\n<div"),a=a.replace(/<\/div>\s*/g,"</div>\n"),a=a.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi,"\n\n[caption$1[/caption]\n\n"),a=a.replace(/caption\]\n\n+\[caption/g,"caption]\n\n[caption"),a=a.replace(new RegExp("\\s*<((?:"+d+")(?: [^>]*)?)\\s*>","g"),"\n<$1>"),a=a.replace(new RegExp("\\s*</("+d+")>\\s*","g"),"</$1>\n"),a=a.replace(/<((li|dt|dd)[^>]*)>/g," \t<$1>"),a.indexOf("<option")!==-1&&(a=a.replace(/\s*<option/g,"\n<option"),a=a.replace(/\s*<\/select>/g,"\n</select>")),a.indexOf("<hr")!==-1&&(a=a.replace(/\s*<hr( [^>]*)?>\s*/g,"\n\n<hr$1>\n\n")),a.indexOf("<object")!==-1&&(a=a.replace(/<object[\s\S]+?<\/object>/g,function(a){return a.replace(/[\r\n]+/g,"")})),a=a.replace(/<\/p#>/g,"</p>\n"),a=a.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g,"\n$1"),a=a.replace(/^\s+/,""),a=a.replace(/[\s\u00a0]+$/,""),e&&(a=a.replace(/<wp-line-break>/g,"\n")),f&&(a=a.replace(/<wp-temp-br([^>]*)>/g,"<br$1>")),g.length&&(a=a.replace(/<wp-preserve>/g,function(){return g.shift()})),a):""}function f(a){var b=!1,c=!1,d="table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary";return a=a.replace(/\r\n|\r/g,"\n"),a.indexOf("\n")===-1?a:(a.indexOf("<object")!==-1&&(a=a.replace(/<object[\s\S]+?<\/object>/g,function(a){return a.replace(/\n+/g,"")})),a=a.replace(/<[^<>]+>/g,function(a){return a.replace(/[\n\t ]+/g," ")}),a.indexOf("<pre")===-1&&a.indexOf("<script")===-1||(b=!0,a=a.replace(/<(pre|script)[^>]*>[\s\S]*?<\/\1>/g,function(a){return a.replace(/\n/g,"<wp-line-break>")})),a.indexOf("<figcaption")!==-1&&(a=a.replace(/\s*(<figcaption[^>]*>)/g,"$1"),a=a.replace(/<\/figcaption>\s*/g,"</figcaption>")),a.indexOf("[caption")!==-1&&(c=!0,a=a.replace(/\[caption[\s\S]+?\[\/caption\]/g,function(a){return a=a.replace(/<br([^>]*)>/g,"<wp-temp-br$1>"),a=a.replace(/<[^<>]+>/g,function(a){return a.replace(/[\n\t ]+/," ")}),a.replace(/\s*\n\s*/g,"<wp-temp-br />")})),a+="\n\n",a=a.replace(/<br \/>\s*<br \/>/gi,"\n\n"),a=a.replace(new RegExp("(<(?:"+d+")(?: [^>]*)?>)","gi"),"\n\n$1"),a=a.replace(new RegExp("(</(?:"+d+")>)","gi"),"$1\n\n"),a=a.replace(/<hr( [^>]*)?>/gi,"<hr$1>\n\n"),a=a.replace(/\s*<option/gi,"<option"),a=a.replace(/<\/option>\s*/gi,"</option>"),a=a.replace(/\n\s*\n+/g,"\n\n"),a=a.replace(/([\s\S]+?)\n\n/g,"<p>$1</p>\n"),a=a.replace(/<p>\s*?<\/p>/gi,""),a=a.replace(new RegExp("<p>\\s*(</?(?:"+d+")(?: [^>]*)?>)\\s*</p>","gi"),"$1"),a=a.replace(/<p>(<li.+?)<\/p>/gi,"$1"),a=a.replace(/<p>\s*<blockquote([^>]*)>/gi,"<blockquote$1><p>"),a=a.replace(/<\/blockquote>\s*<\/p>/gi,"</p></blockquote>"),a=a.replace(new RegExp("<p>\\s*(</?(?:"+d+")(?: [^>]*)?>)","gi"),"$1"),a=a.replace(new RegExp("(</?(?:"+d+")(?: [^>]*)?>)\\s*</p>","gi"),"$1"),a=a.replace(/(<br[^>]*>)\s*\n/gi,"$1"),a=a.replace(/\s*\n/g,"<br />\n"),a=a.replace(new RegExp("(</?(?:"+d+")[^>]*>)\\s*<br />","gi"),"$1"),a=a.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi,"$1"),a=a.replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi,"[caption$1[/caption]"),a=a.replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g,function(a,b,c){return c.match(/<p( [^>]*)?>/)?a:b+"<p>"+c+"</p>"}),b&&(a=a.replace(/<wp-line-break>/g,"\n")),c&&(a=a.replace(/<wp-temp-br([^>]*)>/g,"<br$1>")),a)}function g(b){var c={o:k,data:b,unfiltered:b};return a&&a("body").trigger("beforePreWpautop",[c]),c.data=e(c.data),a&&a("body").trigger("afterPreWpautop",[c]),c.data}function h(b){var c={o:k,data:b,unfiltered:b};return a&&a("body").trigger("beforeWpautop",[c]),c.data=f(c.data),a&&a("body").trigger("afterWpautop",[c]),c.data}var i,j,k={};return a?a(document).ready(b):document.addEventListener?(document.addEventListener("DOMContentLoaded",b,!1),window.addEventListener("load",b,!1)):window.attachEvent&&(window.attachEvent("onload",b),document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&b()})),window.wp=window.wp||{},window.wp.editor=window.wp.editor||{},window.wp.editor.autop=h,window.wp.editor.removep=g,k={go:d,wpautop:h,pre_wpautop:g,_wp_Autop:f,_wp_Nop:e}}window.switchEditors=new b}(window.jQuery);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-includes/css/customize-preview-rtl.min.css
1
.customize-partial-refreshing{opacity:.25;-webkit-transition:opacity .25s;transition:opacity .25s;cursor:progress}.customize-partial-refreshing.widget-customizer-highlighted-widget{-webkit-box-shadow:none;box-shadow:none}.customize-partial-edit-shortcut,.widget .customize-partial-edit-shortcut{position:absolute;float:right;width:1px;height:1px;padding:0;margin:-1px -1px 0 0;border:0;background:0 0;color:transparent;-webkit-box-shadow:none;box-shadow:none;outline:0;z-index:5}.customize-partial-edit-shortcut button,.widget .customize-partial-edit-shortcut button{position:absolute;right:-30px;top:2px;color:#fff;width:30px;height:30px;min-width:30px;min-height:30px;line-height:1em!important;font-size:18px;z-index:5;background:#0085ba!important;-webkit-border-radius:50%;border-radius:50%;border:2px solid #fff;-webkit-box-shadow:0 2px 1px rgba(46,68,83,.15);box-shadow:0 2px 1px rgba(46,68,83,.15);text-align:center;cursor:pointer;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:3px;-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-duration:.4s;animation-duration:.4s;opacity:0;pointer-events:none;text-shadow:0 -1px 1px #006799,-1px 0 1px #006799,0 1px 1px #006799,1px 0 1px #006799}.wp-custom-header .customize-partial-edit-shortcut button{right:2px}.customize-partial-edit-shortcut button svg{fill:#fff;min-width:20px;min-height:20px;width:20px;height:20px;margin:auto}.customize-partial-edit-shortcut button:hover{background:#008ec2!important}.customize-partial-edit-shortcut button:focus{-webkit-box-shadow:0 0 0 2px #008ec2;box-shadow:0 0 0 2px #008ec2}body.customize-partial-edit-shortcuts-shown .customize-partial-edit-shortcut button{-webkit-animation-name:customize-partial-edit-shortcut-bounce-appear;animation-name:customize-partial-edit-shortcut-bounce-appear;pointer-events:auto}body.customize-partial-edit-shortcuts-hidden .customize-partial-edit-shortcut button{-webkit-animation-name:customize-partial-edit-shortcut-bounce-disappear;animation-name:customize-partial-edit-shortcut-bounce-disappear;pointer-events:none}.customize-partial-edit-shortcut-hidden .customize-partial-edit-shortcut button,.page-sidebar-collapsed .customize-partial-edit-shortcut button{visibility:hidden}@-webkit-keyframes customize-partial-edit-shortcut-bounce-appear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}}@keyframes customize-partial-edit-shortcut-bounce-appear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}}@-webkit-keyframes customize-partial-edit-shortcut-bounce-disappear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}20%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}40%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}60%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}80%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}to{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}}@keyframes customize-partial-edit-shortcut-bounce-disappear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}20%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}40%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}60%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}80%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}to{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}}@media screen and (max-width:800px){.customize-partial-edit-shortcut button,.widget .customize-partial-edit-shortcut button{right:-32px}}@media screen and (max-width:320px){.customize-partial-edit-shortcut button,.widget .customize-partial-edit-shortcut button{right:-30px}}
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-includes/js/tinymce/plugins/wordpress/plugin.min.js
1
!function(a){a.ui.FloatPanel.zIndex=100100,a.PluginManager.add("wordpress",function(b){function c(c){var d,f,i,j=0;f="hide"===c,b.theme.panel&&(i=b.theme.panel.find(".toolbar:not(.menubar)")),!i||i.length<2||"hide"===c&&!i[1].visible()||(!c&&i[1].visible()&&(c="hide"),h(i,function(a,b){b>0&&("hide"===c?(a.hide(),j+=30):(a.show(),j-=30))}),j&&!f&&(a.Env.iOS||(d=b.getContentAreaContainer().firstChild,g.setStyle(d,"height",d.clientHeight+j)),"hide"===c?(setUserSetting("hidetb","0"),e&&e.active(!1)):(setUserSetting("hidetb","1"),e&&e.active(!0))),b.fire("wp-toolbar-toggle"))}function d(){}var e,f,g=a.DOM,h=a.each,i=b.editorManager.i18n.translate,j=window.jQuery,k=window.wp,l=k&&k.editor&&k.editor.autop&&b.getParam("wpautop",!0);return j&&j(document).triggerHandler("tinymce-editor-setup",[b]),b.addButton("wp_adv",{tooltip:"Toolbar Toggle",cmd:"WP_Adv",onPostRender:function(){e=this,e.active("1"===getUserSetting("hidetb"))}}),b.on("PostRender",function(){b.getParam("wordpress_adv_hidden",!0)&&"0"===getUserSetting("hidetb","0")&&c("hide")}),b.addCommand("WP_Adv",function(){c()}),b.on("focus",function(){window.wpActiveEditor=b.id}),b.on("BeforeSetContent",function(b){var c;b.content&&(b.content.indexOf("<!--more")!==-1&&(c=i("Read more..."),b.content=b.content.replace(/<!--more(.*?)-->/g,function(b,d){return'<img src="'+a.Env.transparentSrc+'" data-wp-more="more" data-wp-more-text="'+d+'" class="wp-more-tag mce-wp-more" alt="" title="'+c+'" data-mce-resize="false" data-mce-placeholder="1" />'})),b.content.indexOf("<!--nextpage-->")!==-1&&(c=i("Page break"),b.content=b.content.replace(/<!--nextpage-->/g,'<img src="'+a.Env.transparentSrc+'" data-wp-more="nextpage" class="wp-more-tag mce-wp-nextpage" alt="" title="'+c+'" data-mce-resize="false" data-mce-placeholder="1" />')),b.load&&"raw"!==b.format&&l&&(b.content=k.editor.autop(b.content)),b.content.indexOf("<script")===-1&&b.content.indexOf("<style")===-1||(b.content=b.content.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g,function(b,c){return'<img src="'+a.Env.transparentSrc+'" data-wp-preserve="'+encodeURIComponent(b)+'" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;'+c+'&gt;" title="&lt;'+c+'&gt;" />'})))}),b.on("setcontent",function(){b.$("p").each(function(b,c){if(c.innerHTML&&c.innerHTML.length<10){var d=a.trim(c.innerHTML);d&&"&nbsp;"!==d||(c.innerHTML=a.Env.ie&&a.Env.ie<11?"":'<br data-mce-bogus="1">')}})}),b.on("PostProcess",function(a){a.get&&(a.content=a.content.replace(/<img[^>]+>/g,function(a){var b,c,d="";return a.indexOf('data-wp-more="more"')!==-1?((b=a.match(/data-wp-more-text="([^"]+)"/))&&(d=b[1]),c="<!--more"+d+"-->"):a.indexOf('data-wp-more="nextpage"')!==-1?c="<!--nextpage-->":a.indexOf("data-wp-preserve")!==-1&&(b=a.match(/ data-wp-preserve="([^"]+)"/))&&(c=decodeURIComponent(b[1])),c||a}))}),b.on("ResolveName",function(a){var c;"IMG"===a.target.nodeName&&(c=b.dom.getAttrib(a.target,"data-wp-more"))&&(a.name=c)}),b.addCommand("WP_More",function(c){var d,e,f,g="wp-more-tag",h=b.dom,j=b.selection.getNode();return c=c||"more",g+=" mce-wp-"+c,f="more"===c?"Read more...":"Next page",f=i(f),e='<img src="'+a.Env.transparentSrc+'" alt="" title="'+f+'" class="'+g+'" data-wp-more="'+c+'" data-mce-resize="false" data-mce-placeholder="1" />',"BODY"===j.nodeName||"P"===j.nodeName&&"BODY"===j.parentNode.nodeName?void b.insertContent(e):(d=h.getParent(j,function(a){return!(!a.parentNode||"BODY"!==a.parentNode.nodeName)},b.getBody()),void(d&&("P"===d.nodeName?d.appendChild(h.create("p",null,e).firstChild):h.insertAfter(h.create("p",null,e),d),b.nodeChanged())))}),b.addCommand("WP_Code",function(){b.formatter.toggle("code")}),b.addCommand("WP_Page",function(){b.execCommand("WP_More","nextpage")}),b.addCommand("WP_Help",function(){function c(a,b){var c="<tr>",d=0;for(b=b||1,h(a,function(a,b){c+="<td><kbd>"+b+"</kbd></td><td>"+i(a)+"</td>",d++});d<b;)c+="<td></td><td></td>",d++;return c+"</tr>"}var d,e,f,g,j=i(a.Env.mac?"Ctrl + Alt + letter:":"Shift + Alt + letter:"),k=i(a.Env.mac?"Cmd + letter:":"Ctrl + letter:"),l=[],m=[],n={},o={},p=0,q=0,r=b.settings.wp_shortcut_labels;r&&(h(r,function(a,b){var d;a.indexOf("meta")!==-1?(p++,d=a.replace("meta","").toLowerCase(),d&&(n[d]=b,p%2===0&&(l.push(c(n,2)),n={}))):a.indexOf("access")!==-1&&(q++,d=a.replace("access","").toLowerCase(),d&&(o[d]=b,q%2===0&&(m.push(c(o,2)),o={})))}),p%2>0&&l.push(c(n,2)),q%2>0&&m.push(c(o,2)),d=[i("Letter"),i("Action"),i("Letter"),i("Action")],d="<tr><th>"+d.join("</th><th>")+"</th></tr>",e='<div class="wp-editor-help">',e=e+"<h2>"+i("Default shortcuts,")+" "+k+'</h2><table class="wp-help-th-center fixed">'+d+l.join("")+"</table><h2>"+i("Additional shortcuts,")+" "+j+'</h2><table class="wp-help-th-center fixed">'+d+m.join("")+"</table>",b.plugins.wptextpattern&&(!a.Env.ie||a.Env.ie>8)&&(e=e+"<h2>"+i("When starting a new paragraph with one of these formatting shortcuts followed by a space, the formatting will be applied automatically. Press Backspace or Escape to undo.")+'</h2><table class="wp-help-th-center fixed">'+c({"*":"Bullet list","1.":"Numbered list"})+c({"-":"Bullet list","1)":"Numbered list"})+"</table>",e=e+"<h2>"+i("The following formatting shortcuts are replaced when pressing Enter. Press Escape or the Undo button to undo.")+'</h2><table class="wp-help-single">'+c({">":"Blockquote"})+c({"##":"Heading 2"})+c({"###":"Heading 3"})+c({"####":"Heading 4"})+c({"#####":"Heading 5"})+c({"######":"Heading 6"})+c({"---":"Horizontal line"})+"</table>"),e=e+"<h2>"+i("Focus shortcuts:")+'</h2><table class="wp-help-single">'+c({"Alt + F8":"Inline toolbar (when an image, link or preview is selected)"})+c({"Alt + F9":"Editor menu (when enabled)"})+c({"Alt + F10":"Editor toolbar"})+c({"Alt + F11":"Elements path"})+"</table><p>"+i("To move focus to other buttons use Tab or the arrow keys. To return focus to the editor press Escape or use one of the buttons.")+"</p>",e+="</div>",f=b.windowManager.open({title:"Keyboard Shortcuts",items:{type:"container",classes:"wp-help",html:e},buttons:{text:"Close",onclick:"close"}}),f.$el&&(f.$el.find('div[role="application"]').attr("role","document"),g=f.$el.find(".mce-wp-help"),g[0]&&(g.attr("tabindex","0"),g[0].focus(),g.on("keydown",function(a){a.keyCode>=33&&a.keyCode<=40&&a.stopPropagation()}))))}),b.addCommand("WP_Medialib",function(){k&&k.media&&k.media.editor&&k.media.editor.open(b.id)}),b.addButton("wp_more",{tooltip:"Insert Read More tag",onclick:function(){b.execCommand("WP_More","more")}}),b.addButton("wp_page",{tooltip:"Page break",onclick:function(){b.execCommand("WP_More","nextpage")}}),b.addButton("wp_help",{tooltip:"Keyboard Shortcuts",cmd:"WP_Help"}),b.addButton("wp_code",{tooltip:"Code",cmd:"WP_Code",stateSelector:"code"}),k&&k.media&&k.media.editor&&b.addMenuItem("add_media",{text:"Add Media",icon:"wp-media-library",context:"insert",cmd:"WP_Medialib"}),b.addMenuItem("wp_more",{text:"Insert Read More tag",icon:"wp_more",context:"insert",onclick:function(){b.execCommand("WP_More","more")}}),b.addMenuItem("wp_page",{text:"Page break",icon:"wp_page",context:"insert",onclick:function(){b.execCommand("WP_More","nextpage")}}),b.on("BeforeExecCommand",function(c){!a.Env.webkit||"InsertUnorderedList"!==c.command&&"InsertOrderedList"!==c.command||(f||(f=b.dom.create("style",{type:"text/css"},"#tinymce,#tinymce span,#tinymce li,#tinymce li>span,#tinymce p,#tinymce p>span{font:medium sans-serif;color:#000;line-height:normal;}")),b.getDoc().head.appendChild(f))}),b.on("ExecCommand",function(c){a.Env.webkit&&f&&("InsertUnorderedList"===c.command||"InsertOrderedList"===c.command)&&b.dom.remove(f)}),b.on("init",function(){var c=a.Env,d=["mceContentBody"],e=b.getDoc(),f=b.dom;if(c.iOS&&f.addClass(e.documentElement,"ios"),"rtl"===b.getParam("directionality")&&(d.push("rtl"),f.setAttrib(e.documentElement,"dir","rtl")),f.setAttrib(e.documentElement,"lang",b.getParam("wp_lang_attr")),c.ie?9===parseInt(c.ie,10)?d.push("ie9"):8===parseInt(c.ie,10)?d.push("ie8"):c.ie<8&&d.push("ie7"):c.webkit&&d.push("webkit"),d.push("wp-editor"),h(d,function(a){a&&f.addClass(e.body,a)}),b.on("BeforeSetContent",function(a){a.content&&(a.content=a.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)( [^>]*)?>/gi,"<$1$2>").replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)>\s*<\/p>/gi,"</$1>"))}),j&&j(document).triggerHandler("tinymce-editor-init",[b]),window.tinyMCEPreInit&&window.tinyMCEPreInit.dragDropUpload&&f.bind(e,"dragstart dragend dragover drop",function(a){j&&j(document).trigger(new j.Event(a))}),b.getParam("wp_paste_filters",!0)&&(b.on("PastePreProcess",function(b){b.content=b.content.replace(/<br class="?Apple-interchange-newline"?>/gi,""),a.Env.webkit||(b.content=b.content.replace(/(<[^>]+) style="[^"]*"([^>]*>)/gi,"$1$2"),b.content=b.content.replace(/(<[^>]+) data-mce-style=([^>]+>)/gi,"$1 style=$2"))}),b.on("PastePostProcess",function(c){b.$("p",c.node).each(function(a,b){f.isEmpty(b)&&f.remove(b)}),a.isIE&&b.$("a",c.node).find("font, u").each(function(a,b){f.remove(b,!0)})})),b.settings.wp_shortcut_labels&&b.theme.panel){var g={},i="Shift+Alt+",k="Ctrl+";a.Env.mac&&(i="\u2303\u2325",k="\u2318"),h(b.settings.wp_shortcut_labels,function(a,b){g[b]=a.replace("access",i).replace("meta",k)}),h(b.theme.panel.find("button"),function(a){a&&a.settings.tooltip&&g.hasOwnProperty(a.settings.tooltip)&&(a.settings.tooltip=b.translate(a.settings.tooltip)+" ("+g[a.settings.tooltip]+")")}),h(b.theme.panel.find("listbox"),function(a){a&&"Paragraph"===a.settings.text&&h(a.settings.values,function(a){a.text&&g.hasOwnProperty(a.text)&&(a.shortcut="("+g[a.text]+")")})})}}),b.on("SaveContent",function(a){return!b.inline&&b.isHidden()?void(a.content=a.element.value):(a.content=a.content.replace(/<p>(?:<br ?\/?>|\u00a0|\uFEFF| )*<\/p>/g,"<p>&nbsp;</p>"),void(l&&(a.content=k.editor.removep(a.content))))}),b.on("preInit",function(){var c="@[id|accesskey|class|dir|lang|style|tabindex|title|contenteditable|draggable|dropzone|hidden|spellcheck|translate],i,b,script[src|async|defer|type|charset|crossorigin|integrity]";b.schema.addValidElements(c),a.Env.iOS&&(b.settings.height=300),h({c:"JustifyCenter",r:"JustifyRight",l:"JustifyLeft",j:"JustifyFull",q:"mceBlockQuote",u:"InsertUnorderedList",o:"InsertOrderedList",m:"WP_Medialib",z:"WP_Adv",t:"WP_More",d:"Strikethrough",h:"WP_Help",p:"WP_Page",x:"WP_Code"},function(a,c){b.shortcuts.add("access+"+c,"",a)}),b.addShortcut("meta+s","",function(){k&&k.autosave&&k.autosave.server.triggerSave()}),window.getUserSetting("editor_plain_text_paste_warning")>1&&(b.settings.paste_plaintext_inform=!1),a.Env.mac&&a.$(b.iframeElement).attr("title",i("Rich Text Area. Press Control-Option-H for help."))}),b.on("PastePlainTextToggle",function(a){if(a.state===!0){var b=parseInt(window.getUserSetting("editor_plain_text_paste_warning"),10)||0;b<2&&window.setUserSetting("editor_plain_text_paste_warning",++b)}}),b.on("preinit",function(){function c(c,d){function e(){if(!f)return this;var b,c,d=window.pageXOffset||document.documentElement.scrollLeft,e=window.pageYOffset||document.documentElement.scrollTop,h=window.innerWidth,i=window.innerHeight,m=q?q.getBoundingClientRect():{top:0,right:h,bottom:i,left:0,width:h,height:i},n=this.getEl(),o=n.offsetWidth,r=n.clientHeight,s=f.getBoundingClientRect(),t=(s.left+s.right)/2,u=5,v=r+u,w=p?p.getBoundingClientRect().bottom:0,x=j?j.getBoundingClientRect().bottom:0,y=k?i-k.getBoundingClientRect().top:0,z=l?i-l.getBoundingClientRect().top:0,A=Math.max(0,w,x,m.top),B=Math.max(0,y,z,i-m.bottom),C=s.top+m.top-A,D=i-m.top-s.bottom-B,E=i-A-B,F="",G=0,H=0;return C>=E||D>=E?(this.scrolling=!0,this.hide(),this.scrolling=!1,this):(a.Env.iOS&&"IMG"===f.nodeName&&(G=54,H=46),this.bottom?D>=v?(F=" mce-arrow-up",b=s.bottom+m.top+e-H):C>=v&&(F=" mce-arrow-down",b=s.top+m.top+e-r+G):C>=v?(F=" mce-arrow-down",b=s.top+m.top+e-r+G):D>=v&&E/2>s.bottom+m.top-A&&(F=" mce-arrow-up",b=s.bottom+m.top+e-H),"undefined"==typeof b&&(b=e+A+u+H),c=t-o/2+m.left+d,s.left<0||s.right>m.width?c=m.left+d+(m.width-o)/2:o>=h?(F+=" mce-arrow-full",c=0):c<0&&s.left+o>h||c+o>h&&s.right-o<0?c=(h-o)/2:c<m.left+d?(F+=" mce-arrow-left",c=s.left+m.left+d):c+o>m.width+m.left+d&&(F+=" mce-arrow-right",c=s.right-o+m.left+d),a.Env.iOS&&"IMG"===f.nodeName&&(F=F.replace(/ ?mce-arrow-(up|down)/g,"")),n.className=n.className.replace(/ ?mce-arrow-[\w]+/g,"")+F,g.setStyles(n,{left:c,top:b}),this)}var i,o,r=[];return h(c,function(a){function c(){var c=b.selection;"bullist"===d&&c.selectorChanged("ul > li",function(b,c){for(var d,e=c.parents.length;e--&&(d=c.parents[e].nodeName,"OL"!==d&&"UL"!=d););a.active(b&&"UL"===d)}),"numlist"===d&&c.selectorChanged("ol > li",function(b,c){for(var d,e=c.parents.length;e--&&(d=c.parents[e].nodeName,"OL"!==d&&"UL"!==d););a.active(b&&"OL"===d)}),a.settings.stateSelector&&c.selectorChanged(a.settings.stateSelector,function(b){a.active(b)},!0),a.settings.disabledStateSelector&&c.selectorChanged(a.settings.disabledStateSelector,function(b){a.disabled(b)})}var d;"|"===a?o=null:m.has(a)?(a={type:a},n.toolbar_items_size&&(a.size=n.toolbar_items_size),r.push(a),o=null):(o||(o={type:"buttongroup",items:[]},r.push(o)),b.buttons[a]&&(d=a,a=b.buttons[d],"function"==typeof a&&(a=a()),a.type=a.type||"button",n.toolbar_items_size&&(a.size=n.toolbar_items_size),a=m.create(a),o.items.push(a),b.initialized?c():b.on("init",c)))}),i=m.create({type:"panel",layout:"stack",classes:"toolbar-grp inline-toolbar-grp",ariaRoot:!0,ariaRemember:!0,items:[{type:"toolbar",layout:"flow",items:r}]}),i.bottom=d,i.on("show",function(){this.reposition()}),i.on("keydown",function(a){27===a.keyCode&&(this.hide(),b.focus())}),b.on("remove",function(){i.remove()}),i.reposition=e,i.hide().renderTo(document.body),i}function d(a){e&&(e.tempHide||"hide"===a.type?(e.hide(),e=!1):"resizewindow"!==a.type&&"scrollwindow"!==a.type&&"resize"!==a.type&&"scroll"!==a.type||e.blockHide||(clearTimeout(i),i=setTimeout(function(){e&&"function"==typeof e.show&&(e.scrolling=!1,e.show())},250),e.scrolling=!0,e.hide()))}var e,f,i,j,k,l,m=a.ui.Factory,n=b.settings,o=b.getContainer(),p=document.getElementById("wpadminbar"),q=document.getElementById(b.id+"_ifr");o&&(j=a.$(".mce-toolbar-grp",o)[0],k=a.$(".mce-statusbar",o)[0]),"content"===b.id&&(l=document.getElementById("post-status-info")),b.shortcuts.add("alt+119","",function(){var a;e&&(a=e.find("toolbar")[0],a&&a.focus(!0))}),b.on("nodechange",function(a){var c=b.selection.isCollapsed(),d={element:a.element,parents:a.parents,collapsed:c};b.fire("wptoolbar",d),f=d.selection||d.element,e&&e!==d.toolbar&&e.hide(),d.toolbar?(e=d.toolbar,e.visible()?e.reposition():e.show()):e=!1}),b.on("focus",function(){e&&e.show()}),b.on("resizewindow scrollwindow",d),b.dom.bind(b.getWin(),"resize scroll",d),b.on("remove",function(){b.off("resizewindow scrollwindow",d),b.dom.unbind(b.getWin(),"resize scroll",d)}),b.on("blur hide",d),b.wp=b.wp||{},b.wp._createToolbar=c},!0),{_showButtons:d,_hideButtons:d,_setEmbed:d,_getEmbed:d}})}(window.tinymce);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/js/nav-menu.min.js
1
var wpNavMenu;!function(a){var b;b=wpNavMenu={options:{menuItemDepthPerLevel:30,globalMaxDepth:11,sortableItems:"> *",targetTolerance:0},menuList:void 0,targetList:void 0,menusChanged:!1,isRTL:!("undefined"==typeof isRtl||!isRtl),negateIfRTL:"undefined"!=typeof isRtl&&isRtl?-1:1,lastSearch:"",init:function(){b.menuList=a("#menu-to-edit"),b.targetList=b.menuList,this.jQueryExtensions(),this.attachMenuEditListeners(),this.attachQuickSearchListeners(),this.attachThemeLocationsListeners(),this.attachMenuSaveSubmitListeners(),this.attachTabsPanelListeners(),this.attachUnsavedChangesListener(),b.menuList.length&&this.initSortables(),menus.oneThemeLocationNoMenus&&a("#posttype-page").addSelectedToMenu(b.addMenuItemToBottom),this.initManageLocations(),this.initAccessibility(),this.initToggles(),this.initPreviewing()},jQueryExtensions:function(){a.fn.extend({menuItemDepth:function(){var a=b.isRTL?this.eq(0).css("margin-right"):this.eq(0).css("margin-left");return b.pxToDepth(a&&-1!=a.indexOf("px")?a.slice(0,-2):0)},updateDepthClass:function(b,c){return this.each(function(){var d=a(this);c=c||d.menuItemDepth(),a(this).removeClass("menu-item-depth-"+c).addClass("menu-item-depth-"+b)})},shiftDepthClass:function(b){return this.each(function(){var c=a(this),d=c.menuItemDepth(),e=d+b;c.removeClass("menu-item-depth-"+d).addClass("menu-item-depth-"+e),0===e&&c.find(".is-submenu").hide()})},childMenuItems:function(){var b=a();return this.each(function(){for(var c=a(this),d=c.menuItemDepth(),e=c.next(".menu-item");e.length&&e.menuItemDepth()>d;)b=b.add(e),e=e.next(".menu-item")}),b},shiftHorizontally:function(b){return this.each(function(){var c=a(this),d=c.menuItemDepth(),e=d+b;c.moveHorizontally(e,d)})},moveHorizontally:function(b,c){return this.each(function(){var d=a(this),e=d.childMenuItems(),f=b-c,g=d.find(".is-submenu");d.updateDepthClass(b,c).updateParentMenuItemDBId(),e&&e.each(function(){var b=a(this),c=b.menuItemDepth(),d=c+f;b.updateDepthClass(d,c).updateParentMenuItemDBId()}),0===b?g.hide():g.show()})},updateParentMenuItemDBId:function(){return this.each(function(){var b=a(this),c=b.find(".menu-item-data-parent-id"),d=parseInt(b.menuItemDepth(),10),e=d-1,f=b.prevAll(".menu-item-depth-"+e).first();0===d?c.val(0):c.val(f.find(".menu-item-data-db-id").val())})},hideAdvancedMenuItemFields:function(){return this.each(function(){var b=a(this);a(".hide-column-tog").not(":checked").each(function(){b.find(".field-"+a(this).val()).addClass("hidden-field")})})},addSelectedToMenu:function(c){return 0!==a("#menu-to-edit").length&&this.each(function(){var d=a(this),e={},f=menus.oneThemeLocationNoMenus&&0===d.find(".tabs-panel-active .categorychecklist li input:checked").length?d.find('#page-all li input[type="checkbox"]'):d.find(".tabs-panel-active .categorychecklist li input:checked"),g=/menu-item\[([^\]]*)/;return c=c||b.addMenuItemToBottom,!!f.length&&(d.find(".button-controls .spinner").addClass("is-active"),a(f).each(function(){var d=a(this),f=g.exec(d.attr("name")),h="undefined"==typeof f[1]?0:parseInt(f[1],10);this.className&&-1!=this.className.indexOf("add-to-top")&&(c=b.addMenuItemToTop),e[h]=d.closest("li").getItemData("add-menu-item",h)}),void b.addItemToMenu(e,c,function(){f.removeAttr("checked"),d.find(".button-controls .spinner").removeClass("is-active")}))})},getItemData:function(a,b){a=a||"menu-item";var c,d={},e=["menu-item-db-id","menu-item-object-id","menu-item-object","menu-item-parent-id","menu-item-position","menu-item-type","menu-item-title","menu-item-url","menu-item-description","menu-item-attr-title","menu-item-target","menu-item-classes","menu-item-xfn"];return b||"menu-item"!=a||(b=this.find(".menu-item-data-db-id").val()),b?(this.find("input").each(function(){var f;for(c=e.length;c--;)"menu-item"==a?f=e[c]+"["+b+"]":"add-menu-item"==a&&(f="menu-item["+b+"]["+e[c]+"]"),this.name&&f==this.name&&(d[e[c]]=this.value)}),d):d},setItemData:function(b,c,d){return c=c||"menu-item",d||"menu-item"!=c||(d=a(".menu-item-data-db-id",this).val()),d?(this.find("input").each(function(){var e,f=a(this);a.each(b,function(a,b){"menu-item"==c?e=a+"["+d+"]":"add-menu-item"==c&&(e="menu-item["+d+"]["+a+"]"),e==f.attr("name")&&f.val(b)})}),this):this}})},countMenuItems:function(b){return a(".menu-item-depth-"+b).length},moveMenuItem:function(c,d){var e,f,g,h=a("#menu-to-edit li"),i=h.length,j=c.parents("li.menu-item"),k=j.childMenuItems(),l=j.getItemData(),m=parseInt(j.menuItemDepth(),10),n=parseInt(j.index(),10),o=j.next(),p=o.childMenuItems(),q=parseInt(o.menuItemDepth(),10)+1,r=j.prev(),s=parseInt(r.menuItemDepth(),10),t=r.getItemData()["menu-item-db-id"];switch(d){case"up":if(f=n-1,0===n)break;0===f&&0!==m&&j.moveHorizontally(0,m),0!==s&&j.moveHorizontally(s,m),k?(e=j.add(k),e.detach().insertBefore(h.eq(f)).updateParentMenuItemDBId()):j.detach().insertBefore(h.eq(f)).updateParentMenuItemDBId();break;case"down":if(k){if(e=j.add(k),o=h.eq(e.length+n),p=0!==o.childMenuItems().length,p&&(g=parseInt(o.menuItemDepth(),10)+1,j.moveHorizontally(g,m)),i===n+e.length)break;e.detach().insertAfter(h.eq(n+e.length)).updateParentMenuItemDBId()}else{if(0!==p.length&&j.moveHorizontally(q,m),i===n+1)break;j.detach().insertAfter(h.eq(n+1)).updateParentMenuItemDBId()}break;case"top":if(0===n)break;k?(e=j.add(k),e.detach().insertBefore(h.eq(0)).updateParentMenuItemDBId()):j.detach().insertBefore(h.eq(0)).updateParentMenuItemDBId();break;case"left":if(0===m)break;j.shiftHorizontally(-1);break;case"right":if(0===n)break;if(l["menu-item-parent-id"]===t)break;j.shiftHorizontally(1)}c.focus(),b.registerChange(),b.refreshKeyboardAccessibility(),b.refreshAdvancedAccessibility()},initAccessibility:function(){var c=a("#menu-to-edit");b.refreshKeyboardAccessibility(),b.refreshAdvancedAccessibility(),c.on("mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility",".menu-item",function(){b.refreshAdvancedAccessibilityOfItem(a(this).find("a.item-edit"))}),c.on("click","a.item-edit",function(){b.refreshAdvancedAccessibilityOfItem(a(this))}),c.on("click",".menus-move",function(){var c=a(this),d=c.data("dir");"undefined"!=typeof d&&b.moveMenuItem(a(this).parents("li.menu-item").find("a.item-edit"),d)})},refreshAdvancedAccessibilityOfItem:function(b){if(!0===a(b).data("needs_accessibility_refresh")){var c,d,e,f,g,h,i,j,k,l=a(b),m=l.closest("li.menu-item").first(),n=m.menuItemDepth(),o=0===n,p=l.closest(".menu-item-handle").find(".menu-item-title").text(),q=parseInt(m.index(),10),r=o?n:parseInt(n-1,10),s=m.prevAll(".menu-item-depth-"+r).first().find(".menu-item-title").text(),t=m.prevAll(".menu-item-depth-"+n).first().find(".menu-item-title").text(),u=a("#menu-to-edit li").length,v=m.nextAll(".menu-item-depth-"+n).length;m.find(".field-move").toggle(u>1),0!==q&&(c=m.find(".menus-move-up"),c.attr("aria-label",menus.moveUp).css("display","inline")),0!==q&&o&&(c=m.find(".menus-move-top"),c.attr("aria-label",menus.moveToTop).css("display","inline")),q+1!==u&&0!==q&&(c=m.find(".menus-move-down"),c.attr("aria-label",menus.moveDown).css("display","inline")),0===q&&0!==v&&(c=m.find(".menus-move-down"),c.attr("aria-label",menus.moveDown).css("display","inline")),o||(c=m.find(".menus-move-left"),d=menus.outFrom.replace("%s",s),c.attr("aria-label",menus.moveOutFrom.replace("%s",s)).text(d).css("display","inline")),0!==q&&m.find(".menu-item-data-parent-id").val()!==m.prev().find(".menu-item-data-db-id").val()&&(c=m.find(".menus-move-right"),d=menus.under.replace("%s",t),c.attr("aria-label",menus.moveUnder.replace("%s",t)).text(d).css("display","inline")),o?(e=a(".menu-item-depth-0"),f=e.index(m)+1,u=e.length,g=menus.menuFocus.replace("%1$s",p).replace("%2$d",f).replace("%3$d",u)):(h=m.prevAll(".menu-item-depth-"+parseInt(n-1,10)).first(),i=h.find(".menu-item-data-db-id").val(),j=h.find(".menu-item-title").text(),k=a('.menu-item .menu-item-data-parent-id[value="'+i+'"]'),f=a(k.parents(".menu-item").get().reverse()).index(m)+1,g=menus.subMenuFocus.replace("%1$s",p).replace("%2$d",f).replace("%3$s",j)),l.attr("aria-label",g).text(g),l.data("needs_accessibility_refresh",!1)}},refreshAdvancedAccessibility:function(){a(".menu-item-settings .field-move .menus-move").hide(),a("a.item-edit").data("needs_accessibility_refresh",!0),a(".menu-item-edit-active a.item-edit").each(function(){b.refreshAdvancedAccessibilityOfItem(this)})},refreshKeyboardAccessibility:function(){a("a.item-edit").off("focus").on("focus",function(){a(this).off("keydown").on("keydown",function(c){var d,e=a(this),f=e.parents("li.menu-item"),g=f.getItemData();if((37==c.which||38==c.which||39==c.which||40==c.which)&&(e.off("keydown"),1!==a("#menu-to-edit li").length)){switch(d={38:"up",40:"down",37:"left",39:"right"},a("body").hasClass("rtl")&&(d={38:"up",40:"down",39:"left",37:"right"}),d[c.which]){case"up":b.moveMenuItem(e,"up");break;case"down":b.moveMenuItem(e,"down");break;case"left":b.moveMenuItem(e,"left");break;case"right":b.moveMenuItem(e,"right")}return a("#edit-"+g["menu-item-db-id"]).focus(),!1}})})},initPreviewing:function(){a("#menu-to-edit").on("change input",".edit-menu-item-title",function(b){var c,d,e=a(b.currentTarget);c=e.val(),d=e.closest(".menu-item").find(".menu-item-title"),c?d.text(c).removeClass("no-title"):d.text(navMenuL10n.untitled).addClass("no-title")})},initToggles:function(){postboxes.add_postbox_toggles("nav-menus"),columns.useCheckboxesForHidden(),columns.checked=function(b){a(".field-"+b).removeClass("hidden-field")},columns.unchecked=function(b){a(".field-"+b).addClass("hidden-field")},b.menuList.hideAdvancedMenuItemFields(),a(".hide-postbox-tog").click(function(){var b=a(".accordion-container li.accordion-section").filter(":hidden").map(function(){return this.id}).get().join(",");a.post(ajaxurl,{action:"closed-postboxes",hidden:b,closedpostboxesnonce:jQuery("#closedpostboxesnonce").val(),page:"nav-menus"})})},initSortables:function(){function c(a){var c;j=a.placeholder.prev(".menu-item"),k=a.placeholder.next(".menu-item"),j[0]==a.item[0]&&(j=j.prev(".menu-item")),k[0]==a.item[0]&&(k=k.next(".menu-item")),l=j.length?j.offset().top+j.height():0,m=k.length?k.offset().top+k.height()/3:0,h=k.length?k.menuItemDepth():0,i=j.length?(c=j.menuItemDepth()+1)>b.options.globalMaxDepth?b.options.globalMaxDepth:c:0}function d(a,b){a.placeholder.updateDepthClass(b,q),q=b}function e(){if(!s[0].className)return 0;var a=s[0].className.match(/menu-max-depth-(\d+)/);return a&&a[1]?parseInt(a[1],10):0}function f(c){var d,e=t;if(0!==c){if(c>0)d=p+c,d>t&&(e=d);else if(c<0&&p==t)for(;!a(".menu-item-depth-"+e,b.menuList).length&&e>0;)e--;s.removeClass("menu-max-depth-"+t).addClass("menu-max-depth-"+e),t=e}}var g,h,i,j,k,l,m,n,o,p,q=0,r=b.menuList.offset().left,s=a("body"),t=e();0!==a("#menu-to-edit li").length&&a(".drag-instructions").show(),r+=b.isRTL?b.menuList.width():0,b.menuList.sortable({handle:".menu-item-handle",placeholder:"sortable-placeholder",items:b.options.sortableItems,start:function(e,f){var h,i,j,k,l;b.isRTL&&(f.item[0].style.right="auto"),o=f.item.children(".menu-item-transport"),g=f.item.menuItemDepth(),d(f,g),j=f.item.next()[0]==f.placeholder[0]?f.item.next():f.item,k=j.childMenuItems(),o.append(k),h=o.outerHeight(),h+=h>0?1*f.placeholder.css("margin-top").slice(0,-2):0,h+=f.helper.outerHeight(),n=h,h-=2,f.placeholder.height(h),p=g,k.each(function(){var b=a(this).menuItemDepth();p=b>p?b:p}),i=f.helper.find(".menu-item-handle").outerWidth(),i+=b.depthToPx(p-g),i-=2,f.placeholder.width(i),l=f.placeholder.next(".menu-item"),l.css("margin-top",n+"px"),f.placeholder.detach(),a(this).sortable("refresh"),f.item.after(f.placeholder),l.css("margin-top",0),c(f)},stop:function(a,c){var d,e,h=q-g;d=o.children().insertAfter(c.item),e=c.item.find(".item-title .is-submenu"),0<q?e.show():e.hide(),0!==h&&(c.item.updateDepthClass(q),d.shiftDepthClass(h),f(h)),b.registerChange(),c.item.updateParentMenuItemDBId(),c.item[0].style.top=0,b.isRTL&&(c.item[0].style.left="auto",c.item[0].style.right=0),b.refreshKeyboardAccessibility(),b.refreshAdvancedAccessibility()},change:function(a,d){d.placeholder.parent().hasClass("menu")||(j.length?j.after(d.placeholder):b.menuList.prepend(d.placeholder)),c(d)},sort:function(e,f){var g=f.helper.offset(),j=b.isRTL?g.left+f.helper.width():g.left,o=b.negateIfRTL*b.pxToDepth(j-r);o>i||g.top<l-b.options.targetTolerance?o=i:o<h&&(o=h),o!=q&&d(f,o),m&&g.top+n>m&&(k.after(f.placeholder),c(f),a(this).sortable("refreshPositions"))}})},initManageLocations:function(){a("#menu-locations-wrap form").submit(function(){window.onbeforeunload=null}),a(".menu-location-menus select").on("change",function(){var b=a(this).closest("tr").find(".locations-edit-menu-link");a(this).find("option:selected").data("orig")?b.show():b.hide()})},attachMenuEditListeners:function(){var b=this;a("#update-nav-menu").bind("click",function(a){if(a.target&&a.target.className){if(-1!=a.target.className.indexOf("item-edit"))return b.eventOnClickEditLink(a.target);if(-1!=a.target.className.indexOf("menu-save"))return b.eventOnClickMenuSave(a.target);if(-1!=a.target.className.indexOf("menu-delete"))return b.eventOnClickMenuDelete(a.target);if(-1!=a.target.className.indexOf("item-delete"))return b.eventOnClickMenuItemDelete(a.target);if(-1!=a.target.className.indexOf("item-cancel"))return b.eventOnClickCancelLink(a.target)}}),a('#add-custom-links input[type="text"]').keypress(function(b){a("#customlinkdiv").removeClass("form-invalid"),13===b.keyCode&&(b.preventDefault(),a("#submit-customlinkdiv").click())})},attachMenuSaveSubmitListeners:function(){a("#update-nav-menu").submit(function(){var b=a("#update-nav-menu").serializeArray();a('[name="nav-menu-data"]').val(JSON.stringify(b))})},attachThemeLocationsListeners:function(){var b=a("#nav-menu-theme-locations"),c={};c.action="menu-locations-save",c["menu-settings-column-nonce"]=a("#menu-settings-column-nonce").val(),b.find('input[type="submit"]').click(function(){return b.find("select").each(function(){c[this.name]=a(this).val()}),b.find(".spinner").addClass("is-active"),a.post(ajaxurl,c,function(){b.find(".spinner").removeClass("is-active")}),!1})},attachQuickSearchListeners:function(){var c,d;a("#nav-menu-meta").on("submit",function(a){a.preventDefault()}),d="oninput"in document.createElement("input")?"input":"keyup",a("#nav-menu-meta").on(d,".quick-search",function(){var d=a(this);d.attr("autocomplete","off"),c&&clearTimeout(c),c=setTimeout(function(){b.updateQuickSearchResults(d)},500)}).on("blur",".quick-search",function(){b.lastSearch=""})},updateQuickSearchResults:function(c){var d,e,f=2,g=c.val();g.length<f||b.lastSearch==g||(b.lastSearch=g,d=c.parents(".tabs-panel"),e={action:"menu-quick-search","response-format":"markup",menu:a("#menu").val(),"menu-settings-column-nonce":a("#menu-settings-column-nonce").val(),q:g,type:c.attr("name")},a(".spinner",d).addClass("is-active"),a.post(ajaxurl,e,function(a){b.processQuickSearchQueryResponse(a,e,d)}))},addCustomLink:function(c){var d=a("#custom-menu-item-url").val(),e=a("#custom-menu-item-name").val();return c=c||b.addMenuItemToBottom,""===d||"http://"==d?(a("#customlinkdiv").addClass("form-invalid"),!1):(a(".customlinkdiv .spinner").addClass("is-active"),void this.addLinkToMenu(d,e,c,function(){a(".customlinkdiv .spinner").removeClass("is-active"),a("#custom-menu-item-name").val("").blur(),a("#custom-menu-item-url").val("http://")}))},addLinkToMenu:function(a,c,d,e){d=d||b.addMenuItemToBottom,e=e||function(){},b.addItemToMenu({"-1":{"menu-item-type":"custom","menu-item-url":a,"menu-item-title":c}},d,e)},addItemToMenu:function(b,c,d){var e,f=a("#menu").val(),g=a("#menu-settings-column-nonce").val();c=c||function(){},d=d||function(){},e={action:"add-menu-item",menu:f,"menu-settings-column-nonce":g,"menu-item":b},a.post(ajaxurl,e,function(b){var f=a("#menu-instructions");b=a.trim(b),c(b,e),a("li.pending").hide().fadeIn("slow"),a(".drag-instructions").show(),!f.hasClass("menu-instructions-inactive")&&f.siblings().length&&f.addClass("menu-instructions-inactive"),d()})},addMenuItemToBottom:function(c){var d=a(c);d.hideAdvancedMenuItemFields().appendTo(b.targetList),b.refreshKeyboardAccessibility(),b.refreshAdvancedAccessibility(),a(document).trigger("menu-item-added",[d])},addMenuItemToTop:function(c){var d=a(c);d.hideAdvancedMenuItemFields().prependTo(b.targetList),b.refreshKeyboardAccessibility(),b.refreshAdvancedAccessibility(),a(document).trigger("menu-item-added",[d])},attachUnsavedChangesListener:function(){a("#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select").change(function(){b.registerChange()}),0!==a("#menu-to-edit").length||0!==a(".menu-location-menus select").length?window.onbeforeunload=function(){if(b.menusChanged)return navMenuL10n.saveAlert}:a("#menu-settings-column").find("input,select").end().find("a").attr("href","#").unbind("click")},registerChange:function(){b.menusChanged=!0},attachTabsPanelListeners:function(){a("#menu-settings-column").bind("click",function(c){var d,e,f,g,h=a(c.target);if(h.hasClass("nav-tab-link"))e=h.data("type"),f=h.parents(".accordion-section-content").first(),a("input",f).removeAttr("checked"),a(".tabs-panel-active",f).removeClass("tabs-panel-active").addClass("tabs-panel-inactive"),a("#"+e,f).removeClass("tabs-panel-inactive").addClass("tabs-panel-active"),a(".tabs",f).removeClass("tabs"),h.parent().addClass("tabs"),a(".quick-search",f).focus(),f.find(".tabs-panel-active .menu-item-title").length?f.removeClass("has-no-menu-item"):f.addClass("has-no-menu-item"),c.preventDefault();else if(h.hasClass("select-all")){if(d=/#(.*)$/.exec(c.target.href),d&&d[1])return g=a("#"+d[1]+" .tabs-panel-active .menu-item-title input"),g.length===g.filter(":checked").length?g.removeAttr("checked"):g.prop("checked",!0),!1}else if(h.hasClass("submit-add-to-menu"))return b.registerChange(),c.target.id&&"submit-customlinkdiv"==c.target.id?b.addCustomLink(b.addMenuItemToBottom):c.target.id&&-1!=c.target.id.indexOf("submit-")&&a("#"+c.target.id.replace(/submit-/,"")).addSelectedToMenu(b.addMenuItemToBottom),!1}),a("#nav-menu-meta").on("click","a.page-numbers",function(){var b=a(this).closest(".inside");return a.post(ajaxurl,this.href.replace(/.*\?/,"").replace(/action=([^&]*)/,"")+"&action=menu-get-metabox",function(c){var d,e=a.parseJSON(c);-1!==c.indexOf("replace-id")&&(d=document.getElementById(e["replace-id"]),e.markup&&d&&b.html(e.markup))}),!1})},eventOnClickEditLink:function(b){var c,d,e=/#(.*)$/.exec(b.href);if(e&&e[1]&&(c=a("#"+e[1]),d=c.parent(),0!==d.length))return d.hasClass("menu-item-edit-inactive")?(c.data("menu-item-data")||c.data("menu-item-data",c.getItemData()),c.slideDown("fast"),d.removeClass("menu-item-edit-inactive").addClass("menu-item-edit-active")):(c.slideUp("fast"),d.removeClass("menu-item-edit-active").addClass("menu-item-edit-inactive")),!1},eventOnClickCancelLink:function(b){var c=a(b).closest(".menu-item-settings"),d=a(b).closest(".menu-item");return d.removeClass("menu-item-edit-active").addClass("menu-item-edit-inactive"),c.setItemData(c.data("menu-item-data")).hide(),!1},eventOnClickMenuSave:function(){var c="",d=a("#menu-name"),e=d.val();return e&&e!=d.attr("title")&&e.replace(/\s+/,"")?(a("#nav-menu-theme-locations select").each(function(){c+='<input type="hidden" name="'+this.name+'" value="'+a(this).val()+'" />'}),a("#update-nav-menu").append(c),b.menuList.find(".menu-item-data-position").val(function(a){return a+1}),window.onbeforeunload=null,!0):(d.parent().addClass("form-invalid"),!1)},eventOnClickMenuDelete:function(){return!!window.confirm(navMenuL10n.warnDeleteMenu)&&(window.onbeforeunload=null,!0)},eventOnClickMenuItemDelete:function(c){var d=parseInt(c.id.replace("delete-",""),10);return b.removeMenuItem(a("#menu-item-"+d)),b.registerChange(),!1},processQuickSearchQueryResponse:function(b,c,d){var e,f,g,h={},i=document.getElementById("nav-menu-meta"),j=/menu-item[(\[^]\]*/,k=a("<div>").html(b).find("li"),l=d.closest(".accordion-section-content");return k.length?(k.each(function(){if(g=a(this),e=j.exec(g.html()),e&&e[1]){for(f=e[1];i.elements["menu-item["+f+"][menu-item-type]"]||h[f];)f--;h[f]=!0,f!=e[1]&&g.html(g.html().replace(new RegExp("menu-item\\["+e[1]+"\\]","g"),"menu-item["+f+"]"))}}),a(".categorychecklist",d).html(k),a(".spinner",d).removeClass("is-active"),void l.removeClass("has-no-menu-item")):(a(".categorychecklist",d).html("<li><p>"+navMenuL10n.noResultsFound+"</p></li>"),a(".spinner",d).removeClass("is-active"),void l.addClass("has-no-menu-item"))},removeMenuItem:function(c){var d=c.childMenuItems();a(document).trigger("menu-removing-item",[c]),c.addClass("deleting").animate({opacity:0,height:0},350,function(){var e=a("#menu-instructions");c.remove(),d.shiftDepthClass(-1).updateParentMenuItemDBId(),0===a("#menu-to-edit li").length&&(a(".drag-instructions").hide(),e.removeClass("menu-instructions-inactive")),b.refreshAdvancedAccessibility()})},depthToPx:function(a){return a*b.options.menuItemDepthPerLevel},pxToDepth:function(a){return Math.floor(a/b.options.menuItemDepthPerLevel)}},a(document).ready(function(){wpNavMenu.init()})}(jQuery);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-includes/css/customize-preview.min.css
1
.customize-partial-refreshing{opacity:.25;-webkit-transition:opacity .25s;transition:opacity .25s;cursor:progress}.customize-partial-refreshing.widget-customizer-highlighted-widget{-webkit-box-shadow:none;box-shadow:none}.customize-partial-edit-shortcut,.widget .customize-partial-edit-shortcut{position:absolute;float:left;width:1px;height:1px;padding:0;margin:-1px 0 0 -1px;border:0;background:0 0;color:transparent;-webkit-box-shadow:none;box-shadow:none;outline:0;z-index:5}.customize-partial-edit-shortcut button,.widget .customize-partial-edit-shortcut button{position:absolute;left:-30px;top:2px;color:#fff;width:30px;height:30px;min-width:30px;min-height:30px;line-height:1em!important;font-size:18px;z-index:5;background:#0085ba!important;-webkit-border-radius:50%;border-radius:50%;border:2px solid #fff;-webkit-box-shadow:0 2px 1px rgba(46,68,83,.15);box-shadow:0 2px 1px rgba(46,68,83,.15);text-align:center;cursor:pointer;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:3px;-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-duration:.4s;animation-duration:.4s;opacity:0;pointer-events:none;text-shadow:0 -1px 1px #006799,1px 0 1px #006799,0 1px 1px #006799,-1px 0 1px #006799}.wp-custom-header .customize-partial-edit-shortcut button{left:2px}.customize-partial-edit-shortcut button svg{fill:#fff;min-width:20px;min-height:20px;width:20px;height:20px;margin:auto}.customize-partial-edit-shortcut button:hover{background:#008ec2!important}.customize-partial-edit-shortcut button:focus{-webkit-box-shadow:0 0 0 2px #008ec2;box-shadow:0 0 0 2px #008ec2}body.customize-partial-edit-shortcuts-shown .customize-partial-edit-shortcut button{-webkit-animation-name:customize-partial-edit-shortcut-bounce-appear;animation-name:customize-partial-edit-shortcut-bounce-appear;pointer-events:auto}body.customize-partial-edit-shortcuts-hidden .customize-partial-edit-shortcut button{-webkit-animation-name:customize-partial-edit-shortcut-bounce-disappear;animation-name:customize-partial-edit-shortcut-bounce-disappear;pointer-events:none}.customize-partial-edit-shortcut-hidden .customize-partial-edit-shortcut button,.page-sidebar-collapsed .customize-partial-edit-shortcut button{visibility:hidden}@-webkit-keyframes customize-partial-edit-shortcut-bounce-appear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}}@keyframes customize-partial-edit-shortcut-bounce-appear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}}@-webkit-keyframes customize-partial-edit-shortcut-bounce-disappear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}20%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}40%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}60%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}80%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}to{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}}@keyframes customize-partial-edit-shortcut-bounce-disappear{20%,40%,60%,80%,from,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:1;-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}20%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}40%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}60%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}80%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}to{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}}@media screen and (max-width:800px){.customize-partial-edit-shortcut button,.widget .customize-partial-edit-shortcut button{left:-32px}}@media screen and (max-width:320px){.customize-partial-edit-shortcut button,.widget .customize-partial-edit-shortcut button{left:-30px}}
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-admin/js/image-edit.min.js
1
!function(a){var b=window.imageEdit={iasapi:{},hold:{},postid:"",_view:!1,intval:function(a){return 0|a},setDisabled:function(a,b){b?a.removeClass("disabled").prop("disabled",!1):a.addClass("disabled").prop("disabled",!0)},init:function(b){var c=this,d=a("#image-editor-"+c.postid),e=c.intval(a("#imgedit-x-"+b).val()),f=c.intval(a("#imgedit-y-"+b).val());c.postid!==b&&d.length&&c.close(c.postid),c.hold.w=c.hold.ow=e,c.hold.h=c.hold.oh=f,c.hold.xy_ratio=e/f,c.hold.sizer=parseFloat(a("#imgedit-sizer-"+b).val()),c.postid=b,a("#imgedit-response-"+b).empty(),a('input[type="text"]',"#imgedit-panel-"+b).keypress(function(b){var c=b.keyCode;if(36<c&&c<41&&a(this).blur(),13===c)return b.preventDefault(),b.stopPropagation(),!1})},toggleEditor:function(b,c){var d=a("#imgedit-wait-"+b);c?d.fadeIn("fast"):d.fadeOut("fast")},toggleHelp:function(b){var c=a(b);return c.attr("aria-expanded","false"===c.attr("aria-expanded")?"true":"false").parents(".imgedit-group-top").toggleClass("imgedit-help-toggled").find(".imgedit-help").slideToggle("fast"),!1},getTarget:function(b){return a('input[name="imgedit-target-'+b+'"]:checked',"#imgedit-save-target-"+b).val()||"full"},scaleChanged:function(b,c,d){var e=a("#imgedit-scale-width-"+b),f=a("#imgedit-scale-height-"+b),g=a("#imgedit-scale-warn-"+b),h="",i="";!1!==this.validateNumeric(d)&&(c?(i=""!==e.val()?Math.round(e.val()/this.hold.xy_ratio):"",f.val(i)):(h=""!==f.val()?Math.round(f.val()*this.hold.xy_ratio):"",e.val(h)),i&&i>this.hold.oh||h&&h>this.hold.ow?g.css("visibility","visible"):g.css("visibility","hidden"))},getSelRatio:function(b){var c=this.hold.w,d=this.hold.h,e=this.intval(a("#imgedit-crop-width-"+b).val()),f=this.intval(a("#imgedit-crop-height-"+b).val());return e&&f?e+":"+f:c&&d?c+":"+d:"1:1"},filterHistory:function(b,c){var d,e,f,g,h=a("#imgedit-history-"+b).val(),i=[];if(""!==h){if(h=JSON.parse(h),d=this.intval(a("#imgedit-undone-"+b).val()),d>0)for(;d>0;)h.pop(),d--;if(c){if(!h.length)return this.hold.w=this.hold.ow,this.hold.h=this.hold.oh,"";f=h[h.length-1],f=f.c||f.r||f.f||!1,f&&(this.hold.w=f.fw,this.hold.h=f.fh)}for(e in h)g=h[e],g.hasOwnProperty("c")?i[e]={c:{x:g.c.x,y:g.c.y,w:g.c.w,h:g.c.h}}:g.hasOwnProperty("r")?i[e]={r:g.r.r}:g.hasOwnProperty("f")&&(i[e]={f:g.f.f});return JSON.stringify(i)}return""},refreshEditor:function(c,d,e){var f,g,h=this;h.toggleEditor(c,1),f={action:"imgedit-preview",_ajax_nonce:d,postid:c,history:h.filterHistory(c,1),rand:h.intval(1e6*Math.random())},g=a('<img id="image-preview-'+c+'" alt="" />').on("load",{history:f.history},function(d){var f,h,i,j=a("#imgedit-crop-"+c),k=b;""!==d.data.history&&(i=JSON.parse(d.data.history),i[i.length-1].hasOwnProperty("c")&&(k.setDisabled(a("#image-undo-"+c),!0),a("#image-undo-"+c).focus())),j.empty().append(g),f=Math.max(k.hold.w,k.hold.h),h=Math.max(a(g).width(),a(g).height()),k.hold.sizer=f>h?h/f:1,k.initCrop(c,g,j),k.setCropSelection(c,0),"undefined"!=typeof e&&null!==e&&e(),a("#imgedit-history-"+c).val()&&"0"===a("#imgedit-undone-"+c).val()?a("input.imgedit-submit-btn","#imgedit-panel-"+c).removeAttr("disabled"):a("input.imgedit-submit-btn","#imgedit-panel-"+c).prop("disabled",!0),k.toggleEditor(c,0)}).on("error",function(){a("#imgedit-crop-"+c).empty().append('<div class="error"><p>'+imageEditL10n.error+"</p></div>"),h.toggleEditor(c,0)}).attr("src",ajaxurl+"?"+a.param(f))},action:function(b,c,d){var e,f,g,h,i,j=this;if(j.notsaved(b))return!1;if(e={action:"image-editor",_ajax_nonce:c,postid:b},"scale"===d){if(f=a("#imgedit-scale-width-"+b),g=a("#imgedit-scale-height-"+b),h=j.intval(f.val()),i=j.intval(g.val()),h<1)return f.focus(),!1;if(i<1)return g.focus(),!1;if(h===j.hold.ow||i===j.hold.oh)return!1;e["do"]="scale",e.fwidth=h,e.fheight=i}else{if("restore"!==d)return!1;e["do"]="restore"}j.toggleEditor(b,1),a.post(ajaxurl,e,function(c){a("#image-editor-"+b).empty().append(c),j.toggleEditor(b,0),j._view&&j._view.refresh()})},save:function(c,d){var e,f=this.getTarget(c),g=this.filterHistory(c,0),h=this;return""!==g&&(this.toggleEditor(c,1),e={action:"image-editor",_ajax_nonce:d,postid:c,history:g,target:f,context:a("#image-edit-context").length?a("#image-edit-context").val():null,"do":"save"},void a.post(ajaxurl,e,function(d){var e=JSON.parse(d);return e.error?(a("#imgedit-response-"+c).html('<div class="error"><p>'+e.error+"</p></div>"),void b.close(c)):(e.fw&&e.fh&&a("#media-dims-"+c).html(e.fw+" &times; "+e.fh),e.thumbnail&&a(".thumbnail","#thumbnail-head-"+c).attr("src",""+e.thumbnail),e.msg&&a("#imgedit-response-"+c).html('<div class="updated"><p>'+e.msg+"</p></div>"),void(h._view?h._view.save():b.close(c)))}))},open:function(c,d,e){this._view=e;var f,g,h=a("#image-editor-"+c),i=a("#media-head-"+c),j=a("#imgedit-open-btn-"+c),k=j.siblings(".spinner");if(!j.hasClass("button-activated"))return k.addClass("is-active"),g={action:"image-editor",_ajax_nonce:d,postid:c,"do":"open"},f=a.ajax({url:ajaxurl,type:"post",data:g,beforeSend:function(){j.addClass("button-activated")}}).done(function(a){h.html(a),i.fadeOut("fast",function(){h.fadeIn("fast"),j.removeClass("button-activated"),k.removeClass("is-active")}),b.init(c)})},imgLoaded:function(b){var c=a("#image-preview-"+b),d=a("#imgedit-crop-"+b);"undefined"==typeof this.hold.sizer&&this.init(b),this.initCrop(b,c,d),this.setCropSelection(b,0),this.toggleEditor(b,0),a(".imgedit-wrap .imgedit-help-toggle").eq(0).focus()},initCrop:function(c,d,e){var f,g=this,h=a("#imgedit-sel-width-"+c),i=a("#imgedit-sel-height-"+c);g.iasapi=a(d).imgAreaSelect({parent:e,instance:!0,handles:!0,keys:!0,minWidth:3,minHeight:3,onInit:function(b){f=a(b),f.next().css("position","absolute").nextAll(".imgareaselect-outer").css("position","absolute"),e.children().mousedown(function(a){var b,d,e=!1;a.shiftKey&&(b=g.iasapi.getSelection(),d=g.getSelRatio(c),e=b&&b.width&&b.height?b.width+":"+b.height:d),g.iasapi.setOptions({aspectRatio:e})})},onSelectStart:function(){b.setDisabled(a("#imgedit-crop-sel-"+c),1)},onSelectEnd:function(a,d){b.setCropSelection(c,d)},onSelectChange:function(a,c){var d=b.hold.sizer;h.val(b.round(c.width/d)),i.val(b.round(c.height/d))}})},setCropSelection:function(b,c){var d;return c=c||0,!c||c.width<3&&c.height<3?(this.setDisabled(a(".imgedit-crop","#imgedit-panel-"+b),0),this.setDisabled(a("#imgedit-crop-sel-"+b),0),a("#imgedit-sel-width-"+b).val(""),a("#imgedit-sel-height-"+b).val(""),a("#imgedit-selection-"+b).val(""),!1):(d={x:c.x1,y:c.y1,w:c.width,h:c.height},this.setDisabled(a(".imgedit-crop","#imgedit-panel-"+b),1),void a("#imgedit-selection-"+b).val(JSON.stringify(d)))},close:function(b,c){return c=c||!1,(!c||!this.notsaved(b))&&(this.iasapi={},this.hold={},void(this._view?this._view.back():a("#image-editor-"+b).fadeOut("fast",function(){a("#media-head-"+b).fadeIn("fast",function(){a("#imgedit-open-btn-"+b).focus()}),a(this).empty()})))},notsaved:function(b){var c=a("#imgedit-history-"+b).val(),d=""!==c?JSON.parse(c):[],e=this.intval(a("#imgedit-undone-"+b).val());return e<d.length&&!confirm(a("#imgedit-leaving-"+b).html())},addStep:function(b,c,d){for(var e=this,f=a("#imgedit-history-"+c),g=""!==f.val()?JSON.parse(f.val()):[],h=a("#imgedit-undone-"+c),i=e.intval(h.val());i>0;)g.pop(),i--;h.val(0),g.push(b),f.val(JSON.stringify(g)),e.refreshEditor(c,d,function(){e.setDisabled(a("#image-undo-"+c),!0),e.setDisabled(a("#image-redo-"+c),!1)})},rotate:function(b,c,d,e){return!a(e).hasClass("disabled")&&void this.addStep({r:{r:b,fw:this.hold.h,fh:this.hold.w}},c,d)},flip:function(b,c,d,e){return!a(e).hasClass("disabled")&&void this.addStep({f:{f:b,fw:this.hold.w,fh:this.hold.h}},c,d)},crop:function(b,c,d){var e=a("#imgedit-selection-"+b).val(),f=this.intval(a("#imgedit-sel-width-"+b).val()),g=this.intval(a("#imgedit-sel-height-"+b).val());return!a(d).hasClass("disabled")&&""!==e&&(e=JSON.parse(e),void(e.w>0&&e.h>0&&f>0&&g>0&&(e.fw=f,e.fh=g,this.addStep({c:e},b,c))))},undo:function(b,c){var d=this,e=a("#image-undo-"+b),f=a("#imgedit-undone-"+b),g=d.intval(f.val())+1;e.hasClass("disabled")||(f.val(g),d.refreshEditor(b,c,function(){var c=a("#imgedit-history-"+b),f=""!==c.val()?JSON.parse(c.val()):[];d.setDisabled(a("#image-redo-"+b),!0),d.setDisabled(e,g<f.length),f.length===g&&a("#image-redo-"+b).focus()}))},redo:function(b,c){var d=this,e=a("#image-redo-"+b),f=a("#imgedit-undone-"+b),g=d.intval(f.val())-1;e.hasClass("disabled")||(f.val(g),d.refreshEditor(b,c,function(){d.setDisabled(a("#image-undo-"+b),!0),d.setDisabled(e,g>0),0===g&&a("#image-undo-"+b).focus()}))},setNumSelection:function(b,c){var d,e,f,g,h,i=a("#imgedit-sel-width-"+b),j=a("#imgedit-sel-height-"+b),k=this.intval(i.val()),l=this.intval(j.val()),m=a("#image-preview-"+b),n=m.height(),o=m.width(),p=this.hold.sizer,q=this.iasapi;if(!1!==this.validateNumeric(c))return k<1?(i.val(""),!1):l<1?(j.val(""),!1):void(k&&l&&(d=q.getSelection())&&(g=d.x1+Math.round(k*p),h=d.y1+Math.round(l*p),e=d.x1,f=d.y1,g>o&&(e=0,g=o,i.val(Math.round(g/p))),h>n&&(f=0,h=n,j.val(Math.round(h/p))),q.setSelection(e,f,g,h),q.update(),this.setCropSelection(b,q.getSelection())))},round:function(a){var b;return a=Math.round(a),this.hold.sizer>.6?a:(b=a.toString().slice(-1),"1"===b?a-1:"9"===b?a+1:a)},setRatioSelection:function(b,c,d){var e,f,g=this.intval(a("#imgedit-crop-width-"+b).val()),h=this.intval(a("#imgedit-crop-height-"+b).val()),i=a("#image-preview-"+b).height();!1!==this.validateNumeric(d)&&g&&h&&(this.iasapi.setOptions({aspectRatio:g+":"+h}),(e=this.iasapi.getSelection(!0))&&(f=Math.ceil(e.y1+(e.x2-e.x1)/(g/h)),f>i&&(f=i,c?a("#imgedit-crop-height-"+b).val(""):a("#imgedit-crop-width-"+b).val("")),this.iasapi.setSelection(e.x1,e.y1,e.x2,f),this.iasapi.update()))},validateNumeric:function(b){if(!this.intval(a(b).val()))return a(b).val(""),!1}}}(jQuery);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-includes/js/mce-view.min.js
1
!function(a,b,c,d){"use strict";var e={},f={};b.mce=b.mce||{},b.mce.views={register:function(a,c){e[a]=b.mce.View.extend(_.extend(c,{type:a}))},unregister:function(a){delete e[a]},get:function(a){return e[a]},unbind:function(){_.each(f,function(a){a.unbind()})},setMarkers:function(a){var b,c,d=[{content:a}],f=this;return _.each(e,function(a,e){c=d.slice(),d=[],_.each(c,function(c){var g,h,i=c.content;if(c.processed)return void d.push(c);for(;i&&(g=a.prototype.match(i));)g.index&&d.push({content:i.substring(0,g.index)}),b=f.createInstance(e,g.content,g.options),h=b.loader?".":b.text,d.push({content:b.ignore?h:'<p data-wpview-marker="'+b.encodedText+'">'+h+"</p>",processed:!0}),i=i.slice(g.index+g.content.length);i&&d.push({content:i})})}),a=_.pluck(d,"content").join(""),a.replace(/<p>\s*<p data-wpview-marker=/g,"<p data-wpview-marker=").replace(/<\/p>\s*<\/p>/g,"</p>")},createInstance:function(a,b,c,d){var e,g,h=this.get(a);return b=tinymce.DOM.decode(b),b.indexOf("[")!==-1&&b.indexOf("]")!==-1&&(b=b.replace(/\[[^\]]+\]/g,function(a){return a.replace(/[\r\n]/g,"")})),!d&&(g=this.getInstance(b))?g:(e=encodeURIComponent(b),c=_.extend(c||{},{text:b,encodedText:e}),f[e]=new h(c))},getInstance:function(a){return"string"==typeof a?f[encodeURIComponent(a)]:f[d(a).attr("data-wpview-text")]},getText:function(a){return decodeURIComponent(d(a).attr("data-wpview-text")||"")},render:function(a){_.each(f,function(b){b.render(null,a)})},update:function(a,b,c,d){var e=this.getInstance(c);e&&e.update(a,b,c,d)},edit:function(a,b){var c=this.getInstance(b);c&&c.edit&&c.edit(c.text,function(d,e){c.update(d,a,b,e)})},remove:function(a,b){var c=this.getInstance(b);c&&c.remove(a,b)}},b.mce.View=function(a){_.extend(this,a),this.initialize()},b.mce.View.extend=Backbone.View.extend,_.extend(b.mce.View.prototype,{content:null,loader:!0,initialize:function(){},getContent:function(){return this.content},render:function(a,b){null!=a&&(this.content=a),a=this.getContent(),(this.loader||a)&&(b&&this.unbind(),this.replaceMarkers(),a?this.setContent(a,function(a,b){d(b).data("rendered",!0),this.bindNode.call(this,a,b)},!!b&&null):this.setLoader())},bindNode:function(){},unbindNode:function(){},unbind:function(){this.getNodes(function(a,b){this.unbindNode.call(this,a,b)},!0)},getEditors:function(a){_.each(tinymce.editors,function(b){b.plugins.wpview&&a.call(this,b)},this)},getNodes:function(a,b){this.getEditors(function(c){var e=this;d(c.getBody()).find('[data-wpview-text="'+e.encodedText+'"]').filter(function(){var a;return null==b||(a=d(this).data("rendered")===!0,b?a:!a)}).each(function(){a.call(e,c,this,this)})})},getMarkers:function(a){this.getEditors(function(b){var c=this;d(b.getBody()).find('[data-wpview-marker="'+this.encodedText+'"]').each(function(){a.call(c,b,this)})})},replaceMarkers:function(){this.getMarkers(function(a,b){var c,e=b===a.selection.getNode();return this.loader||d(b).text()===this.text?(c=a.$('<div class="wpview wpview-wrap" data-wpview-text="'+this.encodedText+'" data-wpview-type="'+this.type+'" contenteditable="false"></div>'),a.$(b).replaceWith(c),void(e&&setTimeout(function(){a.selection.select(c[0]),a.selection.collapse()}))):void a.dom.setAttrib(b,"data-wpview-marker",null)})},removeMarkers:function(){this.getMarkers(function(a,b){a.dom.setAttrib(b,"data-wpview-marker",null)})},setContent:function(a,b,c){_.isObject(a)&&(a.sandbox||a.head||a.body.indexOf("<script")!==-1)?this.setIframes(a.head||"",a.body,b,c):_.isString(a)&&a.indexOf("<script")!==-1?this.setIframes("",a,b,c):this.getNodes(function(c,d){a=a.body||a,a.indexOf("<iframe")!==-1&&(a+='<span class="mce-shim"></span>'),c.undoManager.transact(function(){d.innerHTML="",d.appendChild(_.isString(a)?c.dom.createFragment(a):a),c.dom.add(d,"span",{"class":"wpview-end"})}),b&&b.call(this,c,d)},c)},setIframes:function(a,c,e,f){var g=this;this.getNodes(function(f,h){function i(){var a;r||l.contentWindow&&(a=d(l),g.iframeHeight=d(n.body).height(),a.height()!==g.iframeHeight&&(a.height(g.iframeHeight),f.nodeChanged()))}function j(){f.isHidden()||(d(h).data("rendered",null),setTimeout(function(){b.mce.views.render()}))}function k(){p=new o(_.debounce(i,100)),p.observe(n.body,{attributes:!0,childList:!0,subtree:!0})}var l,m,n,o,p,q,r,s=f.dom,t="",u=f.getBody().className||"",v=f.getDoc().getElementsByTagName("head")[0];if(tinymce.each(s.$('link[rel="stylesheet"]',v),function(a){a.href&&a.href.indexOf("skins/lightgray/content.min.css")===-1&&a.href.indexOf("skins/wordpress/wp-content.css")===-1&&(t+=s.getOuterHTML(a))}),g.iframeHeight&&s.add(h,"span",{"data-mce-bogus":1,style:{display:"block",width:"100%",height:g.iframeHeight}},"\u200b"),f.undoManager.transact(function(){h.innerHTML="",l=s.add(h,"iframe",{src:tinymce.Env.ie?'javascript:""':"",frameBorder:"0",allowTransparency:"true",scrolling:"no","class":"wpview-sandbox",style:{width:"100%",display:"block"},height:g.iframeHeight}),s.add(h,"span",{"class":"mce-shim"}),s.add(h,"span",{"class":"wpview-end"})}),l.contentWindow){if(m=l.contentWindow,n=m.document,n.open(),n.write('<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'+a+t+'<style>html {background: transparent;padding: 0;margin: 0;}body#wpview-iframe-sandbox {background: transparent;padding: 1px 0 !important;margin: -1px 0 0 !important;}body#wpview-iframe-sandbox:before,body#wpview-iframe-sandbox:after {display: none;content: "";}iframe {max-width: 100%;}</style></head><body id="wpview-iframe-sandbox" class="'+u+'">'+c+"</body></html>"),n.close(),g.iframeHeight&&(r=!0,setTimeout(function(){r=!1,i()},3e3)),d(m).on("load",i).on("unload",j),o=m.MutationObserver||m.WebKitMutationObserver||m.MozMutationObserver)n.body?k():n.addEventListener("DOMContentLoaded",k,!1);else for(q=1;q<6;q++)setTimeout(i,700*q);e&&e.call(g,f,h)}},f)},setLoader:function(a){this.setContent('<div class="loading-placeholder"><div class="dashicons dashicons-'+(a||"admin-media")+'"></div><div class="wpview-loading"><ins></ins></div></div>')},setError:function(a,b){this.setContent('<div class="wpview-error"><div class="dashicons dashicons-'+(b||"no")+'"></div><p>'+a+"</p></div>")},match:function(a){var b=c.next(this.type,a);if(b)return{index:b.index,content:b.content,options:{shortcode:b.shortcode}}},update:function(a,c,f,g){_.find(e,function(e,h){var i=e.prototype.match(a);if(i)return d(f).data("rendered",!1),c.dom.setAttrib(f,"data-wpview-text",encodeURIComponent(a)),b.mce.views.createInstance(h,a,i.options,g).render(),c.focus(),!0})},remove:function(a,b){this.unbindNode.call(this,a,b),a.dom.remove(b),a.focus()}})}(window,window.wp,window.wp.shortcode,window.jQuery),function(a,b,c,d){function e(b){var c={};return a.tinymce?!b||b.indexOf("<")===-1&&b.indexOf(">")===-1?b:(j=j||new a.tinymce.html.Schema(c),k=k||new a.tinymce.html.DomParser(c,j),l=l||new a.tinymce.html.Serializer(c,j),l.serialize(k.parse(b,{forced_root_block:!1}))):b.replace(/<[^>]+>/g,"")}var f,g,h,i,j,k,l;f={state:[],edit:function(a,b){var d=this.type,e=c[d].edit(a);this.pausePlayers&&this.pausePlayers(),_.each(this.state,function(a){e.state(a).on("update",function(a){b(c[d].shortcode(a).string(),"gallery"===d)})}),e.on("close",function(){e.detach()}),e.open()}},g=_.extend({},f,{state:["gallery-edit"],template:c.template("editor-gallery"),initialize:function(){var a=c.gallery.attachments(this.shortcode,c.view.settings.post.id),b=this.shortcode.attrs.named,d=this;a.more().done(function(){a=a.toJSON(),_.each(a,function(a){a.sizes&&(b.size&&a.sizes[b.size]?a.thumbnail=a.sizes[b.size]:a.sizes.thumbnail?a.thumbnail=a.sizes.thumbnail:a.sizes.full&&(a.thumbnail=a.sizes.full))}),d.render(d.template({verifyHTML:e,attachments:a,columns:b.columns?parseInt(b.columns,10):c.galleryDefaults.columns}))}).fail(function(a,b){d.setError(b)})}}),h=_.extend({},f,{action:"parse-media-shortcode",initialize:function(){var a=this;this.url&&(this.loader=!1,this.shortcode=c.embed.shortcode({url:this.text})),wp.ajax.post(this.action,{post_ID:c.view.settings.post.id,type:this.shortcode.tag,shortcode:this.shortcode.string()}).done(function(b){a.render(b)}).fail(function(b){a.url?(a.ignore=!0,a.removeMarkers()):a.setError(b.message||b.statusText,"admin-media")}),this.getEditors(function(b){b.on("wpview-selected",function(){a.pausePlayers()})})},pausePlayers:function(){this.getNodes(function(a,b,c){var e=d("iframe.wpview-sandbox",c).get(0);e&&(e=e.contentWindow)&&e.mejs&&_.each(e.mejs.players,function(a){try{a.pause()}catch(b){}})})}}),i=_.extend({},h,{action:"parse-embed",edit:function(a,b){var d=c.embed.edit(a,this.url),e=this;this.pausePlayers(),d.state("embed").props.on("change:url",function(a,b){b&&a.get("url")&&(d.state("embed").metadata=a.toJSON())}),d.state("embed").on("select",function(){var a=d.state("embed").metadata;b(e.url?a.url:c.embed.shortcode(a).string())}),d.on("close",function(){d.detach()}),d.open()}}),b.register("gallery",_.extend({},g)),b.register("audio",_.extend({},h,{state:["audio-details"]})),b.register("video",_.extend({},h,{state:["video-details"]})),b.register("playlist",_.extend({},h,{state:["playlist-edit","video-playlist-edit"]})),b.register("embed",_.extend({},i)),b.register("embedURL",_.extend({},i,{match:function(a){var b=/(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,c=b.exec(a);if(c)return{index:c.index+c[1].length,content:c[2],options:{url:!0}}}}))}(window,window.wp.mce.views,window.wp.media,window.jQuery);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-includes/js/wp-api.min.js
1
!function(a,b){"use strict";function c(){this.models={},this.collections={},this.views={}}a.wp=a.wp||{},wp.api=wp.api||new c,wp.api.versionString=wp.api.versionString||"wp/v2/",!_.isFunction(_.includes)&&_.isFunction(_.contains)&&(_.includes=_.contains)}(window),function(a,b){"use strict";var c,d;a.wp=a.wp||{},wp.api=wp.api||{},wp.api.utils=wp.api.utils||{},Date.prototype.toISOString||(c=function(a){return d=String(a),1===d.length&&(d="0"+d),d},Date.prototype.toISOString=function(){return this.getUTCFullYear()+"-"+c(this.getUTCMonth()+1)+"-"+c(this.getUTCDate())+"T"+c(this.getUTCHours())+":"+c(this.getUTCMinutes())+":"+c(this.getUTCSeconds())+"."+String((this.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}),wp.api.utils.parseISO8601=function(a){var c,d,e,f,g=0,h=[1,4,5,6,7,10,11];if(d=/^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(a)){for(e=0;f=h[e];++e)d[f]=+d[f]||0;d[2]=(+d[2]||1)-1,d[3]=+d[3]||1,"Z"!==d[8]&&b!==d[9]&&(g=60*d[10]+d[11],"+"===d[9]&&(g=0-g)),c=Date.UTC(d[1],d[2],d[3],d[4],d[5]+g,d[6],d[7])}else c=Date.parse?Date.parse(a):NaN;return c},wp.api.utils.getRootUrl=function(){return a.location.origin?a.location.origin+"/":a.location.protocol+"/"+a.location.host+"/"},wp.api.utils.capitalize=function(a){return _.isUndefined(a)?a:a.charAt(0).toUpperCase()+a.slice(1)},wp.api.utils.extractRoutePart=function(a,b){var c;return b=b||1,a=a.replace(wp.api.versionString,""),c=a.split("/").reverse(),_.isUndefined(c[--b])?"":c[b]},wp.api.utils.extractParentName=function(a){var b,c=a.lastIndexOf("_id>[\\d]+)/");return c<0?"":(b=a.substr(0,c-1),b=b.split("/"),b.pop(),b=b.pop())},wp.api.utils.decorateFromRoute=function(a,b){_.each(a,function(a){_.includes(a.methods,"POST")||_.includes(a.methods,"PUT")?_.isEmpty(a.args)||(_.isEmpty(b.prototype.args)?b.prototype.args=a.args:b.prototype.args=_.union(a.args,b.prototype.defaults)):_.includes(a.methods,"GET")&&(_.isEmpty(a.args)||(_.isEmpty(b.prototype.options)?b.prototype.options=a.args:b.prototype.options=_.union(a.args,b.prototype.options)))})},wp.api.utils.addMixinsAndHelpers=function(a,b,c){var d=!1,e=["date","modified","date_gmt","modified_gmt"],f={setDate:function(a,b){var c=b||"date";return!(_.indexOf(e,c)<0)&&void this.set(c,a.toISOString())},getDate:function(a){var b=a||"date",c=this.get(b);return!(_.indexOf(e,b)<0||_.isNull(c))&&new Date(wp.api.utils.parseISO8601(c))}},g=function(a,b,c,d,e){var f,g,h,i;return i=jQuery.Deferred(),g=a.get("_embedded")||{},_.isNumber(b)&&0!==b?(g[d]&&(h=_.findWhere(g[d],{id:b})),h||(h={id:b}),f=new wp.api.models[c](h),f.get(e)?i.resolve(f):f.fetch({success:function(a){i.resolve(a)},error:function(a,b){i.reject(b)}}),i.promise()):(i.reject(),i)},h=function(a,b,c,d){var e,f,g,h="",j="",k=jQuery.Deferred();return e=a.get("id"),f=a.get("_embedded")||{},_.isNumber(e)&&0!==e?(_.isUndefined(c)||_.isUndefined(f[c])?h={parent:e}:j=_.isUndefined(d)?f[c]:f[c][d],g=new wp.api.collections[b](j,h),_.isUndefined(g.models[0])?g.fetch({success:function(a){i(a,e),k.resolve(a)},error:function(a,b){k.reject(b)}}):(i(g,e),k.resolve(g)),k.promise()):(k.reject(),k)},i=function(a,b){_.each(a.models,function(a){a.set("parent_post",b)})},j={getMeta:function(){return h(this,"PostMeta","https://api.w.org/meta")}},k={getRevisions:function(){return h(this,"PostRevisions")}},l={getTags:function(){var a=this.get("tags"),b=new wp.api.collections.Tags;return _.isEmpty(a)?jQuery.Deferred().resolve([]):b.fetch({data:{include:a}})},setTags:function(a){var b,c,d=this,e=[];return!_.isString(a)&&void(_.isArray(a)?(b=new wp.api.collections.Tags,b.fetch({data:{per_page:100},success:function(b){_.each(a,function(a){c=new wp.api.models.Tag(b.findWhere({slug:a})),c.set("parent_post",d.get("id")),e.push(c)}),a=new wp.api.collections.Tags(e),d.setTagsWithCollection(a)}})):this.setTagsWithCollection(a))},setTagsWithCollection:function(a){return this.set("tags",a.pluck("id")),this.save()}},m={getCategories:function(){var a=this.get("categories"),b=new wp.api.collections.Categories;return _.isEmpty(a)?jQuery.Deferred().resolve([]):b.fetch({data:{include:a}})},setCategories:function(a){var b,c,d=this,e=[];return!_.isString(a)&&void(_.isArray(a)?(b=new wp.api.collections.Categories,b.fetch({data:{per_page:100},success:function(b){_.each(a,function(a){c=new wp.api.models.Category(b.findWhere({slug:a})),c.set("parent_post",d.get("id")),e.push(c)}),a=new wp.api.collections.Categories(e),d.setCategoriesWithCollection(a)}})):this.setCategoriesWithCollection(a))},setCategoriesWithCollection:function(a){return this.set("categories",a.pluck("id")),this.save()}},n={getAuthorUser:function(){return g(this,this.get("author"),"User","author","name")}},o={getFeaturedMedia:function(){return g(this,this.get("featured_media"),"Media","wp:featuredmedia","source_url")}};return _.isUndefined(a.prototype.args)?a:(_.each(e,function(b){_.isUndefined(a.prototype.args[b])||(d=!0)}),d&&(a=a.extend(f)),_.isUndefined(a.prototype.args.author)||(a=a.extend(n)),_.isUndefined(a.prototype.args.featured_media)||(a=a.extend(o)),_.isUndefined(a.prototype.args.categories)||(a=a.extend(m)),_.isUndefined(c.collections[b+"Meta"])||(a=a.extend(j)),_.isUndefined(a.prototype.args.tags)||(a=a.extend(l)),_.isUndefined(c.collections[b+"Revisions"])||(a=a.extend(k)),a)}}(window),function(){"use strict";var a=window.wpApiSettings||{};wp.api.WPApiBaseModel=Backbone.Model.extend({sync:function(b,c,d){var e;return d=d||{},_.isNull(c.get("date_gmt"))&&c.unset("date_gmt"),_.isEmpty(c.get("slug"))&&c.unset("slug"),_.isUndefined(a.nonce)||_.isNull(a.nonce)||(e=d.beforeSend,d.beforeSend=function(b){if(b.setRequestHeader("X-WP-Nonce",a.nonce),e)return e.apply(this,arguments)}),this.requireForceForDelete&&"delete"===b&&(c.url=c.url()+"?force=true"),Backbone.sync(b,c,d)},save:function(a,b){return!(!_.includes(this.methods,"PUT")&&!_.includes(this.methods,"POST"))&&Backbone.Model.prototype.save.call(this,a,b)},destroy:function(a){return!!_.includes(this.methods,"DELETE")&&Backbone.Model.prototype.destroy.call(this,a)}}),wp.api.models.Schema=wp.api.WPApiBaseModel.extend({defaults:{_links:{},namespace:null,routes:{}},initialize:function(b,c){var d=this;c=c||{},wp.api.WPApiBaseModel.prototype.initialize.call(d,b,c),d.apiRoot=c.apiRoot||a.root,d.versionString=c.versionString||a.versionString},url:function(){return this.apiRoot+this.versionString}})}(),function(){"use strict";var a=window.wpApiSettings||{};wp.api.WPApiBaseCollection=Backbone.Collection.extend({initialize:function(a,b){this.state={data:{},currentPage:null,totalPages:null,totalObjects:null},_.isUndefined(b)?this.parent="":this.parent=b.parent},sync:function(b,c,d){var e,f,g=this;return d=d||{},e=d.beforeSend,"undefined"!=typeof a.nonce&&(d.beforeSend=function(b){if(b.setRequestHeader("X-WP-Nonce",a.nonce),e)return e.apply(g,arguments)}),"read"===b&&(d.data?(g.state.data=_.clone(d.data),delete g.state.data.page):g.state.data=d.data={},"undefined"==typeof d.data.page?(g.state.currentPage=null,g.state.totalPages=null,g.state.totalObjects=null):g.state.currentPage=d.data.page-1,f=d.success,d.success=function(a,b,c){if(_.isUndefined(c)||(g.state.totalPages=parseInt(c.getResponseHeader("x-wp-totalpages"),10),g.state.totalObjects=parseInt(c.getResponseHeader("x-wp-total"),10)),null===g.state.currentPage?g.state.currentPage=1:g.state.currentPage++,f)return f.apply(this,arguments)}),Backbone.sync(b,c,d)},more:function(a){if(a=a||{},a.data=a.data||{},_.extend(a.data,this.state.data),"undefined"==typeof a.data.page){if(!this.hasMore())return!1;null===this.state.currentPage||this.state.currentPage<=1?a.data.page=2:a.data.page=this.state.currentPage+1}return this.fetch(a)},hasMore:function(){return null===this.state.totalPages||null===this.state.totalObjects||null===this.state.currentPage?null:this.state.currentPage<this.state.totalPages}})}(),function(){"use strict";var a,b={},c=window.wpApiSettings||{};window.wp=window.wp||{},wp.api=wp.api||{},_.isEmpty(c)&&(c.root=window.location.origin+"/wp-json/"),a=Backbone.Model.extend({defaults:{apiRoot:c.root,versionString:wp.api.versionString,schema:null,models:{},collections:{}},initialize:function(){var a,b=this;Backbone.Model.prototype.initialize.apply(b,arguments),a=jQuery.Deferred(),b.schemaConstructed=a.promise(),b.schemaModel=new wp.api.models.Schema(null,{apiRoot:b.get("apiRoot"),versionString:b.get("versionString")}),b.schemaModel.once("change",function(){b.constructFromSchema(),a.resolve(b)}),b.get("schema")?b.schemaModel.set(b.schemaModel.parse(b.get("schema"))):!_.isUndefined(sessionStorage)&&(_.isUndefined(c.cacheSchema)||c.cacheSchema)&&sessionStorage.getItem("wp-api-schema-model"+b.get("apiRoot")+b.get("versionString"))?b.schemaModel.set(b.schemaModel.parse(JSON.parse(sessionStorage.getItem("wp-api-schema-model"+b.get("apiRoot")+b.get("versionString"))))):b.schemaModel.fetch({success:function(a){if(!_.isUndefined(sessionStorage)&&(_.isUndefined(c.cacheSchema)||c.cacheSchema))try{sessionStorage.setItem("wp-api-schema-model"+b.get("apiRoot")+b.get("versionString"),JSON.stringify(a))}catch(d){}},error:function(a){window.console.log(a)}})},constructFromSchema:function(){var a,b,d,e,f=this,g=c.mapping||{models:{Categories:"Category",Comments:"Comment",Pages:"Page",PagesMeta:"PageMeta",PagesRevisions:"PageRevision",Posts:"Post",PostsCategories:"PostCategory",PostsRevisions:"PostRevision",PostsTags:"PostTag",Schema:"Schema",Statuses:"Status",Tags:"Tag",Taxonomies:"Taxonomy",Types:"Type",Users:"User"},collections:{PagesMeta:"PageMeta",PagesRevisions:"PageRevisions",PostsCategories:"PostCategories",PostsMeta:"PostMeta",PostsRevisions:"PostRevisions",PostsTags:"PostTags"}};a=[],b=[],d=f.get("apiRoot").replace(wp.api.utils.getRootUrl(),""),e={},e.models=f.get("models"),e.collections=f.get("collections"),_.each(f.schemaModel.get("routes"),function(c,e){e!==f.get(" versionString")&&e!==d&&e!=="/"+f.get("versionString").slice(0,-1)&&(/(?:.*[+)]|\/me)$/.test(e)?a.push({index:e,route:c}):b.push({index:e,route:c}))}),_.each(a,function(a){var b,c=wp.api.utils.extractRoutePart(a.index,2),d=wp.api.utils.extractRoutePart(a.index,4),h=wp.api.utils.extractRoutePart(a.index,1);"me"===h&&(c="me"),""!==d&&d!==c?(b=wp.api.utils.capitalize(d)+wp.api.utils.capitalize(c),b=g.models[b]||b,e.models[b]=wp.api.WPApiBaseModel.extend({url:function(){var a=f.get("apiRoot")+f.get("versionString")+d+"/"+(_.isUndefined(this.get("parent"))||0===this.get("parent")?this.get("parent_post"):this.get("parent"))+"/"+c;return _.isUndefined(this.get("id"))||(a+="/"+this.get("id")),a},route:a,name:b,methods:a.route.methods,initialize:function(){"Posts"!==this.name&&"Pages"!==this.name&&_.includes(this.methods,"DELETE")&&(this.requireForceForDelete=!0)}})):(b=wp.api.utils.capitalize(c),b=g.models[b]||b,e.models[b]=wp.api.WPApiBaseModel.extend({url:function(){var a=f.get("apiRoot")+f.get("versionString")+("me"===c?"users/me":c);return _.isUndefined(this.get("id"))||(a+="/"+this.get("id")),a},route:a,name:b,methods:a.route.methods})),wp.api.utils.decorateFromRoute(a.route.endpoints,e.models[b])}),_.each(b,function(a){var b,c,d=a.index.slice(a.index.lastIndexOf("/")+1),h=wp.api.utils.extractRoutePart(a.index,3);""!==h&&h!==d?(b=wp.api.utils.capitalize(h)+wp.api.utils.capitalize(d),c=g.models[b]||b,b=g.collections[b]||b,e.collections[b]=wp.api.WPApiBaseCollection.extend({url:function(){return f.get("apiRoot")+f.get("versionString")+h+"/"+this.parent+"/"+d},model:function(a,b){return new e.models[c](a,b)},name:b,route:a,methods:a.route.methods})):(b=wp.api.utils.capitalize(d),c=g.models[b]||b,b=g.collections[b]||b,e.collections[b]=wp.api.WPApiBaseCollection.extend({url:f.get("apiRoot")+f.get("versionString")+d,model:function(a,b){return new e.models[c](a,b)},name:b,route:a,methods:a.route.methods})),wp.api.utils.decorateFromRoute(a.route.endpoints,e.collections[b])}),_.each(e.models,function(a,b){e.models[b]=wp.api.utils.addMixinsAndHelpers(a,b,e)})}}),wp.api.endpoints=new Backbone.Collection({model:a}),wp.api.init=function(d){var e,f,g,h={};return d=d||{},h.apiRoot=d.apiRoot||c.root,h.versionString=d.versionString||c.versionString,h.schema=d.schema||null,h.schema||h.apiRoot!==c.root||h.versionString!==c.versionString||(h.schema=c.schema),b[h.apiRoot+h.versionString]||(e=wp.api.endpoints.findWhere({apiRoot:h.apiRoot,versionString:h.versionString}),e||(e=new a(h),wp.api.endpoints.add(e)),f=jQuery.Deferred(),g=f.promise(),e.schemaConstructed.done(function(a){wp.api.models=_.extend(a.get("models"),wp.api.models),wp.api.collections=_.extend(a.get("collections"),wp.api.collections),f.resolveWith(wp.api,[a])}),b[h.apiRoot+h.versionString]=g),b[h.apiRoot+h.versionString]},wp.api.loadPromise=wp.api.init()}();
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
wp-includes/js/tinymce/plugins/wpview/plugin.min.js
1
!function(a,b){a.PluginManager.add("wpview",function(c){function d(){}function e(a){return c.dom.hasClass(a,"wpview")}function f(a){function b(a,b){return"<p>"+window.decodeURIComponent(b)+"</p>"}return a?a.replace(/<div[^>]+data-wpview-text="([^"]+)"[^>]*>(?:\.|[\s\S]+?wpview-end[^>]+>\s*<\/span>\s*)?<\/div>/g,b).replace(/<p[^>]+data-wpview-marker="([^"]+)"[^>]*>[\s\S]*?<\/p>/g,b):a}return b&&b.mce&&b.mce.views?(c.on("init",function(){var a=window.MutationObserver||window.WebKitMutationObserver;a&&new a(function(){c.fire("wp-body-class-change")}).observe(c.getBody(),{attributes:!0,attributeFilter:["class"]}),c.on("wp-body-class-change",function(){var a=c.getBody().className;c.$('iframe[class="wpview-sandbox"]').each(function(b,c){if(!c.src||'javascript:""'===c.src)try{c.contentWindow.document.body.className=a}catch(d){}})})}),c.on("beforesetcontent",function(a){var d;if(a.selection||b.mce.views.unbind(),a.content){if(!a.load&&(d=c.selection.getNode(),d&&d!==c.getBody()&&/^\s*https?:\/\/\S+\s*$/i.test(a.content))){if(d=c.dom.getParent(d,"p"),!d||!/^[\s\uFEFF\u00A0]*$/.test(c.$(d).text()||""))return;d.innerHTML=""}a.content=b.mce.views.setMarkers(a.content)}}),c.on("setcontent",function(a){a.load&&!a.initial&&c.quirks.refreshContentEditable&&c.quirks.refreshContentEditable(),b.mce.views.render()}),c.on("preprocess hide",function(a){c.$("div[data-wpview-text], p[data-wpview-marker]",a.node).each(function(a,b){b.innerHTML="."})},!0),c.on("postprocess",function(a){a.content=f(a.content)}),c.on("beforeaddundo",function(a){a.level.content=f(a.level.content)}),c.on("drop objectselected",function(a){e(a.targetClone)&&(a.targetClone=c.getDoc().createTextNode(window.decodeURIComponent(c.dom.getAttrib(a.targetClone,"data-wpview-text"))))}),c.on("pastepreprocess",function(b){var c=b.content;c&&(c=a.trim(c.replace(/<[^>]+>/g,"")),/^https?:\/\/\S+$/i.test(c)&&(b.content=c))}),c.on("resolvename",function(a){e(a.target)&&(a.name=c.dom.getAttrib(a.target,"data-wpview-type")||"object")}),c.on("click keyup",function(){var a=c.selection.getNode();e(a)&&c.dom.getAttrib(a,"data-mce-selected")&&a.setAttribute("data-mce-selected","2")}),c.addButton("wp_view_edit",{tooltip:"Edit ",icon:"dashicon dashicons-edit",onclick:function(){var a=c.selection.getNode();e(a)&&b.mce.views.edit(c,a)}}),c.addButton("wp_view_remove",{tooltip:"Remove",icon:"dashicon dashicons-no",onclick:function(){c.fire("cut")}}),c.once("preinit",function(){var a;c.wp&&c.wp._createToolbar&&(a=c.wp._createToolbar(["wp_view_edit","wp_view_remove"]),c.on("wptoolbar",function(b){!b.collapsed&&e(b.element)&&(b.toolbar=a)}))}),c.wp=c.wp||{},c.wp.getView=d,c.wp.setViewCursor=d,{getView:d}):{getView:d}})}(window.tinymce,window.wp);
WordPress_WordPress
2017-01-28
1015c3b3a07ad6b530bb3aed7e0e11549da791cb
libmscore/style.cpp
955
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2002-2011 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #include "mscore.h" #include "style.h" #include "xml.h" #include "score.h" #include "articulation.h" #include "harmony.h" #include "chordlist.h" #include "page.h" #include "mscore.h" #include "clef.h" #include "tuplet.h" #include "layout.h" #include "property.h" namespace Ms { // 20 points font design size // 72 points/inch point size // 120 dpi screen resolution // spatium = 20/4 points //--------------------------------------------------------- // StyleType //--------------------------------------------------------- struct StyleType { StyleIdx _idx; const char* _name; // xml name for read()/write() QVariant _defaultValue; public: StyleIdx styleIdx() const { return _idx; } int idx() const { return int(_idx); } const char* valueType() const { return _defaultValue.typeName(); } const char* name() const { return _name; } const QVariant& defaultValue() const { return _defaultValue; } }; #define MM(x) ((x)/INCH) static const StyleType styleTypes[] { { StyleIdx::pageWidth, "pageWidth", 210.0/INCH }, { StyleIdx::pageHeight, "pageHeight", 297.0/INCH }, // A4 { StyleIdx::pagePrintableWidth, "pagePrintableWidth", 190.0/INCH }, { StyleIdx::pageEvenLeftMargin, "pageEvenLeftMargin", 10.0/INCH }, { StyleIdx::pageOddLeftMargin, "pageOddLeftMargin", 10.0/INCH }, { StyleIdx::pageEvenTopMargin, "pageEvenTopMargin", 10.0/INCH }, { StyleIdx::pageEvenBottomMargin, "pageEvenBottomMargin", 20.0/INCH }, { StyleIdx::pageOddTopMargin, "pageOddTopMargin", 10.0/INCH }, { StyleIdx::pageOddBottomMargin, "pageOddBottomMargin", 20.0/INCH }, { StyleIdx::pageTwosided, "pageTwosided", true }, { StyleIdx::staffUpperBorder, "staffUpperBorder", Spatium(7.0) }, { StyleIdx::staffLowerBorder, "staffLowerBorder", Spatium(7.0) }, { StyleIdx::staffDistance, "staffDistance", Spatium(6.5) }, { StyleIdx::akkoladeDistance, "akkoladeDistance", Spatium(6.5) }, { StyleIdx::minSystemDistance, "minSystemDistance", Spatium(8.5) }, { StyleIdx::maxSystemDistance, "maxSystemDistance", Spatium(15.0) }, { StyleIdx::lyricsPlacement, "lyricsPlacement", int(Element::Placement::BELOW) }, { StyleIdx::lyricsPosAbove, "lyricsPosAbove", Spatium(-2.0) }, { StyleIdx::lyricsPosBelow, "lyricsPosBelow", Spatium(2.0) }, { StyleIdx::lyricsMinTopDistance, "lyricsMinTopDistance", Spatium(1.0) }, { StyleIdx::lyricsMinBottomDistance, "lyricsMinBottomDistance", Spatium(3.0) }, { StyleIdx::lyricsLineHeight, "lyricsLineHeight", 1.0 }, { StyleIdx::lyricsDashMinLength, "lyricsDashMinLength", Spatium(0.4) }, { StyleIdx::lyricsDashMaxLength, "lyricsDashMaxLegth", Spatium(0.8) }, { StyleIdx::lyricsDashMaxDistance, "lyricsDashMaxDistance", Spatium(16.0) }, { StyleIdx::lyricsDashForce, "lyricsDashForce", QVariant(true) }, { StyleIdx::lyricsAlignVerseNumber, "lyricsAlignVerseNumber", true }, { StyleIdx::lyricsLineThickness, "lyricsLineThickness", Spatium(0.1) }, { StyleIdx::figuredBassFontFamily, "figuredBassFontFamily", QString("MScoreBC") }, // { StyleIdx::figuredBassFontSize, "figuredBassFontSize", QVariant(8.0) }, { StyleIdx::figuredBassYOffset, "figuredBassYOffset", QVariant(6.0) }, { StyleIdx::figuredBassLineHeight, "figuredBassLineHeight", QVariant(1.0) }, { StyleIdx::figuredBassAlignment, "figuredBassAlignment", QVariant(0) }, { StyleIdx::figuredBassStyle, "figuredBassStyle" , QVariant(0) }, { StyleIdx::systemFrameDistance, "systemFrameDistance", Spatium(7.0) }, { StyleIdx::frameSystemDistance, "frameSystemDistance", Spatium(7.0) }, { StyleIdx::minMeasureWidth, "minMeasureWidth", Spatium(5.0) }, { StyleIdx::barWidth, "barWidth", Spatium(0.16) }, // 0.1875 { StyleIdx::doubleBarWidth, "doubleBarWidth", Spatium(0.16) }, { StyleIdx::endBarWidth, "endBarWidth", Spatium(0.5) }, // 0.5 { StyleIdx::doubleBarDistance, "doubleBarDistance", Spatium(0.30) }, { StyleIdx::endBarDistance, "endBarDistance", Spatium(0.40) }, // 0.3 { StyleIdx::repeatBarlineDotSeparation, "repeatBarlineDotSeparation", Spatium(0.40) }, { StyleIdx::repeatBarTips, "repeatBarTips", QVariant(false) }, { StyleIdx::startBarlineSingle, "startBarlineSingle", QVariant(false) }, { StyleIdx::startBarlineMultiple, "startBarlineMultiple", QVariant(true) }, { StyleIdx::bracketWidth, "bracketWidth", Spatium(0.45) }, { StyleIdx::bracketDistance, "bracketDistance", Spatium(0.1) }, { StyleIdx::akkoladeWidth, "akkoladeWidth", Spatium(1.6) }, { StyleIdx::akkoladeBarDistance, "akkoladeBarDistance", Spatium(.4) }, { StyleIdx::dividerLeft, "dividerLeft", QVariant(false) }, { StyleIdx::dividerLeftSym, "dividerLeftSym", QVariant(QString("systemDivider")) }, { StyleIdx::dividerLeftX, "dividerLeftX", QVariant(0.0) }, { StyleIdx::dividerLeftY, "dividerLeftY", QVariant(0.0) }, { StyleIdx::dividerRight, "dividerRight", QVariant(false) }, { StyleIdx::dividerRightSym, "dividerRightSym", QVariant(QString("systemDivider")) }, { StyleIdx::dividerRightX, "dividerRightX", QVariant(0.0) }, { StyleIdx::dividerRightY, "dividerRightY", QVariant(0.0) }, { StyleIdx::clefLeftMargin, "clefLeftMargin", Spatium(0.8) }, // 0.64 (gould: <= 1) { StyleIdx::keysigLeftMargin, "keysigLeftMargin", Spatium(0.5) }, { StyleIdx::ambitusMargin, "ambitusMargin", Spatium(0.5) }, { StyleIdx::timesigLeftMargin, "timesigLeftMargin", Spatium(0.5) }, { StyleIdx::clefKeyRightMargin, "clefKeyRightMargin", Spatium(0.8) }, { StyleIdx::clefKeyDistance, "clefKeyDistance", Spatium(1.0) }, // gould: 1 - 1.25 { StyleIdx::clefTimesigDistance, "clefTimesigDistance", Spatium(1.0) }, { StyleIdx::keyTimesigDistance, "keyTimesigDistance", Spatium(1.0) }, // gould: 1 - 1.5 { StyleIdx::keyBarlineDistance, "keyTimesigDistance", Spatium(1.0) }, { StyleIdx::systemHeaderDistance, "systemHeaderDistance", Spatium(2.5) }, // gould: 2.5 { StyleIdx::systemHeaderTimeSigDistance, "systemHeaderTimeSigDistance", Spatium(2.0) }, // gould: 2.0 { StyleIdx::clefBarlineDistance, "clefBarlineDistance", Spatium(0.18) }, // was 0.5 { StyleIdx::timesigBarlineDistance, "timesigBarlineDistance", Spatium(0.5) }, { StyleIdx::stemWidth, "stemWidth", Spatium(0.13) }, // 0.09375 { StyleIdx::shortenStem, "shortenStem", QVariant(true) }, { StyleIdx::shortStemProgression, "shortStemProgression", Spatium(0.25) }, { StyleIdx::shortestStem, "shortestStem", Spatium(2.25) }, { StyleIdx::beginRepeatLeftMargin, "beginRepeatLeftMargin", Spatium(1.0) }, { StyleIdx::minNoteDistance, "minNoteDistance", Spatium(0.25) }, // 0.4 { StyleIdx::barNoteDistance, "barNoteDistance", Spatium(1.2) }, { StyleIdx::barAccidentalDistance, "barAccidentalDistance", Spatium(.3) }, { StyleIdx::multiMeasureRestMargin, "multiMeasureRestMargin", Spatium(1.2) }, { StyleIdx::noteBarDistance, "noteBarDistance", Spatium(1.0) }, { StyleIdx::measureSpacing, "measureSpacing", QVariant(1.2) }, { StyleIdx::staffLineWidth, "staffLineWidth", Spatium(0.08) }, // 0.09375 { StyleIdx::ledgerLineWidth, "ledgerLineWidth", Spatium(0.16) }, // 0.1875 { StyleIdx::ledgerLineLength, "ledgerLineLength", Spatium(.6) }, // notehead width + this value { StyleIdx::accidentalDistance, "accidentalDistance", Spatium(0.22) }, { StyleIdx::accidentalNoteDistance, "accidentalNoteDistance", Spatium(0.22) }, { StyleIdx::beamWidth, "beamWidth", Spatium(0.5) }, // was 0.48 { StyleIdx::beamDistance, "beamDistance", QVariant(0.5) }, // 0.25sp units { StyleIdx::beamMinLen, "beamMinLen", Spatium(1.32) }, // 1.316178 exactly notehead widthen beams { StyleIdx::beamNoSlope, "beamNoSlope", QVariant(false) }, { StyleIdx::dotMag, "dotMag", QVariant(1.0) }, { StyleIdx::dotNoteDistance, "dotNoteDistance", Spatium(0.35) }, { StyleIdx::dotRestDistance, "dotRestDistance", Spatium(0.25) }, { StyleIdx::dotDotDistance, "dotDotDistance", Spatium(0.5) }, { StyleIdx::propertyDistanceHead, "propertyDistanceHead", Spatium(1.0) }, { StyleIdx::propertyDistanceStem, "propertyDistanceStem", Spatium(1.8) }, { StyleIdx::propertyDistance, "propertyDistance", Spatium(1.0) }, { StyleIdx::articulationMag, "articulationMag", QVariant(1.0) }, { StyleIdx::lastSystemFillLimit, "lastSystemFillLimit", QVariant(0.3) }, { StyleIdx::hairpinPlacement, "hairpinPlacement", int(Element::Placement::BELOW) }, { StyleIdx::hairpinPosAbove, "hairpinPosAbove", Spatium(-3.5) }, { StyleIdx::hairpinPosBelow, "hairpinPosBelow", Spatium(3.5) }, { StyleIdx::hairpinHeight, "hairpinHeight", Spatium(1.2) }, { StyleIdx::hairpinContHeight, "hairpinContHeight", Spatium(0.5) }, { StyleIdx::hairpinLineWidth, "hairpinWidth", Spatium(0.13) }, { StyleIdx::pedalPlacement, "pedalPlacement", int(Element::Placement::BELOW) }, { StyleIdx::pedalPosAbove, "pedalPosAbove", Spatium(-4) }, { StyleIdx::pedalPosBelow, "pedalPosBelow", Spatium(4) }, { StyleIdx::pedalLineWidth, "pedalLineWidth", Spatium(.15) }, { StyleIdx::pedalLineStyle, "pedalListStyle", QVariant(int(Qt::SolidLine)) }, { StyleIdx::trillPlacement, "trillPlacement", int(Element::Placement::ABOVE) }, { StyleIdx::trillPosAbove, "trillPosAbove", Spatium(-1) }, { StyleIdx::trillPosBelow, "trillPosBelow", Spatium(1) }, { StyleIdx::harmonyY, "harmonyY", Spatium(2.5) }, { StyleIdx::harmonyFretDist, "harmonyFretDist", Spatium(0.5) }, { StyleIdx::minHarmonyDistance, "minHarmonyDistance", Spatium(0.5) }, { StyleIdx::maxHarmonyBarDistance, "maxHarmonyBarDistance", Spatium(3.0) }, { StyleIdx::capoPosition, "capoPosition", QVariant(0) }, { StyleIdx::fretNumMag, "fretNumMag", QVariant(2.0) }, { StyleIdx::fretNumPos, "fretNumPos", QVariant(0) }, { StyleIdx::fretY, "fretY", Spatium(2.0) }, { StyleIdx::showPageNumber, "showPageNumber", QVariant(true) }, { StyleIdx::showPageNumberOne, "showPageNumberOne", QVariant(false) }, { StyleIdx::pageNumberOddEven, "pageNumberOddEven", QVariant(true) }, { StyleIdx::showMeasureNumber, "showMeasureNumber", QVariant(true) }, { StyleIdx::showMeasureNumberOne, "showMeasureNumberOne", QVariant(false) }, { StyleIdx::measureNumberInterval, "measureNumberInterval", QVariant(5) }, { StyleIdx::measureNumberSystem, "measureNumberSystem", QVariant(true) }, { StyleIdx::measureNumberAllStaffs, "measureNumberAllStaffs", QVariant(false) }, { StyleIdx::smallNoteMag, "smallNoteMag", QVariant(.7) }, { StyleIdx::graceNoteMag, "graceNoteMag", QVariant(0.7) }, { StyleIdx::smallStaffMag, "smallStaffMag", QVariant(0.7) }, { StyleIdx::smallClefMag, "smallClefMag", QVariant(0.8) }, { StyleIdx::genClef, "genClef", QVariant(true) }, { StyleIdx::genKeysig, "genKeysig", QVariant(true) }, { StyleIdx::genCourtesyTimesig, "genCourtesyTimesig", QVariant(true) }, { StyleIdx::genCourtesyKeysig, "genCourtesyKeysig", QVariant(true) }, { StyleIdx::genCourtesyClef, "genCourtesyClef", QVariant(true) }, { StyleIdx::swingRatio, "swingRatio", QVariant(60) }, { StyleIdx::swingUnit, "swingUnit", QVariant(QString("")) }, { StyleIdx::useStandardNoteNames, "useStandardNoteNames", QVariant(true) }, { StyleIdx::useGermanNoteNames, "useGermanNoteNames", QVariant(false) }, { StyleIdx::useFullGermanNoteNames, "useFullGermanNoteNames", QVariant(false) }, { StyleIdx::useSolfeggioNoteNames, "useSolfeggioNoteNames", QVariant(false) }, { StyleIdx::useFrenchNoteNames, "useFrenchNoteNames", QVariant(false) }, { StyleIdx::automaticCapitalization, "automaticCapitalization", QVariant(true) }, { StyleIdx::lowerCaseMinorChords, "lowerCaseMinorChords", QVariant(false) }, { StyleIdx::lowerCaseBassNotes, "lowerCaseBassNotes", QVariant(false) }, { StyleIdx::allCapsNoteNames, "allCapsNoteNames", QVariant(false) }, { StyleIdx::chordStyle, "chordStyle", QVariant(QString("std")) }, { StyleIdx::chordsXmlFile, "chordsXmlFile", QVariant(false) }, { StyleIdx::chordDescriptionFile, "chordDescriptionFile", QVariant(QString("chords_std.xml")) }, { StyleIdx::concertPitch, "concertPitch", QVariant(false) }, { StyleIdx::createMultiMeasureRests, "createMultiMeasureRests", QVariant(false) }, { StyleIdx::minEmptyMeasures, "minEmptyMeasures", QVariant(2) }, { StyleIdx::minMMRestWidth, "minMMRestWidth", Spatium(4) }, { StyleIdx::hideEmptyStaves, "hideEmptyStaves", QVariant(false) }, { StyleIdx::dontHideStavesInFirstSystem, "dontHidStavesInFirstSystm", QVariant(true) }, { StyleIdx::hideInstrumentNameIfOneInstrument, "hideInstrumentNameIfOneInstrument", QVariant(true) }, { StyleIdx::gateTime, "gateTime", QVariant(100) }, { StyleIdx::tenutoGateTime, "tenutoGateTime", QVariant(100) }, { StyleIdx::staccatoGateTime, "staccatoGateTime", QVariant(50) }, { StyleIdx::slurGateTime, "slurGateTime", QVariant(100) }, { StyleIdx::ArpeggioNoteDistance, "ArpeggioNoteDistance", Spatium(.5) }, { StyleIdx::ArpeggioLineWidth, "ArpeggioLineWidth", Spatium(.18) }, { StyleIdx::ArpeggioHookLen, "ArpeggioHookLen", Spatium(.8) }, { StyleIdx::SlurEndWidth, "slurEndWidth", Spatium(.07) }, { StyleIdx::SlurMidWidth, "slurMidWidth", Spatium(.15) }, { StyleIdx::SlurDottedWidth, "slurDottedWidth", Spatium(.1) }, { StyleIdx::MinTieLength, "minTieLength", Spatium(1.0) }, { StyleIdx::SectionPause, "sectionPause", QVariant(qreal(3.0)) }, { StyleIdx::MusicalSymbolFont, "musicalSymbolFont", QVariant(QString("Emmentaler")) }, { StyleIdx::MusicalTextFont, "musicalTextFont", QVariant(QString("MScore Text")) }, { StyleIdx::showHeader, "showHeader", QVariant(false) }, { StyleIdx::headerFirstPage, "headerFirstPage", QVariant(false) }, { StyleIdx::headerOddEven, "headerOddEven", QVariant(true) }, { StyleIdx::evenHeaderL, "evenHeaderL", QVariant(QString()) }, { StyleIdx::evenHeaderC, "evenHeaderC", QVariant(QString()) }, { StyleIdx::evenHeaderR, "evenHeaderR", QVariant(QString()) }, { StyleIdx::oddHeaderL, "oddHeaderL", QVariant(QString()) }, { StyleIdx::oddHeaderC, "oddHeaderC", QVariant(QString()) }, { StyleIdx::oddHeaderR, "oddHeaderR", QVariant(QString()) }, { StyleIdx::showFooter, "showFooter", QVariant(true) }, { StyleIdx::footerFirstPage, "footerFirstPage", QVariant(true) }, { StyleIdx::footerOddEven, "footerOddEven", QVariant(true) }, { StyleIdx::evenFooterL, "evenFooterL", QVariant(QString("$p")) }, { StyleIdx::evenFooterC, "evenFooterC", QVariant(QString("$:copyright:")) }, { StyleIdx::evenFooterR, "evenFooterR", QVariant(QString()) }, { StyleIdx::oddFooterL, "oddFooterL", QVariant(QString()) }, { StyleIdx::oddFooterC, "oddFooterC", QVariant(QString("$:copyright:")) }, { StyleIdx::oddFooterR, "oddFooterR", QVariant(QString("$p")) }, { StyleIdx::voltaY, "voltaY", Spatium(-3.0) }, { StyleIdx::voltaHook, "voltaHook", Spatium(1.9) }, { StyleIdx::voltaLineWidth, "voltaLineWidth", Spatium(.1) }, { StyleIdx::voltaLineStyle, "voltaLineStyle", QVariant(int(Qt::SolidLine)) }, { StyleIdx::ottavaPlacement, "ottavaPlacement", int(Element::Placement::ABOVE) }, { StyleIdx::ottavaPosAbove, "ottavaPosAbove", Spatium(-3.0) }, { StyleIdx::ottavaPosBelow, "ottavaPosBelow", Spatium(3.0) }, { StyleIdx::ottavaHook, "ottavaHook", Spatium(1.9) }, { StyleIdx::ottavaLineWidth, "ottavaLineWidth", Spatium(.1) }, { StyleIdx::ottavaLineStyle, "ottavaLineStyle", QVariant(int(Qt::DashLine)) }, { StyleIdx::ottavaNumbersOnly, "ottavaNumbersOnly", true }, { StyleIdx::tabClef, "tabClef", QVariant(int(ClefType::TAB)) }, { StyleIdx::tremoloWidth, "tremoloWidth", Spatium(1.2) }, // tremolo stroke width: notehead width { StyleIdx::tremoloBoxHeight, "tremoloBoxHeight", Spatium(0.65) }, { StyleIdx::tremoloStrokeWidth, "tremoloLineWidth", Spatium(0.5) }, // was 0.35 { StyleIdx::tremoloDistance, "tremoloDistance", Spatium(0.8) }, { StyleIdx::linearStretch, "linearStretch", QVariant(qreal(1.5)) }, { StyleIdx::crossMeasureValues, "crossMeasureValues", QVariant(false) }, { StyleIdx::keySigNaturals, "keySigNaturals", QVariant(int(KeySigNatural::NONE)) }, { StyleIdx::tupletMaxSlope, "tupletMaxSlope", QVariant(qreal(0.5)) }, { StyleIdx::tupletOufOfStaff, "tupletOufOfStaff", QVariant(true) }, { StyleIdx::tupletVHeadDistance, "tupletVHeadDistance", Spatium(.5) }, { StyleIdx::tupletVStemDistance, "tupletVStemDistance", Spatium(.25) }, { StyleIdx::tupletStemLeftDistance, "tupletStemLeftDistance", Spatium(.5) }, { StyleIdx::tupletStemRightDistance, "tupletStemRightDistance", Spatium(.5) }, { StyleIdx::tupletNoteLeftDistance, "tupletNoteLeftDistance", Spatium(0.0) }, { StyleIdx::tupletNoteRightDistance, "tupletNoteRightDistance", Spatium(0.0) }, { StyleIdx::tupletBracketWidth, "tupletBracketWidth", Spatium(0.1) }, { StyleIdx::tupletDirection, "tupletDirection", Direction(Direction::AUTO) }, { StyleIdx::tupletNumberType, "tupletNumberType", int(Tuplet::NumberType::SHOW_NUMBER) }, { StyleIdx::tupletBracketType, "tupletBracketType", int(Tuplet::BracketType::AUTO_BRACKET) }, { StyleIdx::barreLineWidth, "barreLineWidth", QVariant(1.0) }, { StyleIdx::fretMag, "fretMag", QVariant(1.0) }, { StyleIdx::scaleBarlines, "scaleBarlines", QVariant(true) }, { StyleIdx::barGraceDistance, "barGraceDistance", Spatium(.6) }, { StyleIdx::minVerticalDistance, "minVerticalDistance", Spatium(0.5) }, { StyleIdx::ornamentStyle, "ornamentStyle", int(MScore::OrnamentStyle::DEFAULT) }, { StyleIdx::spatium, "Spatium", SPATIUM20 }, { StyleIdx::autoplaceHairpinDynamicsDistance, "autoplaceHairpinDynamicsDistance", Spatium(0.5) }, { StyleIdx::dynamicsPlacement, "dynamicsPlacement", int(Element::Placement::BELOW) }, { StyleIdx::dynamicsPosAbove, "dynamicsPosAbove", Spatium(-2.0) }, { StyleIdx::dynamicsPosBelow, "dynamicsPosBelow", Spatium(1.0) }, { StyleIdx::dynamicsMinDistance, "dynamicsMinDistance", Spatium(0.5) }, { StyleIdx::autoplaceVerticalAlignRange, "autoplaceVerticalAlignRange", int(VerticalAlignRange::SYSTEM) }, { StyleIdx::textLinePlacement, "textLinePlacement", int(Element::Placement::ABOVE) }, { StyleIdx::textLinePosAbove, "textLinePosAbove", Spatium(-3.5) }, { StyleIdx::textLinePosBelow, "textLinePosBelow", Spatium(3.5) }, { StyleIdx::tremoloBarLineWidth, "tremoloBarLineWidth", Spatium(0.1) }, //==== { StyleIdx::defaultFontFace, "defaultFontFace", "FreeSerif" }, { StyleIdx::defaultFontSize, "defaultFontSize", 10.0 }, { StyleIdx::defaultFontSpatiumDependent, "defaultFontSpatiumDependent", true }, { StyleIdx::defaultFontBold, "defaultFontBold", false }, { StyleIdx::defaultFontItalic, "defaultFontItalic", false }, { StyleIdx::defaultFontUnderline, "defaultFontUnderline", false }, { StyleIdx::defaultAlign, "defaultAlign", int(Align::LEFT) }, { StyleIdx::defaultFrame, "defaultFrame", false }, { StyleIdx::defaultFrameSquare, "defaultFrameSquare", false }, { StyleIdx::defaultFrameCircle, "defaultFrameCircle", false }, { StyleIdx::defaultFramePadding, "defaultFramePadding", 0.0 }, { StyleIdx::defaultFrameWidth, "defaultFrameWidth", 0.0 }, { StyleIdx::defaultFrameRound, "defaultFrameRound", 0 }, { StyleIdx::defaultFrameFgColor, "defaultFrameFgColor", QColor(0, 0, 0, 255) }, { StyleIdx::defaultFrameBgColor, "defaultFrameBgColor", QColor(255, 255, 255, 0) }, { StyleIdx::defaultOffset, "defaultOffset", QPointF() }, { StyleIdx::defaultOffsetType, "defaultOffsetType", int(OffsetType::SPATIUM) }, { StyleIdx::defaultSystemFlag, "defaultSystemFlag", false }, { StyleIdx::titleFontFace, "titleFontFace", "FreeSerif" }, { StyleIdx::titleFontSize, "titleFontSize", 24.0 }, { StyleIdx::titleFontSpatiumDependent, "titleFontSpatiumDependent", false }, { StyleIdx::titleFontBold, "titleFontBold", false }, { StyleIdx::titleFontItalic, "titleFontItalic", false }, { StyleIdx::titleFontUnderline, "titleFontUnderline", false }, { StyleIdx::titleAlign, "titleAlign", int(Align::HCENTER | Align::TOP) }, { StyleIdx::titleOffset, "titleOffset", QPointF() }, { StyleIdx::titleOffsetType, "titleOffsetType", int(OffsetType::ABS) }, { StyleIdx::subTitleFontFace, "subTitleFontFace", "FreeSerif" }, { StyleIdx::subTitleFontSize, "subTitleFontSize", 14.0 }, { StyleIdx::subTitleFontSpatiumDependent, "subTitleFontSpatiumDependent", false }, { StyleIdx::subTitleFontBold, "subTitleFontBold", false }, { StyleIdx::subTitleFontItalic, "subTtitleFontItalic", false }, { StyleIdx::subTitleFontUnderline, "subTitleFontUnderline", false }, { StyleIdx::subTitleAlign, "subTitleAlign", int(Align::HCENTER | Align::TOP) }, { StyleIdx::subTitleOffset, "subTitleOffset", QPointF(0.0, MM(10.0)) }, { StyleIdx::subTitleOffsetType, "subTitleOffsetType", int(OffsetType::ABS) }, { StyleIdx::composerFontFace, "composerFontFace", "FreeSerif" }, { StyleIdx::composerFontSize, "composerFontSize", 12.0 }, { StyleIdx::composerFontSpatiumDependent, "composerFontSpatiumDependent", false }, { StyleIdx::composerFontBold, "composerFontBold", false }, { StyleIdx::composerFontItalic, "composerFontItalic", false }, { StyleIdx::composerFontUnderline, "composerFontUnderline", false }, { StyleIdx::composerAlign, "composerAlign", int(Align::RIGHT | Align::BOTTOM) }, { StyleIdx::composerOffset, "composerOffset", QPointF() }, { StyleIdx::composerOffsetType, "composerOffsetType", int(OffsetType::ABS) }, { StyleIdx::lyricistFontFace, "lyricistFontFace", "FreeSerif" }, { StyleIdx::lyricistFontSize, "lyricistFontSize", 12.0 }, { StyleIdx::lyricistFontSpatiumDependent, "lyricistFontSpatiumDependent", false }, { StyleIdx::lyricistFontBold, "lyricistFontBold", false }, { StyleIdx::lyricistFontItalic, "lyricistFontItalic", false }, { StyleIdx::lyricistFontUnderline, "lyricistFontUnderline", false }, { StyleIdx::lyricistAlign, "lyricistAlign", int(Align::LEFT | Align::BOTTOM) }, { StyleIdx::lyricistOffset, "lyricistOffset", QPointF() }, { StyleIdx::lyricistOffsetType, "lyricistOffsetType", int(OffsetType::ABS) }, { StyleIdx::lyricsOddFontFace, "lyricsOddFontFace", "FreeSerif" }, { StyleIdx::lyricsOddFontSize, "lyricsOddFontSize", 11.0 }, { StyleIdx::lyricsOddFontBold, "lyricsOddFontBold", false }, { StyleIdx::lyricsOddFontItalic, "lyricsOddFontItalic", false }, { StyleIdx::lyricsOddFontUnderline, "lyricsOddFontUnderline", false }, { StyleIdx::lyricsOddAlign, "lyricistOddAlign", int(Align::HCENTER | Align::BASELINE) }, { StyleIdx::lyricsOddOffset, "lyricistOddOffset", QPointF(0.0, 6.0) }, { StyleIdx::lyricsEvenFontFace, "lyricsEvenFontFace", "FreeSerif" }, { StyleIdx::lyricsEvenFontSize, "lyricsEvenFontSize", 11.0 }, { StyleIdx::lyricsEvenFontBold, "lyricsEvenFontBold", false }, { StyleIdx::lyricsEvenFontItalic, "lyricsEvenFontItalic", false }, { StyleIdx::lyricsEvenFontUnderline, "lyricsEventFontUnderline", false }, { StyleIdx::lyricsEvenAlign, "lyricistEvenAlign", int(Align::HCENTER | Align::BASELINE) }, { StyleIdx::lyricsEvenOffset, "lyricistEvenOffset", QPointF(0.0, 6.0) }, { StyleIdx::fingeringFontFace, "fingeringFontFace", "FreeSerif" }, { StyleIdx::fingeringFontSize, "fingeringFontSize", 8.0 }, { StyleIdx::fingeringFontBold, "fingeringFontBold", false }, { StyleIdx::fingeringFontItalic, "fingeringFontItalic", false }, { StyleIdx::fingeringFontUnderline, "fingeringFontUnderline", false }, { StyleIdx::fingeringAlign, "fingeringAlign", int(Align::CENTER) }, { StyleIdx::fingeringFrame, "fingeringFrame", false }, { StyleIdx::fingeringFrameSquare, "fingeringFrameSquare", false }, { StyleIdx::fingeringFrameCircle, "fingeringFrameCircle", false }, { StyleIdx::fingeringFramePadding, "fingeringFramePadding", 0.0 }, { StyleIdx::fingeringFrameWidth, "fingeringFrameWidth", 0.0 }, { StyleIdx::fingeringFrameRound, "fingeringFrameRound", 0 }, { StyleIdx::fingeringFrameFgColor, "fingeringFrameFgColor", QColor(0, 0, 0, 255) }, { StyleIdx::fingeringFrameBgColor, "fingeringFrameBgColor", QColor(255, 255, 255, 0) }, { StyleIdx::fingeringOffset, "fingeringOffset", QPointF() }, { StyleIdx::lhGuitarFingeringFontFace, "lhGuitarFingeringFontFace", "FreeSerif" }, { StyleIdx::lhGuitarFingeringFontSize, "lhGuitarFingeringFontSize", 8.0 }, { StyleIdx::lhGuitarFingeringFontBold, "lhGuitarFingeringFontBold", false }, { StyleIdx::lhGuitarFingeringFontItalic, "lhGuitarFingeringFontItalic", false }, { StyleIdx::lhGuitarFingeringFontUnderline,"lhGuitarFingeringFontUnderline",false }, { StyleIdx::lhGuitarFingeringAlign, "lhGuitarFingeringAlign", int(Align::RIGHT | Align::VCENTER) }, { StyleIdx::lhGuitarFingeringFrame, "lhGuitarFingeringFrame", false }, { StyleIdx::lhGuitarFingeringFrameSquare, "lhGuitarFingeringFrameSquare", false }, { StyleIdx::lhGuitarFingeringFrameCircle, "lhGuitarFingeringFrameCircle", false }, { StyleIdx::lhGuitarFingeringFramePadding, "lhGuitarFingeringFramePadding", 0.0 }, { StyleIdx::lhGuitarFingeringFrameWidth, "lhGuitarFingeringFrameWidth", 0.0 }, { StyleIdx::lhGuitarFingeringFrameRound, "lhGuitarFingeringFrameRound", 0 }, { StyleIdx::lhGuitarFingeringFrameFgColor, "lhGuitarFingeringFrameFgColor", QColor(0, 0, 0, 255) }, { StyleIdx::lhGuitarFingeringFrameBgColor, "lhGuitarFingeringFrameBgColor", QColor(255, 255, 255, 0) }, { StyleIdx::lhGuitarFingeringOffset, "lhGuitarFingeringOffset", QPointF(-0.5, 0.0) }, { StyleIdx::rhGuitarFingeringFontFace, "rhGuitarFingeringFontFace", "FreeSerif" }, { StyleIdx::rhGuitarFingeringFontSize, "rhGuitarFingeringFontSize", 8.0 }, { StyleIdx::rhGuitarFingeringFontBold, "rhGuitarFingeringFontBold", false }, { StyleIdx::rhGuitarFingeringFontItalic, "rhGuitarFingeringFontItalic", false }, { StyleIdx::rhGuitarFingeringFontUnderline,"rhGuitarFingeringFontUnderline",false }, { StyleIdx::rhGuitarFingeringAlign, "rhGuitarFingeringAlign", int(Align::CENTER) }, { StyleIdx::rhGuitarFingeringFrame, "rhGuitarFingeringFrame", false }, { StyleIdx::rhGuitarFingeringFrameSquare, "rhGuitarFingeringFrameSquare", false }, { StyleIdx::rhGuitarFingeringFrameCircle, "rhGuitarFingeringFrameCircle", false }, { StyleIdx::rhGuitarFingeringFramePadding, "rhGuitarFingeringFramePadding", 0.0 }, { StyleIdx::rhGuitarFingeringFrameWidth, "rhGuitarFingeringFrameWidth", 0.0 }, { StyleIdx::rhGuitarFingeringFrameRound, "rhGuitarFingeringFrameRound", 0 }, { StyleIdx::rhGuitarFingeringFrameFgColor, "rhGuitarFingeringFrameFgColor", QColor(0, 0, 0, 255) }, { StyleIdx::rhGuitarFingeringFrameBgColor, "rhGuitarFingeringFrameBgColor", QColor(255, 255, 255, 0) }, { StyleIdx::rhGuitarFingeringOffset, "rhGuitarFingeringOffset", QPointF() }, { StyleIdx::stringNumberFontFace, "stringNumberFontFace", "FreeSerif" }, { StyleIdx::stringNumberFontSize, "stringNumberFontSize", 8.0 }, { StyleIdx::stringNumberFontBold, "stringNumberFontBold", false }, { StyleIdx::stringNumberFontItalic, "stringNumberFontItalic", false }, { StyleIdx::stringNumberFontUnderline, "stringNumberFontUnderline", false }, { StyleIdx::stringNumberAlign, "stringNumberAlign", int(Align::CENTER) }, { StyleIdx::stringNumberFrame, "stringNumberFrame", true }, { StyleIdx::stringNumberFrameSquare, "stringNumberFrameSquare", false }, { StyleIdx::stringNumberFrameCircle, "stringNumberFrameCircle", true }, { StyleIdx::stringNumberFramePadding, "stringNumberFramePadding", 0.2 }, { StyleIdx::stringNumberFrameWidth, "stringNumberFrameWidth", 0.1 }, { StyleIdx::stringNumberFrameRound, "stringNumberFrameRound", 0 }, { StyleIdx::stringNumberFrameFgColor, "stringNumberFrameFgColor", QColor(0, 0, 0, 255) }, { StyleIdx::stringNumberFrameBgColor, "stringNumberFrameBgColor", QColor(255, 255, 255, 0) }, { StyleIdx::stringNumberOffset, "stringNumberOffset", QPointF(0.0, -2.0) }, { StyleIdx::longInstrumentFontFace, "longInstrumentFontFace", "FreeSerif" }, { StyleIdx::longInstrumentFontSize, "longInstrumentFontSize", 12.0 }, { StyleIdx::longInstrumentFontBold, "longInstrumentFontBold", false }, { StyleIdx::longInstrumentFontItalic, "longInstrumentFontItalic", false }, { StyleIdx::longInstrumentFontUnderline, "longInstrumentFontUnderline", false }, { StyleIdx::shortInstrumentFontFace, "shortInstrumentFontFace", "FreeSerif" }, { StyleIdx::shortInstrumentFontSize, "shortInstrumentFontSize", 12.0 }, { StyleIdx::shortInstrumentFontBold, "shortInstrumentFontBold", false }, { StyleIdx::shortInstrumentFontItalic, "shortInstrumentFontItalic", false }, { StyleIdx::shortInstrumentFontUnderline, "shortInstrumentFontUnderline", false }, { StyleIdx::partInstrumentFontFace, "partInstrumentFontFace", "FreeSerif" }, { StyleIdx::partInstrumentFontSize, "partInstrumentFontSize", 18.0 }, { StyleIdx::partInstrumentFontBold, "partInstrumentFontBold", false }, { StyleIdx::partInstrumentFontItalic, "partInstrumentFontItalic", false }, { StyleIdx::partInstrumentFontUnderline, "partInstrumentFontUnderline", false }, { StyleIdx::dynamicsFontFace, "dynamicsFontFace", "FreeSerif" }, { StyleIdx::dynamicsFontSize, "dynamicsFontSize", 12.0 }, { StyleIdx::dynamicsFontBold, "dynamicsFontBold", false }, { StyleIdx::dynamicsFontItalic, "dynamicsFontItalic", true }, { StyleIdx::dynamicsFontUnderline, "dynamicsFontUnderline", false }, { StyleIdx::dynamicsAlign, "dynamicsAlign", int(Align::HCENTER | Align::BASELINE) }, { StyleIdx::expressionFontFace, "expressionFontFace", "FreeSerif" }, { StyleIdx::expressionFontSize, "expressionFontSize", 11.0 }, { StyleIdx::expressionFontBold, "expressionFontBold", false }, { StyleIdx::expressionFontItalic, "expressionFontItalic", true }, { StyleIdx::expressionFontUnderline, "expressionFontUnderline", false }, { StyleIdx::expressionAlign, "expressionAlign", int(Align::LEFT | Align::BASELINE) }, { StyleIdx::tempoFontFace, "tempoFontFace", "FreeSerif" }, { StyleIdx::tempoFontSize, "tempoFontSize", 12.0 }, { StyleIdx::tempoFontBold, "tempoFontBold", true }, { StyleIdx::tempoFontItalic, "tempoFontItalic", false }, { StyleIdx::tempoFontUnderline, "tempoFontUnderline", false }, { StyleIdx::tempoAlign, "tempoAlign", int(Align::LEFT | Align::BASELINE) }, { StyleIdx::tempoOffset, "tempoOffset", QPointF(0.0, -4.0) }, { StyleIdx::tempoSystemFlag, "tempoSystemFlag", true }, { StyleIdx::metronomeFontFace, "metronomeFontFace", "FreeSerif" }, { StyleIdx::metronomeFontSize, "metronomeFontSize", 12.0 }, { StyleIdx::metronomeFontBold, "metronomeFontBold", true }, { StyleIdx::metronomeFontItalic, "metronomeFontItalic", false }, { StyleIdx::metronomeFontUnderline, "metronomeFontUnderline", false }, { StyleIdx::measureNumberFontFace, "measureNumberFontFace", "FreeSerif" }, { StyleIdx::measureNumberFontSize, "measureNumberFontSize", 8.0 }, { StyleIdx::measureNumberFontBold, "measureNumberFontBold", false }, { StyleIdx::measureNumberFontItalic, "measureNumberFontItalic", false }, { StyleIdx::measureNumberFontUnderline, "measureNumberFontUnderline", false }, { StyleIdx::measureNumberOffset, "measureNumberOffset", QPointF(0.0, -2.0) }, { StyleIdx::measureNumberOffsetType, "measureNumberOffsetType", int(OffsetType::SPATIUM) }, { StyleIdx::translatorFontFace, "translatorFontFace", "FreeSerif" }, { StyleIdx::translatorFontSize, "translatorFontSize", 11.0 }, { StyleIdx::translatorFontBold, "translatorFontBold", false }, { StyleIdx::translatorFontItalic, "translatorFontItalic", false }, { StyleIdx::translatorFontUnderline, "translatorFontUnderline", false }, { StyleIdx::tupletFontFace, "tupletFontFace", "FreeSerif" }, { StyleIdx::tupletFontSize, "tupletFontSize", 10.0 }, { StyleIdx::tupletFontBold, "tupletFontBold", false }, { StyleIdx::tupletFontItalic, "tupletFontItalic", true }, { StyleIdx::tupletFontUnderline, "tupletFontUnderline", false }, { StyleIdx::systemFontFace, "systemFontFace", "FreeSerif" }, { StyleIdx::systemFontSize, "systemFontSize", 10.0 }, { StyleIdx::systemFontBold, "systemFontBold", false }, { StyleIdx::systemFontItalic, "systemFontItalic", false }, { StyleIdx::systemFontUnderline, "systemFontUnderline", false }, { StyleIdx::systemOffset, "systemOffset", QPointF(0.0, -4.0) }, { StyleIdx::systemOffsetType, "defaultOffsetType", int(OffsetType::SPATIUM) }, // { StyleIdx::systemSystemFlag, "systemSystemFlag", true }, { StyleIdx::staffFontFace, "staffFontFace", "FreeSerif" }, { StyleIdx::staffFontSize, "staffFontSize", 10.0 }, { StyleIdx::staffFontBold, "staffFontBold", false }, { StyleIdx::staffFontItalic, "staffFontItalic", false }, { StyleIdx::staffFontUnderline, "staffFontUnderline", false }, { StyleIdx::staffOffset, "staffOffset", QPointF(0.0, -4.0) }, { StyleIdx::staffOffsetType, "defaultOffsetType", int(OffsetType::SPATIUM) }, // { StyleIdx::staffSystemFlag, "staffSystemFlag", false }, { StyleIdx::chordSymbolFontFace, "chordSymbolFontFace", "FreeSerif" }, { StyleIdx::chordSymbolFontSize, "chordSymbolFontSize", 12.0 }, { StyleIdx::chordSymbolFontBold, "chordSymbolFontBold", false }, { StyleIdx::chordSymbolFontItalic, "chordSymbolFontItalic", false }, { StyleIdx::chordSymbolFontUnderline, "chordSymbolFontUnderline", false }, { StyleIdx::rehearsalMarkFontFace, "rehearsalMarkFontFace", "FreeSerif" }, { StyleIdx::rehearsalMarkFontSize, "rehearsalMarkFontSize", 14.0 }, { StyleIdx::rehearsalMarkFontBold, "rehearsalMarkFontBold", true }, { StyleIdx::rehearsalMarkFontItalic, "rehearsalMarkFontItalic", false }, { StyleIdx::rehearsalMarkFontUnderline, "rehearsalMarkFontUnderline", false }, { StyleIdx::rehearsalMarkFrame, "rehearsalMarkFrame", false }, { StyleIdx::rehearsalMarkFrameSquare, "rehearsalMarkFrameSquare", false }, { StyleIdx::rehearsalMarkFrameCircle, "rehearsalMarkFrameCircle", false }, { StyleIdx::rehearsalMarkFramePadding, "rehearsalMarkFramePadding", 0.0 }, { StyleIdx::rehearsalMarkFrameWidth, "rehearsalMarkFrameWidth", 0.0 }, { StyleIdx::rehearsalMarkFrameRound, "rehearsalMarkFrameRound", 0 }, { StyleIdx::rehearsalMarkFrameFgColor, "rehearsalMarkFrameFgColor", QColor(0, 0, 0, 255) }, { StyleIdx::rehearsalMarkFrameBgColor, "rehearsalMarkFrameBgColor", QColor(255, 255, 255, 0) }, { StyleIdx::rehearsalMarkSystemFlag, "rehearsalMarkSystemFlag", true }, { StyleIdx::repeatLeftFontFace, "repeatLeftFontFace", "FreeSerif" }, { StyleIdx::repeatLeftFontSize, "repeatLeftFontSize", 20.0 }, { StyleIdx::repeatLeftFontBold, "repeatLeftFontBold", false }, { StyleIdx::repeatLeftFontItalic, "repeatLeftFontItalic", false }, { StyleIdx::repeatLeftFontUnderline, "repeatLeftFontUnderline", false }, { StyleIdx::repeatLeftSystemFlag, "repeatSystemFlag", true }, { StyleIdx::repeatRightFontFace, "repeatRightFontFace", "FreeSerif" }, { StyleIdx::repeatRightFontSize, "repeatRightFontSize", 12.0 }, { StyleIdx::repeatRightFontBold, "repeatRightFontBold", false }, { StyleIdx::repeatRightFontItalic, "repeatRightFontItalic", false }, { StyleIdx::repeatRightFontUnderline, "repeatRightFontUnderline", false }, { StyleIdx::repeatRightSystemFlag, "repeatRightSystemFlag", true }, { StyleIdx::voltaSubStyle, "voltaSubStyle", int(SubStyle::VOLTA) }, { StyleIdx::voltaFontFace, "voltaFontFace", "FreeSerif" }, { StyleIdx::voltaFontSize, "voltaFontSize", 11.0 }, { StyleIdx::voltaFontBold, "voltaFontBold", true }, { StyleIdx::voltaFontItalic, "voltaFontItalic", false }, { StyleIdx::voltaFontUnderline, "voltaFontUnderline", false }, { StyleIdx::voltaAlign, "voltaAlign", int(Align::LEFT | Align::BASELINE) }, { StyleIdx::voltaOffset, "voltaOffset", QPointF(0.5, 1.9) }, { StyleIdx::frameFontFace, "frameFontFace", "FreeSerif" }, { StyleIdx::frameFontSize, "frameFontSize", 12.0 }, { StyleIdx::frameFontBold, "frameFontBold", false }, { StyleIdx::frameFontItalic, "frameFontItalic", false }, { StyleIdx::frameFontUnderline, "frameFontUnderline", false }, { StyleIdx::textLineFontFace, "textLineFontFace", "FreeSerif" }, { StyleIdx::textLineFontSize, "textLineFontSize", 12.0 }, { StyleIdx::textLineFontBold, "textLineFontBold", false }, { StyleIdx::textLineFontItalic, "textLineFontItalic", false }, { StyleIdx::textLineFontUnderline, "textLineFontUnderline", false }, { StyleIdx::glissandoFontFace, "glissandoFontFace", "FreeSerif" }, { StyleIdx::glissandoFontSize, "glissandoFontSize", 8.0 }, { StyleIdx::glissandoFontBold, "glissandoFontBold", false }, { StyleIdx::glissandoFontItalic, "glissandoFontItalic", true }, { StyleIdx::glissandoFontUnderline, "glissandoFontUnderline", false }, { StyleIdx::ottavaFontFace, "ottavaFontFace", "FreeSerif" }, { StyleIdx::ottavaFontSize, "ottavaFontSize", 12.0 }, { StyleIdx::ottavaFontBold, "ottavaFontBold", false }, { StyleIdx::ottavaFontItalic, "ottavaFontItalic", false }, { StyleIdx::ottavaFontUnderline, "ottavaFontUnderline", false }, { StyleIdx::pedalFontFace, "pedalFontFace", "FreeSerif" }, { StyleIdx::pedalFontSize, "pedalFontSize", 12.0 }, { StyleIdx::pedalFontBold, "pedalFontBold", false }, { StyleIdx::pedalFontItalic, "pedalFontItalic", false }, { StyleIdx::pedalFontUnderline, "pedalFontUnderline", false }, { StyleIdx::hairpinFontFace, "hairpinFontFace", "FreeSerif" }, { StyleIdx::hairpinFontSize, "hairpinFontSize", 12.0 }, { StyleIdx::hairpinFontBold, "hairpinFontBold", false }, { StyleIdx::hairpinFontItalic, "hairpinFontItalic", true }, { StyleIdx::hairpinFontUnderline, "hairpinFontUnderline", false }, { StyleIdx::bendFontFace, "bendFontFace", "FreeSerif" }, { StyleIdx::bendFontSize, "bendFontSize", 8.0 }, { StyleIdx::bendFontBold, "bendFontBold", false }, { StyleIdx::bendFontItalic, "bendFontItalic", false }, { StyleIdx::bendFontUnderline, "bendFontUnderline", false }, { StyleIdx::headerFontFace, "headerFontFace", "FreeSerif" }, { StyleIdx::headerFontSize, "headerFontSize", 8.0 }, { StyleIdx::headerFontBold, "headerFontBold", false }, { StyleIdx::headerFontItalic, "headerFontItalic", false }, { StyleIdx::headerFontUnderline, "headerFontUnderline", false }, { StyleIdx::footerFontFace, "footerFontFace", "FreeSerif" }, { StyleIdx::footerFontSize, "footerFontSize", 8.0 }, { StyleIdx::footerFontBold, "footerFontBold", false }, { StyleIdx::footerFontItalic, "footerFontItalic", false }, { StyleIdx::footerFontUnderline, "footerFontUnderline", false }, { StyleIdx::instrumentChangeFontFace, "instrumentChangeFontFace", "FreeSerif" }, { StyleIdx::instrumentChangeFontSize, "instrumentChangeFontSize", 12.0 }, { StyleIdx::instrumentChangeFontBold, "instrumentChangeFontBold", true }, { StyleIdx::instrumentChangeFontItalic, "instrumentChangeFontItalic", false }, { StyleIdx::instrumentChangeFontUnderline, "instrumentChangeFontUnderline",false }, { StyleIdx::instrumentChangeOffset, "instrumentChangeOffset", QPointF(0, -3.0) }, { StyleIdx::figuredBassFontFace, "figuredBassFontFace", "MScoreBC" }, { StyleIdx::figuredBassFontSize, "figuredBassFontSize", 8.0 }, { StyleIdx::figuredBassFontBold, "figuredBassFontBold", false }, { StyleIdx::figuredBassFontItalic, "figuredBassFontItalic", false }, { StyleIdx::figuredBassFontUnderline, "figuredBassFontUnderline", false }, }; #undef MM //--------------------------------------------------------- // sets of styled properties //--------------------------------------------------------- const std::vector<StyledProperty> defaultStyle { { StyleIdx::defaultFontFace, P_ID::FONT_FACE }, { StyleIdx::defaultFontSize, P_ID::FONT_SIZE }, { StyleIdx::defaultFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT }, { StyleIdx::defaultFontBold, P_ID::FONT_BOLD }, { StyleIdx::defaultFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::defaultFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::defaultAlign, P_ID::ALIGN }, { StyleIdx::defaultFrame, P_ID::FRAME }, { StyleIdx::defaultFrameSquare, P_ID::FRAME_SQUARE }, { StyleIdx::defaultFrameCircle, P_ID::FRAME_CIRCLE }, { StyleIdx::defaultFramePadding, P_ID::FRAME_PADDING }, { StyleIdx::defaultFrameWidth, P_ID::FRAME_WIDTH }, { StyleIdx::defaultFrameRound, P_ID::FRAME_ROUND }, { StyleIdx::defaultFrameFgColor, P_ID::FRAME_FG_COLOR }, { StyleIdx::defaultFrameBgColor, P_ID::FRAME_BG_COLOR }, { StyleIdx::defaultOffset, P_ID::OFFSET }, { StyleIdx::defaultOffsetType, P_ID::OFFSET_TYPE }, { StyleIdx::defaultSystemFlag, P_ID::SYSTEM_FLAG }, }; const std::vector<StyledProperty> titleStyle { { StyleIdx::titleFontFace, P_ID::FONT_FACE }, { StyleIdx::titleFontSize, P_ID::FONT_SIZE }, { StyleIdx::titleFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT }, { StyleIdx::titleFontBold, P_ID::FONT_BOLD }, { StyleIdx::titleFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::titleFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::titleAlign, P_ID::ALIGN }, { StyleIdx::titleOffset, P_ID::OFFSET }, { StyleIdx::titleOffsetType, P_ID::OFFSET_TYPE }, }; const std::vector<StyledProperty> subTitleStyle { { StyleIdx::subTitleFontFace, P_ID::FONT_FACE }, { StyleIdx::subTitleFontSize, P_ID::FONT_SIZE }, { StyleIdx::subTitleFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT }, { StyleIdx::subTitleFontBold, P_ID::FONT_BOLD }, { StyleIdx::subTitleFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::subTitleFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::subTitleAlign, P_ID::ALIGN }, { StyleIdx::subTitleOffset, P_ID::OFFSET }, { StyleIdx::subTitleOffsetType, P_ID::OFFSET_TYPE }, { StyleIdx::subTitleOffset, P_ID::OFFSET }, { StyleIdx::subTitleOffsetType, P_ID::OFFSET_TYPE }, }; const std::vector<StyledProperty> composerStyle { { StyleIdx::composerFontFace, P_ID::FONT_FACE }, { StyleIdx::composerFontSize, P_ID::FONT_SIZE }, { StyleIdx::composerFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT }, { StyleIdx::composerFontBold, P_ID::FONT_BOLD }, { StyleIdx::composerFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::composerFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::composerAlign, P_ID::ALIGN }, { StyleIdx::composerOffset, P_ID::OFFSET }, { StyleIdx::composerOffsetType, P_ID::OFFSET_TYPE }, }; const std::vector<StyledProperty> lyricistStyle { { StyleIdx::lyricistFontFace, P_ID::FONT_FACE }, { StyleIdx::lyricistFontSize, P_ID::FONT_SIZE }, { StyleIdx::lyricistFontBold, P_ID::FONT_BOLD }, { StyleIdx::lyricistFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::lyricistFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::lyricistAlign, P_ID::ALIGN }, { StyleIdx::lyricistOffset, P_ID::OFFSET }, { StyleIdx::lyricistOffsetType, P_ID::OFFSET_TYPE }, }; const std::vector<StyledProperty> lyricsOddStyle { { StyleIdx::lyricsOddFontFace, P_ID::FONT_FACE }, { StyleIdx::lyricsOddFontSize, P_ID::FONT_SIZE }, { StyleIdx::lyricsOddFontBold, P_ID::FONT_BOLD }, { StyleIdx::lyricsOddFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::lyricsOddFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::lyricsOddAlign, P_ID::ALIGN }, }; const std::vector<StyledProperty> lyricsEvenStyle { { StyleIdx::lyricsEvenFontFace, P_ID::FONT_FACE }, { StyleIdx::lyricsEvenFontSize, P_ID::FONT_SIZE }, { StyleIdx::lyricsEvenFontBold, P_ID::FONT_BOLD }, { StyleIdx::lyricsEvenFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::lyricsEvenFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::lyricsEvenAlign, P_ID::ALIGN }, }; const std::vector<StyledProperty> fingeringStyle { { StyleIdx::fingeringFontFace, P_ID::FONT_FACE }, { StyleIdx::fingeringFontSize, P_ID::FONT_SIZE }, { StyleIdx::fingeringFontBold, P_ID::FONT_BOLD }, { StyleIdx::fingeringFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::fingeringFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::fingeringAlign, P_ID::ALIGN }, { StyleIdx::fingeringFrame, P_ID::FRAME }, { StyleIdx::fingeringFrameSquare, P_ID::FRAME_SQUARE }, { StyleIdx::fingeringFrameCircle, P_ID::FRAME_CIRCLE }, { StyleIdx::fingeringFramePadding, P_ID::FRAME_PADDING }, { StyleIdx::fingeringFrameWidth, P_ID::FRAME_WIDTH }, { StyleIdx::fingeringFrameRound, P_ID::FRAME_ROUND }, { StyleIdx::fingeringFrameFgColor, P_ID::FRAME_FG_COLOR }, { StyleIdx::fingeringFrameBgColor, P_ID::FRAME_BG_COLOR }, { StyleIdx::fingeringOffset, P_ID::OFFSET }, }; const std::vector<StyledProperty> lhGuitarFingeringStyle { { StyleIdx::lhGuitarFingeringFontFace, P_ID::FONT_FACE }, { StyleIdx::lhGuitarFingeringFontSize, P_ID::FONT_SIZE }, { StyleIdx::lhGuitarFingeringFontBold, P_ID::FONT_BOLD }, { StyleIdx::lhGuitarFingeringFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::lhGuitarFingeringFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::lhGuitarFingeringAlign, P_ID::ALIGN }, { StyleIdx::lhGuitarFingeringFrame, P_ID::FRAME }, { StyleIdx::lhGuitarFingeringFrameSquare, P_ID::FRAME_SQUARE }, { StyleIdx::lhGuitarFingeringFrameCircle, P_ID::FRAME_CIRCLE }, { StyleIdx::lhGuitarFingeringFramePadding, P_ID::FRAME_PADDING }, { StyleIdx::lhGuitarFingeringFrameWidth, P_ID::FRAME_WIDTH }, { StyleIdx::lhGuitarFingeringFrameRound, P_ID::FRAME_ROUND }, { StyleIdx::lhGuitarFingeringFrameFgColor, P_ID::FRAME_FG_COLOR }, { StyleIdx::lhGuitarFingeringFrameBgColor, P_ID::FRAME_BG_COLOR }, { StyleIdx::lhGuitarFingeringOffset, P_ID::OFFSET }, }; const std::vector<StyledProperty> rhGuitarFingeringStyle { { StyleIdx::rhGuitarFingeringFontFace, P_ID::FONT_FACE }, { StyleIdx::rhGuitarFingeringFontSize, P_ID::FONT_SIZE }, { StyleIdx::rhGuitarFingeringFontBold, P_ID::FONT_BOLD }, { StyleIdx::rhGuitarFingeringFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::rhGuitarFingeringFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::rhGuitarFingeringAlign, P_ID::ALIGN }, { StyleIdx::rhGuitarFingeringFrame, P_ID::FRAME }, { StyleIdx::rhGuitarFingeringFrameSquare, P_ID::FRAME_SQUARE }, { StyleIdx::rhGuitarFingeringFrameCircle, P_ID::FRAME_CIRCLE }, { StyleIdx::rhGuitarFingeringFramePadding, P_ID::FRAME_PADDING }, { StyleIdx::rhGuitarFingeringFrameWidth, P_ID::FRAME_WIDTH }, { StyleIdx::rhGuitarFingeringFrameRound, P_ID::FRAME_ROUND }, { StyleIdx::rhGuitarFingeringFrameFgColor, P_ID::FRAME_FG_COLOR }, { StyleIdx::rhGuitarFingeringFrameBgColor, P_ID::FRAME_BG_COLOR }, { StyleIdx::rhGuitarFingeringOffset, P_ID::OFFSET }, }; const std::vector<StyledProperty> stringNumberStyle { { StyleIdx::stringNumberFontFace, P_ID::FONT_FACE }, { StyleIdx::stringNumberFontSize, P_ID::FONT_SIZE }, { StyleIdx::stringNumberFontBold, P_ID::FONT_BOLD }, { StyleIdx::stringNumberFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::stringNumberFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::stringNumberAlign, P_ID::ALIGN }, { StyleIdx::stringNumberFrame, P_ID::FRAME }, { StyleIdx::stringNumberFrameSquare, P_ID::FRAME_SQUARE }, { StyleIdx::stringNumberFrameCircle, P_ID::FRAME_CIRCLE }, { StyleIdx::stringNumberFramePadding, P_ID::FRAME_PADDING }, { StyleIdx::stringNumberFrameWidth, P_ID::FRAME_WIDTH }, { StyleIdx::stringNumberFrameRound, P_ID::FRAME_ROUND }, { StyleIdx::stringNumberFrameFgColor, P_ID::FRAME_FG_COLOR }, { StyleIdx::stringNumberFrameBgColor, P_ID::FRAME_BG_COLOR }, { StyleIdx::stringNumberOffset, P_ID::OFFSET }, }; const std::vector<StyledProperty> longInstrumentStyle { { StyleIdx::longInstrumentFontFace, P_ID::FONT_FACE }, { StyleIdx::longInstrumentFontSize, P_ID::FONT_SIZE }, { StyleIdx::longInstrumentFontBold, P_ID::FONT_BOLD }, { StyleIdx::longInstrumentFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::longInstrumentFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> shortInstrumentStyle { { StyleIdx::shortInstrumentFontFace, P_ID::FONT_FACE }, { StyleIdx::shortInstrumentFontSize, P_ID::FONT_SIZE }, { StyleIdx::shortInstrumentFontBold, P_ID::FONT_BOLD }, { StyleIdx::shortInstrumentFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::shortInstrumentFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> partInstrumentStyle { { StyleIdx::partInstrumentFontFace, P_ID::FONT_FACE }, { StyleIdx::partInstrumentFontSize, P_ID::FONT_SIZE }, { StyleIdx::partInstrumentFontBold, P_ID::FONT_BOLD }, { StyleIdx::partInstrumentFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::partInstrumentFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> dynamicsStyle { { StyleIdx::dynamicsFontFace, P_ID::FONT_FACE }, { StyleIdx::dynamicsFontSize, P_ID::FONT_SIZE }, { StyleIdx::dynamicsFontBold, P_ID::FONT_BOLD }, { StyleIdx::dynamicsFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::dynamicsFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> expressionStyle { { StyleIdx::expressionFontFace, P_ID::FONT_FACE }, { StyleIdx::expressionFontSize, P_ID::FONT_SIZE }, { StyleIdx::expressionFontBold, P_ID::FONT_BOLD }, { StyleIdx::expressionFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::expressionFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> tempoStyle { { StyleIdx::tempoFontFace, P_ID::FONT_FACE }, { StyleIdx::tempoFontSize, P_ID::FONT_SIZE }, { StyleIdx::tempoFontBold, P_ID::FONT_BOLD }, { StyleIdx::tempoFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::tempoFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::tempoOffset, P_ID::OFFSET }, { StyleIdx::tempoSystemFlag, P_ID::SYSTEM_FLAG }, }; const std::vector<StyledProperty> metronomeStyle { { StyleIdx::metronomeFontFace, P_ID::FONT_FACE }, { StyleIdx::metronomeFontSize, P_ID::FONT_SIZE }, { StyleIdx::metronomeFontBold, P_ID::FONT_BOLD }, { StyleIdx::metronomeFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::metronomeFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> measureNumberStyle { { StyleIdx::measureNumberFontFace, P_ID::FONT_FACE }, { StyleIdx::measureNumberFontSize, P_ID::FONT_SIZE }, { StyleIdx::measureNumberFontBold, P_ID::FONT_BOLD }, { StyleIdx::measureNumberFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::measureNumberFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::measureNumberOffset, P_ID::OFFSET }, { StyleIdx::measureNumberOffsetType, P_ID::OFFSET_TYPE }, }; const std::vector<StyledProperty> translatorStyle { { StyleIdx::translatorFontFace, P_ID::FONT_FACE }, { StyleIdx::translatorFontSize, P_ID::FONT_SIZE }, { StyleIdx::translatorFontBold, P_ID::FONT_BOLD }, { StyleIdx::translatorFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::translatorFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> tupletStyle { { StyleIdx::tupletFontFace, P_ID::FONT_FACE }, { StyleIdx::tupletFontSize, P_ID::FONT_SIZE }, { StyleIdx::tupletFontBold, P_ID::FONT_BOLD }, { StyleIdx::tupletFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::tupletFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> systemStyle { { StyleIdx::systemFontFace, P_ID::FONT_FACE }, { StyleIdx::systemFontSize, P_ID::FONT_SIZE }, { StyleIdx::systemFontBold, P_ID::FONT_BOLD }, { StyleIdx::systemFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::systemFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::systemOffset, P_ID::OFFSET }, { StyleIdx::systemOffsetType, P_ID::OFFSET_TYPE }, // { StyleIdx::systemSystemFlag, P_ID::SYSTEM_FLAG }, }; const std::vector<StyledProperty> staffStyle { { StyleIdx::staffFontFace, P_ID::FONT_FACE }, { StyleIdx::staffFontSize, P_ID::FONT_SIZE }, { StyleIdx::staffFontBold, P_ID::FONT_BOLD }, { StyleIdx::staffFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::staffFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::staffOffset, P_ID::OFFSET }, { StyleIdx::staffOffsetType, P_ID::OFFSET_TYPE }, // { StyleIdx::staffSystemFlag, P_ID::SYSTEM_FLAG }, }; const std::vector<StyledProperty> chordSymbolStyle { { StyleIdx::chordSymbolFontFace, P_ID::FONT_FACE }, { StyleIdx::chordSymbolFontSize, P_ID::FONT_SIZE }, { StyleIdx::chordSymbolFontBold, P_ID::FONT_BOLD }, { StyleIdx::chordSymbolFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::chordSymbolFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> rehearsalMarkStyle { { StyleIdx::rehearsalMarkFontFace, P_ID::FONT_FACE }, { StyleIdx::rehearsalMarkFontSize, P_ID::FONT_SIZE }, { StyleIdx::rehearsalMarkFontBold, P_ID::FONT_BOLD }, { StyleIdx::rehearsalMarkFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::rehearsalMarkFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::rehearsalMarkFrame, P_ID::FRAME }, { StyleIdx::rehearsalMarkFrameSquare, P_ID::FRAME_SQUARE }, { StyleIdx::rehearsalMarkFrameCircle, P_ID::FRAME_CIRCLE }, { StyleIdx::rehearsalMarkFramePadding, P_ID::FRAME_PADDING }, { StyleIdx::rehearsalMarkFrameWidth, P_ID::FRAME_WIDTH }, { StyleIdx::rehearsalMarkFrameRound, P_ID::FRAME_ROUND }, { StyleIdx::rehearsalMarkFrameFgColor, P_ID::FRAME_FG_COLOR }, { StyleIdx::rehearsalMarkFrameBgColor, P_ID::FRAME_BG_COLOR }, { StyleIdx::rehearsalMarkSystemFlag, P_ID::SYSTEM_FLAG }, }; const std::vector<StyledProperty> repeatLeftStyle { { StyleIdx::repeatLeftFontFace, P_ID::FONT_FACE }, { StyleIdx::repeatLeftFontSize, P_ID::FONT_SIZE }, { StyleIdx::repeatLeftFontBold, P_ID::FONT_BOLD }, { StyleIdx::repeatLeftFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::repeatLeftFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::repeatLeftSystemFlag, P_ID::SYSTEM_FLAG }, }; const std::vector<StyledProperty> repeatRightStyle { { StyleIdx::repeatRightFontFace, P_ID::FONT_FACE }, { StyleIdx::repeatRightFontSize, P_ID::FONT_SIZE }, { StyleIdx::repeatRightFontBold, P_ID::FONT_BOLD }, { StyleIdx::repeatRightFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::repeatRightFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::repeatRightSystemFlag, P_ID::SYSTEM_FLAG }, }; const std::vector<StyledProperty> voltaStyle { { StyleIdx::voltaSubStyle, P_ID::SUB_STYLE }, { StyleIdx::voltaFontFace, P_ID::FONT_FACE }, { StyleIdx::voltaFontSize, P_ID::FONT_SIZE }, { StyleIdx::voltaFontBold, P_ID::FONT_BOLD }, { StyleIdx::voltaFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::voltaFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::voltaAlign, P_ID::ALIGN }, { StyleIdx::voltaOffset, P_ID::OFFSET }, }; const std::vector<StyledProperty> frameStyle { { StyleIdx::frameFontFace, P_ID::FONT_FACE }, { StyleIdx::frameFontSize, P_ID::FONT_SIZE }, { StyleIdx::frameFontBold, P_ID::FONT_BOLD }, { StyleIdx::frameFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::frameFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> textLineStyle { { StyleIdx::textLineFontFace, P_ID::FONT_FACE }, { StyleIdx::textLineFontSize, P_ID::FONT_SIZE }, { StyleIdx::textLineFontBold, P_ID::FONT_BOLD }, { StyleIdx::textLineFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::textLineFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> glissandoStyle { { StyleIdx::glissandoFontFace, P_ID::FONT_FACE }, { StyleIdx::glissandoFontSize, P_ID::FONT_SIZE }, { StyleIdx::glissandoFontBold, P_ID::FONT_BOLD }, { StyleIdx::glissandoFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::glissandoFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> ottavaStyle { { StyleIdx::ottavaFontFace, P_ID::FONT_FACE }, { StyleIdx::ottavaFontSize, P_ID::FONT_SIZE }, { StyleIdx::ottavaFontBold, P_ID::FONT_BOLD }, { StyleIdx::ottavaFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::ottavaFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> pedalStyle { { StyleIdx::pedalFontFace, P_ID::FONT_FACE }, { StyleIdx::pedalFontSize, P_ID::FONT_SIZE }, { StyleIdx::pedalFontBold, P_ID::FONT_BOLD }, { StyleIdx::pedalFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::pedalFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> hairpinStyle { { StyleIdx::hairpinFontFace, P_ID::FONT_FACE }, { StyleIdx::hairpinFontSize, P_ID::FONT_SIZE }, { StyleIdx::hairpinFontBold, P_ID::FONT_BOLD }, { StyleIdx::hairpinFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::hairpinFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> bendStyle { { StyleIdx::bendFontFace, P_ID::FONT_FACE }, { StyleIdx::bendFontSize, P_ID::FONT_SIZE }, { StyleIdx::bendFontBold, P_ID::FONT_BOLD }, { StyleIdx::bendFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::bendFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> headerStyle { { StyleIdx::headerFontFace, P_ID::FONT_FACE }, { StyleIdx::headerFontSize, P_ID::FONT_SIZE }, { StyleIdx::headerFontBold, P_ID::FONT_BOLD }, { StyleIdx::headerFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::headerFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> footerStyle { { StyleIdx::footerFontFace, P_ID::FONT_FACE }, { StyleIdx::footerFontSize, P_ID::FONT_SIZE }, { StyleIdx::footerFontBold, P_ID::FONT_BOLD }, { StyleIdx::footerFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::footerFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> instrumentChangeStyle { { StyleIdx::instrumentChangeFontFace, P_ID::FONT_FACE }, { StyleIdx::instrumentChangeFontSize, P_ID::FONT_SIZE }, { StyleIdx::instrumentChangeFontBold, P_ID::FONT_BOLD }, { StyleIdx::instrumentChangeFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::instrumentChangeFontUnderline, P_ID::FONT_UNDERLINE }, { StyleIdx::instrumentChangeOffset, P_ID::OFFSET }, }; const std::vector<StyledProperty> figuredBassStyle { { StyleIdx::figuredBassFontFace, P_ID::FONT_FACE }, { StyleIdx::figuredBassFontSize, P_ID::FONT_SIZE }, { StyleIdx::figuredBassFontBold, P_ID::FONT_BOLD }, { StyleIdx::figuredBassFontItalic, P_ID::FONT_ITALIC }, { StyleIdx::figuredBassFontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> user1Style { { StyleIdx::user1FontFace, P_ID::FONT_FACE }, { StyleIdx::user1FontSize, P_ID::FONT_SIZE }, { StyleIdx::user1FontBold, P_ID::FONT_BOLD }, { StyleIdx::user1FontItalic, P_ID::FONT_ITALIC }, { StyleIdx::user1FontUnderline, P_ID::FONT_UNDERLINE }, }; const std::vector<StyledProperty> user2Style { { StyleIdx::user2FontFace, P_ID::FONT_FACE }, { StyleIdx::user2FontSize, P_ID::FONT_SIZE }, { StyleIdx::user2FontBold, P_ID::FONT_BOLD }, { StyleIdx::user2FontItalic, P_ID::FONT_ITALIC }, { StyleIdx::user2FontUnderline, P_ID::FONT_UNDERLINE }, }; //--------------------------------------------------------- // StyledPropertyListName //--------------------------------------------------------- struct StyledPropertyListName { const char* name; const std::vector<StyledProperty>* spl; SubStyle ss; }; //--------------------------------------------------------- // namedStyles // must be in sync with SubStyle enumeration //--------------------------------------------------------- static const std::array<StyledPropertyListName, int(SubStyle::SUBSTYLES)> namedStyles { { { QT_TRANSLATE_NOOP("TextStyle", "default"), &defaultStyle, SubStyle::DEFAULT }, { QT_TRANSLATE_NOOP("TextStyle", "Title"), &titleStyle, SubStyle::TITLE }, { QT_TRANSLATE_NOOP("TextStyle", "Subtitle"), &subTitleStyle, SubStyle::SUBTITLE }, { QT_TRANSLATE_NOOP("TextStyle", "Composer"), &composerStyle, SubStyle::COMPOSER }, { QT_TRANSLATE_NOOP("TextStyle", "Lyricist"), &lyricistStyle, SubStyle::POET }, { QT_TRANSLATE_NOOP("TextStyle", "Lyrics Odd Lines"), &lyricsOddStyle, SubStyle::LYRIC1 }, { QT_TRANSLATE_NOOP("TextStyle", "Lyrics Even Lines"), &lyricsEvenStyle, SubStyle::LYRIC2 }, { QT_TRANSLATE_NOOP("TextStyle", "Fingering"), &fingeringStyle, SubStyle::FINGERING }, { QT_TRANSLATE_NOOP("TextStyle", "LH Guitar Fingering"), &lhGuitarFingeringStyle, SubStyle::LH_GUITAR_FINGERING }, { QT_TRANSLATE_NOOP("TextStyle", "RH Guitar Fingering"), &rhGuitarFingeringStyle, SubStyle::RH_GUITAR_FINGERING }, { QT_TRANSLATE_NOOP("TextStyle", "String Number"), &stringNumberStyle, SubStyle::STRING_NUMBER }, { QT_TRANSLATE_NOOP("TextStyle", "Instrument Name (Long)"), &longInstrumentStyle, SubStyle::INSTRUMENT_LONG }, { QT_TRANSLATE_NOOP("TextStyle", "Instrument Name (Short)"), &shortInstrumentStyle, SubStyle::INSTRUMENT_SHORT }, { QT_TRANSLATE_NOOP("TextStyle", "Instrument Name (Part)"), &partInstrumentStyle, SubStyle::INSTRUMENT_EXCERPT }, { QT_TRANSLATE_NOOP("TextStyle", "Dynamics"), &dynamicsStyle, SubStyle::DYNAMICS }, { QT_TRANSLATE_NOOP("TextStyle", "Expression"), &expressionStyle, SubStyle::EXPRESSION }, { QT_TRANSLATE_NOOP("TextStyle", "Tempo"), &tempoStyle, SubStyle::TEMPO }, { QT_TRANSLATE_NOOP("TextStyle", "Metronome"), &metronomeStyle, SubStyle::METRONOME }, { QT_TRANSLATE_NOOP("TextStyle", "Measure Number"), &measureNumberStyle, SubStyle::MEASURE_NUMBER }, { QT_TRANSLATE_NOOP("TextStyle", "Translator"), &translatorStyle, SubStyle::TRANSLATOR }, { QT_TRANSLATE_NOOP("TextStyle", "Tuplet"), &tupletStyle, SubStyle::TUPLET }, { QT_TRANSLATE_NOOP("TextStyle", "System"), &systemStyle, SubStyle::SYSTEM }, { QT_TRANSLATE_NOOP("TextStyle", "Staff"), &staffStyle, SubStyle::STAFF }, { QT_TRANSLATE_NOOP("TextStyle", "Chord Symbol"), &chordSymbolStyle, SubStyle::HARMONY }, { QT_TRANSLATE_NOOP("TextStyle", "Rehearsal Mark"), &rehearsalMarkStyle, SubStyle::REHEARSAL_MARK }, { QT_TRANSLATE_NOOP("TextStyle", "Repeat Text Left"), &repeatLeftStyle, SubStyle::REPEAT_LEFT }, { QT_TRANSLATE_NOOP("TextStyle", "Repeat Text Right"), &repeatRightStyle, SubStyle::REPEAT_RIGHT }, { QT_TRANSLATE_NOOP("TextStyle", "Volta"), &voltaStyle, SubStyle::VOLTA }, { QT_TRANSLATE_NOOP("TextStyle", "Frame"), &frameStyle, SubStyle::FRAME }, { QT_TRANSLATE_NOOP("TextStyle", "Text Line"), &textLineStyle, SubStyle::TEXTLINE }, { QT_TRANSLATE_NOOP("TextStyle", "Glissando"), &glissandoStyle, SubStyle::GLISSANDO }, { QT_TRANSLATE_NOOP("TextStyle", "Ottava"), &ottavaStyle, SubStyle::OTTAVA }, { QT_TRANSLATE_NOOP("TextStyle", "Pedal"), &pedalStyle, SubStyle::PEDAL }, { QT_TRANSLATE_NOOP("TextStyle", "Hairpin"), &hairpinStyle, SubStyle::HAIRPIN }, { QT_TRANSLATE_NOOP("TextStyle", "Bend"), &bendStyle, SubStyle::BEND }, { QT_TRANSLATE_NOOP("TextStyle", "Header"), &headerStyle, SubStyle::HEADER }, { QT_TRANSLATE_NOOP("TextStyle", "Footer"), &footerStyle, SubStyle::FOOTER }, { QT_TRANSLATE_NOOP("TextStyle", "Instrument Change"), &instrumentChangeStyle, SubStyle::INSTRUMENT_CHANGE }, { QT_TRANSLATE_NOOP("TextStyle", "Figured Bass"), &figuredBassStyle, SubStyle::FIGURED_BASS }, { QT_TRANSLATE_NOOP("TextStyle", "User-1"), &user1Style, SubStyle::USER1 }, { QT_TRANSLATE_NOOP("TextStyle", "User-2"), &user2Style, SubStyle::USER2 }, } }; //--------------------------------------------------------- // subStyle //--------------------------------------------------------- const std::vector<StyledProperty>& subStyle(const char* name) { for (const StyledPropertyListName& s : namedStyles) { if (strcmp(s.name, name) == 0) return *s.spl; } qDebug("substyle <%s> not known", name); return *namedStyles[0].spl; } const std::vector<StyledProperty>& subStyle(SubStyle idx) { return *namedStyles[int(idx)].spl; } //--------------------------------------------------------- // subStyleFromName //--------------------------------------------------------- SubStyle subStyleFromName(const QString& name) { for (const StyledPropertyListName& s : namedStyles) { if (s.name == name) return SubStyle(s.ss); } qDebug("substyle <%s> not known", qPrintable(name)); return SubStyle::DEFAULT; } //--------------------------------------------------------- // subStyleName //--------------------------------------------------------- const char* subStyleName(SubStyle idx) { return namedStyles[int(idx)].name; } //--------------------------------------------------------- // subStyleUserName //--------------------------------------------------------- QString subStyleUserName(SubStyle idx) { return qApp->translate("TextStyle", subStyleName(idx)); } //--------------------------------------------------------- // valueType //--------------------------------------------------------- const char* MStyle::valueType(const StyleIdx i) { return styleTypes[int(i)].valueType(); } //--------------------------------------------------------- // valueName //--------------------------------------------------------- const char* MStyle::valueName(const StyleIdx i) { return styleTypes[int(i)].name(); } //--------------------------------------------------------- // styleIdx //--------------------------------------------------------- StyleIdx MStyle::styleIdx(const QString &name) { for (StyleType st : styleTypes) { if (st.name() == name) return st.styleIdx(); } return StyleIdx::NOSTYLE; } //--------------------------------------------------------- // Style //--------------------------------------------------------- MStyle::MStyle() { _customChordList = false; for (const StyleType& t : styleTypes) _values[t.idx()] = t.defaultValue(); //precomputeValues(); }; //--------------------------------------------------------- // precomputeValues //--------------------------------------------------------- void MStyle::precomputeValues() { qreal _spatium = value(StyleIdx::spatium).toDouble(); for (const StyleType& t : styleTypes) { if (!strcmp(t.valueType(), "Ms::Spatium")) _precomputedValues[t.idx()] = _values[t.idx()].value<Spatium>().val() * _spatium; } } //--------------------------------------------------------- // isDefault // caution: custom types need to register comparison operator // to make this work //--------------------------------------------------------- bool MStyle::isDefault(StyleIdx idx) const { return _values[int(idx)] == MScore::baseStyle().value(idx); } //--------------------------------------------------------- // chordDescription //--------------------------------------------------------- const ChordDescription* MStyle::chordDescription(int id) const { if (!_chordList.contains(id)) return 0; return &*_chordList.find(id); } //--------------------------------------------------------- // setChordList //--------------------------------------------------------- void MStyle::setChordList(ChordList* cl, bool custom) { _chordList = *cl; _customChordList = custom; } //--------------------------------------------------------- // set //--------------------------------------------------------- void MStyle::set(const StyleIdx t, const QVariant& val) { const int idx = int(t); _values[idx] = val; if (t == StyleIdx::spatium) precomputeValues(); else { if (!strcmp(styleTypes[idx].valueType(), "Ms::Spatium")) { qreal _spatium = value(StyleIdx::spatium).toDouble(); _precomputedValues[idx] = _values[idx].value<Spatium>().val() * _spatium; } } } //--------------------------------------------------------- // readProperties //--------------------------------------------------------- bool MStyle::readProperties(XmlReader& e) { const QStringRef& tag(e.name()); QString val(e.readElementText()); for (const StyleType& t : styleTypes) { StyleIdx idx = t.styleIdx(); if (t.name() == tag) { const char* type = t.valueType(); if (!strcmp("Ms::Spatium", type)) set(idx, Spatium(val.toDouble())); else if (!strcmp("double", type)) set(idx, QVariant(val.toDouble())); else if (!strcmp("bool", type)) set(idx, QVariant(bool(val.toInt()))); else if (!strcmp("int", type)) set(idx, QVariant(val.toInt())); else if (!strcmp("Ms::Direction", type)) set(idx, QVariant::fromValue(Direction(val.toInt()))); else if (!strcmp("QString", type)) set(idx, QVariant(val)); else { qFatal("MStyle::load: unhandled type %s", type); } return true; } } return false; } //--------------------------------------------------------- // load //--------------------------------------------------------- bool MStyle::load(QFile* qf) { XmlReader e(0, qf); while (e.readNextStartElement()) { if (e.name() == "museScore") { QString version = e.attribute("version"); QStringList sl = version.split('.'); int mscVersion = sl[0].toInt() * 100 + sl[1].toInt(); if (mscVersion != MSCVERSION) return false; while (e.readNextStartElement()) { if (e.name() == "Style") load(e); else e.unknown(); } } } return true; } void MStyle::load(XmlReader& e) { QString oldChordDescriptionFile = value(StyleIdx::chordDescriptionFile).toString(); bool chordListTag = false; while (e.readNextStartElement()) { const QStringRef& tag(e.name()); if (tag == "TextStyle") { e.skipCurrentElement(); // TextStyle s; //s.read(e); // setTextStyle(s); } else if (tag == "Spatium") set(StyleIdx::spatium, e.readDouble() * DPMM); else if (tag == "page-layout") // _pageFormat.read(e); e.skipCurrentElement(); else if (tag == "displayInConcertPitch") set(StyleIdx::concertPitch, QVariant(bool(e.readInt()))); else if (tag == "ChordList") { _chordList.clear(); _chordList.read(e); _customChordList = true; chordListTag = true; } else readProperties(e); } // if we just specified a new chord description file // and didn't encounter a ChordList tag // then load the chord description file QString newChordDescriptionFile = value(StyleIdx::chordDescriptionFile).toString(); if (newChordDescriptionFile != oldChordDescriptionFile && !chordListTag) { if (!newChordDescriptionFile.startsWith("chords_") && value(StyleIdx::chordStyle).toString() == "std") { // should not normally happen, // but treat as "old" (114) score just in case set(StyleIdx::chordStyle, QVariant(QString("custom"))); set(StyleIdx::chordsXmlFile, QVariant(true)); qDebug("StyleData::load: custom chord description file %s with chordStyle == std", qPrintable(newChordDescriptionFile)); } if (value(StyleIdx::chordStyle).toString() == "custom") _customChordList = true; else _customChordList = false; _chordList.unload(); } // make sure we have a chordlist if (!_chordList.loaded() && !chordListTag) { if (value(StyleIdx::chordsXmlFile).toBool()) _chordList.read("chords.xml"); _chordList.read(newChordDescriptionFile); } } //--------------------------------------------------------- // save //--------------------------------------------------------- void MStyle::save(XmlWriter& xml, bool optimize) { xml.stag("Style"); for (const StyleType& st : styleTypes) { StyleIdx idx = st.styleIdx(); if (idx == StyleIdx::spatium) // special handling for spatium continue; if (optimize && isDefault(idx)) continue; const char* type = st.valueType(); if (!strcmp("Ms::Spatium", type)) xml.tag(st.name(), value(idx).value<Spatium>().val()); else if (!strcmp("double", type)) xml.tag(st.name(), value(idx).toDouble()); else if (!strcmp("bool", type)) xml.tag(st.name(), value(idx).toInt()); else if (!strcmp("int", type)) xml.tag(st.name(), value(idx).toInt()); else if (!strcmp("Ms::Direction", type)) xml.tag(st.name(), value(idx).toInt()); else if (!strcmp("QString", type)) xml.tag(st.name(), value(idx).toString()); else qFatal("bad style type"); } if (_customChordList && !_chordList.empty()) { xml.stag("ChordList"); _chordList.write(xml); xml.etag(); } xml.tag("Spatium", value(StyleIdx::spatium).toDouble() / DPMM); xml.etag(); } #ifndef NDEBUG //--------------------------------------------------------- // checkStyles //--------------------------------------------------------- void checkStyles() { int idx = 0; for (const StyleType& t : styleTypes) { Q_ASSERT(t.idx() == idx); ++idx; } idx = 0; for (auto a : namedStyles) { Q_ASSERT(int(a.ss) == idx); ++idx; } } #endif //--------------------------------------------------------- // _defaultStyle //--------------------------------------------------------- MStyle MScore::_defaultStyle; }
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
libmscore/fingering.cpp
170
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2010-2011 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #include "fingering.h" #include "score.h" #include "staff.h" #include "undo.h" #include "xml.h" #include "chord.h" #include "part.h" #include "measure.h" #include "stem.h" namespace Ms { //--------------------------------------------------------- // Fingering //--------------------------------------------------------- Fingering::Fingering(Score* s) : Text(SubStyle::FINGERING, s) { setFlag(ElementFlag::HAS_TAG, true); // this is a layered element } //--------------------------------------------------------- // write //--------------------------------------------------------- void Fingering::write(XmlWriter& xml) const { if (!xml.canWrite(this)) return; xml.stag(name()); Text::writeProperties(xml); xml.etag(); } //--------------------------------------------------------- // read //--------------------------------------------------------- void Fingering::read(XmlReader& e) { while (e.readNextStartElement()) { if (!Text::readProperties(e)) e.unknown(); } } //--------------------------------------------------------- // layout //--------------------------------------------------------- void Fingering::layout() { Text::layout(); if (autoplace() && note()) { Chord* chord = note()->chord(); Staff* staff = chord->staff(); Part* part = staff->part(); int n = part->nstaves(); bool voices = chord->measure()->hasVoices(staff->idx()); bool below = voices ? !chord->up() : (n > 1) && (staff->rstaff() == n-1); bool tight = voices && !chord->beam(); qreal x = 0.0; qreal y = 0.0; qreal headWidth = note()->headWidth(); qreal headHeight = note()->headHeight(); qreal fh = headHeight; // TODO: fingering number height if (chord->notes().size() == 1) { x = headWidth * .5; if (below) { // place fingering below note y = fh + spatium() * .4; if (tight) { y += 0.5 * spatium(); if (chord->stem()) x += 0.5 * spatium(); } else if (chord->stem() && !chord->up()) { // on stem side y += chord->stem()->height(); x -= spatium() * .4; } } else { // place fingering above note y = -headHeight - spatium() * .4; if (tight) { y -= 0.5 * spatium(); if (chord->stem()) x -= 0.5 * spatium(); } else if (chord->stem() && chord->up()) { // on stem side y -= chord->stem()->height(); x += spatium() * .4; } } } else { x -= spatium(); } setUserOff(QPointF(x, y)); } } //--------------------------------------------------------- // draw //--------------------------------------------------------- void Fingering::draw(QPainter* painter) const { Text::draw(painter); } //--------------------------------------------------------- // accessibleInfo //--------------------------------------------------------- QString Fingering::accessibleInfo() const { QString rez = Element::accessibleInfo(); if (subStyle() == SubStyle::STRING_NUMBER) { rez += " " + tr("String number"); } return QString("%1: %2").arg(rez).arg(plainText()); } //--------------------------------------------------------- // getProperty //--------------------------------------------------------- QVariant Fingering::getProperty(P_ID propertyId) const { switch (propertyId) { default: return Text::getProperty(propertyId); } } //--------------------------------------------------------- // setProperty //--------------------------------------------------------- bool Fingering::setProperty(P_ID propertyId, const QVariant& v) { switch (propertyId) { default: return Text::setProperty(propertyId, v); } triggerLayout(); return true; } //--------------------------------------------------------- // propertyDefault //--------------------------------------------------------- QVariant Fingering::propertyDefault(P_ID id) const { switch (id) { case P_ID::SUB_STYLE: return int(SubStyle::FINGERING); default: return Text::propertyDefault(id); } } //--------------------------------------------------------- // propertyStyle //--------------------------------------------------------- PropertyFlags Fingering::propertyFlags(P_ID id) const { switch (id) { default: return Text::propertyFlags(id); } } //--------------------------------------------------------- // resetProperty //--------------------------------------------------------- void Fingering::resetProperty(P_ID id) { switch (id) { default: return Text::resetProperty(id); } } //--------------------------------------------------------- // getPropertyStyle //--------------------------------------------------------- StyleIdx Fingering::getPropertyStyle(P_ID id) const { switch (id) { default: return Text::getPropertyStyle(id); } return StyleIdx::NOSTYLE; } //--------------------------------------------------------- // styleChanged // reset all styled values to actual style //--------------------------------------------------------- void Fingering::styleChanged() { Text::styleChanged(); } //--------------------------------------------------------- // reset //--------------------------------------------------------- void Fingering::reset() { Text::reset(); } //--------------------------------------------------------- // subtypeName //--------------------------------------------------------- QString Fingering::subtypeName() const { return subStyleName(subStyle()); } }
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
libmscore/property.cpp
291
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2011 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #include "property.h" #include "mscore.h" #include "layoutbreak.h" #include "groups.h" #include "xml.h" #include "note.h" #include "barline.h" #include "style.h" #include "sym.h" namespace Ms { //--------------------------------------------------------- // PropertyData //--------------------------------------------------------- struct PropertyData { P_ID id; const char* qml; // qml name of property bool link; // link this property for linked elements const char* name; // xml name of property P_TYPE type; }; // // always: propertyList[subtype].id == subtype // // static const PropertyData propertyList[] = { { P_ID::SUBTYPE, "subtype", false, "subtype", P_TYPE::INT }, { P_ID::SELECTED, "selected", false, "selected", P_TYPE::BOOL }, { P_ID::GENERATED, "generated", false, "generated", P_TYPE::BOOL }, { P_ID::COLOR, "color", false, "color", P_TYPE::COLOR }, { P_ID::VISIBLE, "visible", false, "visible", P_TYPE::BOOL }, { P_ID::Z, "z", false, "z", P_TYPE::INT }, { P_ID::SMALL, "small", false, "small", P_TYPE::BOOL }, { P_ID::SHOW_COURTESY, "show_courtesy", false, "showCourtesy", P_TYPE::INT }, { P_ID::LINE_TYPE, "line_type", false, "lineType", P_TYPE::INT }, { P_ID::PITCH, "pitch", true, "pitch", P_TYPE::INT }, { P_ID::TPC1, "tpc1", true, "tpc", P_TYPE::INT }, { P_ID::TPC2, "tpc1", true, "tpc2", P_TYPE::INT }, { P_ID::LINE, "line", false, "line", P_TYPE::INT }, { P_ID::FIXED, "fixed", false, "fixed", P_TYPE::BOOL }, { P_ID::FIXED_LINE, "fixed_line", false, "fixedLine", P_TYPE::INT }, { P_ID::HEAD_TYPE, "head_type", false, "headType", P_TYPE::HEAD_TYPE }, { P_ID::HEAD_GROUP, "head_group", false, "head", P_TYPE::HEAD_GROUP }, { P_ID::VELO_TYPE, "velo_type", false, "veloType", P_TYPE::VALUE_TYPE }, { P_ID::VELO_OFFSET, "velo_offset", false, "velocity", P_TYPE::INT }, { P_ID::ARTICULATION_ANCHOR, "articulation_anchor", false, "anchor", P_TYPE::INT }, { P_ID::DIRECTION, "direction", false, "direction", P_TYPE::DIRECTION }, { P_ID::STEM_DIRECTION, "stem_direction", true, "StemDirection", P_TYPE::DIRECTION }, { P_ID::NO_STEM, "no_stem", false, "noStem", P_TYPE::INT }, { P_ID::SLUR_DIRECTION, "slur_direction", false, "up", P_TYPE::DIRECTION }, { P_ID::LEADING_SPACE, "leading_space", false, "leadingSpace", P_TYPE::SPATIUM }, { P_ID::DISTRIBUTE, "distribute", false, "distribute", P_TYPE::BOOL }, { P_ID::MIRROR_HEAD, "mirror_head", false, "mirror", P_TYPE::DIRECTION_H }, { P_ID::DOT_POSITION, "dot_position", false, "dotPosition", P_TYPE::DIRECTION }, { P_ID::TUNING, "tuning", false, "tuning", P_TYPE::REAL }, { P_ID::PAUSE, "pause", true, "pause", P_TYPE::REAL }, { P_ID::BARLINE_TYPE, "barline_type", false, "subtype", P_TYPE::BARLINE_TYPE }, { P_ID::BARLINE_SPAN, "barline_span", false, "span", P_TYPE::BOOL }, { P_ID::BARLINE_SPAN_FROM, "barline_span_from", false, "spanFromOffset", P_TYPE::INT }, { P_ID::BARLINE_SPAN_TO, "barline_span_to", false, "spanToOffset", P_TYPE::INT }, { P_ID::USER_OFF, "user_off", false, "userOff", P_TYPE::POINT }, { P_ID::FRET, "fret", true, "fret", P_TYPE::INT }, { P_ID::STRING, "string", true, "string", P_TYPE::INT }, { P_ID::GHOST, "ghost", true, "ghost", P_TYPE::BOOL }, { P_ID::PLAY, "play", false, "play", P_TYPE::BOOL }, { P_ID::TIMESIG_NOMINAL, "timesig_nominal", false, 0, P_TYPE::FRACTION }, { P_ID::TIMESIG_ACTUAL, "timesig_actual", true, 0, P_TYPE::FRACTION }, { P_ID::NUMBER_TYPE, "number_type", false, "numberType", P_TYPE::INT }, { P_ID::BRACKET_TYPE, "bracket_type", false, "bracketType", P_TYPE::INT }, { P_ID::NORMAL_NOTES, "normal_notes", false, "normalNotes", P_TYPE::INT }, { P_ID::ACTUAL_NOTES, "actual_notes", false, "actualNotes", P_TYPE::INT }, { P_ID::P1, "p1", false, "p1", P_TYPE::POINT }, { P_ID::P2, "p2", false, "p2", P_TYPE::POINT }, { P_ID::GROW_LEFT, "grow_left", false, "growLeft", P_TYPE::REAL }, { P_ID::GROW_RIGHT, "grow_right", false, "growRight", P_TYPE::REAL }, { P_ID::BOX_HEIGHT, "box_height", false, "height", P_TYPE::SPATIUM }, { P_ID::BOX_WIDTH, "box_width", false, "width", P_TYPE::SPATIUM }, { P_ID::TOP_GAP, "top_gap", false, "topGap", P_TYPE::SP_REAL }, { P_ID::BOTTOM_GAP, "bottom_gap", false, "bottomGap", P_TYPE::SP_REAL }, { P_ID::LEFT_MARGIN, "left_margin", false, "leftMargin", P_TYPE::REAL }, { P_ID::RIGHT_MARGIN, "right_margin", false, "rightMargin", P_TYPE::REAL }, { P_ID::TOP_MARGIN, "top_margin", false, "topMargin", P_TYPE::REAL }, { P_ID::BOTTOM_MARGIN, "bottom_margin", false, "bottomMargin", P_TYPE::REAL }, { P_ID::LAYOUT_BREAK, "layout_break", false, "subtype", P_TYPE::LAYOUT_BREAK }, { P_ID::AUTOSCALE, "autoscale", false, "autoScale", P_TYPE::BOOL }, { P_ID::SIZE, "size", false, "size", P_TYPE::SIZE }, { P_ID::SCALE, "scale", false, 0, P_TYPE::SCALE }, { P_ID::LOCK_ASPECT_RATIO, "lock_aspect_ratio", false, "lockAspectRatio", P_TYPE::BOOL }, { P_ID::SIZE_IS_SPATIUM, "size_is_spatium", false, "sizeIsSpatium", P_TYPE::BOOL }, { P_ID::TEXT, "text", false, 0, P_TYPE::STRING }, { P_ID::HTML_TEXT, "html_text", false, 0, P_TYPE::STRING }, { P_ID::USER_MODIFIED, "user_modified", false, 0, P_TYPE::BOOL }, { P_ID::BEAM_POS, "beam_pos", false, 0, P_TYPE::POINT }, { P_ID::BEAM_MODE, "beam_mode", true, "BeamMode", P_TYPE::BEAM_MODE }, { P_ID::BEAM_NO_SLOPE, "beam_no_slope", true, "noSlope", P_TYPE::BOOL }, { P_ID::USER_LEN, "user_len", false, "userLen", P_TYPE::REAL }, { P_ID::SPACE, "space", false, "space", P_TYPE::SP_REAL }, { P_ID::TEMPO, "tempo", true, "tempo", P_TYPE::TEMPO }, { P_ID::TEMPO_FOLLOW_TEXT, "tempo_follow_text", true, "followText", P_TYPE::BOOL }, { P_ID::ACCIDENTAL_BRACKET, "accidental_bracket", false, "bracket", P_TYPE::BOOL }, { P_ID::NUMERATOR_STRING, "numerator_string", false, "textN", P_TYPE::STRING }, { P_ID::DENOMINATOR_STRING, "denominator_string", false, "textD", P_TYPE::STRING }, { P_ID::FBPREFIX, "fbprefix", false, "prefix", P_TYPE::INT }, { P_ID::FBDIGIT, "fbdigit", false, "digit", P_TYPE::INT }, { P_ID::FBSUFFIX, "fbsuffix", false, "suffix", P_TYPE::INT }, { P_ID::FBCONTINUATIONLINE, "fbcontinuationline", false, "continuationLine", P_TYPE::INT }, { P_ID::FBPARENTHESIS1, "fbparenthesis1", false, "", P_TYPE::INT }, { P_ID::FBPARENTHESIS2, "fbparenthesis2", false, "", P_TYPE::INT }, { P_ID::FBPARENTHESIS3, "fbparenthesis3", false, "", P_TYPE::INT }, { P_ID::FBPARENTHESIS4, "fbparenthesis4", false, "", P_TYPE::INT }, { P_ID::FBPARENTHESIS5, "fbparenthesis5", false, "", P_TYPE::INT }, { P_ID::VOLTA_TYPE, "volta_type", false, "", P_TYPE::INT }, { P_ID::OTTAVA_TYPE, "ottava_type", false, "", P_TYPE::INT }, { P_ID::NUMBERS_ONLY, "numbers_only", false, "numbersOnly", P_TYPE::BOOL }, { P_ID::TRILL_TYPE, "trill_type", false, "", P_TYPE::INT }, { P_ID::HAIRPIN_CIRCLEDTIP, "hairpin_circledtip", false, "hairpinCircledTip", P_TYPE::BOOL }, { P_ID::HAIRPIN_TYPE, "hairpin_type", true, "", P_TYPE::INT }, { P_ID::HAIRPIN_HEIGHT, "hairpin_height", false, "hairpinHeight", P_TYPE::SPATIUM }, { P_ID::HAIRPIN_CONT_HEIGHT, "hairpin_cont_height", false, "hairpinContHeight", P_TYPE::SPATIUM }, { P_ID::VELO_CHANGE, "velo_change", true, "veloChange", P_TYPE::INT }, { P_ID::DYNAMIC_RANGE, "dynamic_range", true, "dynType", P_TYPE::INT }, { P_ID::PLACEMENT, "placement", false, "placement", P_TYPE::PLACEMENT }, { P_ID::VELOCITY, "velocity", false, "velocity", P_TYPE::INT }, { P_ID::JUMP_TO, "jump_to", false, "jumpTo", P_TYPE::STRING }, { P_ID::PLAY_UNTIL, "play_until", false, "playUntil", P_TYPE::STRING }, { P_ID::CONTINUE_AT, "continue_at", false, "continueAt", P_TYPE::STRING }, /*100*/ { P_ID::LABEL, "label", false, "label", P_TYPE::STRING }, { P_ID::MARKER_TYPE, "marker_type", false, 0, P_TYPE::INT }, { P_ID::ARP_USER_LEN1, "arp_user_len1", false, 0, P_TYPE::REAL }, { P_ID::ARP_USER_LEN2, "arp_user_len2", false, 0, P_TYPE::REAL }, { P_ID::REPEAT_END, "repeat_end", true, 0, P_TYPE::BOOL }, { P_ID::REPEAT_START, "repeat_start", true, 0, P_TYPE::BOOL }, { P_ID::REPEAT_JUMP, "repeat_jump", true, 0, P_TYPE::BOOL }, { P_ID::MEASURE_NUMBER_MODE, "measure_number_mode", false, "measureNumberMode", P_TYPE::INT }, { P_ID::GLISS_TYPE, "gliss_type", false, 0, P_TYPE::INT }, { P_ID::GLISS_TEXT, "gliss_text", false, 0, P_TYPE::STRING }, { P_ID::GLISS_SHOW_TEXT, "gliss_show_text", false, 0, P_TYPE::BOOL }, { P_ID::DIAGONAL, "diagonal", false, 0, P_TYPE::BOOL }, { P_ID::GROUPS, "groups", false, 0, P_TYPE::GROUPS }, { P_ID::LINE_STYLE, "line_style", false, "lineStyle", P_TYPE::INT }, { P_ID::LINE_COLOR, "line_color", false, 0, P_TYPE::COLOR }, { P_ID::LINE_WIDTH, "line_width", false, "lineWidth", P_TYPE::SPATIUM }, { P_ID::LASSO_POS, "lasso_pos", false, 0, P_TYPE::POINT_MM }, { P_ID::LASSO_SIZE, "lasso_size", false, 0, P_TYPE::SIZE_MM }, { P_ID::TIME_STRETCH, "time_stretch", false, "timeStretch", P_TYPE::REAL }, { P_ID::ORNAMENT_STYLE, "ornament_style", false, "ornamentStyle", P_TYPE::ORNAMENT_STYLE }, { P_ID::TIMESIG, "timesig", false, 0, P_TYPE::FRACTION }, { P_ID::TIMESIG_GLOBAL, "timesig_global", false, 0, P_TYPE::FRACTION }, { P_ID::TIMESIG_STRETCH, "timesig_stretch", false, 0, P_TYPE::FRACTION }, { P_ID::TIMESIG_TYPE, "timesig_type", true, 0, P_TYPE::INT }, { P_ID::SPANNER_TICK, "spanner_tick", true, "tick", P_TYPE::INT }, { P_ID::SPANNER_TICKS, "spanner_ticks", true, "ticks", P_TYPE::INT }, { P_ID::SPANNER_TRACK2, "spanner_track2", true, "track2", P_TYPE::INT }, { P_ID::USER_OFF2, "user_off2", false, "userOff2", P_TYPE::POINT }, { P_ID::BEGIN_TEXT_PLACE, "begin_text_place", false, "beginTextPlace", P_TYPE::INT }, { P_ID::CONTINUE_TEXT_PLACE, "continue_text_place", false, "continueTextPlace", P_TYPE::INT }, { P_ID::END_TEXT_PLACE, "end_text_place", false, "endTextPlace", P_TYPE::INT }, { P_ID::BEGIN_HOOK, "begin_hook", false, "beginHook", P_TYPE::BOOL }, { P_ID::END_HOOK, "end_hook", false, "endHook", P_TYPE::BOOL }, { P_ID::BEGIN_HOOK_HEIGHT, "begin_hook_height", false, "beginHookHeight", P_TYPE::SPATIUM }, { P_ID::END_HOOK_HEIGHT, "end_hook_height", false, "endHookHeight", P_TYPE::SPATIUM }, { P_ID::BEGIN_HOOK_TYPE, "begin_hook_type", false, "beginHookType", P_TYPE::INT }, { P_ID::END_HOOK_TYPE, "end_hook_type", false, "endHookType", P_TYPE::INT }, { P_ID::BEGIN_TEXT, "begin_text", true, "beginText", P_TYPE::STRING }, { P_ID::CONTINUE_TEXT, "continue_text", true, "continueText", P_TYPE::STRING }, { P_ID::END_TEXT, "end_text", true, "endText", P_TYPE::STRING }, { P_ID::BEGIN_TEXT_STYLE, "begin_text_style", false, "beginTextStyle", P_TYPE::TEXT_STYLE }, { P_ID::CONTINUE_TEXT_STYLE, "continue_text_style", false, "continueTextStyle", P_TYPE::TEXT_STYLE }, { P_ID::END_TEXT_STYLE, "end_text_style", false, "endTextStyle", P_TYPE::TEXT_STYLE }, { P_ID::BREAK_MMR, "break_mmr", false, "breakMultiMeasureRest", P_TYPE::BOOL }, { P_ID::REPEAT_COUNT, "repeat_count", true, "endRepeat", P_TYPE::INT }, { P_ID::USER_STRETCH, "user_stretch", false, "stretch", P_TYPE::REAL }, { P_ID::NO_OFFSET, "no_offset", false, "noOffset", P_TYPE::INT }, { P_ID::IRREGULAR, "irregular", true, "irregular", P_TYPE::BOOL }, { P_ID::ANCHOR, "anchor", false, "anchor", P_TYPE::INT }, { P_ID::SLUR_UOFF1, "slur_uoff1", false, "o1", P_TYPE::POINT }, //150 { P_ID::SLUR_UOFF2, "slur_uoff2", false, "o2", P_TYPE::POINT }, { P_ID::SLUR_UOFF3, "slur_uoff3", false, "o3", P_TYPE::POINT }, { P_ID::SLUR_UOFF4, "slur_uoff4", false, "o4", P_TYPE::POINT }, { P_ID::STAFF_MOVE, "staff_move", true, "move", P_TYPE::INT }, { P_ID::VERSE, "verse", true, "no", P_TYPE::ZERO_INT }, { P_ID::SYLLABIC, "syllabic", true, "syllabic", P_TYPE::INT }, { P_ID::LYRIC_TICKS, "lyric_ticks", true, "ticks", P_TYPE::INT }, { P_ID::VOLTA_ENDING, "volta_ending", true, "endings", P_TYPE::INT_LIST }, { P_ID::LINE_VISIBLE, "line_visible", true, "lineVisible", P_TYPE::BOOL }, { P_ID::MAG, "mag", false, "mag", P_TYPE::REAL }, { P_ID::USE_DRUMSET, "use_drumset", false, "useDrumset", P_TYPE::BOOL }, { P_ID::PART_VOLUME, "part_volume", false, "volume", P_TYPE::INT }, { P_ID::PART_MUTE, "part_mute", false, "mute", P_TYPE::BOOL }, { P_ID::PART_PAN, "part_pan", false, "pan", P_TYPE::INT }, { P_ID::PART_REVERB, "part_reverb", false, "reverb", P_TYPE::INT }, { P_ID::PART_CHORUS, "part_chorus", false, "chorus", P_TYPE::INT }, { P_ID::DURATION, "duration", false, 0, P_TYPE::FRACTION }, { P_ID::DURATION_TYPE, "duration_type", false, 0, P_TYPE::TDURATION }, { P_ID::ROLE, "role", false, "role", P_TYPE::INT }, { P_ID::TRACK, "track", false, 0, P_TYPE::INT }, { P_ID::GLISSANDO_STYLE, "glissando_style", false, "glissandoStyle", P_TYPE::GLISSANDO_STYLE }, { P_ID::FRET_STRINGS, "fret_strings", false, "strings", P_TYPE::INT }, { P_ID::FRET_FRETS, "fret_frets", false, "frets", P_TYPE::INT }, { P_ID::FRET_BARRE, "fret_barre", false, "barre", P_TYPE::INT }, { P_ID::FRET_OFFSET, "fret_offset", false, "fretOffset", P_TYPE::INT }, { P_ID::SYSTEM_BRACKET, "system_bracket", false, "type", P_TYPE::INT }, { P_ID::GAP, "gap", false, 0, P_TYPE::BOOL }, { P_ID::AUTOPLACE, "autoplace", false, 0, P_TYPE::BOOL }, { P_ID::DASH_LINE_LEN, "dash_line_len", false, "dashLineLength", P_TYPE::REAL }, { P_ID::DASH_GAP_LEN, "dash_gap_len", false, "dashGapLength", P_TYPE::REAL }, { P_ID::TICK, "tick", false, 0, P_TYPE::INT }, { P_ID::PLAYBACK_VOICE1, "playback_voice1", false, "playbackVoice1", P_TYPE::BOOL }, { P_ID::PLAYBACK_VOICE2, "playback_voice2", false, "playbackVoice2", P_TYPE::BOOL }, { P_ID::PLAYBACK_VOICE3, "playback_voice3", false, "playbackVoice3", P_TYPE::BOOL }, { P_ID::PLAYBACK_VOICE4, "playback_voice4", false, "playbackVoice4", P_TYPE::BOOL }, { P_ID::SYMBOL, "symbol", true, "symbol", P_TYPE::SYMID }, { P_ID::PLAY_REPEATS, "play_repeats", false, "playRepeats", P_TYPE::BOOL }, { P_ID::CREATE_SYSTEM_HEADER, "create_system_header", false, "createSystemHeader", P_TYPE::BOOL }, { P_ID::STAFF_LINES, "staff_lines", true, "lines", P_TYPE::INT }, { P_ID::LINE_DISTANCE, "line_distance", true, "lineDistance", P_TYPE::SPATIUM }, { P_ID::STEP_OFFSET, "step_offset", true, "stepOffset", P_TYPE::INT }, { P_ID::STAFF_SHOW_BARLINES, "staff_show_barlines", false, "", P_TYPE::BOOL }, { P_ID::STAFF_SHOW_LEDGERLINES, "staff_show_ledgerlines", false, "", P_TYPE::BOOL }, { P_ID::STAFF_SLASH_STYLE, "staff_slash_style", false, "", P_TYPE::BOOL }, { P_ID::STAFF_NOTEHEAD_SCHEME, "staff_notehead_scheme", false, "", P_TYPE::INT }, { P_ID::STAFF_GEN_CLEF, "staff_gen_clef", false, "", P_TYPE::BOOL }, { P_ID::STAFF_GEN_TIMESIG, "staff_gen_timesig", false, "", P_TYPE::BOOL }, { P_ID::STAFF_GEN_KEYSIG, "staff_gen_keysig", false, "", P_TYPE::BOOL }, { P_ID::STAFF_YOFFSET, "staff_yoffset", false, "", P_TYPE::SPATIUM }, { P_ID::STAFF_USERDIST, "staff_userdist", false, "distOffset", P_TYPE::SP_REAL }, //200 { P_ID::STAFF_BARLINE_SPAN, "staff_barline_span", false, "barLineSpan", P_TYPE::BOOL }, { P_ID::STAFF_BARLINE_SPAN_FROM, "staff_barline_span_from", false, "barLineSpanFrom", P_TYPE::INT }, { P_ID::STAFF_BARLINE_SPAN_TO, "staff_barline_span_to", false, "barLineSpanTo", P_TYPE::INT }, { P_ID::BRACKET_COLUMN, "bracket_column", false, "level", P_TYPE::INT }, { P_ID::INAME_LAYOUT_POSITION, "iname_layout_position", false, "layoutPosition", P_TYPE::INT }, { P_ID::SUB_STYLE, "sub_style", false, "style", P_TYPE::SUB_STYLE }, { P_ID::FONT_FACE, "font_face", false, "family", P_TYPE::FONT }, { P_ID::FONT_SIZE, "font_size", false, "size", P_TYPE::REAL }, { P_ID::FONT_BOLD, "font_bold", false, "bold", P_TYPE::BOOL }, { P_ID::FONT_ITALIC, "font_italic", false, "italic", P_TYPE::BOOL }, { P_ID::FONT_UNDERLINE, "font_underline", false, "underline", P_TYPE::BOOL }, { P_ID::FRAME, "has_frame", false, "hasFrame", P_TYPE::BOOL }, { P_ID::FRAME_SQUARE, "frame_square", false, "frameSquare", P_TYPE::BOOL }, { P_ID::FRAME_CIRCLE, "frame_circle", false, "frameCircle", P_TYPE::BOOL }, { P_ID::FRAME_WIDTH, "frame_width", false, "frameWidth", P_TYPE::SPATIUM }, { P_ID::FRAME_PADDING, "frame_padding", false, "framePadding", P_TYPE::SPATIUM }, { P_ID::FRAME_ROUND, "frame_round", false, "frameRound", P_TYPE::INT }, { P_ID::FRAME_FG_COLOR, "frame_fg_color", false, "frameFgColor", P_TYPE::COLOR }, { P_ID::FRAME_BG_COLOR, "frame_bg_color", false, "frameBgColor", P_TYPE::COLOR }, { P_ID::FONT_SPATIUM_DEPENDENT, "font_spatium_dependent", false, "sizeIsSpatiumDependent", P_TYPE::BOOL }, { P_ID::ALIGN, "align", false, "align", P_TYPE::ALIGN }, { P_ID::OFFSET, "offset", false, "offset", P_TYPE::POINT }, { P_ID::OFFSET_TYPE, "offset_type", false, "offsetType", P_TYPE::INT }, { P_ID::SYSTEM_FLAG, "system_flag", false, "systemFlag", P_TYPE::BOOL }, { P_ID::END, "", false, "", P_TYPE::INT } }; //--------------------------------------------------------- // propertyType //--------------------------------------------------------- P_TYPE propertyType(P_ID id) { Q_ASSERT( propertyList[int(id)].id == id); return propertyList[int(id)].type; } //--------------------------------------------------------- // propertyLink //--------------------------------------------------------- bool propertyLink(P_ID id) { Q_ASSERT( propertyList[int(id)].id == id); return propertyList[int(id)].link; } //--------------------------------------------------------- // propertyName //--------------------------------------------------------- const char* propertyName(P_ID id) { Q_ASSERT( propertyList[int(id)].id == id); return propertyList[int(id)].name; } const char* propertyQmlName(P_ID id) { Q_ASSERT( propertyList[int(id)].id == id); return propertyList[int(id)].qml; } //--------------------------------------------------------- // getProperty //--------------------------------------------------------- QVariant getProperty(P_ID id, XmlReader& e) { switch (propertyType(id)) { case P_TYPE::BOOL: return QVariant(bool(e.readInt())); case P_TYPE::SUBTYPE: case P_TYPE::ZERO_INT: case P_TYPE::INT: return QVariant(e.readInt()); case P_TYPE::REAL: case P_TYPE::SPATIUM: case P_TYPE::SP_REAL: case P_TYPE::TEMPO: return QVariant(e.readDouble()); case P_TYPE::FRACTION: return QVariant::fromValue(e.readFraction()); case P_TYPE::COLOR: return QVariant(e.readColor()); case P_TYPE::POINT: return QVariant(e.readPoint()); case P_TYPE::SCALE: case P_TYPE::SIZE: return QVariant(e.readSize()); case P_TYPE::FONT: case P_TYPE::STRING: return QVariant(e.readElementText()); case P_TYPE::GLISSANDO_STYLE: { QString value(e.readElementText()); if ( value == "whitekeys") return QVariant(int(MScore::GlissandoStyle::WHITE_KEYS)); else if ( value == "blackkeys") return QVariant(int(MScore::GlissandoStyle::BLACK_KEYS)); else if ( value == "diatonic") return QVariant(int(MScore::GlissandoStyle::DIATONIC)); else // e.g., normally "Chromatic" return QVariant(int(MScore::GlissandoStyle::CHROMATIC)); } break; case P_TYPE::ORNAMENT_STYLE: { QString value(e.readElementText()); if ( value == "baroque") return QVariant(int(MScore::OrnamentStyle::BAROQUE)); return QVariant(int(MScore::OrnamentStyle::DEFAULT)); } case P_TYPE::DIRECTION: return QVariant::fromValue(Direction(e.readElementText())); case P_TYPE::DIRECTION_H: { QString value(e.readElementText()); if (value == "left" || value == "1") return QVariant(int(MScore::DirectionH::LEFT)); else if (value == "right" || value == "2") return QVariant(int(MScore::DirectionH::RIGHT)); else if (value == "auto") return QVariant(int(MScore::DirectionH::AUTO)); } break; case P_TYPE::LAYOUT_BREAK: { QString value(e.readElementText()); if (value == "line") return QVariant(int(LayoutBreak::LINE)); if (value == "page") return QVariant(int(LayoutBreak::PAGE)); if (value == "section") return QVariant(int(LayoutBreak::SECTION)); if (value == "nobreak") return QVariant(int(LayoutBreak::NOBREAK)); qDebug("getProperty: invalid P_TYPE::LAYOUT_BREAK: <%s>", qPrintable(value)); } break; case P_TYPE::VALUE_TYPE: { QString value(e.readElementText()); if (value == "offset") return QVariant(int(Note::ValueType::OFFSET_VAL)); else if (value == "user") return QVariant(int(Note::ValueType::USER_VAL)); } break; case P_TYPE::PLACEMENT: { QString value(e.readElementText()); if (value == "above") return QVariant(int(Element::Placement::ABOVE)); else if (value == "below") return QVariant(int(Element::Placement::BELOW)); } break; case P_TYPE::BARLINE_TYPE: { bool ok; const QString& val(e.readElementText()); int ct = val.toInt(&ok); if (ok) return QVariant(ct); else { BarLineType t = BarLine::barLineType(val); return QVariant::fromValue(t); } } break; case P_TYPE::BEAM_MODE: // TODO return QVariant(int(0)); case P_TYPE::GROUPS: { Groups g; g.read(e); return QVariant::fromValue(g); } case P_TYPE::SYMID: return QVariant::fromValue(Sym::name2id(e.readElementText())); break; case P_TYPE::HEAD_GROUP: return QVariant::fromValue(NoteHead::name2group(e.readElementText()));; case P_TYPE::HEAD_TYPE: return QVariant::fromValue(NoteHead::name2type(e.readElementText())); case P_TYPE::POINT_MM: // not supported case P_TYPE::TDURATION: case P_TYPE::SIZE_MM: case P_TYPE::TEXT_STYLE: case P_TYPE::INT_LIST: return QVariant(); case P_TYPE::SUB_STYLE: return int(subStyleFromName(e.readElementText())); case P_TYPE::ALIGN: { QString s = e.readElementText(); QStringList sl = s.split(','); if (sl.size() != 2) { qDebug("bad align text <%s>", qPrintable(s)); return QVariant(); } Align align = Align::LEFT; if (sl[0] == "center") align = align | Align::HCENTER; else if (sl[0] == "right") align = align | Align::RIGHT; else if (sl[0] == "left") ; else { qDebug("bad align text <%s>", qPrintable(sl[0])); return QVariant(); } if (sl[1] == "center") align = align | Align::VCENTER; else if (sl[1] == "bottom") align = align | Align::BOTTOM; else if (sl[1] == "baseline") align = align | Align::BASELINE; else if (sl[1] == "top") ; else { qDebug("bad align text <%s>", qPrintable(sl[1])); return QVariant(); } return int(align); } } return QVariant(); } #ifndef NDEBUG //--------------------------------------------------------- // checkProperties //--------------------------------------------------------- void checkProperties() { int idx = 0; for (const PropertyData& d : propertyList) { if (int(d.id) != idx) qDebug("====%s %d != %d", d.qml, int(d.id), idx); Q_ASSERT(int(d.id) == idx); ++idx; } } #endif }
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
libmscore/scoreElement.cpp
232
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2015 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #include "scoreElement.h" #include "score.h" #include "undo.h" #include "xml.h" namespace Ms { // // list has to be synchronized with ElementType enum // static const ElementName elementNames[] = { { ElementType::INVALID, "invalid", QT_TRANSLATE_NOOP("elementName", "invalid") }, { ElementType::PART, "Part", QT_TRANSLATE_NOOP("elementName", "Part") }, { ElementType::STAFF, "Staff", QT_TRANSLATE_NOOP("elementName", "Staff") }, { ElementType::SCORE, "Score", QT_TRANSLATE_NOOP("elementName", "Score") }, { ElementType::SYMBOL, "Symbol", QT_TRANSLATE_NOOP("elementName", "Symbol") }, { ElementType::TEXT, "Text", QT_TRANSLATE_NOOP("elementName", "Text") }, { ElementType::INSTRUMENT_NAME, "InstrumentName", QT_TRANSLATE_NOOP("elementName", "Instrument Name") }, { ElementType::SLUR_SEGMENT, "SlurSegment", QT_TRANSLATE_NOOP("elementName", "Slur Segment") }, { ElementType::TIE_SEGMENT, "TieSegment", QT_TRANSLATE_NOOP("elementName", "Tie Segment") }, { ElementType::STAFF_LINES, "StaffLines", QT_TRANSLATE_NOOP("elementName", "Staff Lines") }, { ElementType::BAR_LINE, "BarLine", QT_TRANSLATE_NOOP("elementName", "Barline") }, { ElementType::SYSTEM_DIVIDER, "SystemDivider", QT_TRANSLATE_NOOP("elementName", "System Divider") }, { ElementType::STEM_SLASH, "StemSlash", QT_TRANSLATE_NOOP("elementName", "Stem Slash") }, { ElementType::LINE, "Line", QT_TRANSLATE_NOOP("elementName", "Line") }, { ElementType::ARPEGGIO, "Arpeggio", QT_TRANSLATE_NOOP("elementName", "Arpeggio") }, { ElementType::ACCIDENTAL, "Accidental", QT_TRANSLATE_NOOP("elementName", "Accidental") }, { ElementType::LEDGER_LINE, "LedgerLine", QT_TRANSLATE_NOOP("elementName", "Ledger Line") }, { ElementType::STEM, "Stem", QT_TRANSLATE_NOOP("elementName", "Stem") }, { ElementType::NOTE, "Note", QT_TRANSLATE_NOOP("elementName", "Note") }, { ElementType::CLEF, "Clef", QT_TRANSLATE_NOOP("elementName", "Clef") }, { ElementType::KEYSIG, "KeySig", QT_TRANSLATE_NOOP("elementName", "Key Signature") }, { ElementType::AMBITUS, "Ambitus", QT_TRANSLATE_NOOP("elementName", "Ambitus") }, { ElementType::TIMESIG, "TimeSig", QT_TRANSLATE_NOOP("elementName", "Time Signature") }, { ElementType::REST, "Rest", QT_TRANSLATE_NOOP("elementName", "Rest") }, { ElementType::BREATH, "Breath", QT_TRANSLATE_NOOP("elementName", "Breath") }, { ElementType::REPEAT_MEASURE, "RepeatMeasure", QT_TRANSLATE_NOOP("elementName", "Repeat Measure") }, { ElementType::TIE, "Tie", QT_TRANSLATE_NOOP("elementName", "Tie") }, { ElementType::ARTICULATION, "Articulation", QT_TRANSLATE_NOOP("elementName", "Articulation") }, { ElementType::CHORDLINE, "ChordLine", QT_TRANSLATE_NOOP("elementName", "Chord Line") }, { ElementType::DYNAMIC, "Dynamic", QT_TRANSLATE_NOOP("elementName", "Dynamic") }, { ElementType::BEAM, "Beam", QT_TRANSLATE_NOOP("elementName", "Beam") }, { ElementType::HOOK, "Hook", QT_TRANSLATE_NOOP("elementName", "Hook") }, { ElementType::LYRICS, "Lyrics", QT_TRANSLATE_NOOP("elementName", "Lyrics") }, { ElementType::FIGURED_BASS, "FiguredBass", QT_TRANSLATE_NOOP("elementName", "Figured Bass") }, { ElementType::MARKER, "Marker", QT_TRANSLATE_NOOP("elementName", "Marker") }, { ElementType::JUMP, "Jump", QT_TRANSLATE_NOOP("elementName", "Jump") }, { ElementType::FINGERING, "Fingering", QT_TRANSLATE_NOOP("elementName", "Fingering") }, { ElementType::TUPLET, "Tuplet", QT_TRANSLATE_NOOP("elementName", "Tuplet") }, { ElementType::TEMPO_TEXT, "Tempo", QT_TRANSLATE_NOOP("elementName", "Tempo") }, { ElementType::STAFF_TEXT, "StaffText", QT_TRANSLATE_NOOP("elementName", "Staff Text") }, { ElementType::SYSTEM_TEXT, "SystemText", QT_TRANSLATE_NOOP("elementName", "System Text") }, { ElementType::REHEARSAL_MARK, "RehearsalMark", QT_TRANSLATE_NOOP("elementName", "Rehearsal Mark") }, { ElementType::INSTRUMENT_CHANGE, "InstrumentChange", QT_TRANSLATE_NOOP("elementName", "Instrument Change") }, { ElementType::STAFFTYPE_CHANGE, "StaffTypeChange", QT_TRANSLATE_NOOP("elementName", "Staff Typeype Change") }, { ElementType::HARMONY, "Harmony", QT_TRANSLATE_NOOP("elementName", "Chord Symbol") }, { ElementType::FRET_DIAGRAM, "FretDiagram", QT_TRANSLATE_NOOP("elementName", "Fretboard Diagram") }, { ElementType::BEND, "Bend", QT_TRANSLATE_NOOP("elementName", "Bend") }, { ElementType::TREMOLOBAR, "TremoloBar", QT_TRANSLATE_NOOP("elementName", "Tremolo Bar") }, { ElementType::VOLTA, "Volta", QT_TRANSLATE_NOOP("elementName", "Volta") }, { ElementType::HAIRPIN_SEGMENT, "HairpinSegment", QT_TRANSLATE_NOOP("elementName", "Hairpin Segment") }, { ElementType::OTTAVA_SEGMENT, "OttavaSegment", QT_TRANSLATE_NOOP("elementName", "Ottava Segment") }, { ElementType::TRILL_SEGMENT, "TrillSegment", QT_TRANSLATE_NOOP("elementName", "Trill Segment") }, { ElementType::TEXTLINE_SEGMENT, "TextLineSegment", QT_TRANSLATE_NOOP("elementName", "Text Line Segment") }, { ElementType::VOLTA_SEGMENT, "VoltaSegment", QT_TRANSLATE_NOOP("elementName", "Volta Segment") }, { ElementType::PEDAL_SEGMENT, "PedalSegment", QT_TRANSLATE_NOOP("elementName", "Pedal Segment") }, { ElementType::LYRICSLINE_SEGMENT, "LyricsLineSegment", QT_TRANSLATE_NOOP("elementName", "Melisma Line Segment") }, { ElementType::GLISSANDO_SEGMENT, "GlissandoSegment", QT_TRANSLATE_NOOP("elementName", "Glissando Segment") }, { ElementType::LAYOUT_BREAK, "LayoutBreak", QT_TRANSLATE_NOOP("elementName", "Layout Break") }, { ElementType::SPACER, "Spacer", QT_TRANSLATE_NOOP("elementName", "Spacer") }, { ElementType::STAFF_STATE, "StaffState", QT_TRANSLATE_NOOP("elementName", "Staff State") }, { ElementType::NOTEHEAD, "NoteHead", QT_TRANSLATE_NOOP("elementName", "Notehead") }, { ElementType::NOTEDOT, "NoteDot", QT_TRANSLATE_NOOP("elementName", "Note Dot") }, { ElementType::TREMOLO, "Tremolo", QT_TRANSLATE_NOOP("elementName", "Tremolo") }, { ElementType::IMAGE, "Image", QT_TRANSLATE_NOOP("elementName", "Image") }, { ElementType::MEASURE, "Measure", QT_TRANSLATE_NOOP("elementName", "Measure") }, { ElementType::SELECTION, "Selection", QT_TRANSLATE_NOOP("elementName", "Selection") }, { ElementType::LASSO, "Lasso", QT_TRANSLATE_NOOP("elementName", "Lasso") }, { ElementType::SHADOW_NOTE, "ShadowNote", QT_TRANSLATE_NOOP("elementName", "Shadow Note") }, { ElementType::TAB_DURATION_SYMBOL, "TabDurationSymbol", QT_TRANSLATE_NOOP("elementName", "Tab Duration Symbol") }, { ElementType::FSYMBOL, "FSymbol", QT_TRANSLATE_NOOP("elementName", "Font Symbol") }, { ElementType::PAGE, "Page", QT_TRANSLATE_NOOP("elementName", "Page") }, { ElementType::HAIRPIN, "HairPin", QT_TRANSLATE_NOOP("elementName", "Hairpin") }, { ElementType::OTTAVA, "Ottava", QT_TRANSLATE_NOOP("elementName", "Ottava") }, { ElementType::PEDAL, "Pedal", QT_TRANSLATE_NOOP("elementName", "Pedal") }, { ElementType::TRILL, "Trill", QT_TRANSLATE_NOOP("elementName", "Trill") }, { ElementType::TEXTLINE, "TextLine", QT_TRANSLATE_NOOP("elementName", "Text Line") }, { ElementType::TEXTLINE_BASE, "TextLineBase", QT_TRANSLATE_NOOP("elementName", "Text Line Base") }, // remove { ElementType::NOTELINE, "NoteLine", QT_TRANSLATE_NOOP("elementName", "Note Line") }, { ElementType::LYRICSLINE, "LyricsLine", QT_TRANSLATE_NOOP("elementName", "Melisma Line") }, { ElementType::GLISSANDO, "Glissando", QT_TRANSLATE_NOOP("elementName", "Glissando") }, { ElementType::BRACKET, "Bracket", QT_TRANSLATE_NOOP("elementName", "Bracket") }, { ElementType::SEGMENT, "Segment", QT_TRANSLATE_NOOP("elementName", "Segment") }, { ElementType::SYSTEM, "System", QT_TRANSLATE_NOOP("elementName", "System") }, { ElementType::COMPOUND, "Compound", QT_TRANSLATE_NOOP("elementName", "Compound") }, { ElementType::CHORD, "Chord", QT_TRANSLATE_NOOP("elementName", "Chord") }, { ElementType::SLUR, "Slur", QT_TRANSLATE_NOOP("elementName", "Slur") }, { ElementType::ELEMENT, "Element", QT_TRANSLATE_NOOP("elementName", "Element") }, { ElementType::ELEMENT_LIST, "ElementList", QT_TRANSLATE_NOOP("elementName", "Element List") }, { ElementType::STAFF_LIST, "StaffList", QT_TRANSLATE_NOOP("elementName", "Staff List") }, { ElementType::MEASURE_LIST, "MeasureList", QT_TRANSLATE_NOOP("elementName", "Measure List") }, { ElementType::HBOX, "HBox", QT_TRANSLATE_NOOP("elementName", "Horizontal Frame") }, { ElementType::VBOX, "VBox", QT_TRANSLATE_NOOP("elementName", "Vertical Frame") }, { ElementType::TBOX, "TBox", QT_TRANSLATE_NOOP("elementName", "Text Frame") }, { ElementType::FBOX, "FBox", QT_TRANSLATE_NOOP("elementName", "Fretboard Diagram Frame") }, { ElementType::ICON, "Icon", QT_TRANSLATE_NOOP("elementName", "Icon") }, { ElementType::OSSIA, "Ossia", QT_TRANSLATE_NOOP("elementName", "Ossia") }, { ElementType::BAGPIPE_EMBELLISHMENT,"BagpipeEmbellishment", QT_TRANSLATE_NOOP("elementName", "Bagpipe Embellishment") } }; //--------------------------------------------------------- // ScoreElement //--------------------------------------------------------- ScoreElement::ScoreElement(const ScoreElement& se) : QObject(0) { _score = se._score; _links = 0; } //--------------------------------------------------------- // ~ScoreElement //--------------------------------------------------------- ScoreElement::~ScoreElement() { if (_links) { _links->removeOne(this); if (_links->empty()) { delete _links; _links = 0; } } } //--------------------------------------------------------- // resetProperty //--------------------------------------------------------- void ScoreElement::resetProperty(P_ID id) { QVariant v = propertyDefault(id); if (v.isValid()) setProperty(id, v); } //--------------------------------------------------------- // undoResetProperty //--------------------------------------------------------- void ScoreElement::undoResetProperty(P_ID id) { PropertyFlags f = propertyFlags(id); if (f == PropertyFlags::UNSTYLED) undoChangeProperty(id, propertyDefault(id), PropertyFlags::STYLED); else undoChangeProperty(id, propertyDefault(id), f); } //--------------------------------------------------------- // undoChangeProperty //--------------------------------------------------------- void ScoreElement::undoChangeProperty(P_ID id, const QVariant& v) { undoChangeProperty(id, v, propertyFlags(id)); } void ScoreElement::undoChangeProperty(P_ID id, const QVariant& v, PropertyFlags ps) { if (id == P_ID::AUTOPLACE && v.toBool() && !getProperty(id).toBool()) { // special case: if we switch to autoplace, we must save // user offset values undoResetProperty(P_ID::USER_OFF); if (isSlurSegment()) { undoResetProperty(P_ID::SLUR_UOFF1); undoResetProperty(P_ID::SLUR_UOFF2); undoResetProperty(P_ID::SLUR_UOFF3); undoResetProperty(P_ID::SLUR_UOFF4); } } else if (id == P_ID::SUB_STYLE) { // // change a list of properties // auto l = subStyle(SubStyle(v.toInt())); // Change to SubStyle defaults for (const StyledProperty& p : l) score()->undoChangeProperty(this, p.propertyIdx, score()->styleV(p.styleIdx), PropertyFlags::STYLED); } score()->undoChangeProperty(this, id, v, ps); } //--------------------------------------------------------- // undoPushProperty //--------------------------------------------------------- void ScoreElement::undoPushProperty(P_ID id) { QVariant val = getProperty(id); score()->undoStack()->push1(new ChangeProperty(this, id, val)); } //--------------------------------------------------------- // writeProperty //--------------------------------------------------------- void ScoreElement::writeProperty(XmlWriter& xml, P_ID id) const { if (propertyType(id) == P_TYPE::SP_REAL) { qreal _spatium = score()->spatium(); xml.tag(id, QVariant(getProperty(id).toReal()/_spatium), QVariant(propertyDefault(id).toReal()/_spatium)); } else xml.tag(id, getProperty(id), propertyDefault(id)); } //--------------------------------------------------------- // linkTo //--------------------------------------------------------- void ScoreElement::linkTo(ScoreElement* element) { Q_ASSERT(element != this); if (!_links) { if (element->links()) { _links = element->_links; Q_ASSERT(_links->contains(element)); } else { _links = new LinkedElements(score()); _links->append(element); element->_links = _links; } Q_ASSERT(!_links->contains(this)); _links->append(this); } else { _links->append(element); element->_links = _links; } } //--------------------------------------------------------- // unlink //--------------------------------------------------------- void ScoreElement::unlink() { if (_links) { Q_ASSERT(_links->contains(this)); _links->removeOne(this); // if link list is empty, remove list if (_links->size() <= 1) { if (!_links->empty()) // abnormal case: only "this" is in list _links->front()->_links = 0; delete _links; } _links = 0; } } //--------------------------------------------------------- // undoUnlink //--------------------------------------------------------- void ScoreElement::undoUnlink() { if (_links) _score->undo(new Unlink(this)); } //--------------------------------------------------------- // linkList //--------------------------------------------------------- QList<ScoreElement*> ScoreElement::linkList() const { QList<ScoreElement*> el; if (links()) el.append(*links()); else el.append((Element*)this); return el; } //--------------------------------------------------------- // LinkedElements //--------------------------------------------------------- LinkedElements::LinkedElements(Score* score) { _lid = score->linkId(); // create new unique id } LinkedElements::LinkedElements(Score* score, int id) { _lid = id; score->linkId(id); // remember used id } //--------------------------------------------------------- // setLid //--------------------------------------------------------- void LinkedElements::setLid(Score* score, int id) { _lid = id; score->linkId(id); } //--------------------------------------------------------- // masterScore //--------------------------------------------------------- MasterScore* ScoreElement::masterScore() const { return _score->masterScore(); } //--------------------------------------------------------- // propertyStyle //--------------------------------------------------------- PropertyFlags ScoreElement::propertyFlags(P_ID) const { return PropertyFlags::NOSTYLE; } //--------------------------------------------------------- // getPropertyStyle //--------------------------------------------------------- StyleIdx ScoreElement::getPropertyStyle(P_ID) const { return StyleIdx::NOSTYLE; } //--------------------------------------------------------- // name //--------------------------------------------------------- const char* ScoreElement::name() const { return name(type()); } //--------------------------------------------------------- // name //--------------------------------------------------------- const char* ScoreElement::name(ElementType type) { return elementNames[int(type)].name; } //--------------------------------------------------------- // userName //--------------------------------------------------------- QString ScoreElement::userName() const { return qApp->translate("elementName", elementNames[int(type())].userName); } //--------------------------------------------------------- // name2type //--------------------------------------------------------- ElementType ScoreElement::name2type(const QStringRef& s) { for (int i = 0; i < int(ElementType::MAXTYPE); ++i) { if (s == elementNames[i].name) return ElementType(i); } qDebug("unknown type"); return ElementType::INVALID; } //--------------------------------------------------------- // isSLine //--------------------------------------------------------- bool ScoreElement::isSLine() const { return isHairpin() || isOttava() || isPedal() || isTrill() || isVolta() || isTextLine() || isNoteLine() || isGlissando(); } //--------------------------------------------------------- // isSLineSegment //--------------------------------------------------------- bool ScoreElement::isSLineSegment() const { return isHairpinSegment() || isOttavaSegment() || isPedalSegment() || isTrillSegment() || isVoltaSegment() || isTextLineSegment() || isGlissandoSegment(); } //--------------------------------------------------------- // isText //--------------------------------------------------------- bool ScoreElement::isText() const { return type() == ElementType::TEXT || type() == ElementType::LYRICS || type() == ElementType::DYNAMIC || type() == ElementType::FINGERING || type() == ElementType::HARMONY || type() == ElementType::MARKER || type() == ElementType::JUMP || type() == ElementType::STAFF_TEXT || type() == ElementType::REHEARSAL_MARK || type() == ElementType::INSTRUMENT_CHANGE || type() == ElementType::FIGURED_BASS || type() == ElementType::TEMPO_TEXT || type() == ElementType::INSTRUMENT_NAME ; } }
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
libmscore/systemtext.cpp
61
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2011 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #include "systemtext.h" namespace Ms { //--------------------------------------------------------- // SystemText //--------------------------------------------------------- SystemText::SystemText(Score* s) : StaffText(SubStyle::SYSTEM, s) { setSystemFlag(true); } SystemText::SystemText(SubStyle ss, Score* s) : StaffText(ss, s) { setSystemFlag(true); } //--------------------------------------------------------- // propertyDefault //--------------------------------------------------------- QVariant SystemText::propertyDefault(P_ID id) const { switch (id) { case P_ID::SUB_STYLE: return int(SubStyle::SYSTEM); default: return StaffText::propertyDefault(id); } } //--------------------------------------------------------- // write //--------------------------------------------------------- void SystemText::write(XmlWriter& xml) const { if (!xml.canWrite(this)) return; xml.stag("SystemText"); StaffText::writeProperties(xml); xml.etag(); } } // namespace Ms
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
mscore/inspector/inspectorFingering.cpp
61
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2013-2017 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENSE.GPL //============================================================================= #include "inspectorFingering.h" #include "musescore.h" #include "libmscore/fingering.h" #include "libmscore/score.h" namespace Ms { //--------------------------------------------------------- // InspectorFingering //--------------------------------------------------------- InspectorFingering::InspectorFingering(QWidget* parent) : InspectorElementBase(parent) { t.setupUi(addWidget()); f.setupUi(addWidget()); const std::vector<InspectorItem> iiList = { { P_ID::FONT_FACE, 0, 0, t.fontFace, t.resetFontFace }, { P_ID::FONT_SIZE, 0, 0, t.fontSize, t.resetFontSize }, { P_ID::FONT_BOLD, 0, 0, t.bold, t.resetBold }, { P_ID::FONT_ITALIC, 0, 0, t.italic, t.resetItalic }, { P_ID::FONT_UNDERLINE, 0, 0, t.underline, t.resetUnderline }, { P_ID::FRAME, 0, 0, t.hasFrame, t.resetHasFrame }, { P_ID::FRAME_FG_COLOR, 0, 0, t.frameColor, t.resetFrameColor }, { P_ID::FRAME_BG_COLOR, 0, 0, t.bgColor, t.resetBgColor }, { P_ID::FRAME_CIRCLE, 0, 0, t.circle, t.resetCircle }, { P_ID::FRAME_SQUARE, 0, 0, t.square, t.resetSquare }, { P_ID::FRAME_WIDTH, 0, 0, t.frameWidth, t.resetFrameWidth }, { P_ID::FRAME_PADDING, 0, 0, t.paddingWidth, t.resetPaddingWidth }, { P_ID::FRAME_ROUND, 0, 0, t.frameRound, t.resetFrameRound }, { P_ID::ALIGN, 0, 0, t.align, t.resetAlign }, { P_ID::SUB_STYLE, 0, 0, f.subStyle, f.resetSubStyle }, }; const std::vector<InspectorPanel> ppList = { { t.title, t.panel }, { f.title, f.panel } }; f.subStyle->clear(); for (auto ss : { SubStyle::FINGERING, SubStyle::LH_GUITAR_FINGERING, SubStyle::RH_GUITAR_FINGERING, SubStyle::STRING_NUMBER } ) { f.subStyle->addItem(subStyleUserName(ss), int(ss)); } mapSignals(iiList, ppList); } }
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
mscore/inspector/alignSelect.cpp
115
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2017 Werner Schweer and others // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENSE.GPL //============================================================================= #include "alignSelect.h" #include "libmscore/elementlayout.h" #include "icons.h" namespace Ms { //--------------------------------------------------------- // AlignSelect //--------------------------------------------------------- AlignSelect::AlignSelect(QWidget* parent) : QWidget(parent) { setupUi(this); g1 = new QButtonGroup(this); g1->addButton(alignLeft); g1->addButton(alignHCenter); g1->addButton(alignRight); g2 = new QButtonGroup(this); g2->addButton(alignTop); g2->addButton(alignVCenter); g2->addButton(alignBaseline); g2->addButton(alignBottom); alignLeft->setIcon(*icons[int(Icons::textLeft_ICON)]); alignRight->setIcon(*icons[int(Icons::textRight_ICON)]); alignHCenter->setIcon(*icons[int(Icons::textCenter_ICON)]); alignVCenter->setIcon(*icons[int(Icons::textVCenter_ICON)]); alignTop->setIcon(*icons[int(Icons::textTop_ICON)]); alignBaseline->setIcon(*icons[int(Icons::textBaseline_ICON)]); alignBottom->setIcon(*icons[int(Icons::textBaseline_ICON)]); connect(g1, SIGNAL(buttonToggled(int,bool)), SLOT(_alignChanged())); connect(g2, SIGNAL(buttonToggled(int,bool)), SLOT(_alignChanged())); } //--------------------------------------------------------- // _alignChanged //--------------------------------------------------------- void AlignSelect::_alignChanged() { emit alignChanged(align()); } //--------------------------------------------------------- // align //--------------------------------------------------------- Align AlignSelect::align() const { Align a = Align::LEFT; if (alignHCenter->isChecked()) a = a | Align::HCENTER; else if (alignRight->isChecked()) a = a | Align::RIGHT; if (alignVCenter->isChecked()) a = a | Align::VCENTER; else if (alignBottom->isChecked()) a = a | Align::BOTTOM; else if (alignBaseline->isChecked()) a = a | Align::BASELINE; return a; } //--------------------------------------------------------- // blockAlign //--------------------------------------------------------- void AlignSelect::blockAlign(bool val) { g1->blockSignals(val); g2->blockSignals(val); } //--------------------------------------------------------- // setElement //--------------------------------------------------------- void AlignSelect::setAlign(Align a) { blockAlign(true); if (a & Align::HCENTER) alignHCenter->setChecked(true); else if (a & Align::RIGHT) alignRight->setChecked(true); else alignLeft->setChecked(true); if (a & Align::VCENTER) alignVCenter->setChecked(true); else if (a & Align::BOTTOM) alignBottom->setChecked(true); else if (a & Align::BASELINE) alignBaseline->setChecked(true); else alignTop->setChecked(true); blockAlign(false); } }
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
mtest/libmscore/element/tst_element.cpp
59
//============================================================================= // MuseScore // Music Composition & Notation // $Id:$ // // Copyright (C) 2012 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #include <QtTest/QtTest> #include "libmscore/score.h" #include "libmscore/element.h" #include "mtest/testutils.h" using namespace Ms; //--------------------------------------------------------- // TestElement //--------------------------------------------------------- class TestElement : public QObject, public MTest { Q_OBJECT private slots: void initTestCase() { initMTest(); } void testIds(); }; //--------------------------------------------------------- // testIds //--------------------------------------------------------- void TestElement::testIds() { ElementType ids[] = { ElementType::VOLTA, ElementType::OTTAVA, ElementType::TEXTLINE, ElementType::TRILL, ElementType::PEDAL, ElementType::HAIRPIN, ElementType::CLEF, ElementType::KEYSIG, ElementType::TIMESIG, ElementType::BAR_LINE, ElementType::ARPEGGIO, ElementType::BREATH, ElementType::GLISSANDO, ElementType::BRACKET, ElementType::ARTICULATION, ElementType::CHORDLINE, ElementType::ACCIDENTAL, ElementType::DYNAMIC, ElementType::TEXT, ElementType::INSTRUMENT_NAME, ElementType::STAFF_TEXT, ElementType::REHEARSAL_MARK, ElementType::INSTRUMENT_CHANGE, ElementType::NOTEHEAD, ElementType::NOTEDOT, ElementType::TREMOLO, ElementType::LAYOUT_BREAK, ElementType::MARKER, ElementType::JUMP, ElementType::REPEAT_MEASURE, ElementType::ICON, ElementType::NOTE, ElementType::SYMBOL, ElementType::FSYMBOL, ElementType::CHORD, ElementType::REST, ElementType::SPACER, ElementType::STAFF_STATE, ElementType::TEMPO_TEXT, ElementType::HARMONY, ElementType::FRET_DIAGRAM, ElementType::BEND, ElementType::TREMOLOBAR, ElementType::LYRICS, ElementType::FIGURED_BASS, ElementType::STEM, ElementType::SLUR, ElementType::FINGERING, ElementType::HBOX, ElementType::VBOX, ElementType::TBOX, ElementType::FBOX, ElementType::MEASURE, ElementType::TAB_DURATION_SYMBOL, ElementType::OSSIA, ElementType::INVALID }; for (int i = 0; ids[i] != ElementType::INVALID; ++i) { ElementType t = ids[i]; Element* e = Element::create(t, score); Element* ee = writeReadElement(e); QCOMPARE(e->type(), ee->type()); delete e; delete ee; } } QTEST_MAIN(TestElement) #include "tst_element.moc"
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
mscore/inspector/inspectorText.cpp
33
//============================================================================= // MuseScore // Music Composition & Notation // // Copyright (C) 2011 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENSE.GPL //============================================================================= #include "inspectorText.h" #include "libmscore/score.h" #include "icons.h" namespace Ms { //--------------------------------------------------------- // InspectorText //--------------------------------------------------------- InspectorText::InspectorText(QWidget* parent) : InspectorElementBase(parent) { t.setupUi(addWidget()); f.setupUi(addWidget()); const std::vector<InspectorItem> iiList = { { P_ID::FONT_FACE, 0, 0, t.fontFace, t.resetFontFace }, { P_ID::FONT_SIZE, 0, 0, t.fontSize, t.resetFontSize }, { P_ID::FONT_BOLD, 0, 0, t.bold, t.resetBold }, { P_ID::FONT_ITALIC, 0, 0, t.italic, t.resetItalic }, { P_ID::FONT_UNDERLINE, 0, 0, t.underline, t.resetUnderline }, { P_ID::FRAME, 0, 0, t.hasFrame, t.resetHasFrame }, { P_ID::FRAME_FG_COLOR, 0, 0, t.frameColor, t.resetFrameColor }, { P_ID::FRAME_BG_COLOR, 0, 0, t.bgColor, t.resetBgColor }, { P_ID::FRAME_CIRCLE, 0, 0, t.circle, t.resetCircle }, { P_ID::FRAME_SQUARE, 0, 0, t.square, t.resetSquare }, { P_ID::FRAME_WIDTH, 0, 0, t.frameWidth, t.resetFrameWidth }, { P_ID::FRAME_PADDING, 0, 0, t.paddingWidth, t.resetPaddingWidth }, { P_ID::FRAME_ROUND, 0, 0, t.frameRound, t.resetFrameRound }, { P_ID::ALIGN, 0, 0, t.align, t.resetAlign }, { P_ID::SUB_STYLE, 0, 0, f.subStyle, f.resetSubStyle }, }; const std::vector<InspectorPanel> ppList = { { t.title, t.panel }, { f.title, f.panel } }; f.subStyle->clear(); for (auto ss : { SubStyle::FRAME, SubStyle::TITLE, SubStyle::SUBTITLE,SubStyle::COMPOSER, SubStyle::POET, SubStyle::INSTRUMENT_EXCERPT, SubStyle::TRANSLATOR, SubStyle::HEADER, SubStyle::FOOTER, SubStyle::USER1, SubStyle::USER2 } ) { f.subStyle->addItem(subStyleUserName(ss), int(ss)); } connect(t.resetToStyle, SIGNAL(clicked()), SLOT(resetToStyle())); mapSignals(iiList, ppList); } }
musescore_MuseScore
2017-01-27
ac9de15554925578bc13dd4b3894e6fb880e6f1e
samples/cpp/tutorial_code/core/how_to_use_OpenCV_parallel_for_/how_to_use_OpenCV_parallel_for_.cpp
122
#include <iostream> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> using namespace std; using namespace cv; namespace { //! [mandelbrot-escape-time-algorithm] int mandelbrot(const complex<float> &z0, const int max) { complex<float> z = z0; for (int t = 0; t < max; t++) { if (z.real()*z.real() + z.imag()*z.imag() > 4.0f) return t; z = z*z + z0; } return max; } //! [mandelbrot-escape-time-algorithm] //! [mandelbrot-grayscale-value] int mandelbrotFormula(const complex<float> &z0, const int maxIter=500) { int value = mandelbrot(z0, maxIter); if(maxIter - value == 0) { return 0; } return cvRound(sqrt(value / (float) maxIter) * 255); } //! [mandelbrot-grayscale-value] //! [mandelbrot-parallel] class ParallelMandelbrot : public ParallelLoopBody { public: ParallelMandelbrot (Mat &img, const float x1, const float y1, const float scaleX, const float scaleY) : m_img(img), m_x1(x1), m_y1(y1), m_scaleX(scaleX), m_scaleY(scaleY) { } virtual void operator ()(const Range& range) const { for (int r = range.start; r < range.end; r++) { int i = r / m_img.cols; int j = r % m_img.cols; float x0 = j / m_scaleX + m_x1; float y0 = i / m_scaleY + m_y1; complex<float> z0(x0, y0); uchar value = (uchar) mandelbrotFormula(z0); m_img.ptr<uchar>(i)[j] = value; } } ParallelMandelbrot& operator=(const ParallelMandelbrot &) { return *this; }; private: Mat &m_img; float m_x1; float m_y1; float m_scaleX; float m_scaleY; }; //! [mandelbrot-parallel] //! [mandelbrot-sequential] void sequentialMandelbrot(Mat &img, const float x1, const float y1, const float scaleX, const float scaleY) { for (int i = 0; i < img.rows; i++) { for (int j = 0; j < img.cols; j++) { float x0 = j / scaleX + x1; float y0 = i / scaleY + y1; complex<float> z0(x0, y0); uchar value = (uchar) mandelbrotFormula(z0); img.ptr<uchar>(i)[j] = value; } } } //! [mandelbrot-sequential] } int main() { //! [mandelbrot-transformation] Mat mandelbrotImg(4800, 5400, CV_8U); float x1 = -2.1f, x2 = 0.6f; float y1 = -1.2f, y2 = 1.2f; float scaleX = mandelbrotImg.cols / (x2 - x1); float scaleY = mandelbrotImg.rows / (y2 - y1); //! [mandelbrot-transformation] double t1 = (double) getTickCount(); //! [mandelbrot-parallel-call] ParallelMandelbrot parallelMandelbrot(mandelbrotImg, x1, y1, scaleX, scaleY); parallel_for_(Range(0, mandelbrotImg.rows*mandelbrotImg.cols), parallelMandelbrot); //! [mandelbrot-parallel-call] t1 = ((double) getTickCount() - t1) / getTickFrequency(); cout << "Parallel Mandelbrot: " << t1 << " s" << endl; Mat mandelbrotImgSequential(4800, 5400, CV_8U); double t2 = (double) getTickCount(); sequentialMandelbrot(mandelbrotImgSequential, x1, y1, scaleX, scaleY); t2 = ((double) getTickCount() - t2) / getTickFrequency(); cout << "Sequential Mandelbrot: " << t2 << " s" << endl; cout << "Speed-up: " << t2/t1 << " X" << endl; imwrite("Mandelbrot_parallel.png", mandelbrotImg); imwrite("Mandelbrot_sequential.png", mandelbrotImgSequential); return EXIT_SUCCESS; }
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
samples/cpp/tutorial_code/ImgProc/changing_contrast_brightness_image/changing_contrast_brightness_image.cpp
91
#include <iostream> #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" using namespace std; using namespace cv; namespace { /** Global Variables */ int alpha = 100; int beta = 100; int gamma_cor = 100; Mat img_original, img_corrected, img_gamma_corrected; void basicLinearTransform(const Mat &img, const double alpha_, const int beta_) { Mat res; img.convertTo(res, -1, alpha_, beta_); hconcat(img, res, img_corrected); } void gammaCorrection(const Mat &img, const double gamma_) { CV_Assert(gamma_ >= 0); //![changing-contrast-brightness-gamma-correction] Mat lookUpTable(1, 256, CV_8U); uchar* p = lookUpTable.ptr(); for( int i = 0; i < 256; ++i) p[i] = saturate_cast<uchar>(pow(i / 255.0, gamma_) * 255.0); Mat res = img.clone(); LUT(img, lookUpTable, res); //![changing-contrast-brightness-gamma-correction] hconcat(img, res, img_gamma_corrected); } void on_linear_transform_alpha_trackbar(int, void *) { double alpha_value = alpha / 100.0; int beta_value = beta - 100; basicLinearTransform(img_original, alpha_value, beta_value); } void on_linear_transform_beta_trackbar(int, void *) { double alpha_value = alpha / 100.0; int beta_value = beta - 100; basicLinearTransform(img_original, alpha_value, beta_value); } void on_gamma_correction_trackbar(int, void *) { double gamma_value = gamma_cor / 100.0; gammaCorrection(img_original, gamma_value); } } int main( int, char** argv ) { img_original = imread( argv[1] ); img_corrected = Mat(img_original.rows, img_original.cols*2, img_original.type()); img_gamma_corrected = Mat(img_original.rows, img_original.cols*2, img_original.type()); hconcat(img_original, img_original, img_corrected); hconcat(img_original, img_original, img_gamma_corrected); namedWindow("Brightness and contrast adjustments", WINDOW_AUTOSIZE); namedWindow("Gamma correction", WINDOW_AUTOSIZE); createTrackbar("Alpha gain (contrast)", "Brightness and contrast adjustments", &alpha, 500, on_linear_transform_alpha_trackbar); createTrackbar("Beta bias (brightness)", "Brightness and contrast adjustments", &beta, 200, on_linear_transform_beta_trackbar); createTrackbar("Gamma correction", "Gamma correction", &gamma_cor, 200, on_gamma_correction_trackbar); while (true) { imshow("Brightness and contrast adjustments", img_corrected); imshow("Gamma correction", img_gamma_corrected); int c = waitKey(30); if (c == 27) break; } imwrite("linear_transform_correction.png", img_corrected); imwrite("gamma_correction.png", img_gamma_corrected); return 0; }
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
platforms/ios/build_framework.py
118
#!/usr/bin/env python """ The script builds OpenCV.framework for iOS. The built framework is universal, it can be used to build app and run it on either iOS simulator or real device. Usage: ./build_framework.py <outputdir> By cmake conventions (and especially if you work with OpenCV repository), the output dir should not be a subdirectory of OpenCV source tree. Script will create <outputdir>, if it's missing, and a few its subdirectories: <outputdir> build/ iPhoneOS-*/ [cmake-generated build tree for an iOS device target] iPhoneSimulator-*/ [cmake-generated build tree for iOS simulator] opencv2.framework/ [the framework content] The script should handle minor OpenCV updates efficiently - it does not recompile the library from scratch each time. However, opencv2.framework directory is erased and recreated on each run. Adding --dynamic parameter will build opencv2.framework as App Store dynamic framework. Only iOS 8+ versions are supported. """ from __future__ import print_function import glob, re, os, os.path, shutil, string, sys, argparse, traceback from subprocess import check_call, check_output, CalledProcessError def execute(cmd, cwd = None): print("Executing: %s in %s" % (cmd, cwd), file=sys.stderr) retcode = check_call(cmd, cwd = cwd) if retcode != 0: raise Exception("Child returned:", retcode) def getXCodeMajor(): ret = check_output(["xcodebuild", "-version"]) m = re.match(r'XCode\s+(\d)\..*', ret, flags=re.IGNORECASE) if m: return int(m.group(1)) return 0 class Builder: def __init__(self, opencv, contrib, dynamic, bitcodedisabled, exclude, targets): self.opencv = os.path.abspath(opencv) self.contrib = None if contrib: modpath = os.path.join(contrib, "modules") if os.path.isdir(modpath): self.contrib = os.path.abspath(modpath) else: print("Note: contrib repository is bad - modules subfolder not found", file=sys.stderr) self.dynamic = dynamic self.bitcodedisabled = bitcodedisabled self.exclude = exclude self.targets = targets def getBD(self, parent, t): if len(t[0]) == 1: res = os.path.join(parent, 'build-%s-%s' % (t[0][0].lower(), t[1].lower())) else: res = os.path.join(parent, 'build-%s' % t[1].lower()) if not os.path.isdir(res): os.makedirs(res) return os.path.abspath(res) def _build(self, outdir): outdir = os.path.abspath(outdir) if not os.path.isdir(outdir): os.makedirs(outdir) mainWD = os.path.join(outdir, "build") dirs = [] xcode_ver = getXCodeMajor() if self.dynamic: alltargets = self.targets else: # if we are building a static library, we must build each architecture separately alltargets = [] for t in self.targets: for at in t[0]: current = ( [at], t[1] ) alltargets.append(current) for t in alltargets: mainBD = self.getBD(mainWD, t) dirs.append(mainBD) cmake_flags = [] if self.contrib: cmake_flags.append("-DOPENCV_EXTRA_MODULES_PATH=%s" % self.contrib) if xcode_ver >= 7 and t[1] == 'iPhoneOS' and self.bitcodedisabled == False: cmake_flags.append("-DCMAKE_C_FLAGS=-fembed-bitcode") cmake_flags.append("-DCMAKE_CXX_FLAGS=-fembed-bitcode") self.buildOne(t[0], t[1], mainBD, cmake_flags) if self.dynamic == False: self.mergeLibs(mainBD) self.makeFramework(outdir, dirs) def build(self, outdir): try: self._build(outdir) except Exception as e: print("="*60, file=sys.stderr) print("ERROR: %s" % e, file=sys.stderr) print("="*60, file=sys.stderr) traceback.print_exc(file=sys.stderr) sys.exit(1) def getToolchain(self, arch, target): return None def getCMakeArgs(self, arch, target): if self.dynamic: args = [ "cmake", "-GXcode", "-DAPPLE_FRAMEWORK=ON", "-DCMAKE_INSTALL_PREFIX=install", "-DCMAKE_BUILD_TYPE=Release", "-DBUILD_SHARED_LIBS=ON", "-DCMAKE_MACOSX_BUNDLE=ON", "-DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=NO", ] else: args = [ "cmake", "-GXcode", "-DAPPLE_FRAMEWORK=ON", "-DCMAKE_INSTALL_PREFIX=install", "-DCMAKE_BUILD_TYPE=Release", ] if len(self.exclude) > 0: args += ["-DBUILD_opencv_world=OFF"] args += ("-DBUILD_opencv_%s=OFF" % m for m in self.exclude) return args def getBuildCommand(self, archs, target): if self.dynamic: buildcmd = [ "xcodebuild", "IPHONEOS_DEPLOYMENT_TARGET=8.0", "ONLY_ACTIVE_ARCH=NO", ] for arch in archs: buildcmd.append("-arch") buildcmd.append(arch.lower()) buildcmd += [ "-sdk", target.lower(), "-configuration", "Release", "-parallelizeTargets", "-jobs", "4", "-target","ALL_BUILD", ] else: arch = ";".join(archs) buildcmd = [ "xcodebuild", "IPHONEOS_DEPLOYMENT_TARGET=6.0", "ARCHS=%s" % arch, "-sdk", target.lower(), "-configuration", "Release", "-parallelizeTargets", "-jobs", "4" ] return buildcmd def getInfoPlist(self, builddirs): return os.path.join(builddirs[0], "ios", "Info.plist") def buildOne(self, arch, target, builddir, cmakeargs = []): # Run cmake toolchain = self.getToolchain(arch, target) cmakecmd = self.getCMakeArgs(arch, target) + \ (["-DCMAKE_TOOLCHAIN_FILE=%s" % toolchain] if toolchain is not None else []) if target.lower().startswith("iphoneos"): cmakecmd.append("-DENABLE_NEON=ON") cmakecmd.append(self.opencv) cmakecmd.extend(cmakeargs) execute(cmakecmd, cwd = builddir) # Clean and build clean_dir = os.path.join(builddir, "install") if os.path.isdir(clean_dir): shutil.rmtree(clean_dir) buildcmd = self.getBuildCommand(arch, target) execute(buildcmd + ["-target", "ALL_BUILD", "build"], cwd = builddir) execute(["cmake", "-P", "cmake_install.cmake"], cwd = builddir) def mergeLibs(self, builddir): res = os.path.join(builddir, "lib", "Release", "libopencv_merged.a") libs = glob.glob(os.path.join(builddir, "install", "lib", "*.a")) libs3 = glob.glob(os.path.join(builddir, "install", "share", "OpenCV", "3rdparty", "lib", "*.a")) print("Merging libraries:\n\t%s" % "\n\t".join(libs + libs3), file=sys.stderr) execute(["libtool", "-static", "-o", res] + libs + libs3) def makeFramework(self, outdir, builddirs): name = "opencv2" # set the current dir to the dst root framework_dir = os.path.join(outdir, "%s.framework" % name) if os.path.isdir(framework_dir): shutil.rmtree(framework_dir) os.makedirs(framework_dir) if self.dynamic: dstdir = framework_dir libname = "opencv2.framework/opencv2" else: dstdir = os.path.join(framework_dir, "Versions", "A") libname = "libopencv_merged.a" # copy headers from one of build folders shutil.copytree(os.path.join(builddirs[0], "install", "include", "opencv2"), os.path.join(dstdir, "Headers")) # make universal static lib libs = [os.path.join(d, "lib", "Release", libname) for d in builddirs] lipocmd = ["lipo", "-create"] lipocmd.extend(libs) lipocmd.extend(["-o", os.path.join(dstdir, name)]) print("Creating universal library from:\n\t%s" % "\n\t".join(libs), file=sys.stderr) execute(lipocmd) # dynamic framework has different structure, just copy the Plist directly if self.dynamic: resdir = dstdir shutil.copyfile(self.getInfoPlist(builddirs), os.path.join(resdir, "Info.plist")) else: # copy Info.plist resdir = os.path.join(dstdir, "Resources") os.makedirs(resdir) shutil.copyfile(self.getInfoPlist(builddirs), os.path.join(resdir, "Info.plist")) # make symbolic links links = [ (["A"], ["Versions", "Current"]), (["Versions", "Current", "Headers"], ["Headers"]), (["Versions", "Current", "Resources"], ["Resources"]), (["Versions", "Current", name], [name]) ] for l in links: s = os.path.join(*l[0]) d = os.path.join(framework_dir, *l[1]) os.symlink(s, d) class iOSBuilder(Builder): def getToolchain(self, arch, target): toolchain = os.path.join(self.opencv, "platforms", "ios", "cmake", "Toolchains", "Toolchain-%s_Xcode.cmake" % target) return toolchain def getCMakeArgs(self, arch, target): arch = ";".join(arch) args = Builder.getCMakeArgs(self, arch, target) args = args + [ '-DIOS_ARCH=%s' % arch ] return args if __name__ == "__main__": folder = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "../..")) parser = argparse.ArgumentParser(description='The script builds OpenCV.framework for iOS.') parser.add_argument('out', metavar='OUTDIR', help='folder to put built framework') parser.add_argument('--opencv', metavar='DIR', default=folder, help='folder with opencv repository (default is "../.." relative to script location)') parser.add_argument('--contrib', metavar='DIR', default=None, help='folder with opencv_contrib repository (default is "None" - build only main framework)') parser.add_argument('--without', metavar='MODULE', default=[], action='append', help='OpenCV modules to exclude from the framework') parser.add_argument('--dynamic', default=False, action='store_true', help='build dynamic framework (default is "False" - builds static framework)') parser.add_argument('--disable-bitcode', default=False, dest='bitcodedisabled', action='store_true', help='disable bitcode (enabled by default)') args = parser.parse_args() b = iOSBuilder(args.opencv, args.contrib, args.dynamic, args.bitcodedisabled, args.without, [ (["armv7", "arm64"], "iPhoneOS"), ] if os.environ.get('BUILD_PRECOMMIT', None) else [ (["armv7", "armv7s", "arm64"], "iPhoneOS"), (["i386", "x86_64"], "iPhoneSimulator"), ]) b.build(args.out)
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
modules/core/misc/java/src/java/core+Rect2d.java
100
package org.opencv.core; //javadoc:Rect2d_ public class Rect2d { public double x, y, width, height; public Rect2d(double x, double y, double width, double height) { this.x = x; this.y = y; this.width = width; this.height = height; } public Rect2d() { this(0, 0, 0, 0); } public Rect2d(Point p1, Point p2) { x = (double) (p1.x < p2.x ? p1.x : p2.x); y = (double) (p1.y < p2.y ? p1.y : p2.y); width = (double) (p1.x > p2.x ? p1.x : p2.x) - x; height = (double) (p1.y > p2.y ? p1.y : p2.y) - y; } public Rect2d(Point p, Size s) { this((double) p.x, (double) p.y, (double) s.width, (double) s.height); } public Rect2d(double[] vals) { set(vals); } public void set(double[] vals) { if (vals != null) { x = vals.length > 0 ? (double) vals[0] : 0; y = vals.length > 1 ? (double) vals[1] : 0; width = vals.length > 2 ? (double) vals[2] : 0; height = vals.length > 3 ? (double) vals[3] : 0; } else { x = 0; y = 0; width = 0; height = 0; } } public Rect2d clone() { return new Rect2d(x, y, width, height); } public Point tl() { return new Point(x, y); } public Point br() { return new Point(x + width, y + height); } public Size size() { return new Size(width, height); } public double area() { return width * height; } public boolean contains(Point p) { return x <= p.x && p.x < x + width && y <= p.y && p.y < y + height; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(height); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(width); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(x); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(y); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Rect2d)) return false; Rect2d it = (Rect2d) obj; return x == it.x && y == it.y && width == it.width && height == it.height; } @Override public String toString() { return "{" + x + ", " + y + ", " + width + "x" + height + "}"; } }
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
samples/cpp/tutorial_code/ImgProc/BasicLinearTransforms.cpp
42
/** * @file BasicLinearTransforms.cpp * @brief Simple program to change contrast and brightness * @author OpenCV team */ #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace std; using namespace cv; /** * @function main * @brief Main function */ int main( int, char** argv ) { //! [basic-linear-transform-parameters] double alpha = 1.0; /*< Simple contrast control */ int beta = 0; /*< Simple brightness control */ //! [basic-linear-transform-parameters] /// Read image given by user //! [basic-linear-transform-load] Mat image = imread( argv[1] ); //! [basic-linear-transform-load] //! [basic-linear-transform-output] Mat new_image = Mat::zeros( image.size(), image.type() ); //! [basic-linear-transform-output] /// Initialize values cout << " Basic Linear Transforms " << endl; cout << "-------------------------" << endl; cout << "* Enter the alpha value [1.0-3.0]: "; cin >> alpha; cout << "* Enter the beta value [0-100]: "; cin >> beta; /// Do the operation new_image(i,j) = alpha*image(i,j) + beta /// Instead of these 'for' loops we could have used simply: /// image.convertTo(new_image, -1, alpha, beta); /// but we wanted to show you how to access the pixels :) //! [basic-linear-transform-operation] for( int y = 0; y < image.rows; y++ ) { for( int x = 0; x < image.cols; x++ ) { for( int c = 0; c < 3; c++ ) { new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( alpha*( image.at<Vec3b>(y,x)[c] ) + beta ); } } } //! [basic-linear-transform-operation] //! [basic-linear-transform-display] /// Create Windows namedWindow("Original Image", WINDOW_AUTOSIZE); namedWindow("New Image", WINDOW_AUTOSIZE); /// Show stuff imshow("Original Image", image); imshow("New Image", new_image); /// Wait until user press some key waitKey(); //! [basic-linear-transform-display] return 0; }
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
samples/cpp/tutorial_code/ImgProc/HitMiss.cpp
37
#include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> using namespace cv; int main(){ Mat input_image = (Mat_<uchar>(8, 8) << 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 255, 0, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 0, 255, 0, 0, 255, 255, 255, 0, 0, 0, 0); Mat kernel = (Mat_<int>(3, 3) << 0, 1, 0, 1, -1, 1, 0, 1, 0); Mat output_image; morphologyEx(input_image, output_image, MORPH_HITMISS, kernel); const int rate = 10; kernel = (kernel + 1) * 127; kernel.convertTo(kernel, CV_8U); cv::resize(kernel, kernel, cv::Size(), rate, rate, INTER_NEAREST); imshow("kernel", kernel); cv::resize(input_image, input_image, cv::Size(), rate, rate, INTER_NEAREST); imshow("Original", input_image); cv::resize(output_image, output_image, cv::Size(), rate, rate, INTER_NEAREST); imshow("Hit or Miss", output_image); waitKey(0); return 0; }
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
modules/core/misc/java/src/java/core+MatOfRect2d.java
81
package org.opencv.core; import java.util.Arrays; import java.util.List; public class MatOfRect2d extends Mat { // 64FC4 private static final int _depth = CvType.CV_64F; private static final int _channels = 4; public MatOfRect2d() { super(); } protected MatOfRect2d(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } public static MatOfRect2d fromNativeAddr(long addr) { return new MatOfRect2d(addr); } public MatOfRect2d(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } public MatOfRect2d(Rect2d...a) { super(); fromArray(a); } public void alloc(int elemNumber) { if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } public void fromArray(Rect2d...a) { if(a==null || a.length==0) return; int num = a.length; alloc(num); double buff[] = new double[num * _channels]; for(int i=0; i<num; i++) { Rect2d r = a[i]; buff[_channels*i+0] = (double) r.x; buff[_channels*i+1] = (double) r.y; buff[_channels*i+2] = (double) r.width; buff[_channels*i+3] = (double) r.height; } put(0, 0, buff); //TODO: check ret val! } public Rect2d[] toArray() { int num = (int) total(); Rect2d[] a = new Rect2d[num]; if(num == 0) return a; double buff[] = new double[num * _channels]; get(0, 0, buff); //TODO: check ret val! for(int i=0; i<num; i++) a[i] = new Rect2d(buff[i*_channels], buff[i*_channels+1], buff[i*_channels+2], buff[i*_channels+3]); return a; } public void fromList(List<Rect2d> lr) { Rect2d ap[] = lr.toArray(new Rect2d[0]); fromArray(ap); } public List<Rect2d> toList() { Rect2d[] ar = toArray(); return Arrays.asList(ar); } }
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
modules/python/test/test_shape.py
23
#!/usr/bin/env python import cv2 from tests_common import NewOpenCVTests class shape_test(NewOpenCVTests): def test_computeDistance(self): a = self.get_sample('samples/data/shape_sample/1.png', cv2.IMREAD_GRAYSCALE); b = self.get_sample('samples/data/shape_sample/2.png', cv2.IMREAD_GRAYSCALE); _, ca, _ = cv2.findContours(a, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS) _, cb, _ = cv2.findContours(b, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS) hd = cv2.createHausdorffDistanceExtractor() sd = cv2.createShapeContextDistanceExtractor() d1 = hd.computeDistance(ca[0], cb[0]) d2 = sd.computeDistance(ca[0], cb[0]) self.assertAlmostEqual(d1, 26.4196891785, 3, "HausdorffDistanceExtractor") self.assertAlmostEqual(d2, 0.25804194808, 3, "ShapeContextDistanceExtractor")
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
samples/python/tutorial_code/imgProc/hough_line_transform/probabilistic_hough_line_transform.py
12
import cv2 import numpy as np img = cv2.imread('../data/sudoku.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,50,150,apertureSize = 3) lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=100,maxLineGap=10) for line in lines: x1,y1,x2,y2 = line[0] cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2) cv2.imwrite('houghlines5.jpg',img)
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
cmake/checks/lapack_check.cpp
14
#include "opencv_lapack.h" static char* check_fn1 = (char*)sgesv_; static char* check_fn2 = (char*)sposv_; static char* check_fn3 = (char*)spotrf_; static char* check_fn4 = (char*)sgesdd_; int main(int argc, char* argv[]) { (void)argv; if(argc > 1000) return check_fn1[0] + check_fn2[0] + check_fn3[0] + check_fn4[0]; return 0; }
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
samples/python/tutorial_code/imgProc/hough_line_transform/hough_line_transform.py
22
import cv2 import numpy as np img = cv2.imread('../data/sudoku.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,50,150,apertureSize = 3) lines = cv2.HoughLines(edges,1,np.pi/180,200) for line in lines: rho,theta = line[0] a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) cv2.imwrite('houghlines3.jpg',img)
opencv_opencv
2017-01-28
a8aff6f64330a0ab2c9d71033412af892dd9b710
tests/template_tests/syntax_tests/i18n/test_blocktrans.py
433
import os from threading import local from django.template import Context, Template, TemplateSyntaxError from django.test import SimpleTestCase, override_settings from django.utils import translation from django.utils.safestring import mark_safe from django.utils.translation import trans_real from ...utils import setup from .base import MultipleLocaleActivationTestCase, extended_locale_paths, here class I18nBlockTransTagTests(SimpleTestCase): libraries = {'i18n': 'django.templatetags.i18n'} @setup({'i18n03': '{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}'}) def test_i18n03(self): """simple translation of a variable""" output = self.engine.render_to_string('i18n03', {'anton': b'\xc3\x85'}) self.assertEqual(output, 'Å') @setup({'i18n04': '{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}'}) def test_i18n04(self): """simple translation of a variable and filter""" output = self.engine.render_to_string('i18n04', {'anton': b'\xc3\x85'}) self.assertEqual(output, 'å') @setup({'legacyi18n04': '{% load i18n %}' '{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}'}) def test_legacyi18n04(self): """simple translation of a variable and filter""" output = self.engine.render_to_string('legacyi18n04', {'anton': b'\xc3\x85'}) self.assertEqual(output, 'å') @setup({'i18n05': '{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}'}) def test_i18n05(self): """simple translation of a string with interpolation""" output = self.engine.render_to_string('i18n05', {'anton': 'yyy'}) self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n07': '{% load i18n %}' '{% blocktrans count counter=number %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_i18n07(self): """translation of singular form""" output = self.engine.render_to_string('i18n07', {'number': 1}) self.assertEqual(output, 'singular') @setup({'legacyi18n07': '{% load i18n %}' '{% blocktrans count number as counter %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_legacyi18n07(self): """translation of singular form""" output = self.engine.render_to_string('legacyi18n07', {'number': 1}) self.assertEqual(output, 'singular') @setup({'i18n08': '{% load i18n %}' '{% blocktrans count number as counter %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_i18n08(self): """translation of plural form""" output = self.engine.render_to_string('i18n08', {'number': 2}) self.assertEqual(output, '2 plural') @setup({'legacyi18n08': '{% load i18n %}' '{% blocktrans count counter=number %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_legacyi18n08(self): """translation of plural form""" output = self.engine.render_to_string('legacyi18n08', {'number': 2}) self.assertEqual(output, '2 plural') @setup({'i18n17': '{% load i18n %}' '{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}'}) def test_i18n17(self): """ Escaping inside blocktrans and trans works as if it was directly in the template. """ output = self.engine.render_to_string('i18n17', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n18': '{% load i18n %}' '{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}'}) def test_i18n18(self): output = self.engine.render_to_string('i18n18', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n19': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'}) def test_i18n19(self): output = self.engine.render_to_string('i18n19', {'andrew': 'a & b'}) self.assertEqual(output, 'a &amp; b') @setup({'i18n21': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'}) def test_i18n21(self): output = self.engine.render_to_string('i18n21', {'andrew': mark_safe('a & b')}) self.assertEqual(output, 'a & b') @setup({'legacyi18n17': '{% load i18n %}' '{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}'}) def test_legacyi18n17(self): output = self.engine.render_to_string('legacyi18n17', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'legacyi18n18': '{% load i18n %}' '{% blocktrans with anton|force_escape as berta %}' '{{ berta }}{% endblocktrans %}'}) def test_legacyi18n18(self): output = self.engine.render_to_string('legacyi18n18', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n26': '{% load i18n %}' '{% blocktrans with extra_field=myextra_field count counter=number %}' 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'}) def test_i18n26(self): """ translation of plural form with extra field in singular form (#13568) """ output = self.engine.render_to_string('i18n26', {'myextra_field': 'test', 'number': 1}) self.assertEqual(output, 'singular test') @setup({'legacyi18n26': '{% load i18n %}' '{% blocktrans with myextra_field as extra_field count number as counter %}' 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'}) def test_legacyi18n26(self): output = self.engine.render_to_string('legacyi18n26', {'myextra_field': 'test', 'number': 1}) self.assertEqual(output, 'singular test') @setup({'i18n27': '{% load i18n %}{% blocktrans count counter=number %}' '{{ counter }} result{% plural %}{{ counter }} results' '{% endblocktrans %}'}) def test_i18n27(self): """translation of singular form in Russian (#14126)""" with translation.override('ru'): output = self.engine.render_to_string('i18n27', {'number': 1}) self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') @setup({'legacyi18n27': '{% load i18n %}' '{% blocktrans count number as counter %}{{ counter }} result' '{% plural %}{{ counter }} results{% endblocktrans %}'}) def test_legacyi18n27(self): with translation.override('ru'): output = self.engine.render_to_string('legacyi18n27', {'number': 1}) self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') @setup({'i18n28': '{% load i18n %}' '{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}'}) def test_i18n28(self): """simple translation of multiple variables""" output = self.engine.render_to_string('i18n28', {'anton': 'α', 'berta': 'β'}) self.assertEqual(output, 'α + β') @setup({'legacyi18n28': '{% load i18n %}' '{% blocktrans with anton as a and berta as b %}' '{{ a }} + {{ b }}{% endblocktrans %}'}) def test_legacyi18n28(self): output = self.engine.render_to_string('legacyi18n28', {'anton': 'α', 'berta': 'β'}) self.assertEqual(output, 'α + β') # blocktrans handling of variables which are not in the context. # this should work as if blocktrans was not there (#19915) @setup({'i18n34': '{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}'}) def test_i18n34(self): output = self.engine.render_to_string('i18n34') if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n34_2': '{% load i18n %}{% blocktrans with a=\'α\' %}{{ missing }}{% endblocktrans %}'}) def test_i18n34_2(self): output = self.engine.render_to_string('i18n34_2') if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n34_3': '{% load i18n %}{% blocktrans with a=anton %}{{ missing }}{% endblocktrans %}'}) def test_i18n34_3(self): output = self.engine.render_to_string( 'i18n34_3', {'anton': '\xce\xb1'}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n37': '{% load i18n %}' '{% trans "Page not found" as page_not_found %}' '{% blocktrans %}Error: {{ page_not_found }}{% endblocktrans %}'}) def test_i18n37(self): with translation.override('de'): output = self.engine.render_to_string('i18n37') self.assertEqual(output, 'Error: Seite nicht gefunden') # blocktrans tag with asvar @setup({'i18n39': '{% load i18n %}' '{% blocktrans asvar page_not_found %}Page not found{% endblocktrans %}' '>{{ page_not_found }}<'}) def test_i18n39(self): with translation.override('de'): output = self.engine.render_to_string('i18n39') self.assertEqual(output, '>Seite nicht gefunden<') @setup({'i18n40': '{% load i18n %}' '{% trans "Page not found" as pg_404 %}' '{% blocktrans with page_not_found=pg_404 asvar output %}' 'Error: {{ page_not_found }}' '{% endblocktrans %}'}) def test_i18n40(self): output = self.engine.render_to_string('i18n40') self.assertEqual(output, '') @setup({'i18n41': '{% load i18n %}' '{% trans "Page not found" as pg_404 %}' '{% blocktrans with page_not_found=pg_404 asvar output %}' 'Error: {{ page_not_found }}' '{% endblocktrans %}' '>{{ output }}<'}) def test_i18n41(self): with translation.override('de'): output = self.engine.render_to_string('i18n41') self.assertEqual(output, '>Error: Seite nicht gefunden<') @setup({'template': '{% load i18n %}{% blocktrans asvar %}Yes{% endblocktrans %}'}) def test_blocktrans_syntax_error_missing_assignment(self): msg = "No argument provided to the 'blocktrans' tag for the asvar option." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% blocktrans %}%s{% endblocktrans %}'}) def test_blocktrans_tag_using_a_string_that_looks_like_str_fmt(self): output = self.engine.render_to_string('template') self.assertEqual(output, '%s') class TranslationBlockTransTagTests(SimpleTestCase): @override_settings(LOCALE_PATHS=extended_locale_paths) def test_template_tags_pgettext(self): """{% blocktrans %} takes message contexts into account (#14806).""" trans_real._active = local() trans_real._translations = {} with translation.override('de'): # Nonexistent context t = Template('{% load i18n %}{% blocktrans context "nonexistent" %}May{% endblocktrans %}') rendered = t.render(Context()) self.assertEqual(rendered, 'May') # Existing context... using a literal t = Template('{% load i18n %}{% blocktrans context "month name" %}May{% endblocktrans %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% blocktrans context "verb" %}May{% endblocktrans %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Kann') # Using a variable t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'month name'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'verb'})) self.assertEqual(rendered, 'Kann') # Using a filter t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'MONTH NAME'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}') rendered = t.render(Context({'message_context': 'VERB'})) self.assertEqual(rendered, 'Kann') # Using 'count' t = Template( '{% load i18n %}{% blocktrans count number=1 context "super search" %}' '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '1 Super-Ergebnis') t = Template( '{% load i18n %}{% blocktrans count number=2 context "super search" %}{{ number }}' ' super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '2 Super-Ergebnisse') t = Template( '{% load i18n %}{% blocktrans context "other super search" count number=1 %}' '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '1 anderen Super-Ergebnis') t = Template( '{% load i18n %}{% blocktrans context "other super search" count number=2 %}' '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '2 andere Super-Ergebnisse') # Using 'with' t = Template( '{% load i18n %}{% blocktrans with num_comments=5 context "comment count" %}' 'There are {{ num_comments }} comments{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'Es gibt 5 Kommentare') t = Template( '{% load i18n %}{% blocktrans with num_comments=5 context "other comment count" %}' 'There are {{ num_comments }} comments{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'Andere: Es gibt 5 Kommentare') # Using trimmed t = Template( '{% load i18n %}{% blocktrans trimmed %}\n\nThere\n\t are 5 ' '\n\n comments\n{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'There are 5 comments') t = Template( '{% load i18n %}{% blocktrans with num_comments=5 context "comment count" trimmed %}\n\n' 'There are \t\n \t {{ num_comments }} comments\n\n{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, 'Es gibt 5 Kommentare') t = Template( '{% load i18n %}{% blocktrans context "other super search" count number=2 trimmed %}\n' '{{ number }} super \n result{% plural %}{{ number }} super results{% endblocktrans %}' ) rendered = t.render(Context()) self.assertEqual(rendered, '2 andere Super-Ergebnisse') # Misuses with self.assertRaises(TemplateSyntaxError): Template('{% load i18n %}{% blocktrans context with month="May" %}{{ month }}{% endblocktrans %}') with self.assertRaises(TemplateSyntaxError): Template('{% load i18n %}{% blocktrans context %}{% endblocktrans %}') with self.assertRaises(TemplateSyntaxError): Template( '{% load i18n %}{% blocktrans count number=2 context %}' '{{ number }} super result{% plural %}{{ number }}' ' super results{% endblocktrans %}' ) @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')]) def test_bad_placeholder_1(self): """ Error in translation file should not crash template rendering (#16516). (%(person)s is translated as %(personne)s in fr.po). """ with translation.override('fr'): t = Template('{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}') rendered = t.render(Context({'person': 'James'})) self.assertEqual(rendered, 'My name is James.') @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')]) def test_bad_placeholder_2(self): """ Error in translation file should not crash template rendering (#18393). (%(person) misses a 's' in fr.po, causing the string formatting to fail) . """ with translation.override('fr'): t = Template('{% load i18n %}{% blocktrans %}My other name is {{ person }}.{% endblocktrans %}') rendered = t.render(Context({'person': 'James'})) self.assertEqual(rendered, 'My other name is James.') class MultipleLocaleActivationBlockTransTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override('fr'): self.assertEqual( Template("{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}").render(Context({})), 'Oui' ) def test_multiple_locale_btrans(self): with translation.override('de'): t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") with translation.override(self._old_language), translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate_btrans(self): with translation.override('de', deactivate=True): t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch_btrans(self): with translation.override('de'): t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') class MiscTests(SimpleTestCase): @override_settings(LOCALE_PATHS=extended_locale_paths) def test_percent_in_translatable_block(self): t_sing = Template("{% load i18n %}{% blocktrans %}The result was {{ percent }}%{% endblocktrans %}") t_plur = Template( "{% load i18n %}{% blocktrans count num as number %}" "{{ percent }}% represents {{ num }} object{% plural %}" "{{ percent }}% represents {{ num }} objects{% endblocktrans %}" ) with translation.override('de'): self.assertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar') @override_settings(LOCALE_PATHS=extended_locale_paths) def test_percent_formatting_in_blocktrans(self): """ Python's %-formatting is properly escaped in blocktrans, singular, or plural. """ t_sing = Template("{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}") t_plur = Template( "{% load i18n %}{% blocktrans count num as number %}" "%(percent)s% represents {{ num }} object{% plural %}" "%(percent)s% represents {{ num }} objects{% endblocktrans %}" ) with translation.override('de'): # Strings won't get translated as they don't match after escaping % self.assertEqual(t_sing.render(Context({'num_comments': 42})), 'There are %(num_comments)s comments') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '%(percent)s% represents 1 object') self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '%(percent)s% represents 4 objects')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/forms_tests/widget_tests/test_input.py
15
from django.forms.widgets import Input from .base import WidgetTest class InputTests(WidgetTest): def test_attrs_with_type(self): attrs = {'type': 'date'} widget = Input(attrs) self.check_html(widget, 'name', 'value', '<input type="date" name="name" value="value" />') # reuse the same attrs for another widget self.check_html(Input(attrs), 'name', 'value', '<input type="date" name="name" value="value" />') attrs['type'] = 'number' # shouldn't change the widget type self.check_html(widget, 'name', 'value', '<input type="date" name="name" value="value" />')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/queries/test_qs_combinators.py
108
from django.db.models import F, IntegerField, Value from django.db.utils import DatabaseError from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import Number, ReservedName @skipUnlessDBFeature('supports_select_union') class QuerySetSetOperationTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.bulk_create(Number(num=i) for i in range(10)) def number_transform(self, value): return value.num def assertNumbersEqual(self, queryset, expected_numbers, ordered=True): self.assertQuerysetEqual(queryset, expected_numbers, self.number_transform, ordered) def test_simple_union(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = Number.objects.filter(num=5) self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False) @skipUnlessDBFeature('supports_select_intersection') def test_simple_intersection(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__gte=5) qs3 = Number.objects.filter(num__gte=4, num__lte=6) self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False) @skipUnlessDBFeature('supports_select_difference') def test_simple_difference(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__lte=4) self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False) def test_union_distinct(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) def test_union_bad_kwarg(self): qs1 = Number.objects.all() msg = "union() received an unexpected keyword argument 'bad'" with self.assertRaisesMessage(TypeError, msg): self.assertEqual(len(list(qs1.union(qs1, bad=True))), 20) def test_limits(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2)[:2])), 2) def test_ordering(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by('-num'), [3, 2, 1, 0]) @skipUnlessDBFeature('supports_slicing_ordering_in_compound') def test_ordering_subqueries(self): qs1 = Number.objects.order_by('num')[:2] qs2 = Number.objects.order_by('-num')[:2] self.assertNumbersEqual(qs1.union(qs2).order_by('-num')[:4], [9, 8, 1, 0]) @skipIfDBFeature('supports_slicing_ordering_in_compound') def test_unsupported_ordering_slicing_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'LIMIT/OFFSET not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2[:10])) msg = 'ORDER BY not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.order_by('id').union(qs2)) @skipIfDBFeature('supports_select_intersection') def test_unsupported_intersection_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'intersection not supported on this database backend' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.intersection(qs2)) def test_combining_multiple_models(self): ReservedName.objects.create(name='99 little bugs', order=99) qs1 = Number.objects.filter(num=1).values_list('num', flat=True) qs2 = ReservedName.objects.values_list('order') self.assertEqual(list(qs1.union(qs2).order_by('num')), [1, 99]) def test_order_raises_on_non_selected_column(self): qs1 = Number.objects.filter().annotate( annotation=Value(1, IntegerField()), ).values('annotation', num2=F('num')) qs2 = Number.objects.filter().values('id', 'num') # Should not raise list(qs1.union(qs2).order_by('annotation')) list(qs1.union(qs2).order_by('num2')) msg = 'ORDER BY term does not match any column in the result set' # 'id' is not part of the select with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('id')) # 'num' got realiased to num2 with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('num')) # switched order, now 'exists' again: list(qs2.union(qs1).order_by('num'))
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/staticfiles_tests/project/loop/foo.css
1
@import url("bar.css")
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
django/contrib/gis/static/gis/js/OLMapWidget.js
208
/* global ol */ var GeometryTypeControl = function(opt_options) { 'use strict'; // Map control to switch type when geometry type is unknown var options = opt_options || {}; var element = document.createElement('div'); element.className = 'switch-type type-' + options.type + ' ol-control ol-unselectable'; if (options.active) { element.className += " type-active"; } var self = this; var switchType = function(e) { e.preventDefault(); if (options.widget.currentGeometryType !== self) { options.widget.map.removeInteraction(options.widget.interactions.draw); options.widget.interactions.draw = new ol.interaction.Draw({ features: options.widget.featureCollection, type: options.type }); options.widget.map.addInteraction(options.widget.interactions.draw); var className = options.widget.currentGeometryType.element.className.replace(/ type-active/g, ''); options.widget.currentGeometryType.element.className = className; options.widget.currentGeometryType = self; element.className += " type-active"; } }; element.addEventListener('click', switchType, false); element.addEventListener('touchstart', switchType, false); ol.control.Control.call(this, { element: element }); }; ol.inherits(GeometryTypeControl, ol.control.Control); // TODO: allow deleting individual features (#8972) (function() { 'use strict'; var jsonFormat = new ol.format.GeoJSON(); function MapWidget(options) { this.map = null; this.interactions = {draw: null, modify: null}; this.typeChoices = false; this.ready = false; // Default options this.options = { default_lat: 0, default_lon: 0, default_zoom: 12, is_collection: options.geom_name.indexOf('Multi') > -1 || options.geom_name.indexOf('Collection') > -1 }; // Altering using user-provided options for (var property in options) { if (options.hasOwnProperty(property)) { this.options[property] = options[property]; } } if (!options.base_layer) { this.options.base_layer = new ol.layer.Tile({source: new ol.source.OSM()}); } this.map = this.createMap(); this.featureCollection = new ol.Collection(); this.featureOverlay = new ol.layer.Vector({ map: this.map, source: new ol.source.Vector({ features: this.featureCollection, useSpatialIndex: false // improve performance }), updateWhileAnimating: true, // optional, for instant visual feedback updateWhileInteracting: true // optional, for instant visual feedback }); // Populate and set handlers for the feature container var self = this; this.featureCollection.on('add', function(event) { var feature = event.element; feature.on('change', function() { self.serializeFeatures(); }); if (self.ready) { self.serializeFeatures(); if (!self.options.is_collection) { self.disableDrawing(); // Only allow one feature at a time } } }); var initial_value = document.getElementById(this.options.id).value; if (initial_value) { var features = jsonFormat.readFeatures('{"type": "Feature", "geometry": ' + initial_value + '}'); var extent = ol.extent.createEmpty(); features.forEach(function(feature) { this.featureOverlay.getSource().addFeature(feature); ol.extent.extend(extent, feature.getGeometry().getExtent()); }, this); // Center/zoom the map this.map.getView().fit(extent, this.map.getSize(), {maxZoom: this.options.default_zoom}); } else { this.map.getView().setCenter(this.defaultCenter()); } this.createInteractions(); if (initial_value && !this.options.is_collection) { this.disableDrawing(); } this.ready = true; } MapWidget.prototype.createMap = function() { var map = new ol.Map({ target: this.options.map_id, layers: [this.options.base_layer], view: new ol.View({ zoom: this.options.default_zoom }) }); return map; }; MapWidget.prototype.createInteractions = function() { // Initialize the modify interaction this.interactions.modify = new ol.interaction.Modify({ features: this.featureCollection, deleteCondition: function(event) { return ol.events.condition.shiftKeyOnly(event) && ol.events.condition.singleClick(event); } }); // Initialize the draw interaction var geomType = this.options.geom_name; if (geomType === "Unknown" || geomType === "GeometryCollection") { // Default to Point, but create icons to switch type geomType = "Point"; this.currentGeometryType = new GeometryTypeControl({widget: this, type: "Point", active: true}); this.map.addControl(this.currentGeometryType); this.map.addControl(new GeometryTypeControl({widget: this, type: "LineString", active: false})); this.map.addControl(new GeometryTypeControl({widget: this, type: "Polygon", active: false})); this.typeChoices = true; } this.interactions.draw = new ol.interaction.Draw({ features: this.featureCollection, type: geomType }); this.map.addInteraction(this.interactions.draw); this.map.addInteraction(this.interactions.modify); }; MapWidget.prototype.defaultCenter = function() { var center = [this.options.default_lon, this.options.default_lat]; if (this.options.map_srid) { return ol.proj.transform(center, 'EPSG:4326', this.map.getView().getProjection()); } return center; }; MapWidget.prototype.enableDrawing = function() { this.interactions.draw.setActive(true); if (this.typeChoices) { // Show geometry type icons var divs = document.getElementsByClassName("switch-type"); for (var i = 0; i !== divs.length; i++) { divs[i].style.visibility = "visible"; } } }; MapWidget.prototype.disableDrawing = function() { if (this.interactions.draw) { this.interactions.draw.setActive(false); if (this.typeChoices) { // Hide geometry type icons var divs = document.getElementsByClassName("switch-type"); for (var i = 0; i !== divs.length; i++) { divs[i].style.visibility = "hidden"; } } } }; MapWidget.prototype.clearFeatures = function() { this.featureCollection.clear(); // Empty textarea widget document.getElementById(this.options.id).value = ''; this.enableDrawing(); }; MapWidget.prototype.serializeFeatures = function() { // Three use cases: GeometryCollection, multigeometries, and single geometry var geometry = null; var features = this.featureOverlay.getSource().getFeatures(); if (this.options.is_collection) { if (this.options.geom_name === "GeometryCollection") { var geometries = []; for (var i = 0; i < features.length; i++) { geometries.push(features[i].getGeometry()); } geometry = new ol.geom.GeometryCollection(geometries); } else { geometry = features[0].getGeometry().clone(); for (var j = 1; j < features.length; j++) { switch(geometry.getType()) { case "MultiPoint": geometry.appendPoint(features[j].getGeometry().getPoint(0)); break; case "MultiLineString": geometry.appendLineString(features[j].getGeometry().getLineString(0)); break; case "MultiPolygon": geometry.appendPolygon(features[j].getGeometry().getPolygon(0)); } } } } else { if (features[0]) { geometry = features[0].getGeometry(); } } document.getElementById(this.options.id).value = jsonFormat.writeGeometry(geometry); }; window.MapWidget = MapWidget; })();
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/template_tests/syntax_tests/i18n/test_trans.py
205
from threading import local from django.template import Context, Template, TemplateSyntaxError from django.test import SimpleTestCase, override_settings from django.utils import translation from django.utils.safestring import mark_safe from django.utils.translation import trans_real from ...utils import setup from .base import MultipleLocaleActivationTestCase, extended_locale_paths class I18nTransTagTests(SimpleTestCase): libraries = {'i18n': 'django.templatetags.i18n'} @setup({'i18n01': '{% load i18n %}{% trans \'xxxyyyxxx\' %}'}) def test_i18n01(self): """simple translation of a string delimited by '.""" output = self.engine.render_to_string('i18n01') self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n02': '{% load i18n %}{% trans "xxxyyyxxx" %}'}) def test_i18n02(self): """simple translation of a string delimited by ".""" output = self.engine.render_to_string('i18n02') self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n06': '{% load i18n %}{% trans "Page not found" %}'}) def test_i18n06(self): """simple translation of a string to German""" with translation.override('de'): output = self.engine.render_to_string('i18n06') self.assertEqual(output, 'Seite nicht gefunden') @setup({'i18n09': '{% load i18n %}{% trans "Page not found" noop %}'}) def test_i18n09(self): """simple non-translation (only marking) of a string to German""" with translation.override('de'): output = self.engine.render_to_string('i18n09') self.assertEqual(output, 'Page not found') @setup({'i18n20': '{% load i18n %}{% trans andrew %}'}) def test_i18n20(self): output = self.engine.render_to_string('i18n20', {'andrew': 'a & b'}) self.assertEqual(output, 'a &amp; b') @setup({'i18n22': '{% load i18n %}{% trans andrew %}'}) def test_i18n22(self): output = self.engine.render_to_string('i18n22', {'andrew': mark_safe('a & b')}) self.assertEqual(output, 'a & b') @setup({'i18n23': '{% load i18n %}{% trans "Page not found"|capfirst|slice:"6:" %}'}) def test_i18n23(self): """Using filters with the {% trans %} tag (#5972).""" with translation.override('de'): output = self.engine.render_to_string('i18n23') self.assertEqual(output, 'nicht gefunden') @setup({'i18n24': '{% load i18n %}{% trans \'Page not found\'|upper %}'}) def test_i18n24(self): with translation.override('de'): output = self.engine.render_to_string('i18n24') self.assertEqual(output, 'SEITE NICHT GEFUNDEN') @setup({'i18n25': '{% load i18n %}{% trans somevar|upper %}'}) def test_i18n25(self): with translation.override('de'): output = self.engine.render_to_string('i18n25', {'somevar': 'Page not found'}) self.assertEqual(output, 'SEITE NICHT GEFUNDEN') # trans tag with as var @setup({'i18n35': '{% load i18n %}{% trans "Page not found" as page_not_found %}{{ page_not_found }}'}) def test_i18n35(self): with translation.override('de'): output = self.engine.render_to_string('i18n35') self.assertEqual(output, 'Seite nicht gefunden') @setup({'i18n36': '{% load i18n %}' '{% trans "Page not found" noop as page_not_found %}{{ page_not_found }}'}) def test_i18n36(self): with translation.override('de'): output = self.engine.render_to_string('i18n36') self.assertEqual(output, 'Page not found') @setup({'template': '{% load i18n %}{% trans %}A}'}) def test_syntax_error_no_arguments(self): msg = "'trans' takes at least one argument" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" badoption %}'}) def test_syntax_error_bad_option(self): msg = "Unknown argument for 'trans' tag: 'badoption'" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" as %}'}) def test_syntax_error_missing_assignment(self): msg = "No argument provided to the 'trans' tag for the as option." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" as var context %}'}) def test_syntax_error_missing_context(self): msg = "No argument provided to the 'trans' tag for the context option." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" context as var %}'}) def test_syntax_error_context_as(self): msg = "Invalid argument 'as' provided to the 'trans' tag for the context option" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" context noop %}'}) def test_syntax_error_context_noop(self): msg = "Invalid argument 'noop' provided to the 'trans' tag for the context option" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "Yes" noop noop %}'}) def test_syntax_error_duplicate_option(self): msg = "The 'noop' option was specified more than once." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string('template') @setup({'template': '{% load i18n %}{% trans "%s" %}'}) def test_trans_tag_using_a_string_that_looks_like_str_fmt(self): output = self.engine.render_to_string('template') self.assertEqual(output, '%s') class TranslationTransTagTests(SimpleTestCase): @override_settings(LOCALE_PATHS=extended_locale_paths) def test_template_tags_pgettext(self): """{% trans %} takes message contexts into account (#14806).""" trans_real._active = local() trans_real._translations = {} with translation.override('de'): # Nonexistent context... t = Template('{% load i18n %}{% trans "May" context "nonexistent" %}') rendered = t.render(Context()) self.assertEqual(rendered, 'May') # Existing context... using a literal t = Template('{% load i18n %}{% trans "May" context "month name" %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% trans "May" context "verb" %}') rendered = t.render(Context()) self.assertEqual(rendered, 'Kann') # Using a variable t = Template('{% load i18n %}{% trans "May" context message_context %}') rendered = t.render(Context({'message_context': 'month name'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% trans "May" context message_context %}') rendered = t.render(Context({'message_context': 'verb'})) self.assertEqual(rendered, 'Kann') # Using a filter t = Template('{% load i18n %}{% trans "May" context message_context|lower %}') rendered = t.render(Context({'message_context': 'MONTH NAME'})) self.assertEqual(rendered, 'Mai') t = Template('{% load i18n %}{% trans "May" context message_context|lower %}') rendered = t.render(Context({'message_context': 'VERB'})) self.assertEqual(rendered, 'Kann') # Using 'as' t = Template('{% load i18n %}{% trans "May" context "month name" as var %}Value: {{ var }}') rendered = t.render(Context()) self.assertEqual(rendered, 'Value: Mai') t = Template('{% load i18n %}{% trans "May" as var context "verb" %}Value: {{ var }}') rendered = t.render(Context()) self.assertEqual(rendered, 'Value: Kann') class MultipleLocaleActivationTransTagTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override('fr'): self.assertEqual(Template("{% load i18n %}{% trans 'Yes' %}").render(Context({})), 'Oui') def test_multiple_locale_trans(self): with translation.override('de'): t = Template("{% load i18n %}{% trans 'No' %}") with translation.override(self._old_language), translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate_trans(self): with translation.override('de', deactivate=True): t = Template("{% load i18n %}{% trans 'No' %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch_trans(self): with translation.override('de'): t = Template("{% load i18n %}{% trans 'No' %}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/template_tests/syntax_tests/i18n/base.py
24
import os from django.conf import settings from django.test import SimpleTestCase from django.utils.translation import activate, get_language here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) pdir = os.path.split(os.path.split(os.path.abspath(here))[0])[0] extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(pdir, 'i18n', 'other', 'locale'), ] class MultipleLocaleActivationTestCase(SimpleTestCase): """ Tests for template rendering when multiple locales are activated during the lifetime of the same process. """ def setUp(self): self._old_language = get_language() def tearDown(self): activate(self._old_language)
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
django/contrib/admindocs/utils.py
91
"Misc. utility functions/classes for admin documentation generator." import re from email.errors import HeaderParseError from email.parser import HeaderParser from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.safestring import mark_safe try: import docutils.core import docutils.nodes import docutils.parsers.rst.roles except ImportError: docutils_is_available = False else: docutils_is_available = True def trim_docstring(docstring): """ Uniformly trim leading/trailing whitespace from docstrings. Based on https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation """ if not docstring or not docstring.strip(): return '' # Convert tabs to spaces and split into lines lines = docstring.expandtabs().splitlines() indent = min(len(line) - len(line.lstrip()) for line in lines if line.lstrip()) trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]] return "\n".join(trimmed).strip() def parse_docstring(docstring): """ Parse out the parts of a docstring. Return (title, body, metadata). """ docstring = trim_docstring(docstring) parts = re.split(r'\n{2,}', docstring) title = parts[0] if len(parts) == 1: body = '' metadata = {} else: parser = HeaderParser() try: metadata = parser.parsestr(parts[-1]) except HeaderParseError: metadata = {} body = "\n\n".join(parts[1:]) else: metadata = dict(metadata.items()) if metadata: body = "\n\n".join(parts[1:-1]) else: body = "\n\n".join(parts[1:]) return title, body, metadata def parse_rst(text, default_reference_context, thing_being_parsed=None): """ Convert the string from reST to an XHTML fragment. """ overrides = { 'doctitle_xform': True, 'initial_header_level': 3, "default_reference_context": default_reference_context, "link_base": reverse('django-admindocs-docroot').rstrip('/'), 'raw_enabled': False, 'file_insertion_enabled': False, } if thing_being_parsed: thing_being_parsed = force_bytes("<%s>" % thing_being_parsed) # Wrap ``text`` in some reST that sets the default role to ``cmsreference``, # then restores it. source = """ .. default-role:: cmsreference %s .. default-role:: """ parts = docutils.core.publish_parts( source % text, source_path=thing_being_parsed, destination_path=None, writer_name='html', settings_overrides=overrides, ) return mark_safe(parts['fragment']) # # reST roles # ROLES = { 'model': '%s/models/%s/', 'view': '%s/views/%s/', 'template': '%s/templates/%s/', 'filter': '%s/filters/#%s', 'tag': '%s/tags/#%s', } def create_reference_role(rolename, urlbase): def _role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] node = docutils.nodes.reference( rawtext, text, refuri=(urlbase % ( inliner.document.settings.link_base, text.lower(), )), **options ) return [node], [] docutils.parsers.rst.roles.register_canonical_role(rolename, _role) def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] context = inliner.document.settings.default_reference_context node = docutils.nodes.reference( rawtext, text, refuri=(ROLES[context] % ( inliner.document.settings.link_base, text.lower(), )), **options ) return [node], [] if docutils_is_available: docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role) for name, urlbase in ROLES.items(): create_reference_role(name, urlbase) # Match the beginning of a named or unnamed group. named_group_matcher = re.compile(r'\(\?P(<\w+>)') unnamed_group_matcher = re.compile(r'\(') def replace_named_groups(pattern): r""" Find named groups in `pattern` and replace them with the group name. E.g., 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^<a>/b/(\w+)$ 2. ^(?P<a>\w+)/b/(?P<c>\w+)/$ ==> ^<a>/b/<c>/$ """ named_group_indices = [ (m.start(0), m.end(0), m.group(1)) for m in named_group_matcher.finditer(pattern) ] # Tuples of (named capture group pattern, group name). group_pattern_and_name = [] # Loop over the groups and their start and end indices. for start, end, group_name in named_group_indices: # Handle nested parentheses, e.g. '^(?P<a>(x|y))/b'. unmatched_open_brackets, prev_char = 1, None for idx, val in enumerate(list(pattern[end:])): # If brackets are balanced, the end of the string for the current # named capture group pattern has been reached. if unmatched_open_brackets == 0: group_pattern_and_name.append((pattern[start:end + idx], group_name)) break # Check for unescaped `(` and `)`. They mark the start and end of a # nested group. if val == '(' and prev_char != '\\': unmatched_open_brackets += 1 elif val == ')' and prev_char != '\\': unmatched_open_brackets -= 1 prev_char = val # Replace the string for named capture groups with their group names. for group_pattern, group_name in group_pattern_and_name: pattern = pattern.replace(group_pattern, group_name) return pattern def replace_unnamed_groups(pattern): r""" Find unnamed groups in `pattern` and replace them with '<var>'. E.g., 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^(?P<a>\w+)/b/<var>$ 2. ^(?P<a>\w+)/b/((x|y)\w+)$ ==> ^(?P<a>\w+)/b/<var>$ """ unnamed_group_indices = [m.start(0) for m in unnamed_group_matcher.finditer(pattern)] # Indices of the start of unnamed capture groups. group_indices = [] # Loop over the start indices of the groups. for start in unnamed_group_indices: # Handle nested parentheses, e.g. '^b/((x|y)\w+)$'. unmatched_open_brackets, prev_char = 1, None for idx, val in enumerate(list(pattern[start + 1:])): if unmatched_open_brackets == 0: group_indices.append((start, start + 1 + idx)) break # Check for unescaped `(` and `)`. They mark the start and end of # a nested group. if val == '(' and prev_char != '\\': unmatched_open_brackets += 1 elif val == ')' and prev_char != '\\': unmatched_open_brackets -= 1 prev_char = val # Remove unnamed group matches inside other unnamed capture groups. group_start_end_indices = [] prev_end = None for start, end in group_indices: if prev_end and start > prev_end or not prev_end: group_start_end_indices.append((start, end)) prev_end = end if group_start_end_indices: # Replace unnamed groups with <var>. Handle the fact that replacing the # string between indices will change string length and thus indices # will point to the wrong substring if not corrected. final_pattern, prev_end = [], None for start, end in group_start_end_indices: if prev_end: final_pattern.append(pattern[prev_end:start]) final_pattern.append(pattern[:start] + '<var>') prev_end = end final_pattern.append(pattern[prev_end:]) return ''.join(final_pattern) else: return pattern
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
14
from django.test import SimpleTestCase from ...utils import setup class GetAvailableLanguagesTagTests(SimpleTestCase): libraries = {'i18n': 'django.templatetags.i18n'} @setup({'i18n12': '{% load i18n %}' '{% get_available_languages as langs %}{% for lang in langs %}' '{% if lang.0 == "de" %}{{ lang.0 }}{% endif %}{% endfor %}'}) def test_i18n12(self): output = self.engine.render_to_string('i18n12') self.assertEqual(output, 'de')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/staticfiles_tests/project/loop/bar.css
1
@import url("foo.css")
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/backends/test_postgresql.py
54
import unittest from collections import namedtuple from django.db import connection from django.test import TestCase from .models import Person @unittest.skipUnless(connection.vendor == 'postgresql', "Test only for PostgreSQL") class ServerSideCursorsPostgres(TestCase): cursor_fields = 'name, statement, is_holdable, is_binary, is_scrollable, creation_time' PostgresCursor = namedtuple('PostgresCursor', cursor_fields) @classmethod def setUpTestData(cls): Person.objects.create(first_name='a', last_name='a') Person.objects.create(first_name='b', last_name='b') def inspect_cursors(self): with connection.cursor() as cursor: cursor.execute('SELECT {fields} FROM pg_cursors;'.format(fields=self.cursor_fields)) cursors = cursor.fetchall() return [self.PostgresCursor._make(cursor) for cursor in cursors] def test_server_side_cursor(self): persons = Person.objects.iterator() next(persons) # Open a server-side cursor cursors = self.inspect_cursors() self.assertEqual(len(cursors), 1) self.assertIn('_django_curs_', cursors[0].name) self.assertFalse(cursors[0].is_scrollable) self.assertFalse(cursors[0].is_holdable) self.assertFalse(cursors[0].is_binary) def test_server_side_cursor_many_cursors(self): persons = Person.objects.iterator() persons2 = Person.objects.iterator() next(persons) # Open a server-side cursor next(persons2) # Open a second server-side cursor cursors = self.inspect_cursors() self.assertEqual(len(cursors), 2) for cursor in cursors: self.assertIn('_django_curs_', cursor.name) self.assertFalse(cursor.is_scrollable) self.assertFalse(cursor.is_holdable) self.assertFalse(cursor.is_binary) def test_closed_server_side_cursor(self): persons = Person.objects.iterator() next(persons) # Open a server-side cursor del persons cursors = self.inspect_cursors() self.assertEqual(len(cursors), 0)
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/forms_tests/widget_tests/test_widget.py
11
from django.forms import Widget from django.forms.widgets import Input from .base import WidgetTest class WidgetTests(WidgetTest): def test_value_omitted_from_data(self): widget = Widget() self.assertIs(widget.value_omitted_from_data({}, {}, 'field'), True) self.assertIs(widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False) def test_no_trailing_newline_in_attrs(self): self.check_html(Input(), 'name', 'value', strict=True, html='<input type="None" name="name" value="value" />') def test_attr_false_not_rendered(self): html = '<input type="None" name="name" value="value" />' self.check_html(Input(), 'name', 'value', html=html, attrs={'readonly': False})
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
107
from django.template import Context, Template from django.test import SimpleTestCase from django.utils import translation from ...utils import setup from .base import MultipleLocaleActivationTestCase class MultipleLocaleActivationTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override('fr'): self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui') # Literal marked up with _() in a filter expression def test_multiple_locale_filter(self): with translation.override('de'): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override(self._old_language), translation.override('nl'): self.assertEqual(t.render(Context({})), 'nee') def test_multiple_locale_filter_deactivate(self): with translation.override('de', deactivate=True): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'nee') def test_multiple_locale_filter_direct_switch(self): with translation.override('de'): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'nee') # Literal marked up with _() def test_multiple_locale(self): with translation.override('de'): t = Template("{{ _('No') }}") with translation.override(self._old_language), translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate(self): with translation.override('de', deactivate=True): t = Template("{{ _('No') }}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch(self): with translation.override('de'): t = Template("{{ _('No') }}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') # Literal marked up with _(), loading the i18n template tag library def test_multiple_locale_loadi18n(self): with translation.override('de'): t = Template("{% load i18n %}{{ _('No') }}") with translation.override(self._old_language), translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_loadi18n_deactivate(self): with translation.override('de', deactivate=True): t = Template("{% load i18n %}{{ _('No') }}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_loadi18n_direct_switch(self): with translation.override('de'): t = Template("{% load i18n %}{{ _('No') }}") with translation.override('nl'): self.assertEqual(t.render(Context({})), 'Nee') class I18nStringLiteralTests(SimpleTestCase): """translation of constant strings""" libraries = {'i18n': 'django.templatetags.i18n'} @setup({'i18n13': '{{ _("Password") }}'}) def test_i18n13(self): with translation.override('de'): output = self.engine.render_to_string('i18n13') self.assertEqual(output, 'Passwort') @setup({'i18n14': '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}'}) def test_i18n14(self): with translation.override('de'): output = self.engine.render_to_string('i18n14') self.assertEqual(output, 'foo Passwort Passwort') @setup({'i18n15': '{{ absent|default:_("Password") }}'}) def test_i18n15(self): with translation.override('de'): output = self.engine.render_to_string('i18n15', {'absent': ''}) self.assertEqual(output, 'Passwort') @setup({'i18n16': '{{ _("<") }}'}) def test_i18n16(self): with translation.override('de'): output = self.engine.render_to_string('i18n16') self.assertEqual(output, '<')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/postgres_tests/test_indexes.py
49
from django.contrib.postgres.indexes import BrinIndex, GinIndex from django.db import connection from django.test import skipUnlessDBFeature from . import PostgreSQLTestCase from .models import CharFieldModel, IntegerArrayModel @skipUnlessDBFeature('has_brin_index_support') class BrinIndexTests(PostgreSQLTestCase): def test_repr(self): index = BrinIndex(fields=['title'], pages_per_range=4) another_index = BrinIndex(fields=['title']) self.assertEqual(repr(index), "<BrinIndex: fields='title', pages_per_range=4>") self.assertEqual(repr(another_index), "<BrinIndex: fields='title'>") def test_not_eq(self): index = BrinIndex(fields=['title']) index_with_page_range = BrinIndex(fields=['title'], pages_per_range=16) self.assertNotEqual(index, index_with_page_range) def test_deconstruction(self): index = BrinIndex(fields=['title'], name='test_title_brin') path, args, kwargs = index.deconstruct() self.assertEqual(path, 'django.contrib.postgres.indexes.BrinIndex') self.assertEqual(args, ()) self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_brin', 'pages_per_range': None}) def test_deconstruction_with_pages_per_range(self): index = BrinIndex(fields=['title'], name='test_title_brin', pages_per_range=16) path, args, kwargs = index.deconstruct() self.assertEqual(path, 'django.contrib.postgres.indexes.BrinIndex') self.assertEqual(args, ()) self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_brin', 'pages_per_range': 16}) def test_invalid_pages_per_range(self): with self.assertRaisesMessage(ValueError, 'pages_per_range must be None or a positive integer'): BrinIndex(fields=['title'], name='test_title_brin', pages_per_range=0) class GinIndexTests(PostgreSQLTestCase): def test_repr(self): index = GinIndex(fields=['title']) self.assertEqual(repr(index), "<GinIndex: fields='title'>") def test_eq(self): index = GinIndex(fields=['title']) same_index = GinIndex(fields=['title']) another_index = GinIndex(fields=['author']) self.assertEqual(index, same_index) self.assertNotEqual(index, another_index) def test_name_auto_generation(self): index = GinIndex(fields=['field']) index.set_name_with_model(IntegerArrayModel) self.assertEqual(index.name, 'postgres_te_field_def2f8_gin') def test_deconstruction(self): index = GinIndex(fields=['title'], name='test_title_gin') path, args, kwargs = index.deconstruct() self.assertEqual(path, 'django.contrib.postgres.indexes.GinIndex') self.assertEqual(args, ()) self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_gin'}) class SchemaTests(PostgreSQLTestCase): def get_constraints(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_gin_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn('field', self.get_constraints(IntegerArrayModel._meta.db_table)) # Add the index index_name = 'integer_array_model_field_gin' index = GinIndex(fields=['field'], name=index_name) with connection.schema_editor() as editor: editor.add_index(IntegerArrayModel, index) constraints = self.get_constraints(IntegerArrayModel._meta.db_table) # Check gin index was added self.assertEqual(constraints[index_name]['type'], 'gin') # Drop the index with connection.schema_editor() as editor: editor.remove_index(IntegerArrayModel, index) self.assertNotIn(index_name, self.get_constraints(IntegerArrayModel._meta.db_table)) @skipUnlessDBFeature('has_brin_index_support') def test_brin_index(self): index_name = 'char_field_model_field_brin' index = BrinIndex(fields=['field'], name=index_name, pages_per_range=4) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]['type'], 'brin') self.assertEqual(constraints[index_name]['options'], ['pages_per_range=4']) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
django/db/backends/postgresql_psycopg2/__init__.py
9
import warnings from django.utils.deprecation import RemovedInDjango30Warning warnings.warn( "The django.db.backends.postgresql_psycopg2 module is deprecated in " "favor of django.db.backends.postgresql.", RemovedInDjango30Warning, stacklevel=2 )
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
45
from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class GetLanguageInfoListTests(SimpleTestCase): libraries = { 'custom': 'template_tests.templatetags.custom', 'i18n': 'django.templatetags.i18n', } @setup({'i18n30': '{% load i18n %}' '{% get_language_info_list for langcodes as langs %}' '{% for l in langs %}{{ l.code }}: {{ l.name }}/' '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'}) def test_i18n30(self): output = self.engine.render_to_string('i18n30', {'langcodes': ['it', 'no']}) self.assertEqual(output, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; ') @setup({'i18n31': '{% load i18n %}' '{% get_language_info_list for langcodes as langs %}' '{% for l in langs %}{{ l.code }}: {{ l.name }}/' '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'}) def test_i18n31(self): output = self.engine.render_to_string('i18n31', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))}) self.assertEqual( output, 'sl: Slovenian/Sloven\u0161\u010dina bidi=False; ' 'fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; ' ) @setup({'i18n38_2': '{% load i18n custom %}' '{% get_language_info_list for langcodes|noop:"x y" as langs %}' '{% for l in langs %}{{ l.code }}: {{ l.name }}/' '{{ l.name_local }}/{{ l.name_translated }} ' 'bidi={{ l.bidi }}; {% endfor %}'}) def test_i18n38_2(self): with translation.override('cs'): output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'fr']}) self.assertEqual( output, 'it: Italian/italiano/italsky bidi=False; ' 'fr: French/français/francouzsky bidi=False; ' )
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
django/contrib/postgres/indexes.py
34
from django.db.models import Index __all__ = ['BrinIndex', 'GinIndex'] class BrinIndex(Index): suffix = 'brin' def __init__(self, fields=[], name=None, pages_per_range=None): if pages_per_range is not None and pages_per_range <= 0: raise ValueError('pages_per_range must be None or a positive integer') self.pages_per_range = pages_per_range super().__init__(fields, name) def __repr__(self): if self.pages_per_range is not None: return '<%(name)s: fields=%(fields)s, pages_per_range=%(pages_per_range)s>' % { 'name': self.__class__.__name__, 'fields': "'{}'".format(', '.join(self.fields)), 'pages_per_range': self.pages_per_range, } else: return super().__repr__() def deconstruct(self): path, args, kwargs = super().deconstruct() kwargs['pages_per_range'] = self.pages_per_range return path, args, kwargs def get_sql_create_template_values(self, model, schema_editor, using): parameters = super().get_sql_create_template_values(model, schema_editor, using=' USING brin') if self.pages_per_range is not None: parameters['extra'] = ' WITH (pages_per_range={})'.format( schema_editor.quote_value(self.pages_per_range)) + parameters['extra'] return parameters class GinIndex(Index): suffix = 'gin' def create_sql(self, model, schema_editor): return super().create_sql(model, schema_editor, using=' USING gin')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/backends/test_mysql.py
46
import unittest from django.core.exceptions import ImproperlyConfigured from django.db import connection from django.test import TestCase, override_settings @override_settings(DEBUG=True) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific test.') class MySQLTests(TestCase): @staticmethod def get_isolation_level(connection): with connection.cursor() as cursor: cursor.execute("SELECT @@session.tx_isolation") return cursor.fetchone()[0] def test_auto_is_null_auto_config(self): query = 'set sql_auto_is_null = 0' connection.init_connection_state() last_query = connection.queries[-1]['sql'].lower() if connection.features.is_sql_auto_is_null_enabled: self.assertIn(query, last_query) else: self.assertNotIn(query, last_query) def test_connect_isolation_level(self): read_committed = 'read committed' repeatable_read = 'repeatable read' isolation_values = { level: level.replace(' ', '-').upper() for level in (read_committed, repeatable_read) } configured_level = connection.isolation_level or isolation_values[repeatable_read] configured_level = configured_level.upper() other_level = read_committed if configured_level != isolation_values[read_committed] else repeatable_read self.assertEqual(self.get_isolation_level(connection), configured_level) new_connection = connection.copy() new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level try: self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level]) finally: new_connection.close() # Upper case values are also accepted in 'isolation_level'. new_connection = connection.copy() new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level.upper() try: self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level]) finally: new_connection.close() def test_isolation_level_validation(self): new_connection = connection.copy() new_connection.settings_dict['OPTIONS']['isolation_level'] = 'xxx' msg = ( "Invalid transaction isolation level 'xxx' specified.\n" "Use one of 'read committed', 'read uncommitted', " "'repeatable read', 'serializable', or None." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): new_connection.cursor()
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/auth_tests/client.py
41
import re from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, INTERNAL_RESET_URL_TOKEN, ) from django.test import Client def extract_token_from_url(url): token_search = re.search(r'/reset/.*/(.+?)/', url) if token_search: return token_search.group(1) class PasswordResetConfirmClient(Client): """ This client eases testing the password reset flow by emulating the PasswordResetConfirmView's redirect and saving of the reset token in the user's session. This request puts 'my-token' in the session and redirects to '/reset/bla/set-password/': >>> client = PasswordResetConfirmClient() >>> client.get('/reset/bla/my-token/') """ def _get_password_reset_confirm_redirect_url(self, url): token = extract_token_from_url(url) if not token: return url # Add the token to the session session = self.session session[INTERNAL_RESET_SESSION_TOKEN] = token session.save() return url.replace(token, INTERNAL_RESET_URL_TOKEN) def get(self, path, *args, **kwargs): redirect_url = self._get_password_reset_confirm_redirect_url(path) return super().get(redirect_url, *args, **kwargs) def post(self, path, *args, **kwargs): redirect_url = self._get_password_reset_confirm_redirect_url(path) return super().post(redirect_url, *args, **kwargs)
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/template_tests/syntax_tests/i18n/test_filters.py
47
from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class I18nFiltersTests(SimpleTestCase): libraries = { 'custom': 'template_tests.templatetags.custom', 'i18n': 'django.templatetags.i18n', } @setup({'i18n32': '{% load i18n %}{{ "hu"|language_name }} ' '{{ "hu"|language_name_local }} {{ "hu"|language_bidi }} ' '{{ "hu"|language_name_translated }}'}) def test_i18n32(self): output = self.engine.render_to_string('i18n32') self.assertEqual(output, 'Hungarian Magyar False Hungarian') with translation.override('cs'): output = self.engine.render_to_string('i18n32') self.assertEqual(output, 'Hungarian Magyar False maďarsky') @setup({'i18n33': '{% load i18n %}' '{{ langcode|language_name }} {{ langcode|language_name_local }} ' '{{ langcode|language_bidi }} {{ langcode|language_name_translated }}'}) def test_i18n33(self): output = self.engine.render_to_string('i18n33', {'langcode': 'nl'}) self.assertEqual(output, 'Dutch Nederlands False Dutch') with translation.override('cs'): output = self.engine.render_to_string('i18n33', {'langcode': 'nl'}) self.assertEqual(output, 'Dutch Nederlands False nizozemsky') @setup({'i18n38_2': '{% load i18n custom %}' '{% get_language_info_list for langcodes|noop:"x y" as langs %}' '{% for l in langs %}{{ l.code }}: {{ l.name }}/' '{{ l.name_local }}/{{ l.name_translated }} ' 'bidi={{ l.bidi }}; {% endfor %}'}) def test_i18n38_2(self): with translation.override('cs'): output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'fr']}) self.assertEqual( output, 'it: Italian/italiano/italsky bidi=False; ' 'fr: French/français/francouzsky bidi=False; ' )
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/template_tests/syntax_tests/i18n/test_get_language_info.py
36
from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class I18nGetLanguageInfoTagTests(SimpleTestCase): libraries = { 'custom': 'template_tests.templatetags.custom', 'i18n': 'django.templatetags.i18n', } # retrieving language information @setup({'i18n28_2': '{% load i18n %}' '{% get_language_info for "de" as l %}' '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'}) def test_i18n28_2(self): output = self.engine.render_to_string('i18n28_2') self.assertEqual(output, 'de: German/Deutsch bidi=False') @setup({'i18n29': '{% load i18n %}' '{% get_language_info for LANGUAGE_CODE as l %}' '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'}) def test_i18n29(self): output = self.engine.render_to_string('i18n29', {'LANGUAGE_CODE': 'fi'}) self.assertEqual(output, 'fi: Finnish/suomi bidi=False') # Test whitespace in filter arguments @setup({'i18n38': '{% load i18n custom %}' '{% get_language_info for "de"|noop:"x y" as l %}' '{{ l.code }}: {{ l.name }}/{{ l.name_local }}/' '{{ l.name_translated }} bidi={{ l.bidi }}'}) def test_i18n38(self): with translation.override('cs'): output = self.engine.render_to_string('i18n38') self.assertEqual(output, 'de: German/Deutsch/německy bidi=False')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
django/contrib/gis/static/gis/css/ol3.css
31
.switch-type { background-repeat: no-repeat; cursor: pointer; top: 0.5em; width: 22px; height: 20px; } .type-Point { background-image: url("../img/draw_point_off.svg"); right: 5px; } .type-Point.type-active { background-image: url("../img/draw_point_on.svg"); } .type-LineString { background-image: url("../img/draw_line_off.svg"); right: 30px; } .type-LineString.type-active { background-image: url("../img/draw_line_on.svg"); } .type-Polygon { background-image: url("../img/draw_polygon_off.svg"); right: 55px; } .type-Polygon.type-active { background-image: url("../img/draw_polygon_on.svg"); }
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/auth_tests/test_templates.py
28
from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.contrib.auth.views import ( PasswordChangeDoneView, PasswordChangeView, PasswordResetCompleteView, PasswordResetDoneView, PasswordResetView, ) from django.test import RequestFactory, TestCase, override_settings from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from .client import PasswordResetConfirmClient @override_settings(ROOT_URLCONF='auth_tests.urls') class AuthTemplateTests(TestCase): @classmethod def setUpTestData(cls): rf = RequestFactory() user = User.objects.create_user('jsmith', '[email protected]', 'pass') user = authenticate(username=user.username, password='pass') request = rf.get('/somepath/') request.user = user cls.user, cls.request = user, request def test_PasswordResetView(self): response = PasswordResetView.as_view(success_url='dummy/')(self.request) self.assertContains(response, '<title>Password reset</title>') self.assertContains(response, '<h1>Password reset</h1>') def test_PasswordResetDoneView(self): response = PasswordResetDoneView.as_view()(self.request) self.assertContains(response, '<title>Password reset sent</title>') self.assertContains(response, '<h1>Password reset sent</h1>') def test_PasswordResetConfirmView_invalid_token(self): # PasswordResetConfirmView invalid token client = PasswordResetConfirmClient() url = reverse('password_reset_confirm', kwargs={'uidb64': 'Bad', 'token': 'Bad-Token'}) response = client.get(url) self.assertContains(response, '<title>Password reset unsuccessful</title>') self.assertContains(response, '<h1>Password reset unsuccessful</h1>') def test_PasswordResetConfirmView_valid_token(self): # PasswordResetConfirmView valid token client = PasswordResetConfirmClient() default_token_generator = PasswordResetTokenGenerator() token = default_token_generator.make_token(self.user) uidb64 = urlsafe_base64_encode(force_bytes(self.user.pk)).decode() url = reverse('password_reset_confirm', kwargs={'uidb64': uidb64, 'token': token}) response = client.get(url) self.assertContains(response, '<title>Enter new password</title>') self.assertContains(response, '<h1>Enter new password</h1>') def test_PasswordResetCompleteView(self): response = PasswordResetCompleteView.as_view()(self.request) self.assertContains(response, '<title>Password reset complete</title>') self.assertContains(response, '<h1>Password reset complete</h1>') def test_PasswordResetChangeView(self): response = PasswordChangeView.as_view(success_url='dummy/')(self.request) self.assertContains(response, '<title>Password change</title>') self.assertContains(response, '<h1>Password change</h1>') def test_PasswordChangeDoneView(self): response = PasswordChangeDoneView.as_view()(self.request) self.assertContains(response, '<title>Password change successful</title>') self.assertContains(response, '<h1>Password change successful</h1>')
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/messages_tests/test_api.py
31
from django.contrib import messages from django.test import RequestFactory, SimpleTestCase class DummyStorage: """ dummy message-store to test the api methods """ def __init__(self): self.store = [] def add(self, level, message, extra_tags=''): self.store.append(message) class ApiTests(SimpleTestCase): def setUp(self): self.rf = RequestFactory() self.request = self.rf.request() self.storage = DummyStorage() def test_ok(self): msg = 'some message' self.request._messages = self.storage messages.add_message(self.request, messages.DEBUG, msg) self.assertIn(msg, self.storage.store) def test_request_is_none(self): msg = "add_message() argument must be an HttpRequest object, not 'NoneType'." self.request._messages = self.storage with self.assertRaisesMessage(TypeError, msg): messages.add_message(None, messages.DEBUG, 'some message') self.assertEqual(self.storage.store, []) def test_middleware_missing(self): msg = 'You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware' with self.assertRaisesMessage(messages.MessageFailure, msg): messages.add_message(self.request, messages.DEBUG, 'some message') self.assertEqual(self.storage.store, []) def test_middleware_missing_silently(self): messages.add_message(self.request, messages.DEBUG, 'some message', fail_silently=True) self.assertEqual(self.storage.store, []) class CustomRequest: def __init__(self, request): self._request = request def __getattribute__(self, attr): try: return super().__getattribute__(attr) except AttributeError: return getattr(self._request, attr) class CustomRequestApiTests(ApiTests): """ add_message() should use ducktyping to allow request wrappers such as the one in Django REST framework. """ def setUp(self): super().setUp() self.request = CustomRequest(self.request)
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
tests/shell/tests.py
24
import sys import unittest from unittest import mock from django import __version__ from django.core.management import CommandError, call_command from django.test import SimpleTestCase from django.test.utils import captured_stdin, captured_stdout, patch_logger class ShellCommandTestCase(SimpleTestCase): def test_command_option(self): with patch_logger('test', 'info') as logger: call_command( 'shell', command=( 'import django; from logging import getLogger; ' 'getLogger("test").info(django.__version__)' ), ) self.assertEqual(len(logger), 1) self.assertEqual(logger[0], __version__) @unittest.skipIf(sys.platform == 'win32', "Windows select() doesn't support file descriptors.") @mock.patch('django.core.management.commands.shell.select') def test_stdin_read(self, select): with captured_stdin() as stdin, captured_stdout() as stdout: stdin.write('print(100)\n') stdin.seek(0) call_command('shell') self.assertEqual(stdout.getvalue().strip(), '100') @mock.patch('django.core.management.commands.shell.select.select') # [1] @mock.patch.dict('sys.modules', {'IPython': None}) def test_shell_with_ipython_not_installed(self, select): select.return_value = ([], [], []) with self.assertRaisesMessage(CommandError, "Couldn't import ipython interface."): call_command('shell', interface='ipython') @mock.patch('django.core.management.commands.shell.select.select') # [1] @mock.patch.dict('sys.modules', {'bpython': None}) def test_shell_with_bpython_not_installed(self, select): select.return_value = ([], [], []) with self.assertRaisesMessage(CommandError, "Couldn't import bpython interface."): call_command('shell', interface='bpython') # [1] Patch select to prevent tests failing when when the test suite is run # in parallel mode. The tests are run in a subprocess and the subprocess's # stdin is closed and replaced by /dev/null. Reading from /dev/null always # returns EOF and so select always shows that sys.stdin is ready to read. # This causes problems because of the call to select.select() towards the # end of shell's handle() method.
django_django
2017-01-28
e34f4e6f8735a6ad102fda096aa99cbb5600761e
common/network-common/src/main/java/org/apache/spark/network/crypto/AuthEngine.java
284
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.io.Closeable; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.Properties; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.primitives.Bytes; import org.apache.commons.crypto.cipher.CryptoCipher; import org.apache.commons.crypto.cipher.CryptoCipherFactory; import org.apache.commons.crypto.random.CryptoRandom; import org.apache.commons.crypto.random.CryptoRandomFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.network.util.TransportConf; /** * A helper class for abstracting authentication and key negotiation details. This is used by * both client and server sides, since the operations are basically the same. */ class AuthEngine implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(AuthEngine.class); private static final BigInteger ONE = new BigInteger(new byte[] { 0x1 }); private final byte[] appId; private final char[] secret; private final TransportConf conf; private final Properties cryptoConf; private final CryptoRandom random; private byte[] authNonce; @VisibleForTesting byte[] challenge; private TransportCipher sessionCipher; private CryptoCipher encryptor; private CryptoCipher decryptor; AuthEngine(String appId, String secret, TransportConf conf) throws GeneralSecurityException { this.appId = appId.getBytes(UTF_8); this.conf = conf; this.cryptoConf = conf.cryptoConf(); this.secret = secret.toCharArray(); this.random = CryptoRandomFactory.getCryptoRandom(cryptoConf); } /** * Create the client challenge. * * @return A challenge to be sent the remote side. */ ClientChallenge challenge() throws GeneralSecurityException, IOException { this.authNonce = randomBytes(conf.encryptionKeyLength() / Byte.SIZE); SecretKeySpec authKey = generateKey(conf.keyFactoryAlgorithm(), conf.keyFactoryIterations(), authNonce, conf.encryptionKeyLength()); initializeForAuth(conf.cipherTransformation(), authNonce, authKey); this.challenge = randomBytes(conf.encryptionKeyLength() / Byte.SIZE); return new ClientChallenge(new String(appId, UTF_8), conf.keyFactoryAlgorithm(), conf.keyFactoryIterations(), conf.cipherTransformation(), conf.encryptionKeyLength(), authNonce, challenge(appId, authNonce, challenge)); } /** * Validates the client challenge, and create the encryption backend for the channel from the * parameters sent by the client. * * @param clientChallenge The challenge from the client. * @return A response to be sent to the client. */ ServerResponse respond(ClientChallenge clientChallenge) throws GeneralSecurityException, IOException { SecretKeySpec authKey = generateKey(clientChallenge.kdf, clientChallenge.iterations, clientChallenge.nonce, clientChallenge.keyLength); initializeForAuth(clientChallenge.cipher, clientChallenge.nonce, authKey); byte[] challenge = validateChallenge(clientChallenge.nonce, clientChallenge.challenge); byte[] response = challenge(appId, clientChallenge.nonce, rawResponse(challenge)); byte[] sessionNonce = randomBytes(conf.encryptionKeyLength() / Byte.SIZE); byte[] inputIv = randomBytes(conf.ivLength()); byte[] outputIv = randomBytes(conf.ivLength()); SecretKeySpec sessionKey = generateKey(clientChallenge.kdf, clientChallenge.iterations, sessionNonce, clientChallenge.keyLength); this.sessionCipher = new TransportCipher(cryptoConf, clientChallenge.cipher, sessionKey, inputIv, outputIv); // Note the IVs are swapped in the response. return new ServerResponse(response, encrypt(sessionNonce), encrypt(outputIv), encrypt(inputIv)); } /** * Validates the server response and initializes the cipher to use for the session. * * @param serverResponse The response from the server. */ void validate(ServerResponse serverResponse) throws GeneralSecurityException { byte[] response = validateChallenge(authNonce, serverResponse.response); byte[] expected = rawResponse(challenge); Preconditions.checkArgument(Arrays.equals(expected, response)); byte[] nonce = decrypt(serverResponse.nonce); byte[] inputIv = decrypt(serverResponse.inputIv); byte[] outputIv = decrypt(serverResponse.outputIv); SecretKeySpec sessionKey = generateKey(conf.keyFactoryAlgorithm(), conf.keyFactoryIterations(), nonce, conf.encryptionKeyLength()); this.sessionCipher = new TransportCipher(cryptoConf, conf.cipherTransformation(), sessionKey, inputIv, outputIv); } TransportCipher sessionCipher() { Preconditions.checkState(sessionCipher != null); return sessionCipher; } @Override public void close() throws IOException { // Close ciphers (by calling "doFinal()" with dummy data) and the random instance so that // internal state is cleaned up. Error handling here is just for paranoia, and not meant to // accurately report the errors when they happen. RuntimeException error = null; byte[] dummy = new byte[8]; try { doCipherOp(encryptor, dummy, true); } catch (Exception e) { error = new RuntimeException(e); } try { doCipherOp(decryptor, dummy, true); } catch (Exception e) { error = new RuntimeException(e); } random.close(); if (error != null) { throw error; } } @VisibleForTesting byte[] challenge(byte[] appId, byte[] nonce, byte[] challenge) throws GeneralSecurityException { return encrypt(Bytes.concat(appId, nonce, challenge)); } @VisibleForTesting byte[] rawResponse(byte[] challenge) { BigInteger orig = new BigInteger(challenge); BigInteger response = orig.add(ONE); return response.toByteArray(); } private byte[] decrypt(byte[] in) throws GeneralSecurityException { return doCipherOp(decryptor, in, false); } private byte[] encrypt(byte[] in) throws GeneralSecurityException { return doCipherOp(encryptor, in, false); } private void initializeForAuth(String cipher, byte[] nonce, SecretKeySpec key) throws GeneralSecurityException { // commons-crypto currently only supports ciphers that require an initial vector; so // create a dummy vector so that we can initialize the ciphers. In the future, if // different ciphers are supported, this will have to be configurable somehow. byte[] iv = new byte[conf.ivLength()]; System.arraycopy(nonce, 0, iv, 0, Math.min(nonce.length, iv.length)); encryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf); encryptor.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); decryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf); decryptor.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); } /** * Validates an encrypted challenge as defined in the protocol, and returns the byte array * that corresponds to the actual challenge data. */ private byte[] validateChallenge(byte[] nonce, byte[] encryptedChallenge) throws GeneralSecurityException { byte[] challenge = decrypt(encryptedChallenge); checkSubArray(appId, challenge, 0); checkSubArray(nonce, challenge, appId.length); return Arrays.copyOfRange(challenge, appId.length + nonce.length, challenge.length); } private SecretKeySpec generateKey(String kdf, int iterations, byte[] salt, int keyLength) throws GeneralSecurityException { SecretKeyFactory factory = SecretKeyFactory.getInstance(kdf); PBEKeySpec spec = new PBEKeySpec(secret, salt, iterations, keyLength); long start = System.nanoTime(); SecretKey key = factory.generateSecret(spec); long end = System.nanoTime(); LOG.debug("Generated key with {} iterations in {} us.", conf.keyFactoryIterations(), (end - start) / 1000); return new SecretKeySpec(key.getEncoded(), conf.keyAlgorithm()); } private byte[] doCipherOp(CryptoCipher cipher, byte[] in, boolean isFinal) throws GeneralSecurityException { Preconditions.checkState(cipher != null); int scale = 1; while (true) { int size = in.length * scale; byte[] buffer = new byte[size]; try { int outSize = isFinal ? cipher.doFinal(in, 0, in.length, buffer, 0) : cipher.update(in, 0, in.length, buffer, 0); if (outSize != buffer.length) { byte[] output = new byte[outSize]; System.arraycopy(buffer, 0, output, 0, output.length); return output; } else { return buffer; } } catch (ShortBufferException e) { // Try again with a bigger buffer. scale *= 2; } } } private byte[] randomBytes(int count) { byte[] bytes = new byte[count]; random.nextBytes(bytes); return bytes; } /** Checks that the "test" array is in the data array starting at the given offset. */ private void checkSubArray(byte[] test, byte[] data, int offset) { Preconditions.checkArgument(data.length >= test.length + offset); for (int i = 0; i < test.length; i++) { Preconditions.checkArgument(test[i] == data[i + offset]); } } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
examples/src/main/java/org/apache/spark/examples/sql/JavaUserDefinedTypedAggregation.java
160
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.examples.sql; // $example on:typed_custom_aggregation$ import java.io.Serializable; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Encoder; import org.apache.spark.sql.Encoders; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.TypedColumn; import org.apache.spark.sql.expressions.Aggregator; // $example off:typed_custom_aggregation$ public class JavaUserDefinedTypedAggregation { // $example on:typed_custom_aggregation$ public static class Employee implements Serializable { private String name; private long salary; // Constructors, getters, setters... // $example off:typed_custom_aggregation$ public String getName() { return name; } public void setName(String name) { this.name = name; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } // $example on:typed_custom_aggregation$ } public static class Average implements Serializable { private long sum; private long count; // Constructors, getters, setters... // $example off:typed_custom_aggregation$ public Average() { } public Average(long sum, long count) { this.sum = sum; this.count = count; } public long getSum() { return sum; } public void setSum(long sum) { this.sum = sum; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } // $example on:typed_custom_aggregation$ } public static class MyAverage extends Aggregator<Employee, Average, Double> { // A zero value for this aggregation. Should satisfy the property that any b + zero = b public Average zero() { return new Average(0L, 0L); } // Combine two values to produce a new value. For performance, the function may modify `buffer` // and return it instead of constructing a new object public Average reduce(Average buffer, Employee employee) { long newSum = buffer.getSum() + employee.getSalary(); long newCount = buffer.getCount() + 1; buffer.setSum(newSum); buffer.setCount(newCount); return buffer; } // Merge two intermediate values public Average merge(Average b1, Average b2) { long mergedSum = b1.getSum() + b2.getSum(); long mergedCount = b1.getCount() + b2.getCount(); b1.setSum(mergedSum); b1.setCount(mergedCount); return b1; } // Transform the output of the reduction public Double finish(Average reduction) { return ((double) reduction.getSum()) / reduction.getCount(); } // Specifies the Encoder for the intermediate value type public Encoder<Average> bufferEncoder() { return Encoders.bean(Average.class); } // Specifies the Encoder for the final output value type public Encoder<Double> outputEncoder() { return Encoders.DOUBLE(); } } // $example off:typed_custom_aggregation$ public static void main(String[] args) { SparkSession spark = SparkSession .builder() .appName("Java Spark SQL user-defined Datasets aggregation example") .getOrCreate(); // $example on:typed_custom_aggregation$ Encoder<Employee> employeeEncoder = Encoders.bean(Employee.class); String path = "examples/src/main/resources/employees.json"; Dataset<Employee> ds = spark.read().json(path).as(employeeEncoder); ds.show(); // +-------+------+ // | name|salary| // +-------+------+ // |Michael| 3000| // | Andy| 4500| // | Justin| 3500| // | Berta| 4000| // +-------+------+ MyAverage myAverage = new MyAverage(); // Convert the function to a `TypedColumn` and give it a name TypedColumn<Employee, Double> averageSalary = myAverage.toColumn().name("average_salary"); Dataset<Double> result = ds.select(averageSalary); result.show(); // +--------------+ // |average_salary| // +--------------+ // | 3750.0| // +--------------+ // $example off:typed_custom_aggregation$ spark.stop(); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/test/java/org/apache/spark/network/crypto/AuthIntegrationSuite.java
213
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import io.netty.channel.Channel; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import org.apache.spark.network.TestUtils; import org.apache.spark.network.TransportContext; import org.apache.spark.network.client.RpcResponseCallback; import org.apache.spark.network.client.TransportClient; import org.apache.spark.network.client.TransportClientBootstrap; import org.apache.spark.network.sasl.SaslRpcHandler; import org.apache.spark.network.sasl.SaslServerBootstrap; import org.apache.spark.network.sasl.SecretKeyHolder; import org.apache.spark.network.server.RpcHandler; import org.apache.spark.network.server.StreamManager; import org.apache.spark.network.server.TransportServer; import org.apache.spark.network.server.TransportServerBootstrap; import org.apache.spark.network.util.JavaUtils; import org.apache.spark.network.util.MapConfigProvider; import org.apache.spark.network.util.TransportConf; public class AuthIntegrationSuite { private AuthTestCtx ctx; @After public void cleanUp() throws Exception { if (ctx != null) { ctx.close(); } ctx = null; } @Test public void testNewAuth() throws Exception { ctx = new AuthTestCtx(); ctx.createServer("secret"); ctx.createClient("secret"); ByteBuffer reply = ctx.client.sendRpcSync(JavaUtils.stringToBytes("Ping"), 5000); assertEquals("Pong", JavaUtils.bytesToString(reply)); assertTrue(ctx.authRpcHandler.doDelegate); assertFalse(ctx.authRpcHandler.delegate instanceof SaslRpcHandler); } @Test public void testAuthFailure() throws Exception { ctx = new AuthTestCtx(); ctx.createServer("server"); try { ctx.createClient("client"); fail("Should have failed to create client."); } catch (Exception e) { assertFalse(ctx.authRpcHandler.doDelegate); assertFalse(ctx.serverChannel.isActive()); } } @Test public void testSaslServerFallback() throws Exception { ctx = new AuthTestCtx(); ctx.createServer("secret", true); ctx.createClient("secret", false); ByteBuffer reply = ctx.client.sendRpcSync(JavaUtils.stringToBytes("Ping"), 5000); assertEquals("Pong", JavaUtils.bytesToString(reply)); } @Test public void testSaslClientFallback() throws Exception { ctx = new AuthTestCtx(); ctx.createServer("secret", false); ctx.createClient("secret", true); ByteBuffer reply = ctx.client.sendRpcSync(JavaUtils.stringToBytes("Ping"), 5000); assertEquals("Pong", JavaUtils.bytesToString(reply)); } @Test public void testAuthReplay() throws Exception { // This test covers the case where an attacker replays a challenge message sniffed from the // network, but doesn't know the actual secret. The server should close the connection as // soon as a message is sent after authentication is performed. This is emulated by removing // the client encryption handler after authentication. ctx = new AuthTestCtx(); ctx.createServer("secret"); ctx.createClient("secret"); assertNotNull(ctx.client.getChannel().pipeline() .remove(TransportCipher.ENCRYPTION_HANDLER_NAME)); try { ctx.client.sendRpcSync(JavaUtils.stringToBytes("Ping"), 5000); fail("Should have failed unencrypted RPC."); } catch (Exception e) { assertTrue(ctx.authRpcHandler.doDelegate); } } private class AuthTestCtx { private final String appId = "testAppId"; private final TransportConf conf; private final TransportContext ctx; TransportClient client; TransportServer server; volatile Channel serverChannel; volatile AuthRpcHandler authRpcHandler; AuthTestCtx() throws Exception { Map<String, String> testConf = ImmutableMap.of("spark.network.crypto.enabled", "true"); this.conf = new TransportConf("rpc", new MapConfigProvider(testConf)); RpcHandler rpcHandler = new RpcHandler() { @Override public void receive( TransportClient client, ByteBuffer message, RpcResponseCallback callback) { assertEquals("Ping", JavaUtils.bytesToString(message)); callback.onSuccess(JavaUtils.stringToBytes("Pong")); } @Override public StreamManager getStreamManager() { return null; } }; this.ctx = new TransportContext(conf, rpcHandler); } void createServer(String secret) throws Exception { createServer(secret, true); } void createServer(String secret, boolean enableAes) throws Exception { TransportServerBootstrap introspector = new TransportServerBootstrap() { @Override public RpcHandler doBootstrap(Channel channel, RpcHandler rpcHandler) { AuthTestCtx.this.serverChannel = channel; if (rpcHandler instanceof AuthRpcHandler) { AuthTestCtx.this.authRpcHandler = (AuthRpcHandler) rpcHandler; } return rpcHandler; } }; SecretKeyHolder keyHolder = createKeyHolder(secret); TransportServerBootstrap auth = enableAes ? new AuthServerBootstrap(conf, keyHolder) : new SaslServerBootstrap(conf, keyHolder); this.server = ctx.createServer(Lists.newArrayList(auth, introspector)); } void createClient(String secret) throws Exception { createClient(secret, true); } void createClient(String secret, boolean enableAes) throws Exception { TransportConf clientConf = enableAes ? conf : new TransportConf("rpc", MapConfigProvider.EMPTY); List<TransportClientBootstrap> bootstraps = Lists.<TransportClientBootstrap>newArrayList( new AuthClientBootstrap(clientConf, appId, createKeyHolder(secret))); this.client = ctx.createClientFactory(bootstraps) .createClient(TestUtils.getLocalHost(), server.getPort()); } void close() { if (client != null) { client.close(); } if (server != null) { server.close(); } } private SecretKeyHolder createKeyHolder(String secret) { SecretKeyHolder keyHolder = mock(SecretKeyHolder.class); when(keyHolder.getSaslUser(anyString())).thenReturn(appId); when(keyHolder.getSecretKey(anyString())).thenReturn(secret); return keyHolder; } } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/main/java/org/apache/spark/network/crypto/AuthRpcHandler.java
170
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.io.IOException; import java.nio.ByteBuffer; import javax.security.sasl.Sasl; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.network.client.RpcResponseCallback; import org.apache.spark.network.client.TransportClient; import org.apache.spark.network.sasl.SecretKeyHolder; import org.apache.spark.network.sasl.SaslRpcHandler; import org.apache.spark.network.server.RpcHandler; import org.apache.spark.network.server.StreamManager; import org.apache.spark.network.util.JavaUtils; import org.apache.spark.network.util.TransportConf; /** * RPC Handler which performs authentication using Spark's auth protocol before delegating to a * child RPC handler. If the configuration allows, this handler will delegate messages to a SASL * RPC handler for further authentication, to support for clients that do not support Spark's * protocol. * * The delegate will only receive messages if the given connection has been successfully * authenticated. A connection may be authenticated at most once. */ class AuthRpcHandler extends RpcHandler { private static final Logger LOG = LoggerFactory.getLogger(AuthRpcHandler.class); /** Transport configuration. */ private final TransportConf conf; /** The client channel. */ private final Channel channel; /** * RpcHandler we will delegate to for authenticated connections. When falling back to SASL * this will be replaced with the SASL RPC handler. */ @VisibleForTesting RpcHandler delegate; /** Class which provides secret keys which are shared by server and client on a per-app basis. */ private final SecretKeyHolder secretKeyHolder; /** Whether auth is done and future calls should be delegated. */ @VisibleForTesting boolean doDelegate; AuthRpcHandler( TransportConf conf, Channel channel, RpcHandler delegate, SecretKeyHolder secretKeyHolder) { this.conf = conf; this.channel = channel; this.delegate = delegate; this.secretKeyHolder = secretKeyHolder; } @Override public void receive(TransportClient client, ByteBuffer message, RpcResponseCallback callback) { if (doDelegate) { delegate.receive(client, message, callback); return; } int position = message.position(); int limit = message.limit(); ClientChallenge challenge; try { challenge = ClientChallenge.decodeMessage(message); LOG.debug("Received new auth challenge for client {}.", channel.remoteAddress()); } catch (RuntimeException e) { if (conf.saslFallback()) { LOG.warn("Failed to parse new auth challenge, reverting to SASL for client {}.", channel.remoteAddress()); delegate = new SaslRpcHandler(conf, channel, delegate, secretKeyHolder); message.position(position); message.limit(limit); delegate.receive(client, message, callback); doDelegate = true; } else { LOG.debug("Unexpected challenge message from client {}, closing channel.", channel.remoteAddress()); callback.onFailure(new IllegalArgumentException("Unknown challenge message.")); channel.close(); } return; } // Here we have the client challenge, so perform the new auth protocol and set up the channel. AuthEngine engine = null; try { engine = new AuthEngine(challenge.appId, secretKeyHolder.getSecretKey(challenge.appId), conf); ServerResponse response = engine.respond(challenge); ByteBuf responseData = Unpooled.buffer(response.encodedLength()); response.encode(responseData); callback.onSuccess(responseData.nioBuffer()); engine.sessionCipher().addToChannel(channel); } catch (Exception e) { // This is a fatal error: authentication has failed. Close the channel explicitly. LOG.debug("Authentication failed for client {}, closing channel.", channel.remoteAddress()); callback.onFailure(new IllegalArgumentException("Authentication failed.")); channel.close(); return; } finally { if (engine != null) { try { engine.close(); } catch (Exception e) { throw Throwables.propagate(e); } } } LOG.debug("Authorization successful for client {}.", channel.remoteAddress()); doDelegate = true; } @Override public void receive(TransportClient client, ByteBuffer message) { delegate.receive(client, message); } @Override public StreamManager getStreamManager() { return delegate.getStreamManager(); } @Override public void channelActive(TransportClient client) { delegate.channelActive(client); } @Override public void channelInactive(TransportClient client) { delegate.channelInactive(client); } @Override public void exceptionCaught(Throwable cause, TransportClient client) { delegate.exceptionCaught(cause, client); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/main/java/org/apache/spark/network/crypto/AuthClientBootstrap.java
128
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.io.IOException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.Key; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.network.client.TransportClient; import org.apache.spark.network.client.TransportClientBootstrap; import org.apache.spark.network.sasl.SaslClientBootstrap; import org.apache.spark.network.sasl.SecretKeyHolder; import org.apache.spark.network.util.JavaUtils; import org.apache.spark.network.util.TransportConf; /** * Bootstraps a {@link TransportClient} by performing authentication using Spark's auth protocol. * * This bootstrap falls back to using the SASL bootstrap if the server throws an error during * authentication, and the configuration allows it. This is used for backwards compatibility * with external shuffle services that do not support the new protocol. * * It also automatically falls back to SASL if the new encryption backend is disabled, so that * callers only need to install this bootstrap when authentication is enabled. */ public class AuthClientBootstrap implements TransportClientBootstrap { private static final Logger LOG = LoggerFactory.getLogger(AuthClientBootstrap.class); private final TransportConf conf; private final String appId; private final String authUser; private final SecretKeyHolder secretKeyHolder; public AuthClientBootstrap( TransportConf conf, String appId, SecretKeyHolder secretKeyHolder) { this.conf = conf; // TODO: right now this behaves like the SASL backend, because when executors start up // they don't necessarily know the app ID. So they send a hardcoded "user" that is defined // in the SecurityManager, which will also always return the same secret (regardless of the // user name). All that's needed here is for this "user" to match on both sides, since that's // required by the protocol. At some point, though, it would be better for the actual app ID // to be provided here. this.appId = appId; this.authUser = secretKeyHolder.getSaslUser(appId); this.secretKeyHolder = secretKeyHolder; } @Override public void doBootstrap(TransportClient client, Channel channel) { if (!conf.encryptionEnabled()) { LOG.debug("AES encryption disabled, using old auth protocol."); doSaslAuth(client, channel); return; } try { doSparkAuth(client, channel); } catch (GeneralSecurityException | IOException e) { throw Throwables.propagate(e); } catch (RuntimeException e) { // There isn't a good exception that can be caught here to know whether it's really // OK to switch back to SASL (because the server doesn't speak the new protocol). So // try it anyway, and in the worst case things will fail again. if (conf.saslFallback()) { LOG.warn("New auth protocol failed, trying SASL.", e); doSaslAuth(client, channel); } else { throw e; } } } private void doSparkAuth(TransportClient client, Channel channel) throws GeneralSecurityException, IOException { AuthEngine engine = new AuthEngine(authUser, secretKeyHolder.getSecretKey(authUser), conf); try { ClientChallenge challenge = engine.challenge(); ByteBuf challengeData = Unpooled.buffer(challenge.encodedLength()); challenge.encode(challengeData); ByteBuffer responseData = client.sendRpcSync(challengeData.nioBuffer(), conf.authRTTimeoutMs()); ServerResponse response = ServerResponse.decodeMessage(responseData); engine.validate(response); engine.sessionCipher().addToChannel(channel); } finally { engine.close(); } } private void doSaslAuth(TransportClient client, Channel channel) { SaslClientBootstrap sasl = new SaslClientBootstrap(conf, appId, secretKeyHolder); sasl.doBootstrap(client, channel); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/test/java/org/apache/spark/network/crypto/AuthEngineSuite.java
109
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.util.Arrays; import java.util.Map; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableMap; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.apache.spark.network.util.MapConfigProvider; import org.apache.spark.network.util.TransportConf; public class AuthEngineSuite { private static TransportConf conf; @BeforeClass public static void setUp() { conf = new TransportConf("rpc", MapConfigProvider.EMPTY); } @Test public void testAuthEngine() throws Exception { AuthEngine client = new AuthEngine("appId", "secret", conf); AuthEngine server = new AuthEngine("appId", "secret", conf); try { ClientChallenge clientChallenge = client.challenge(); ServerResponse serverResponse = server.respond(clientChallenge); client.validate(serverResponse); TransportCipher serverCipher = server.sessionCipher(); TransportCipher clientCipher = client.sessionCipher(); assertTrue(Arrays.equals(serverCipher.getInputIv(), clientCipher.getOutputIv())); assertTrue(Arrays.equals(serverCipher.getOutputIv(), clientCipher.getInputIv())); assertEquals(serverCipher.getKey(), clientCipher.getKey()); } finally { client.close(); server.close(); } } @Test public void testMismatchedSecret() throws Exception { AuthEngine client = new AuthEngine("appId", "secret", conf); AuthEngine server = new AuthEngine("appId", "different_secret", conf); ClientChallenge clientChallenge = client.challenge(); try { server.respond(clientChallenge); fail("Should have failed to validate response."); } catch (IllegalArgumentException e) { // Expected. } } @Test(expected = IllegalArgumentException.class) public void testWrongAppId() throws Exception { AuthEngine engine = new AuthEngine("appId", "secret", conf); ClientChallenge challenge = engine.challenge(); byte[] badChallenge = engine.challenge(new byte[] { 0x00 }, challenge.nonce, engine.rawResponse(engine.challenge)); engine.respond(new ClientChallenge(challenge.appId, challenge.kdf, challenge.iterations, challenge.cipher, challenge.keyLength, challenge.nonce, badChallenge)); } @Test(expected = IllegalArgumentException.class) public void testWrongNonce() throws Exception { AuthEngine engine = new AuthEngine("appId", "secret", conf); ClientChallenge challenge = engine.challenge(); byte[] badChallenge = engine.challenge(challenge.appId.getBytes(UTF_8), new byte[] { 0x00 }, engine.rawResponse(engine.challenge)); engine.respond(new ClientChallenge(challenge.appId, challenge.kdf, challenge.iterations, challenge.cipher, challenge.keyLength, challenge.nonce, badChallenge)); } @Test(expected = IllegalArgumentException.class) public void testBadChallenge() throws Exception { AuthEngine engine = new AuthEngine("appId", "secret", conf); ClientChallenge challenge = engine.challenge(); byte[] badChallenge = new byte[challenge.challenge.length]; engine.respond(new ClientChallenge(challenge.appId, challenge.kdf, challenge.iterations, challenge.cipher, challenge.keyLength, challenge.nonce, badChallenge)); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
examples/src/main/java/org/apache/spark/examples/sql/JavaUserDefinedUntypedAggregation.java
132
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.examples.sql; // $example on:untyped_custom_aggregation$ import java.util.ArrayList; import java.util.List; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.expressions.MutableAggregationBuffer; import org.apache.spark.sql.expressions.UserDefinedAggregateFunction; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; // $example off:untyped_custom_aggregation$ public class JavaUserDefinedUntypedAggregation { // $example on:untyped_custom_aggregation$ public static class MyAverage extends UserDefinedAggregateFunction { private StructType inputSchema; private StructType bufferSchema; public MyAverage() { List<StructField> inputFields = new ArrayList<>(); inputFields.add(DataTypes.createStructField("inputColumn", DataTypes.LongType, true)); inputSchema = DataTypes.createStructType(inputFields); List<StructField> bufferFields = new ArrayList<>(); bufferFields.add(DataTypes.createStructField("sum", DataTypes.LongType, true)); bufferFields.add(DataTypes.createStructField("count", DataTypes.LongType, true)); bufferSchema = DataTypes.createStructType(bufferFields); } // Data types of input arguments of this aggregate function public StructType inputSchema() { return inputSchema; } // Data types of values in the aggregation buffer public StructType bufferSchema() { return bufferSchema; } // The data type of the returned value public DataType dataType() { return DataTypes.DoubleType; } // Whether this function always returns the same output on the identical input public boolean deterministic() { return true; } // Initializes the given aggregation buffer. The buffer itself is a `Row` that in addition to // standard methods like retrieving a value at an index (e.g., get(), getBoolean()), provides // the opportunity to update its values. Note that arrays and maps inside the buffer are still // immutable. public void initialize(MutableAggregationBuffer buffer) { buffer.update(0, 0L); buffer.update(1, 0L); } // Updates the given aggregation buffer `buffer` with new input data from `input` public void update(MutableAggregationBuffer buffer, Row input) { if (!input.isNullAt(0)) { long updatedSum = buffer.getLong(0) + input.getLong(0); long updatedCount = buffer.getLong(1) + 1; buffer.update(0, updatedSum); buffer.update(1, updatedCount); } } // Merges two aggregation buffers and stores the updated buffer values back to `buffer1` public void merge(MutableAggregationBuffer buffer1, Row buffer2) { long mergedSum = buffer1.getLong(0) + buffer2.getLong(0); long mergedCount = buffer1.getLong(1) + buffer2.getLong(1); buffer1.update(0, mergedSum); buffer1.update(1, mergedCount); } // Calculates the final result public Double evaluate(Row buffer) { return ((double) buffer.getLong(0)) / buffer.getLong(1); } } // $example off:untyped_custom_aggregation$ public static void main(String[] args) { SparkSession spark = SparkSession .builder() .appName("Java Spark SQL user-defined DataFrames aggregation example") .getOrCreate(); // $example on:untyped_custom_aggregation$ // Register the function to access it spark.udf().register("myAverage", new MyAverage()); Dataset<Row> df = spark.read().json("examples/src/main/resources/employees.json"); df.createOrReplaceTempView("employees"); df.show(); // +-------+------+ // | name|salary| // +-------+------+ // |Michael| 3000| // | Andy| 4500| // | Justin| 3500| // | Berta| 4000| // +-------+------+ Dataset<Row> result = spark.sql("SELECT myAverage(salary) as average_salary FROM employees"); result.show(); // +--------------+ // |average_salary| // +--------------+ // | 3750.0| // +--------------+ // $example off:untyped_custom_aggregation$ spark.stop(); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/main/java/org/apache/spark/network/crypto/ClientChallenge.java
101
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.nio.ByteBuffer; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.apache.spark.network.protocol.Encodable; import org.apache.spark.network.protocol.Encoders; /** * The client challenge message, used to initiate authentication. * * @see README.md */ public class ClientChallenge implements Encodable { /** Serialization tag used to catch incorrect payloads. */ private static final byte TAG_BYTE = (byte) 0xFA; public final String appId; public final String kdf; public final int iterations; public final String cipher; public final int keyLength; public final byte[] nonce; public final byte[] challenge; public ClientChallenge( String appId, String kdf, int iterations, String cipher, int keyLength, byte[] nonce, byte[] challenge) { this.appId = appId; this.kdf = kdf; this.iterations = iterations; this.cipher = cipher; this.keyLength = keyLength; this.nonce = nonce; this.challenge = challenge; } @Override public int encodedLength() { return 1 + 4 + 4 + Encoders.Strings.encodedLength(appId) + Encoders.Strings.encodedLength(kdf) + Encoders.Strings.encodedLength(cipher) + Encoders.ByteArrays.encodedLength(nonce) + Encoders.ByteArrays.encodedLength(challenge); } @Override public void encode(ByteBuf buf) { buf.writeByte(TAG_BYTE); Encoders.Strings.encode(buf, appId); Encoders.Strings.encode(buf, kdf); buf.writeInt(iterations); Encoders.Strings.encode(buf, cipher); buf.writeInt(keyLength); Encoders.ByteArrays.encode(buf, nonce); Encoders.ByteArrays.encode(buf, challenge); } public static ClientChallenge decodeMessage(ByteBuffer buffer) { ByteBuf buf = Unpooled.wrappedBuffer(buffer); if (buf.readByte() != TAG_BYTE) { throw new IllegalArgumentException("Expected ClientChallenge, received something else."); } return new ClientChallenge( Encoders.Strings.decode(buf), Encoders.Strings.decode(buf), buf.readInt(), Encoders.Strings.decode(buf), buf.readInt(), Encoders.ByteArrays.decode(buf), Encoders.ByteArrays.decode(buf)); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
R/install-source-package.sh
57
#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This scripts packages the SparkR source files (R and C files) and # creates a package that can be loaded in R. The package is by default installed to # $FWDIR/lib and the package can be loaded by using the following command in R: # # library(SparkR, lib.loc="$FWDIR/lib") # # NOTE(shivaram): Right now we use $SPARK_HOME/R/lib to be the installation directory # to load the SparkR package on the worker nodes. set -o pipefail set -e FWDIR="$(cd `dirname "${BASH_SOURCE[0]}"`; pwd)" pushd $FWDIR > /dev/null . $FWDIR/find-r.sh if [ -z "$VERSION" ]; then VERSION=`grep Version $FWDIR/pkg/DESCRIPTION | awk '{print $NF}'` fi if [ ! -f "$FWDIR"/SparkR_"$VERSION".tar.gz ]; then echo -e "R source package file $FWDIR/SparkR_$VERSION.tar.gz is not found." echo -e "Please build R source package with check-cran.sh" exit -1; fi echo "Removing lib path and installing from source package" LIB_DIR="$FWDIR/lib" rm -rf $LIB_DIR mkdir -p $LIB_DIR "$R_SCRIPT_PATH/"R CMD INSTALL SparkR_"$VERSION".tar.gz --library=$LIB_DIR # Zip the SparkR package so that it can be distributed to worker nodes on YARN pushd $LIB_DIR > /dev/null jar cfM "$LIB_DIR/sparkr.zip" SparkR popd > /dev/null popd
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
R/find-r.sh
34
#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if [ -z "$R_SCRIPT_PATH" ] then if [ ! -z "$R_HOME" ] then R_SCRIPT_PATH="$R_HOME/bin" else # if system wide R_HOME is not found, then exit if [ ! `command -v R` ]; then echo "Cannot find 'R_HOME'. Please specify 'R_HOME' or make sure R is properly installed." exit 1 fi R_SCRIPT_PATH="$(dirname $(which R))" fi echo "Using R_SCRIPT_PATH = ${R_SCRIPT_PATH}" fi
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/test/java/org/apache/spark/network/crypto/AuthMessagesSuite.java
80
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.nio.ByteBuffer; import java.util.Arrays; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import static org.junit.Assert.*; import org.apache.spark.network.protocol.Encodable; public class AuthMessagesSuite { private static int COUNTER = 0; private static String string() { return String.valueOf(COUNTER++); } private static byte[] byteArray() { byte[] bytes = new byte[COUNTER++]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) COUNTER; } return bytes; } private static int integer() { return COUNTER++; } @Test public void testClientChallenge() { ClientChallenge msg = new ClientChallenge(string(), string(), integer(), string(), integer(), byteArray(), byteArray()); ClientChallenge decoded = ClientChallenge.decodeMessage(encode(msg)); assertEquals(msg.appId, decoded.appId); assertEquals(msg.kdf, decoded.kdf); assertEquals(msg.iterations, decoded.iterations); assertEquals(msg.cipher, decoded.cipher); assertEquals(msg.keyLength, decoded.keyLength); assertTrue(Arrays.equals(msg.nonce, decoded.nonce)); assertTrue(Arrays.equals(msg.challenge, decoded.challenge)); } @Test public void testServerResponse() { ServerResponse msg = new ServerResponse(byteArray(), byteArray(), byteArray(), byteArray()); ServerResponse decoded = ServerResponse.decodeMessage(encode(msg)); assertTrue(Arrays.equals(msg.response, decoded.response)); assertTrue(Arrays.equals(msg.nonce, decoded.nonce)); assertTrue(Arrays.equals(msg.inputIv, decoded.inputIv)); assertTrue(Arrays.equals(msg.outputIv, decoded.outputIv)); } private ByteBuffer encode(Encodable msg) { ByteBuf buf = Unpooled.buffer(); msg.encode(buf); return buf.nioBuffer(); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/main/java/org/apache/spark/network/crypto/AuthServerBootstrap.java
55
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import io.netty.channel.Channel; import org.apache.spark.network.sasl.SaslServerBootstrap; import org.apache.spark.network.sasl.SecretKeyHolder; import org.apache.spark.network.server.RpcHandler; import org.apache.spark.network.server.TransportServerBootstrap; import org.apache.spark.network.util.TransportConf; /** * A bootstrap which is executed on a TransportServer's client channel once a client connects * to the server, enabling authentication using Spark's auth protocol (and optionally SASL for * clients that don't support the new protocol). * * It also automatically falls back to SASL if the new encryption backend is disabled, so that * callers only need to install this bootstrap when authentication is enabled. */ public class AuthServerBootstrap implements TransportServerBootstrap { private final TransportConf conf; private final SecretKeyHolder secretKeyHolder; public AuthServerBootstrap(TransportConf conf, SecretKeyHolder secretKeyHolder) { this.conf = conf; this.secretKeyHolder = secretKeyHolder; } public RpcHandler doBootstrap(Channel channel, RpcHandler rpcHandler) { if (!conf.encryptionEnabled()) { TransportServerBootstrap sasl = new SaslServerBootstrap(conf, secretKeyHolder); return sasl.doBootstrap(channel, rpcHandler); } return new AuthRpcHandler(conf, channel, rpcHandler, secretKeyHolder); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
common/network-common/src/main/java/org/apache/spark/network/crypto/ServerResponse.java
85
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.network.crypto; import java.nio.ByteBuffer; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.apache.spark.network.protocol.Encodable; import org.apache.spark.network.protocol.Encoders; /** * Server's response to client's challenge. * * @see README.md */ public class ServerResponse implements Encodable { /** Serialization tag used to catch incorrect payloads. */ private static final byte TAG_BYTE = (byte) 0xFB; public final byte[] response; public final byte[] nonce; public final byte[] inputIv; public final byte[] outputIv; public ServerResponse( byte[] response, byte[] nonce, byte[] inputIv, byte[] outputIv) { this.response = response; this.nonce = nonce; this.inputIv = inputIv; this.outputIv = outputIv; } @Override public int encodedLength() { return 1 + Encoders.ByteArrays.encodedLength(response) + Encoders.ByteArrays.encodedLength(nonce) + Encoders.ByteArrays.encodedLength(inputIv) + Encoders.ByteArrays.encodedLength(outputIv); } @Override public void encode(ByteBuf buf) { buf.writeByte(TAG_BYTE); Encoders.ByteArrays.encode(buf, response); Encoders.ByteArrays.encode(buf, nonce); Encoders.ByteArrays.encode(buf, inputIv); Encoders.ByteArrays.encode(buf, outputIv); } public static ServerResponse decodeMessage(ByteBuffer buffer) { ByteBuf buf = Unpooled.wrappedBuffer(buffer); if (buf.readByte() != TAG_BYTE) { throw new IllegalArgumentException("Expected ServerResponse, received something else."); } return new ServerResponse( Encoders.ByteArrays.decode(buf), Encoders.ByteArrays.decode(buf), Encoders.ByteArrays.decode(buf), Encoders.ByteArrays.decode(buf)); } }
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
R/create-rd.sh
37
#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This scripts packages the SparkR source files (R and C files) and # creates a package that can be loaded in R. The package is by default installed to # $FWDIR/lib and the package can be loaded by using the following command in R: # # library(SparkR, lib.loc="$FWDIR/lib") # # NOTE(shivaram): Right now we use $SPARK_HOME/R/lib to be the installation directory # to load the SparkR package on the worker nodes. set -o pipefail set -e FWDIR="$(cd `dirname "${BASH_SOURCE[0]}"`; pwd)" pushd $FWDIR > /dev/null . $FWDIR/find-r.sh # Generate Rd files if devtools is installed "$R_SCRIPT_PATH/"Rscript -e ' if("devtools" %in% rownames(installed.packages())) { library(devtools); devtools::document(pkg="./pkg", roclets=c("rd")) }'
apache_spark
2017-01-28
42ad93b2c9047a68c14cbf681508157101f43c0e
Wox.Infrastructure/Logger/Log.cs
112
using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using NLog; using NLog.Config; using NLog.Targets; namespace Wox.Infrastructure.Logger { public static class Log { public const string DirectoryName = "Logs"; static Log() { var path = Path.Combine(Constant.DataDirectory, DirectoryName, Constant.Version); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var configuration = new LoggingConfiguration(); var target = new FileTarget(); configuration.AddTarget("file", target); target.FileName = "${specialfolder:folder=ApplicationData}/" + Constant.Wox + "/" + DirectoryName + "/" + Constant.Version + "/${shortdate}.txt"; #if DEBUG var rule = new LoggingRule("*", LogLevel.Debug, target); #else var rule = new LoggingRule("*", LogLevel.Info, target); #endif configuration.LoggingRules.Add(rule); LogManager.Configuration = configuration; } private static void LogFaultyFormat(string message) { var logger = LogManager.GetLogger("FaultyLogger"); message = $"Wrong logger message format <{message}>"; System.Diagnostics.Debug.WriteLine($"FATAL|{message}"); logger.Fatal(message); } private static bool FormatValid(string message) { var parts = message.Split('|'); var valid = parts.Length == 3 && !string.IsNullOrWhiteSpace(parts[1]) && !string.IsNullOrWhiteSpace(parts[2]); return valid; } /// <param name="message">example: "|prefix|unprefixed" </param> public static void Error(string message) { if (FormatValid(message)) { var parts = message.Split('|'); var prefix = parts[1]; var unprefixed = parts[2]; var logger = LogManager.GetLogger(prefix); System.Diagnostics.Debug.WriteLine($"ERROR|{message}"); logger.Error(unprefixed); } else { LogFaultyFormat(message); } } /// <param name="message">example: "|prefix|unprefixed" </param> [MethodImpl(MethodImplOptions.Synchronized)] public static void Exception(string message, System.Exception e) { #if DEBUG throw e; #else if (FormatValid(message)) { var parts = message.Split('|'); var prefix = parts[1]; var unprefixed = parts[2]; var logger = LogManager.GetLogger(prefix); System.Diagnostics.Debug.WriteLine($"ERROR|{message}"); logger.Error("-------------------------- Begin exception --------------------------"); logger.Error(unprefixed); do { logger.Error($"Exception message:\n <{e.Message}>"); logger.Error($"Exception stack trace:\n <{e.StackTrace}>"); e = e.InnerException; } while (e != null); logger.Error("-------------------------- End exception --------------------------"); } else { LogFaultyFormat(message); } #endif } /// <param name="message">example: "|prefix|unprefixed" </param> public static void Debug(string message) { if (FormatValid(message)) { var parts = message.Split('|'); var prefix = parts[1]; var unprefixed = parts[2]; var logger = LogManager.GetLogger(prefix); System.Diagnostics.Debug.WriteLine($"DEBUG|{message}"); logger.Debug(unprefixed); } else { LogFaultyFormat(message); } } /// <param name="message">example: "|prefix|unprefixed" </param> public static void Info(string message) { if (FormatValid(message)) { var parts = message.Split('|'); var prefix = parts[1]; var unprefixed = parts[2]; var logger = LogManager.GetLogger(prefix); System.Diagnostics.Debug.WriteLine($"INFO|{message}"); logger.Info(unprefixed); } else { LogFaultyFormat(message); } } /// <param name="message">example: "|prefix|unprefixed" </param> public static void Warn(string message) { if (FormatValid(message)) { var parts = message.Split('|'); var prefix = parts[1]; var unprefixed = parts[2]; var logger = LogManager.GetLogger(prefix); System.Diagnostics.Debug.WriteLine($"WARN|{message}"); logger.Warn(unprefixed); } else { LogFaultyFormat(message); } } } }
microsoft_PowerToys
2017-01-28
dc46277d0c088c48e1a13ea5f72209ea462de929
Wox.Infrastructure/Alphabet.cs
51
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using hyjiacan.util.p4n; using hyjiacan.util.p4n.format; namespace Wox.Infrastructure { public static class Alphabet { private static readonly HanyuPinyinOutputFormat Format = new HanyuPinyinOutputFormat(); private static readonly ConcurrentDictionary<string, string[][]> PinyinCache = new ConcurrentDictionary<string, string[][]>(); static Alphabet() { Format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); } /// <summary> /// replace chinese character with pinyin, non chinese character won't be modified /// <param name="word"> should be word or sentence, instead of single character. e.g. 微软 </param> /// </summary> public static string[] Pinyin(string word) { var pinyin = word.Select(c => { var pinyins = PinyinHelper.toHanyuPinyinStringArray(c); var result = pinyins == null ? c.ToString() : pinyins[0]; return result; }).ToArray(); return pinyin; } /// <summmary> /// replace chinese character with pinyin, non chinese character won't be modified /// Because we don't have words dictionary, so we can only return all possiblie pinyin combination /// e.g. 音乐 will return yinyue and yinle /// <param name="characters"> should be word or sentence, instead of single character. e.g. 微软 </param> /// </summmary> public static string[][] PinyinComination(string characters) { if (!string.IsNullOrEmpty(characters)) { if (!PinyinCache.ContainsKey(characters)) { var allPinyins = new List<string[]>(); foreach (var c in characters) { var pinyins = PinyinHelper.toHanyuPinyinStringArray(c, Format); if (pinyins != null) { var r = pinyins.Distinct().ToArray(); allPinyins.Add(r); } else { var r = new[] { c.ToString() }; allPinyins.Add(r); } } var combination = allPinyins.Aggregate(Combination).Select(c => c.Split(';')).ToArray(); PinyinCache[characters] = combination; return combination; } else { return PinyinCache[characters]; } } else { return new string[][] { }; } } public static string Acronym(string[] pinyin) { var acronym = string.Join("", pinyin.Select(p => p[0])); return acronym; } public static bool ContainsChinese(string word) { var chinese = word.Select(PinyinHelper.toHanyuPinyinStringArray) .Any(p => p != null); return chinese; } private static string[] Combination(string[] array1, string[] array2) { var combination = ( from a1 in array1 from a2 in array2 select $"{a1};{a2}" ).ToArray(); return combination; } } }
microsoft_PowerToys
2017-01-28
dc46277d0c088c48e1a13ea5f72209ea462de929
Wox.Infrastructure/Image/ImageCache.cs
23
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Windows.Media; namespace Wox.Infrastructure.Image { [Serializable] public class ImageCache { private const int MaxCached = 200; public ConcurrentDictionary<string, int> Usage = new ConcurrentDictionary<string, int>(); private readonly ConcurrentDictionary<string, ImageSource> _data = new ConcurrentDictionary<string, ImageSource>(); public ImageSource this[string path] { get { Usage.AddOrUpdate(path, 1, (k, v) => v + 1); var i = _data[path]; return i; } set { _data[path] = value; } } public void Cleanup() { var images = Usage .OrderByDescending(o => o.Value) .Take(MaxCached) .ToDictionary(i => i.Key, i => i.Value); Usage = new ConcurrentDictionary<string, int>(images); } public bool ContainsKey(string key) { var contains = _data.ContainsKey(key); return contains; } } }
microsoft_PowerToys
2017-01-28
dc46277d0c088c48e1a13ea5f72209ea462de929
requests/packages/urllib3/util/selectors.py
524
# Backport of selectors.py from Python 3.5+ to support Python < 3.4 # Also has the behavior specified in PEP 475 which is to retry syscalls # in the case of an EINTR error. This module is required because selectors34 # does not follow this behavior and instead returns that no dile descriptor # events have occurred rather than retry the syscall. The decision to drop # support for select.devpoll is made to maintain 100% test coverage. import errno import math import select from collections import namedtuple, Mapping import time try: monotonic = time.monotonic except (AttributeError, ImportError): # Python 3.3< monotonic = time.time EVENT_READ = (1 << 0) EVENT_WRITE = (1 << 1) HAS_SELECT = True # Variable that shows whether the platform has a selector. _SYSCALL_SENTINEL = object() # Sentinel in case a system call returns None. class SelectorError(Exception): def __init__(self, errcode): super(SelectorError, self).__init__() self.errno = errcode def __repr__(self): return "<SelectorError errno={0}>".format(self.errno) def __str__(self): return self.__repr__() def _fileobj_to_fd(fileobj): """ Return a file descriptor from a file object. If given an integer will simply return that integer back. """ if isinstance(fileobj, int): fd = fileobj else: try: fd = int(fileobj.fileno()) except (AttributeError, TypeError, ValueError): raise ValueError("Invalid file object: {0!r}".format(fileobj)) if fd < 0: raise ValueError("Invalid file descriptor: {0}".format(fd)) return fd def _syscall_wrapper(func, recalc_timeout, *args, **kwargs): """ Wrapper function for syscalls that could fail due to EINTR. All functions should be retried if there is time left in the timeout in accordance with PEP 475. """ timeout = kwargs.get("timeout", None) if timeout is None: expires = None recalc_timeout = False else: timeout = float(timeout) if timeout < 0.0: # Timeout less than 0 treated as no timeout. expires = None else: expires = monotonic() + timeout args = list(args) if recalc_timeout and "timeout" not in kwargs: raise ValueError( "Timeout must be in args or kwargs to be recalculated") result = _SYSCALL_SENTINEL while result is _SYSCALL_SENTINEL: try: result = func(*args, **kwargs) # OSError is thrown by select.select # IOError is thrown by select.epoll.poll # select.error is thrown by select.poll.poll # Aren't we thankful for Python 3.x rework for exceptions? except (OSError, IOError, select.error) as e: # select.error wasn't a subclass of OSError in the past. errcode = None if hasattr(e, "errno"): errcode = e.errno elif hasattr(e, "args"): errcode = e.args[0] # Also test for the Windows equivalent of EINTR. is_interrupt = (errcode == errno.EINTR or (hasattr(errno, "WSAEINTR") and errcode == errno.WSAEINTR)) if is_interrupt: if expires is not None: current_time = monotonic() if current_time > expires: raise OSError(errno=errno.ETIMEDOUT) if recalc_timeout: if "timeout" in kwargs: kwargs["timeout"] = expires - current_time continue if errcode: raise SelectorError(errcode) else: raise return result SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data']) class _SelectorMapping(Mapping): """ Mapping of file objects to selector keys """ def __init__(self, selector): self._selector = selector def __len__(self): return len(self._selector._fd_to_key) def __getitem__(self, fileobj): try: fd = self._selector._fileobj_lookup(fileobj) return self._selector._fd_to_key[fd] except KeyError: raise KeyError("{0!r} is not registered.".format(fileobj)) def __iter__(self): return iter(self._selector._fd_to_key) class BaseSelector(object): """ Abstract Selector class A selector supports registering file objects to be monitored for specific I/O events. A file object is a file descriptor or any object with a `fileno()` method. An arbitrary object can be attached to the file object which can be used for example to store context info, a callback, etc. A selector can use various implementations (select(), poll(), epoll(), and kqueue()) depending on the platform. The 'DefaultSelector' class uses the most efficient implementation for the current platform. """ def __init__(self): # Maps file descriptors to keys. self._fd_to_key = {} # Read-only mapping returned by get_map() self._map = _SelectorMapping(self) def _fileobj_lookup(self, fileobj): """ Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. Used by unregister() so we can unregister an object that was previously registered even if it is closed. It is also used by _SelectorMapping """ try: return _fileobj_to_fd(fileobj) except ValueError: # Search through all our mapped keys. for key in self._fd_to_key.values(): if key.fileobj is fileobj: return key.fd # Raise ValueError after all. raise def register(self, fileobj, events, data=None): """ Register a file object for a set of events to monitor. """ if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)): raise ValueError("Invalid events: {0!r}".format(events)) key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data) if key.fd in self._fd_to_key: raise KeyError("{0!r} (FD {1}) is already registered" .format(fileobj, key.fd)) self._fd_to_key[key.fd] = key return key def unregister(self, fileobj): """ Unregister a file object from being monitored. """ try: key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) except KeyError: raise KeyError("{0!r} is not registered".format(fileobj)) return key def modify(self, fileobj, events, data=None): """ Change a registered file object monitored events and data. """ # NOTE: Some subclasses optimize this operation even further. try: key = self._fd_to_key[self._fileobj_lookup(fileobj)] except KeyError: raise KeyError("{0!r} is not registered".format(fileobj)) if events != key.events: self.unregister(fileobj) key = self.register(fileobj, events, data) elif data != key.data: # Use a shortcut to update the data. key = key._replace(data=data) self._fd_to_key[key.fd] = key return key def select(self, timeout=None): """ Perform the actual selection until some monitored file objects are ready or the timeout expires. """ raise NotImplementedError() def close(self): """ Close the selector. This must be called to ensure that all underlying resources are freed. """ self._fd_to_key.clear() self._map = None def get_key(self, fileobj): """ Return the key associated with a registered file object. """ mapping = self.get_map() if mapping is None: raise RuntimeError("Selector is closed") try: return mapping[fileobj] except KeyError: raise KeyError("{0!r} is not registered".format(fileobj)) def get_map(self): """ Return a mapping of file objects to selector keys """ return self._map def _key_from_fd(self, fd): """ Return the key associated to a given file descriptor Return None if it is not found. """ try: return self._fd_to_key[fd] except KeyError: return None def __enter__(self): return self def __exit__(self, *args): self.close() # Almost all platforms have select.select() if hasattr(select, "select"): class SelectSelector(BaseSelector): """ Select-based selector. """ def __init__(self): super(SelectSelector, self).__init__() self._readers = set() self._writers = set() def register(self, fileobj, events, data=None): key = super(SelectSelector, self).register(fileobj, events, data) if events & EVENT_READ: self._readers.add(key.fd) if events & EVENT_WRITE: self._writers.add(key.fd) return key def unregister(self, fileobj): key = super(SelectSelector, self).unregister(fileobj) self._readers.discard(key.fd) self._writers.discard(key.fd) return key def _select(self, r, w, timeout=None): """ Wrapper for select.select because timeout is a positional arg """ return select.select(r, w, [], timeout) def select(self, timeout=None): # Selecting on empty lists on Windows errors out. if not len(self._readers) and not len(self._writers): return [] timeout = None if timeout is None else max(timeout, 0.0) ready = [] r, w, _ = _syscall_wrapper(self._select, True, self._readers, self._writers, timeout) r = set(r) w = set(w) for fd in r | w: events = 0 if fd in r: events |= EVENT_READ if fd in w: events |= EVENT_WRITE key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready if hasattr(select, "poll"): class PollSelector(BaseSelector): """ Poll-based selector """ def __init__(self): super(PollSelector, self).__init__() self._poll = select.poll() def register(self, fileobj, events, data=None): key = super(PollSelector, self).register(fileobj, events, data) event_mask = 0 if events & EVENT_READ: event_mask |= select.POLLIN if events & EVENT_WRITE: event_mask |= select.POLLOUT self._poll.register(key.fd, event_mask) return key def unregister(self, fileobj): key = super(PollSelector, self).unregister(fileobj) self._poll.unregister(key.fd) return key def _wrap_poll(self, timeout=None): """ Wrapper function for select.poll.poll() so that _syscall_wrapper can work with only seconds. """ if timeout is not None: if timeout <= 0: timeout = 0 else: # select.poll.poll() has a resolution of 1 millisecond, # round away from zero to wait *at least* timeout seconds. timeout = math.ceil(timeout * 1e3) result = self._poll.poll(timeout) return result def select(self, timeout=None): ready = [] fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout) for fd, event_mask in fd_events: events = 0 if event_mask & ~select.POLLIN: events |= EVENT_WRITE if event_mask & ~select.POLLOUT: events |= EVENT_READ key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready if hasattr(select, "epoll"): class EpollSelector(BaseSelector): """ Epoll-based selector """ def __init__(self): super(EpollSelector, self).__init__() self._epoll = select.epoll() def fileno(self): return self._epoll.fileno() def register(self, fileobj, events, data=None): key = super(EpollSelector, self).register(fileobj, events, data) events_mask = 0 if events & EVENT_READ: events_mask |= select.EPOLLIN if events & EVENT_WRITE: events_mask |= select.EPOLLOUT _syscall_wrapper(self._epoll.register, False, key.fd, events_mask) return key def unregister(self, fileobj): key = super(EpollSelector, self).unregister(fileobj) try: _syscall_wrapper(self._epoll.unregister, False, key.fd) except SelectorError: # This can occur when the fd was closed since registry. pass return key def select(self, timeout=None): if timeout is not None: if timeout <= 0: timeout = 0.0 else: # select.epoll.poll() has a resolution of 1 millisecond # but luckily takes seconds so we don't need a wrapper # like PollSelector. Just for better rounding. timeout = math.ceil(timeout * 1e3) * 1e-3 timeout = float(timeout) else: timeout = -1.0 # epoll.poll() must have a float. # We always want at least 1 to ensure that select can be called # with no file descriptors registered. Otherwise will fail. max_events = max(len(self._fd_to_key), 1) ready = [] fd_events = _syscall_wrapper(self._epoll.poll, True, timeout=timeout, maxevents=max_events) for fd, event_mask in fd_events: events = 0 if event_mask & ~select.EPOLLIN: events |= EVENT_WRITE if event_mask & ~select.EPOLLOUT: events |= EVENT_READ key = self._key_from_fd(fd) if key: ready.append((key, events & key.events)) return ready def close(self): self._epoll.close() super(EpollSelector, self).close() if hasattr(select, "kqueue"): class KqueueSelector(BaseSelector): """ Kqueue / Kevent-based selector """ def __init__(self): super(KqueueSelector, self).__init__() self._kqueue = select.kqueue() def fileno(self): return self._kqueue.fileno() def register(self, fileobj, events, data=None): key = super(KqueueSelector, self).register(fileobj, events, data) if events & EVENT_READ: kevent = select.kevent(key.fd, select.KQ_FILTER_READ, select.KQ_EV_ADD) _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) if events & EVENT_WRITE: kevent = select.kevent(key.fd, select.KQ_FILTER_WRITE, select.KQ_EV_ADD) _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) return key def unregister(self, fileobj): key = super(KqueueSelector, self).unregister(fileobj) if key.events & EVENT_READ: kevent = select.kevent(key.fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE) try: _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) except SelectorError: pass if key.events & EVENT_WRITE: kevent = select.kevent(key.fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE) try: _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) except SelectorError: pass return key def select(self, timeout=None): if timeout is not None: timeout = max(timeout, 0) max_events = len(self._fd_to_key) * 2 ready_fds = {} kevent_list = _syscall_wrapper(self._kqueue.control, True, None, max_events, timeout) for kevent in kevent_list: fd = kevent.ident event_mask = kevent.filter events = 0 if event_mask == select.KQ_FILTER_READ: events |= EVENT_READ if event_mask == select.KQ_FILTER_WRITE: events |= EVENT_WRITE key = self._key_from_fd(fd) if key: if key.fd not in ready_fds: ready_fds[key.fd] = (key, events & key.events) else: old_events = ready_fds[key.fd][1] ready_fds[key.fd] = (key, (events | old_events) & key.events) return list(ready_fds.values()) def close(self): self._kqueue.close() super(KqueueSelector, self).close() # Choose the best implementation, roughly: # kqueue == epoll > poll > select. Devpoll not supported. (See above) # select() also can't accept a FD > FD_SETSIZE (usually around 1024) if 'KqueueSelector' in globals(): # Platform-specific: Mac OS and BSD DefaultSelector = KqueueSelector elif 'EpollSelector' in globals(): # Platform-specific: Linux DefaultSelector = EpollSelector elif 'PollSelector' in globals(): # Platform-specific: Linux DefaultSelector = PollSelector elif 'SelectSelector' in globals(): # Platform-specific: Windows DefaultSelector = SelectSelector else: # Platform-specific: AppEngine def no_selector(_): raise ValueError("Platform does not have a selector") DefaultSelector = no_selector HAS_SELECT = False
psf_requests
2017-01-27
8a58427d8aa73d6af81b6e5f6fd934b3386ef3de
requests/packages/urllib3/util/request.py
47
from __future__ import absolute_import from base64 import b64encode from ..packages.six import b, integer_types from ..exceptions import UnrewindableBodyError ACCEPT_ENCODING = 'gzip,deflate' _FAILEDTELL = object() def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None): """ Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} """ headers = {} if accept_encoding: if isinstance(accept_encoding, str): pass elif isinstance(accept_encoding, list): accept_encoding = ','.join(accept_encoding) else: accept_encoding = ACCEPT_ENCODING headers['accept-encoding'] = accept_encoding if user_agent: headers['user-agent'] = user_agent if keep_alive: headers['connection'] = 'keep-alive' if basic_auth: headers['authorization'] = 'Basic ' + \ b64encode(b(basic_auth)).decode('utf-8') if proxy_basic_auth: headers['proxy-authorization'] = 'Basic ' + \ b64encode(b(proxy_basic_auth)).decode('utf-8') if disable_cache: headers['cache-control'] = 'no-cache' return headers def set_file_position(body, pos): """ If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. """ if pos is not None: rewind_body(body, pos) elif getattr(body, 'tell', None) is not None: try: pos = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body. pos = _FAILEDTELL return pos def rewind_body(body, body_pos): """ Attempt to rewind body to a certain position. Primarily used for request redirects and retries. :param body: File-like object that supports seek. :param int pos: Position to seek to in file. """ body_seek = getattr(body, 'seek', None) if body_seek is not None and isinstance(body_pos, integer_types): try: body_seek(body_pos) except (IOError, OSError): raise UnrewindableBodyError("An error occured when rewinding request " "body for redirect/retry.") elif body_pos is _FAILEDTELL: raise UnrewindableBodyError("Unable to record file position for rewinding " "request body during a redirect/retry.") else: raise ValueError("body_pos must be of type integer, " "instead it was %s." % type(body_pos))
psf_requests
2017-01-27
8a58427d8aa73d6af81b6e5f6fd934b3386ef3de
requests/packages/urllib3/util/wait.py
40
from .selectors import ( HAS_SELECT, DefaultSelector, EVENT_READ, EVENT_WRITE ) def _wait_for_io_events(socks, events, timeout=None): """ Waits for IO events to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be interacted with immediately. """ if not HAS_SELECT: raise ValueError('Platform does not have a selector') if not isinstance(socks, list): # Probably just a single socket. if hasattr(socks, "fileno"): socks = [socks] # Otherwise it might be a non-list iterable. else: socks = list(socks) with DefaultSelector() as selector: for sock in socks: selector.register(sock, events) return [key[0].fileobj for key in selector.select(timeout) if key[1] & events] def wait_for_read(socks, timeout=None): """ Waits for reading to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be read from immediately. """ return _wait_for_io_events(socks, EVENT_READ, timeout) def wait_for_write(socks, timeout=None): """ Waits for writing to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be written to immediately. """ return _wait_for_io_events(socks, EVENT_WRITE, timeout)
psf_requests
2017-01-27
8a58427d8aa73d6af81b6e5f6fd934b3386ef3de
keras/utils/generic_utils.py
146
"""Python utilities required by Keras.""" from __future__ import absolute_import import numpy as np import time import sys import six import marshal import types as python_types _GLOBAL_CUSTOM_OBJECTS = {} class CustomObjectScope(object): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. # Example Consider a custom object `MyObject` ```python with CustomObjectScope({"MyObject":MyObject}): layer = Dense(..., W_regularizer="MyObject") # save, load, etc. will recognize custom object by name ``` """ def __init__(self, *args): self.custom_objects = args self.backup = None def __enter__(self): self.backup = _GLOBAL_CUSTOM_OBJECTS.copy() for objects in self.custom_objects: _GLOBAL_CUSTOM_OBJECTS.update(objects) return self def __exit__(self, type, value, traceback): _GLOBAL_CUSTOM_OBJECTS.clear() _GLOBAL_CUSTOM_OBJECTS.update(self.backup) def custom_object_scope(*args): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Convenience wrapper for `CustomObjectScope`. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. # Example Consider a custom object `MyObject` ```python with custom_object_scope({"MyObject":MyObject}): layer = Dense(..., W_regularizer="MyObject") # save, load, etc. will recognize custom object by name ``` # Arguments *args: Variable length list of dictionaries of name, class pairs to add to custom objects. # Returns Object of type `CustomObjectScope`. """ return CustomObjectScope(*args) def get_custom_objects(): """Retrieves a live reference to the global dictionary of custom objects (`_GLOBAL_CUSTOM_OBJECTS`). Updating and clearing custom objects using `custom_object_scope` is preferred, but `get_custom_objects` can be used to directly access `_GLOBAL_CUSTOM_OBJECTS`. # Example ```python get_custom_objects().clear() get_custom_objects()["MyObject"] = MyObject ``` # Returns Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`). """ return _GLOBAL_CUSTOM_OBJECTS def get_from_module(identifier, module_params, module_name, instantiate=False, kwargs=None): """Retrieves a class or function member of a module. First checks `_GLOBAL_CUSTOM_OBJECTS` for `module_name`, then checks `module_params`. # Arguments identifier: the object to retrieve. It could be specified by name (as a string), or by dict. In any other case, `identifier` itself will be returned without any changes. module_params: the members of a module (e.g. the output of `globals()`). module_name: string; the name of the target module. Only used to format error messages. instantiate: whether to instantiate the returned object (if it's a class). kwargs: a dictionary of keyword arguments to pass to the class constructor if `instantiate` is `True`. # Returns The target object. # Raises ValueError: if the identifier cannot be found. """ if isinstance(identifier, six.string_types): res = None if identifier in _GLOBAL_CUSTOM_OBJECTS: res = _GLOBAL_CUSTOM_OBJECTS[identifier] if not res: res = module_params.get(identifier) if not res: raise ValueError('Invalid ' + str(module_name) + ': ' + str(identifier)) if instantiate and not kwargs: return res() elif instantiate and kwargs: return res(**kwargs) else: return res elif isinstance(identifier, dict): name = identifier.pop('name') res = None if name in _GLOBAL_CUSTOM_OBJECTS: res = _GLOBAL_CUSTOM_OBJECTS[name] if not res: res = module_params.get(name) if res: return res(**identifier) else: raise ValueError('Invalid ' + str(module_name) + ': ' + str(identifier)) return identifier def make_tuple(*args): return args def func_dump(func): """Serializes a user defined function. # Arguments func: the function to serialize. # Returns A tuple `(code, defaults, closure)`. """ code = marshal.dumps(func.__code__).decode('raw_unicode_escape') defaults = func.__defaults__ if func.__closure__: closure = tuple(c.cell_contents for c in func.__closure__) else: closure = None return code, defaults, closure def func_load(code, defaults=None, closure=None, globs=None): """Deserializes a user defined function. # Arguments code: bytecode of the function. defaults: defaults of the function. closure: closure of the function. globs: dictionary of global objects. # Returns A function object. """ if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code code = marshal.loads(code.encode('raw_unicode_escape')) if globs is None: globs = globals() return python_types.FunctionType(code, globs, name=code.co_name, argdefs=defaults, closure=closure) class Progbar(object): """Displays a progress bar. # Arguments target: Total number of steps expected. interval: Minimum visual progress update interval (in seconds). """ def __init__(self, target, width=30, verbose=1, interval=0.01): self.width = width self.target = target self.sum_values = {} self.unique_values = [] self.start = time.time() self.last_update = 0 self.interval = interval self.total_width = 0 self.seen_so_far = 0 self.verbose = verbose def update(self, current, values=None, force=False): """Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. force: Whether to force visual progress update. """ values = values or [] for k, v in values: if k not in self.sum_values: self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far] self.unique_values.append(k) else: self.sum_values[k][0] += v * (current - self.seen_so_far) self.sum_values[k][1] += (current - self.seen_so_far) self.seen_so_far = current now = time.time() if self.verbose == 1: if not force and (now - self.last_update) < self.interval: return prev_total_width = self.total_width sys.stdout.write('\b' * prev_total_width) sys.stdout.write('\r') numdigits = int(np.floor(np.log10(self.target))) + 1 barstr = '%%%dd/%%%dd [' % (numdigits, numdigits) bar = barstr % (current, self.target) prog = float(current) / self.target prog_width = int(self.width * prog) if prog_width > 0: bar += ('=' * (prog_width - 1)) if current < self.target: bar += '>' else: bar += '=' bar += ('.' * (self.width - prog_width)) bar += ']' sys.stdout.write(bar) self.total_width = len(bar) if current: time_per_unit = (now - self.start) / current else: time_per_unit = 0 eta = time_per_unit * (self.target - current) info = '' if current < self.target: info += ' - ETA: %ds' % eta else: info += ' - %ds' % (now - self.start) for k in self.unique_values: info += ' - %s:' % k if isinstance(self.sum_values[k], list): avg = self.sum_values[k][0] / max(1, self.sum_values[k][1]) if abs(avg) > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg else: info += ' %s' % self.sum_values[k] self.total_width += len(info) if prev_total_width > self.total_width: info += ((prev_total_width - self.total_width) * ' ') sys.stdout.write(info) sys.stdout.flush() if current >= self.target: sys.stdout.write('\n') if self.verbose == 2: if current >= self.target: info = '%ds' % (now - self.start) for k in self.unique_values: info += ' - %s:' % k avg = self.sum_values[k][0] / max(1, self.sum_values[k][1]) if avg > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg sys.stdout.write(info + "\n") self.last_update = now def add(self, n, values=None): self.update(self.seen_so_far + n, values)
keras-team_keras
2017-01-28
ab3b93e8dd103f1d9729305825791a084c7c8493
keras/utils/np_utils.py
63
"""Numpy-related utilities.""" from __future__ import absolute_import import numpy as np from six.moves import range from six.moves import zip from .. import backend as K def to_categorical(y, nb_classes=None): """Converts a class vector (integers) to binary class matrix. E.g. for use with categorical_crossentropy. # Arguments y: class vector to be converted into a matrix (integers from 0 to nb_classes). nb_classes: total number of classes. # Returns A binary matrix representation of the input. """ y = np.array(y, dtype='int').ravel() if not nb_classes: nb_classes = np.max(y) + 1 n = y.shape[0] categorical = np.zeros((n, nb_classes)) categorical[np.arange(n), y] = 1 return categorical def normalize(a, axis=-1, order=2): l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) l2[l2 == 0] = 1 return a / np.expand_dims(l2, axis) def binary_logloss(p, y): epsilon = 1e-15 p = np.maximum(epsilon, p) p = np.minimum(1 - epsilon, p) res = sum(y * np.log(p) + np.subtract(1, y) * np.log(np.subtract(1, p))) res *= -1.0 / len(y) return res def multiclass_logloss(p, y): npreds = [p[i][y[i] - 1] for i in range(len(y))] score = -(1. / len(y)) * np.sum(np.log(npreds)) return score def accuracy(p, y): return np.mean([a == b for a, b in zip(p, y)]) def probas_to_classes(y_pred): if len(y_pred.shape) > 1 and y_pred.shape[1] > 1: return categorical_probas_to_classes(y_pred) return np.array([1 if p > 0.5 else 0 for p in y_pred]) def categorical_probas_to_classes(p): return np.argmax(p, axis=1) def convert_kernel(kernel, dim_ordering=None): """Converts a Numpy kernel matrix from Theano format to TensorFlow format. Also works reciprocally, since the transformation is its own inverse. # Arguments kernel: Numpy array (4D or 5D). dim_ordering: the data format. # Returns The converted kernel. # Raises ValueError: in case of invalid kernel shape or invalid dim_ordering. """ if dim_ordering is None: dim_ordering = K.image_dim_ordering() if not 4 <= kernel.ndim <= 5: raise ValueError('Invalid kernel shape:', kernel.shape) slices = [slice(None, None, -1) for _ in range(kernel.ndim)] no_flip = (slice(None, None), slice(None, None)) if dim_ordering == 'th': # (out_depth, input_depth, ...) slices[:2] = no_flip elif dim_ordering == 'tf': # (..., input_depth, out_depth) slices[-2:] = no_flip else: raise ValueError('Invalid dim_ordering:', dim_ordering) return np.copy(kernel[slices]) def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): """Determines output length of a convolution given input length. # Arguments input_length: integer. filter_size: integer. border_mode: one of "same", "valid", "full". stride: integer. dilation: dilation rate, integer. # Returns The output length (integer). """ if input_length is None: return None assert border_mode in {'same', 'valid', 'full'} dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1) if border_mode == 'same': output_length = input_length elif border_mode == 'valid': output_length = input_length - dilated_filter_size + 1 elif border_mode == 'full': output_length = input_length + dilated_filter_size - 1 return (output_length + stride - 1) // stride def conv_input_length(output_length, filter_size, border_mode, stride): """Determines input length of a convolution given output length. # Arguments output_length: integer. filter_size: integer. border_mode: one of "same", "valid", "full". stride: integer. # Returns The input length (integer). """ if output_length is None: return None assert border_mode in {'same', 'valid', 'full'} if border_mode == 'same': pad = filter_size // 2 elif border_mode == 'valid': pad = 0 elif border_mode == 'full': pad = filter_size - 1 return (output_length - 1) * stride - 2 * pad + filter_size
keras-team_keras
2017-01-28
ab3b93e8dd103f1d9729305825791a084c7c8493
keras/preprocessing/text.py
127
# -*- coding: utf-8 -*- """Utilities for text input preprocessing. May benefit from a fast Cython rewrite. """ from __future__ import absolute_import from __future__ import division import string import sys import numpy as np from six.moves import range from six.moves import zip if sys.version_info < (3,): maketrans = string.maketrans else: maketrans = str.maketrans def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" "): """Converts a text to a sequence of word indices. # Arguments text: Input text (string). filters: Sequence of characters to filter out. lower: Whether to convert the input to lowercase. split: Sentence split marker (string). # Returns A list of integer word indices. """ if lower: text = text.lower() text = text.translate(maketrans(filters, split * len(filters))) seq = text.split(split) return [i for i in seq if i] def one_hot(text, n, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=' '): seq = text_to_word_sequence(text, filters=filters, lower=lower, split=split) return [(abs(hash(w)) % (n - 1) + 1) for w in seq] class Tokenizer(object): """Text tokenization utility class. This class allows to vectorize a text corpus, by turning each text into either a sequence of integers (each integer being the index of a token in a dictionary) or into a vector where the coefficient for each token could be binary, based on word count, based on tf-idf... # Arguments nb_words: the maximum number of words to keep, based on word frequency. Only the most common `nb_words` words will be kept. filters: a string where each element is a character that will be filtered from the texts. The default is all punctuation, plus tabs and line breaks, minus the `'` character. lower: boolean. Whether to convert the texts to lowercase. split: character or string to use for token splitting. char_level: if True, every character will be treated as a word. By default, all punctuation is removed, turning the texts into space-separated sequences of words (words maybe include the `'` character). These sequences are then split into lists of tokens. They will then be indexed or vectorized. `0` is a reserved index that won't be assigned to any word. """ def __init__(self, nb_words=None, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=' ', char_level=False): self.word_counts = {} self.word_docs = {} self.filters = filters self.split = split self.lower = lower self.nb_words = nb_words self.document_count = 0 self.char_level = char_level def fit_on_texts(self, texts): """Updates internal vocabulary based on a list of texts. Required before using `texts_to_sequences` or `texts_to_matrix`. # Arguments texts: can be a list of strings, or a generator of strings (for memory-efficiency) """ self.document_count = 0 for text in texts: self.document_count += 1 seq = text if self.char_level else text_to_word_sequence(text, self.filters, self.lower, self.split) for w in seq: if w in self.word_counts: self.word_counts[w] += 1 else: self.word_counts[w] = 1 for w in set(seq): if w in self.word_docs: self.word_docs[w] += 1 else: self.word_docs[w] = 1 wcounts = list(self.word_counts.items()) wcounts.sort(key=lambda x: x[1], reverse=True) sorted_voc = [wc[0] for wc in wcounts] # note that index 0 is reserved, never assigned to an existing word self.word_index = dict(list(zip(sorted_voc, list(range(1, len(sorted_voc) + 1))))) self.index_docs = {} for w, c in list(self.word_docs.items()): self.index_docs[self.word_index[w]] = c def fit_on_sequences(self, sequences): """Updates internal vocabulary based on a list of sequences. Required before using `sequences_to_matrix` (if `fit_on_texts` was never called). # Arguments sequences: A list of sequence. A "sequence" is a list of integer word indices. """ self.document_count = len(sequences) self.index_docs = {} for seq in sequences: seq = set(seq) for i in seq: if i not in self.index_docs: self.index_docs[i] = 1 else: self.index_docs[i] += 1 def texts_to_sequences(self, texts): """Transforms each text in texts in a sequence of integers. Only top "nb_words" most frequent words will be taken into account. Only words known by the tokenizer will be taken into account. # Arguments texts: A list of texts (strings). # Returns A list of sequences. """ res = [] for vect in self.texts_to_sequences_generator(texts): res.append(vect) return res def texts_to_sequences_generator(self, texts): """Transforms each text in texts in a sequence of integers. Only top "nb_words" most frequent words will be taken into account. Only words known by the tokenizer will be taken into account. # Arguments texts: A list of texts (strings). # Yields Yields individual sequences. """ nb_words = self.nb_words for text in texts: seq = text if self.char_level else text_to_word_sequence(text, self.filters, self.lower, self.split) vect = [] for w in seq: i = self.word_index.get(w) if i is not None: if nb_words and i >= nb_words: continue else: vect.append(i) yield vect def texts_to_matrix(self, texts, mode='binary'): """Convert a list of texts to a Numpy matrix. # Arguments texts: list of strings. mode: one of "binary", "count", "tfidf", "freq". # Returns A Numpy matrix. """ sequences = self.texts_to_sequences(texts) return self.sequences_to_matrix(sequences, mode=mode) def sequences_to_matrix(self, sequences, mode='binary'): """Converts a list of sequences into a Numpy matrix. # Arguments sequences: list of sequences (a sequence is a list of integer word indices). mode: one of "binary", "count", "tfidf", "freq" # Returns A Numpy matrix. # Raises ValueError: In case of invalid `mode` argument, or if the Tokenizer requires to be fit to sample data. """ if not self.nb_words: if self.word_index: nb_words = len(self.word_index) + 1 else: raise ValueError('Specify a dimension (nb_words argument), ' 'or fit on some text data first.') else: nb_words = self.nb_words if mode == 'tfidf' and not self.document_count: raise ValueError('Fit the Tokenizer on some data ' 'before using tfidf mode.') x = np.zeros((len(sequences), nb_words)) for i, seq in enumerate(sequences): if not seq: continue counts = {} for j in seq: if j >= nb_words: continue if j not in counts: counts[j] = 1. else: counts[j] += 1 for j, c in list(counts.items()): if mode == 'count': x[i][j] = c elif mode == 'freq': x[i][j] = c / len(seq) elif mode == 'binary': x[i][j] = 1 elif mode == 'tfidf': # Use weighting scheme 2 in # https://en.wikipedia.org/wiki/Tf%E2%80%93idf tf = 1 + np.log(c) idf = np.log(1 + self.document_count / (1 + self.index_docs.get(j, 0))) x[i][j] = tf * idf else: raise ValueError('Unknown vectorization mode:', mode) return x
keras-team_keras
2017-01-28
ab3b93e8dd103f1d9729305825791a084c7c8493
tests/keras/test_multiprocessing.py
96
from __future__ import print_function import pytest import numpy as np from keras.models import Sequential from keras.layers.core import Dense from keras.utils.test_utils import keras_test @keras_test def test_multiprocessing_training(): reached_end = False arr_data = np.random.randint(0, 256, (500, 2)) arr_labels = np.random.randint(0, 2, 500) def myGenerator(): batch_size = 32 n_samples = 500 while True: batch_index = np.random.randint(0, n_samples - batch_size) start = batch_index end = start + batch_size X = arr_data[start: end] y = arr_labels[start: end] yield X, y # Build a NN model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') model.fit_generator(myGenerator(), samples_per_epoch=320, nb_epoch=1, verbose=1, max_q_size=10, nb_worker=4, pickle_safe=True) model.fit_generator(myGenerator(), samples_per_epoch=320, nb_epoch=1, verbose=1, max_q_size=10, pickle_safe=False) reached_end = True assert reached_end @keras_test def test_multiprocessing_training_fromfile(): reached_end = False arr_data = np.random.randint(0, 256, (500, 2)) arr_labels = np.random.randint(0, 2, 500) np.savez("data.npz", **{"data": arr_data, "labels": arr_labels}) def myGenerator(): batch_size = 32 n_samples = 500 arr = np.load("data.npz") while True: batch_index = np.random.randint(0, n_samples - batch_size) start = batch_index end = start + batch_size X = arr["data"][start: end] y = arr["labels"][start: end] yield X, y # Build a NN model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') model.fit_generator(myGenerator(), samples_per_epoch=320, nb_epoch=1, verbose=1, max_q_size=10, nb_worker=2, pickle_safe=True) model.fit_generator(myGenerator(), samples_per_epoch=320, nb_epoch=1, verbose=1, max_q_size=10, pickle_safe=False) reached_end = True assert reached_end @keras_test def test_multiprocessing_predicting(): reached_end = False arr_data = np.random.randint(0, 256, (500, 2)) def myGenerator(): batch_size = 32 n_samples = 500 while True: batch_index = np.random.randint(0, n_samples - batch_size) start = batch_index end = start + batch_size X = arr_data[start: end] yield X # Build a NN model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') model.predict_generator(myGenerator(), val_samples=320, max_q_size=10, nb_worker=2, pickle_safe=True) model.predict_generator(myGenerator(), val_samples=320, max_q_size=10, pickle_safe=False) reached_end = True assert reached_end @keras_test def test_multiprocessing_evaluating(): reached_end = False arr_data = np.random.randint(0, 256, (500, 2)) arr_labels = np.random.randint(0, 2, 500) def myGenerator(): batch_size = 32 n_samples = 500 while True: batch_index = np.random.randint(0, n_samples - batch_size) start = batch_index end = start + batch_size X = arr_data[start: end] y = arr_labels[start: end] yield X, y # Build a NN model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') model.evaluate_generator(myGenerator(), val_samples=320, max_q_size=10, nb_worker=2, pickle_safe=True) model.evaluate_generator(myGenerator(), val_samples=320, max_q_size=10, pickle_safe=False) reached_end = True assert reached_end @keras_test def test_multiprocessing_fit_error(): batch_size = 32 good_batches = 5 def myGenerator(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (500, 2)), np.random.randint(batch_size, 2, 500)) raise RuntimeError model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') samples = batch_size * (good_batches + 1) with pytest.raises(Exception): model.fit_generator( myGenerator(), samples, 1, nb_worker=4, pickle_safe=True, ) with pytest.raises(Exception): model.fit_generator( myGenerator(), samples, 1, pickle_safe=False, ) @keras_test def test_multiprocessing_evaluate_error(): batch_size = 32 good_batches = 5 def myGenerator(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (500, 2)), np.random.randint(batch_size, 2, 500)) raise RuntimeError model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') samples = batch_size * (good_batches + 1) with pytest.raises(Exception): model.evaluate_generator( myGenerator(), samples, 1, nb_worker=4, pickle_safe=True, ) with pytest.raises(Exception): model.evaluate_generator( myGenerator(), samples, 1, pickle_safe=False, ) @keras_test def test_multiprocessing_predict_error(): batch_size = 32 good_batches = 5 def myGenerator(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (500, 2)), np.random.randint(batch_size, 2, 500)) raise RuntimeError model = Sequential() model.add(Dense(1, input_shape=(2, ))) model.compile(loss='mse', optimizer='adadelta') samples = batch_size * (good_batches + 1) with pytest.raises(Exception): model.predict_generator( myGenerator(), samples, 1, nb_worker=4, pickle_safe=True, ) with pytest.raises(Exception): model.predict_generator( myGenerator(), samples, 1, pickle_safe=False, ) if __name__ == '__main__': pytest.main([__file__])
keras-team_keras
2017-01-28
ab3b93e8dd103f1d9729305825791a084c7c8493
keras/datasets/cifar100.py
16
from __future__ import absolute_import from .cifar import load_batch from ..utils.data_utils import get_file from .. import backend as K import numpy as np import os def load_data(label_mode='fine'): """Loads CIFAR100 dataset. # Arguments label_mode: one of "fine", "coarse". # Returns Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. # Raises ValueError: in case of invalid `label_mode`. """ if label_mode not in ['fine', 'coarse']: raise ValueError('label_mode must be one of "fine" "coarse".') dirname = 'cifar-100-python' origin = 'http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz' path = get_file(dirname, origin=origin, untar=True) fpath = os.path.join(path, 'train') x_train, y_train = load_batch(fpath, label_key=label_mode + '_labels') fpath = os.path.join(path, 'test') x_test, y_test = load_batch(fpath, label_key=label_mode + '_labels') y_train = np.reshape(y_train, (len(y_train), 1)) y_test = np.reshape(y_test, (len(y_test), 1)) if K.image_dim_ordering() == 'tf': x_train = x_train.transpose(0, 2, 3, 1) x_test = x_test.transpose(0, 2, 3, 1) return (x_train, y_train), (x_test, y_test)
keras-team_keras
2017-01-28
ab3b93e8dd103f1d9729305825791a084c7c8493
keras/datasets/cifar.py
13
# -*- coding: utf-8 -*- from __future__ import absolute_import import sys from six.moves import cPickle def load_batch(fpath, label_key='labels'): """Internal utility for parsing CIFAR data. # Arguments fpath: path the file to parse. label_key: key for label data in the retrieve dictionary. # Returns A tuple `(data, labels)`. """ f = open(fpath, 'rb') if sys.version_info < (3,): d = cPickle.load(f) else: d = cPickle.load(f, encoding='bytes') # decode utf8 d_decoded = {} for k, v in d.items(): d_decoded[k.decode('utf8')] = v d = d_decoded f.close() data = d['data'] labels = d[label_key] data = data.reshape(data.shape[0], 3, 32, 32) return data, labels
keras-team_keras
2017-01-28
ab3b93e8dd103f1d9729305825791a084c7c8493
tests/keras/utils/test_generic_utils.py
30
import pytest import keras from keras import backend as K from keras.utils.generic_utils import custom_object_scope, get_custom_objects, get_from_module def test_custom_object_scope_adds_objects(): get_custom_objects().clear() assert (len(get_custom_objects()) == 0) with custom_object_scope({"Test1": object, "Test2": object}, {"Test3": object}): assert (len(get_custom_objects()) == 3) assert (len(get_custom_objects()) == 0) class CustomObject(object): def __init__(self): pass def test_get_from_module_uses_custom_object(): get_custom_objects().clear() assert (get_from_module("CustomObject", globals(), "test_generic_utils") == CustomObject) with pytest.raises(ValueError): get_from_module("TestObject", globals(), "test_generic_utils") with custom_object_scope({"TestObject": CustomObject}): assert (get_from_module("TestObject", globals(), "test_generic_utils") == CustomObject) if __name__ == '__main__': pytest.main([__file__])
keras-team_keras
2017-01-28
ab3b93e8dd103f1d9729305825791a084c7c8493
fuzz/server.c
345
/* * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL licenses, (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.openssl.org/source/license.html * or in the file LICENSE in the source distribution. */ /* Shamelessly copied from BoringSSL and converted to C. */ /* Test first part of SSL server handshake. */ #include <openssl/rand.h> #include <openssl/ssl.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/ec.h> #include <openssl/dh.h> #include <openssl/err.h> #include "fuzzer.h" static const uint8_t kCertificateDER[] = { 0x30, 0x82, 0x02, 0xff, 0x30, 0x82, 0x01, 0xe7, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, 0xb1, 0x84, 0xee, 0x34, 0x99, 0x98, 0x76, 0xfb, 0x6f, 0xb2, 0x15, 0xc8, 0x47, 0x79, 0x05, 0x9b, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x12, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x07, 0x41, 0x63, 0x6d, 0x65, 0x20, 0x43, 0x6f, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x35, 0x31, 0x31, 0x30, 0x37, 0x30, 0x30, 0x32, 0x34, 0x35, 0x36, 0x5a, 0x17, 0x0d, 0x31, 0x36, 0x31, 0x31, 0x30, 0x36, 0x30, 0x30, 0x32, 0x34, 0x35, 0x36, 0x5a, 0x30, 0x12, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x07, 0x41, 0x63, 0x6d, 0x65, 0x20, 0x43, 0x6f, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xce, 0x47, 0xcb, 0x11, 0xbb, 0xd2, 0x9d, 0x8e, 0x9e, 0xd2, 0x1e, 0x14, 0xaf, 0xc7, 0xea, 0xb6, 0xc9, 0x38, 0x2a, 0x6f, 0xb3, 0x7e, 0xfb, 0xbc, 0xfc, 0x59, 0x42, 0xb9, 0x56, 0xf0, 0x4c, 0x3f, 0xf7, 0x31, 0x84, 0xbe, 0xac, 0x03, 0x9e, 0x71, 0x91, 0x85, 0xd8, 0x32, 0xbd, 0x00, 0xea, 0xac, 0x65, 0xf6, 0x03, 0xc8, 0x0f, 0x8b, 0xfd, 0x6e, 0x58, 0x88, 0x04, 0x41, 0x92, 0x74, 0xa6, 0x57, 0x2e, 0x8e, 0x88, 0xd5, 0x3d, 0xda, 0x14, 0x3e, 0x63, 0x88, 0x22, 0xe3, 0x53, 0xe9, 0xba, 0x39, 0x09, 0xac, 0xfb, 0xd0, 0x4c, 0xf2, 0x3c, 0x20, 0xd6, 0x97, 0xe6, 0xed, 0xf1, 0x62, 0x1e, 0xe5, 0xc9, 0x48, 0xa0, 0xca, 0x2e, 0x3c, 0x14, 0x5a, 0x82, 0xd4, 0xed, 0xb1, 0xe3, 0x43, 0xc1, 0x2a, 0x59, 0xa5, 0xb9, 0xc8, 0x48, 0xa7, 0x39, 0x23, 0x74, 0xa7, 0x37, 0xb0, 0x6f, 0xc3, 0x64, 0x99, 0x6c, 0xa2, 0x82, 0xc8, 0xf6, 0xdb, 0x86, 0x40, 0xce, 0xd1, 0x85, 0x9f, 0xce, 0x69, 0xf4, 0x15, 0x2a, 0x23, 0xca, 0xea, 0xb7, 0x7b, 0xdf, 0xfb, 0x43, 0x5f, 0xff, 0x7a, 0x49, 0x49, 0x0e, 0xe7, 0x02, 0x51, 0x45, 0x13, 0xe8, 0x90, 0x64, 0x21, 0x0c, 0x26, 0x2b, 0x5d, 0xfc, 0xe4, 0xb5, 0x86, 0x89, 0x43, 0x22, 0x4c, 0xf3, 0x3b, 0xf3, 0x09, 0xc4, 0xa4, 0x10, 0x80, 0xf2, 0x46, 0xe2, 0x46, 0x8f, 0x76, 0x50, 0xbf, 0xaf, 0x2b, 0x90, 0x1b, 0x78, 0xc7, 0xcf, 0xc1, 0x77, 0xd0, 0xfb, 0xa9, 0xfb, 0xc9, 0x66, 0x5a, 0xc5, 0x9b, 0x31, 0x41, 0x67, 0x01, 0xbe, 0x33, 0x10, 0xba, 0x05, 0x58, 0xed, 0x76, 0x53, 0xde, 0x5d, 0xc1, 0xe8, 0xbb, 0x9f, 0xf1, 0xcd, 0xfb, 0xdf, 0x64, 0x7f, 0xd7, 0x18, 0xab, 0x0f, 0x94, 0x28, 0x95, 0x4a, 0xcc, 0x6a, 0xa9, 0x50, 0xc7, 0x05, 0x47, 0x10, 0x41, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x05, 0xa0, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x0c, 0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x19, 0x06, 0x03, 0x55, 0x1d, 0x11, 0x04, 0x12, 0x30, 0x10, 0x82, 0x0e, 0x66, 0x75, 0x7a, 0x7a, 0x2e, 0x62, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x73, 0x73, 0x6c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x92, 0xde, 0xef, 0x96, 0x06, 0x7b, 0xff, 0x71, 0x7d, 0x4e, 0xa0, 0x7d, 0xae, 0xb8, 0x22, 0xb4, 0x2c, 0xf7, 0x96, 0x9c, 0x37, 0x1d, 0x8f, 0xe7, 0xd9, 0x47, 0xff, 0x3f, 0xe9, 0x35, 0x95, 0x0e, 0xdd, 0xdc, 0x7f, 0xc8, 0x8a, 0x1e, 0x36, 0x1d, 0x38, 0x47, 0xfc, 0x76, 0xd2, 0x1f, 0x98, 0xa1, 0x36, 0xac, 0xc8, 0x70, 0x38, 0x0a, 0x3d, 0x51, 0x8d, 0x0f, 0x03, 0x1b, 0xef, 0x62, 0xa1, 0xcb, 0x2b, 0x4a, 0x8c, 0x12, 0x2b, 0x54, 0x50, 0x9a, 0x6b, 0xfe, 0xaf, 0xd9, 0xf6, 0xbf, 0x58, 0x11, 0x58, 0x5e, 0xe5, 0x86, 0x1e, 0x3b, 0x6b, 0x30, 0x7e, 0x72, 0x89, 0xe8, 0x6b, 0x7b, 0xb7, 0xaf, 0xef, 0x8b, 0xa9, 0x3e, 0xb0, 0xcd, 0x0b, 0xef, 0xb0, 0x0c, 0x96, 0x2b, 0xc5, 0x3b, 0xd5, 0xf1, 0xc2, 0xae, 0x3a, 0x60, 0xd9, 0x0f, 0x75, 0x37, 0x55, 0x4d, 0x62, 0xd2, 0xed, 0x96, 0xac, 0x30, 0x6b, 0xda, 0xa1, 0x48, 0x17, 0x96, 0x23, 0x85, 0x9a, 0x57, 0x77, 0xe9, 0x22, 0xa2, 0x37, 0x03, 0xba, 0x49, 0x77, 0x40, 0x3b, 0x76, 0x4b, 0xda, 0xc1, 0x04, 0x57, 0x55, 0x34, 0x22, 0x83, 0x45, 0x29, 0xab, 0x2e, 0x11, 0xff, 0x0d, 0xab, 0x55, 0xb1, 0xa7, 0x58, 0x59, 0x05, 0x25, 0xf9, 0x1e, 0x3d, 0xb7, 0xac, 0x04, 0x39, 0x2c, 0xf9, 0xaf, 0xb8, 0x68, 0xfb, 0x8e, 0x35, 0x71, 0x32, 0xff, 0x70, 0xe9, 0x46, 0x6d, 0x5c, 0x06, 0x90, 0x88, 0x23, 0x48, 0x0c, 0x50, 0xeb, 0x0a, 0xa9, 0xae, 0xe8, 0xfc, 0xbe, 0xa5, 0x76, 0x94, 0xd7, 0x64, 0x22, 0x38, 0x98, 0x17, 0xa4, 0x3a, 0xa7, 0x59, 0x9f, 0x1d, 0x3b, 0x75, 0x90, 0x1a, 0x81, 0xef, 0x19, 0xfb, 0x2b, 0xb7, 0xa7, 0x64, 0x61, 0x22, 0xa4, 0x6f, 0x7b, 0xfa, 0x58, 0xbb, 0x8c, 0x4e, 0x77, 0x67, 0xd0, 0x5d, 0x58, 0x76, 0x8a, 0xbb, }; static const uint8_t kRSAPrivateKeyDER[] = { 0x30, 0x82, 0x04, 0xa5, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xce, 0x47, 0xcb, 0x11, 0xbb, 0xd2, 0x9d, 0x8e, 0x9e, 0xd2, 0x1e, 0x14, 0xaf, 0xc7, 0xea, 0xb6, 0xc9, 0x38, 0x2a, 0x6f, 0xb3, 0x7e, 0xfb, 0xbc, 0xfc, 0x59, 0x42, 0xb9, 0x56, 0xf0, 0x4c, 0x3f, 0xf7, 0x31, 0x84, 0xbe, 0xac, 0x03, 0x9e, 0x71, 0x91, 0x85, 0xd8, 0x32, 0xbd, 0x00, 0xea, 0xac, 0x65, 0xf6, 0x03, 0xc8, 0x0f, 0x8b, 0xfd, 0x6e, 0x58, 0x88, 0x04, 0x41, 0x92, 0x74, 0xa6, 0x57, 0x2e, 0x8e, 0x88, 0xd5, 0x3d, 0xda, 0x14, 0x3e, 0x63, 0x88, 0x22, 0xe3, 0x53, 0xe9, 0xba, 0x39, 0x09, 0xac, 0xfb, 0xd0, 0x4c, 0xf2, 0x3c, 0x20, 0xd6, 0x97, 0xe6, 0xed, 0xf1, 0x62, 0x1e, 0xe5, 0xc9, 0x48, 0xa0, 0xca, 0x2e, 0x3c, 0x14, 0x5a, 0x82, 0xd4, 0xed, 0xb1, 0xe3, 0x43, 0xc1, 0x2a, 0x59, 0xa5, 0xb9, 0xc8, 0x48, 0xa7, 0x39, 0x23, 0x74, 0xa7, 0x37, 0xb0, 0x6f, 0xc3, 0x64, 0x99, 0x6c, 0xa2, 0x82, 0xc8, 0xf6, 0xdb, 0x86, 0x40, 0xce, 0xd1, 0x85, 0x9f, 0xce, 0x69, 0xf4, 0x15, 0x2a, 0x23, 0xca, 0xea, 0xb7, 0x7b, 0xdf, 0xfb, 0x43, 0x5f, 0xff, 0x7a, 0x49, 0x49, 0x0e, 0xe7, 0x02, 0x51, 0x45, 0x13, 0xe8, 0x90, 0x64, 0x21, 0x0c, 0x26, 0x2b, 0x5d, 0xfc, 0xe4, 0xb5, 0x86, 0x89, 0x43, 0x22, 0x4c, 0xf3, 0x3b, 0xf3, 0x09, 0xc4, 0xa4, 0x10, 0x80, 0xf2, 0x46, 0xe2, 0x46, 0x8f, 0x76, 0x50, 0xbf, 0xaf, 0x2b, 0x90, 0x1b, 0x78, 0xc7, 0xcf, 0xc1, 0x77, 0xd0, 0xfb, 0xa9, 0xfb, 0xc9, 0x66, 0x5a, 0xc5, 0x9b, 0x31, 0x41, 0x67, 0x01, 0xbe, 0x33, 0x10, 0xba, 0x05, 0x58, 0xed, 0x76, 0x53, 0xde, 0x5d, 0xc1, 0xe8, 0xbb, 0x9f, 0xf1, 0xcd, 0xfb, 0xdf, 0x64, 0x7f, 0xd7, 0x18, 0xab, 0x0f, 0x94, 0x28, 0x95, 0x4a, 0xcc, 0x6a, 0xa9, 0x50, 0xc7, 0x05, 0x47, 0x10, 0x41, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, 0x01, 0x00, 0xa8, 0x47, 0xb9, 0x4a, 0x06, 0x47, 0x93, 0x71, 0x3d, 0xef, 0x7b, 0xca, 0xb4, 0x7c, 0x0a, 0xe6, 0x82, 0xd0, 0xe7, 0x0d, 0xa9, 0x08, 0xf6, 0xa4, 0xfd, 0xd8, 0x73, 0xae, 0x6f, 0x56, 0x29, 0x5e, 0x25, 0x72, 0xa8, 0x30, 0x44, 0x73, 0xcf, 0x56, 0x26, 0xb9, 0x61, 0xde, 0x42, 0x81, 0xf4, 0xf0, 0x1f, 0x5d, 0xcb, 0x47, 0xf2, 0x26, 0xe9, 0xe0, 0x93, 0x28, 0xa3, 0x10, 0x3b, 0x42, 0x1e, 0x51, 0x11, 0x12, 0x06, 0x5e, 0xaf, 0xce, 0xb0, 0xa5, 0x14, 0xdd, 0x82, 0x58, 0xa1, 0xa4, 0x12, 0xdf, 0x65, 0x1d, 0x51, 0x70, 0x64, 0xd5, 0x58, 0x68, 0x11, 0xa8, 0x6a, 0x23, 0xc2, 0xbf, 0xa1, 0x25, 0x24, 0x47, 0xb3, 0xa4, 0x3c, 0x83, 0x96, 0xb7, 0x1f, 0xf4, 0x44, 0xd4, 0xd1, 0xe9, 0xfc, 0x33, 0x68, 0x5e, 0xe2, 0x68, 0x99, 0x9c, 0x91, 0xe8, 0x72, 0xc9, 0xd7, 0x8c, 0x80, 0x20, 0x8e, 0x77, 0x83, 0x4d, 0xe4, 0xab, 0xf9, 0x74, 0xa1, 0xdf, 0xd3, 0xc0, 0x0d, 0x5b, 0x05, 0x51, 0xc2, 0x6f, 0xb2, 0x91, 0x02, 0xec, 0xc0, 0x02, 0x1a, 0x5c, 0x91, 0x05, 0xf1, 0xe3, 0xfa, 0x65, 0xc2, 0xad, 0x24, 0xe6, 0xe5, 0x3c, 0xb6, 0x16, 0xf1, 0xa1, 0x67, 0x1a, 0x9d, 0x37, 0x56, 0xbf, 0x01, 0xd7, 0x3b, 0x35, 0x30, 0x57, 0x73, 0xf4, 0xf0, 0x5e, 0xa7, 0xe8, 0x0a, 0xc1, 0x94, 0x17, 0xcf, 0x0a, 0xbd, 0xf5, 0x31, 0xa7, 0x2d, 0xf7, 0xf5, 0xd9, 0x8c, 0xc2, 0x01, 0xbd, 0xda, 0x16, 0x8e, 0xb9, 0x30, 0x40, 0xa6, 0x6e, 0xbd, 0xcd, 0x4d, 0x84, 0x67, 0x4e, 0x0b, 0xce, 0xd5, 0xef, 0xf8, 0x08, 0x63, 0x02, 0xc6, 0xc7, 0xf7, 0x67, 0x92, 0xe2, 0x23, 0x9d, 0x27, 0x22, 0x1d, 0xc6, 0x67, 0x5e, 0x66, 0xbf, 0x03, 0xb8, 0xa9, 0x67, 0xd4, 0x39, 0xd8, 0x75, 0xfa, 0xe8, 0xed, 0x56, 0xb8, 0x81, 0x02, 0x81, 0x81, 0x00, 0xf7, 0x46, 0x68, 0xc6, 0x13, 0xf8, 0xba, 0x0f, 0x83, 0xdb, 0x05, 0xa8, 0x25, 0x00, 0x70, 0x9c, 0x9e, 0x8b, 0x12, 0x34, 0x0d, 0x96, 0xcf, 0x0d, 0x98, 0x9b, 0x8d, 0x9c, 0x96, 0x78, 0xd1, 0x3c, 0x01, 0x8c, 0xb9, 0x35, 0x5c, 0x20, 0x42, 0xb4, 0x38, 0xe3, 0xd6, 0x54, 0xe7, 0x55, 0xd6, 0x26, 0x8a, 0x0c, 0xf6, 0x1f, 0xe0, 0x04, 0xc1, 0x22, 0x42, 0x19, 0x61, 0xc4, 0x94, 0x7c, 0x07, 0x2e, 0x80, 0x52, 0xfe, 0x8d, 0xe6, 0x92, 0x3a, 0x91, 0xfe, 0x72, 0x99, 0xe1, 0x2a, 0x73, 0x76, 0xb1, 0x24, 0x20, 0x67, 0xde, 0x28, 0xcb, 0x0e, 0xe6, 0x52, 0xb5, 0xfa, 0xfb, 0x8b, 0x1e, 0x6a, 0x1d, 0x09, 0x26, 0xb9, 0xa7, 0x61, 0xba, 0xf8, 0x79, 0xd2, 0x66, 0x57, 0x28, 0xd7, 0x31, 0xb5, 0x0b, 0x27, 0x19, 0x1e, 0x6f, 0x46, 0xfc, 0x54, 0x95, 0xeb, 0x78, 0x01, 0xb6, 0xd9, 0x79, 0x5a, 0x4d, 0x02, 0x81, 0x81, 0x00, 0xd5, 0x8f, 0x16, 0x53, 0x2f, 0x57, 0x93, 0xbf, 0x09, 0x75, 0xbf, 0x63, 0x40, 0x3d, 0x27, 0xfd, 0x23, 0x21, 0xde, 0x9b, 0xe9, 0x73, 0x3f, 0x49, 0x02, 0xd2, 0x38, 0x96, 0xcf, 0xc3, 0xba, 0x92, 0x07, 0x87, 0x52, 0xa9, 0x35, 0xe3, 0x0c, 0xe4, 0x2f, 0x05, 0x7b, 0x37, 0xa5, 0x40, 0x9c, 0x3b, 0x94, 0xf7, 0xad, 0xa0, 0xee, 0x3a, 0xa8, 0xfb, 0x1f, 0x11, 0x1f, 0xd8, 0x9a, 0x80, 0x42, 0x3d, 0x7f, 0xa4, 0xb8, 0x9a, 0xaa, 0xea, 0x72, 0xc1, 0xe3, 0xed, 0x06, 0x60, 0x92, 0x37, 0xf9, 0xba, 0xfb, 0x9e, 0xed, 0x05, 0xa6, 0xd4, 0x72, 0x68, 0x4f, 0x63, 0xfe, 0xd6, 0x10, 0x0d, 0x4f, 0x0a, 0x93, 0xc6, 0xb9, 0xd7, 0xaf, 0xfd, 0xd9, 0x57, 0x7d, 0xcb, 0x75, 0xe8, 0x93, 0x2b, 0xae, 0x4f, 0xea, 0xd7, 0x30, 0x0b, 0x58, 0x44, 0x82, 0x0f, 0x84, 0x5d, 0x62, 0x11, 0x78, 0xea, 0x5f, 0xc5, 0x02, 0x81, 0x81, 0x00, 0x82, 0x0c, 0xc1, 0xe6, 0x0b, 0x72, 0xf1, 0x48, 0x5f, 0xac, 0xbd, 0x98, 0xe5, 0x7d, 0x09, 0xbd, 0x15, 0x95, 0x47, 0x09, 0xa1, 0x6c, 0x03, 0x91, 0xbf, 0x05, 0x70, 0xc1, 0x3e, 0x52, 0x64, 0x99, 0x0e, 0xa7, 0x98, 0x70, 0xfb, 0xf6, 0xeb, 0x9e, 0x25, 0x9d, 0x8e, 0x88, 0x30, 0xf2, 0xf0, 0x22, 0x6c, 0xd0, 0xcc, 0x51, 0x8f, 0x5c, 0x70, 0xc7, 0x37, 0xc4, 0x69, 0xab, 0x1d, 0xfc, 0xed, 0x3a, 0x03, 0xbb, 0xa2, 0xad, 0xb6, 0xea, 0x89, 0x6b, 0x67, 0x4b, 0x96, 0xaa, 0xd9, 0xcc, 0xc8, 0x4b, 0xfa, 0x18, 0x21, 0x08, 0xb2, 0xa3, 0xb9, 0x3e, 0x61, 0x99, 0xdc, 0x5a, 0x97, 0x9c, 0x73, 0x6a, 0xb9, 0xf9, 0x68, 0x03, 0x24, 0x5f, 0x55, 0x77, 0x9c, 0xb4, 0xbe, 0x7a, 0x78, 0x53, 0x68, 0x48, 0x69, 0x53, 0xc8, 0xb1, 0xf5, 0xbf, 0x98, 0x2d, 0x11, 0x1e, 0x98, 0xa8, 0x36, 0x50, 0xa0, 0xb1, 0x02, 0x81, 0x81, 0x00, 0x90, 0x88, 0x30, 0x71, 0xc7, 0xfe, 0x9b, 0x6d, 0x95, 0x37, 0x6d, 0x79, 0xfc, 0x85, 0xe7, 0x44, 0x78, 0xbc, 0x79, 0x6e, 0x47, 0x86, 0xc9, 0xf3, 0xdd, 0xc6, 0xec, 0xa9, 0x94, 0x9f, 0x40, 0xeb, 0x87, 0xd0, 0xdb, 0xee, 0xcd, 0x1b, 0x87, 0x23, 0xff, 0x76, 0xd4, 0x37, 0x8a, 0xcd, 0xb9, 0x6e, 0xd1, 0x98, 0xf6, 0x97, 0x8d, 0xe3, 0x81, 0x6d, 0xc3, 0x4e, 0xd1, 0xa0, 0xc4, 0x9f, 0xbd, 0x34, 0xe5, 0xe8, 0x53, 0x4f, 0xca, 0x10, 0xb5, 0xed, 0xe7, 0x16, 0x09, 0x54, 0xde, 0x60, 0xa7, 0xd1, 0x16, 0x6e, 0x2e, 0xb7, 0xbe, 0x7a, 0xd5, 0x9b, 0x26, 0xef, 0xe4, 0x0e, 0x77, 0xfa, 0xa9, 0xdd, 0xdc, 0xb9, 0x88, 0x19, 0x23, 0x70, 0xc7, 0xe1, 0x60, 0xaf, 0x8c, 0x73, 0x04, 0xf7, 0x71, 0x17, 0x81, 0x36, 0x75, 0xbb, 0x97, 0xd7, 0x75, 0xb6, 0x8e, 0xbc, 0xac, 0x9c, 0x6a, 0x9b, 0x24, 0x89, 0x02, 0x81, 0x80, 0x5a, 0x2b, 0xc7, 0x6b, 0x8c, 0x65, 0xdb, 0x04, 0x73, 0xab, 0x25, 0xe1, 0x5b, 0xbc, 0x3c, 0xcf, 0x5a, 0x3c, 0x04, 0xae, 0x97, 0x2e, 0xfd, 0xa4, 0x97, 0x1f, 0x05, 0x17, 0x27, 0xac, 0x7c, 0x30, 0x85, 0xb4, 0x82, 0x3f, 0x5b, 0xb7, 0x94, 0x3b, 0x7f, 0x6c, 0x0c, 0xc7, 0x16, 0xc6, 0xa0, 0xbd, 0x80, 0xb0, 0x81, 0xde, 0xa0, 0x23, 0xa6, 0xf6, 0x75, 0x33, 0x51, 0x35, 0xa2, 0x75, 0x55, 0x70, 0x4d, 0x42, 0xbb, 0xcf, 0x54, 0xe4, 0xdb, 0x2d, 0x88, 0xa0, 0x7a, 0xf2, 0x17, 0xa7, 0xdd, 0x13, 0x44, 0x9f, 0x5f, 0x6b, 0x2c, 0x42, 0x42, 0x8b, 0x13, 0x4d, 0xf9, 0x5b, 0xf8, 0x33, 0x42, 0xd9, 0x9e, 0x50, 0x1c, 0x7c, 0xbc, 0xfa, 0x62, 0x85, 0x0b, 0xcf, 0x99, 0xda, 0x9e, 0x04, 0x90, 0xb2, 0xc6, 0xb2, 0x0a, 0x2a, 0x7c, 0x6d, 0x6a, 0x40, 0xfc, 0xf5, 0x50, 0x98, 0x46, 0x89, 0x82, 0x40, }; #ifndef OPENSSL_NO_EC /* * -----BEGIN EC PRIVATE KEY----- * MHcCAQEEIJLyl7hJjpQL/RhP1x2zS79xdiPJQB683gWeqcqHPeZkoAoGCCqGSM49 * AwEHoUQDQgAEdsjygVYjjaKBF4CNECVllNf017p5/MxNSWDoTHy9I2GeDwEDDazI * D/xy8JiYjtPKVE/Zqwbmivp2UwtH28a7NQ== * -----END EC PRIVATE KEY----- */ static const char ECDSAPrivateKeyPEM[] = { 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x45, 0x43, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b, 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x48, 0x63, 0x43, 0x41, 0x51, 0x45, 0x45, 0x49, 0x4a, 0x4c, 0x79, 0x6c, 0x37, 0x68, 0x4a, 0x6a, 0x70, 0x51, 0x4c, 0x2f, 0x52, 0x68, 0x50, 0x31, 0x78, 0x32, 0x7a, 0x53, 0x37, 0x39, 0x78, 0x64, 0x69, 0x50, 0x4a, 0x51, 0x42, 0x36, 0x38, 0x33, 0x67, 0x57, 0x65, 0x71, 0x63, 0x71, 0x48, 0x50, 0x65, 0x5a, 0x6b, 0x6f, 0x41, 0x6f, 0x47, 0x43, 0x43, 0x71, 0x47, 0x53, 0x4d, 0x34, 0x39, 0x0a, 0x41, 0x77, 0x45, 0x48, 0x6f, 0x55, 0x51, 0x44, 0x51, 0x67, 0x41, 0x45, 0x64, 0x73, 0x6a, 0x79, 0x67, 0x56, 0x59, 0x6a, 0x6a, 0x61, 0x4b, 0x42, 0x46, 0x34, 0x43, 0x4e, 0x45, 0x43, 0x56, 0x6c, 0x6c, 0x4e, 0x66, 0x30, 0x31, 0x37, 0x70, 0x35, 0x2f, 0x4d, 0x78, 0x4e, 0x53, 0x57, 0x44, 0x6f, 0x54, 0x48, 0x79, 0x39, 0x49, 0x32, 0x47, 0x65, 0x44, 0x77, 0x45, 0x44, 0x44, 0x61, 0x7a, 0x49, 0x0a, 0x44, 0x2f, 0x78, 0x79, 0x38, 0x4a, 0x69, 0x59, 0x6a, 0x74, 0x50, 0x4b, 0x56, 0x45, 0x2f, 0x5a, 0x71, 0x77, 0x62, 0x6d, 0x69, 0x76, 0x70, 0x32, 0x55, 0x77, 0x74, 0x48, 0x32, 0x38, 0x61, 0x37, 0x4e, 0x51, 0x3d, 0x3d, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x45, 0x43, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b, 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a }; /* * -----BEGIN CERTIFICATE----- * MIIBXzCCAQagAwIBAgIJAK6/Yvf/ain6MAoGCCqGSM49BAMCMBIxEDAOBgNVBAoM * B0FjbWUgQ28wHhcNMTYxMjI1MTEzOTI3WhcNMjYxMjI1MTEzOTI3WjASMRAwDgYD * VQQKDAdBY21lIENvMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEdsjygVYjjaKB * F4CNECVllNf017p5/MxNSWDoTHy9I2GeDwEDDazID/xy8JiYjtPKVE/Zqwbmivp2 * UwtH28a7NaNFMEMwCQYDVR0TBAIwADALBgNVHQ8EBAMCBaAwEwYDVR0lBAwwCgYI * KwYBBQUHAwEwFAYDVR0RBA0wC4IJbG9jYWxob3N0MAoGCCqGSM49BAMCA0cAMEQC * IEzr3t/jejVE9oSnBp8c3P2p+lDLVRrB8zxLyjZvirUXAiAyQPaE9MNcL8/nRpuu * 99I1enCSmWIAJ57IwuJ/n1d45Q== * -----END CERTIFICATE----- */ static const char ECDSACertPEM[] = { 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x49, 0x49, 0x42, 0x58, 0x7a, 0x43, 0x43, 0x41, 0x51, 0x61, 0x67, 0x41, 0x77, 0x49, 0x42, 0x41, 0x67, 0x49, 0x4a, 0x41, 0x4b, 0x36, 0x2f, 0x59, 0x76, 0x66, 0x2f, 0x61, 0x69, 0x6e, 0x36, 0x4d, 0x41, 0x6f, 0x47, 0x43, 0x43, 0x71, 0x47, 0x53, 0x4d, 0x34, 0x39, 0x42, 0x41, 0x4d, 0x43, 0x4d, 0x42, 0x49, 0x78, 0x45, 0x44, 0x41, 0x4f, 0x42, 0x67, 0x4e, 0x56, 0x42, 0x41, 0x6f, 0x4d, 0x0a, 0x42, 0x30, 0x46, 0x6a, 0x62, 0x57, 0x55, 0x67, 0x51, 0x32, 0x38, 0x77, 0x48, 0x68, 0x63, 0x4e, 0x4d, 0x54, 0x59, 0x78, 0x4d, 0x6a, 0x49, 0x31, 0x4d, 0x54, 0x45, 0x7a, 0x4f, 0x54, 0x49, 0x33, 0x57, 0x68, 0x63, 0x4e, 0x4d, 0x6a, 0x59, 0x78, 0x4d, 0x6a, 0x49, 0x31, 0x4d, 0x54, 0x45, 0x7a, 0x4f, 0x54, 0x49, 0x33, 0x57, 0x6a, 0x41, 0x53, 0x4d, 0x52, 0x41, 0x77, 0x44, 0x67, 0x59, 0x44, 0x0a, 0x56, 0x51, 0x51, 0x4b, 0x44, 0x41, 0x64, 0x42, 0x59, 0x32, 0x31, 0x6c, 0x49, 0x45, 0x4e, 0x76, 0x4d, 0x46, 0x6b, 0x77, 0x45, 0x77, 0x59, 0x48, 0x4b, 0x6f, 0x5a, 0x49, 0x7a, 0x6a, 0x30, 0x43, 0x41, 0x51, 0x59, 0x49, 0x4b, 0x6f, 0x5a, 0x49, 0x7a, 0x6a, 0x30, 0x44, 0x41, 0x51, 0x63, 0x44, 0x51, 0x67, 0x41, 0x45, 0x64, 0x73, 0x6a, 0x79, 0x67, 0x56, 0x59, 0x6a, 0x6a, 0x61, 0x4b, 0x42, 0x0a, 0x46, 0x34, 0x43, 0x4e, 0x45, 0x43, 0x56, 0x6c, 0x6c, 0x4e, 0x66, 0x30, 0x31, 0x37, 0x70, 0x35, 0x2f, 0x4d, 0x78, 0x4e, 0x53, 0x57, 0x44, 0x6f, 0x54, 0x48, 0x79, 0x39, 0x49, 0x32, 0x47, 0x65, 0x44, 0x77, 0x45, 0x44, 0x44, 0x61, 0x7a, 0x49, 0x44, 0x2f, 0x78, 0x79, 0x38, 0x4a, 0x69, 0x59, 0x6a, 0x74, 0x50, 0x4b, 0x56, 0x45, 0x2f, 0x5a, 0x71, 0x77, 0x62, 0x6d, 0x69, 0x76, 0x70, 0x32, 0x0a, 0x55, 0x77, 0x74, 0x48, 0x32, 0x38, 0x61, 0x37, 0x4e, 0x61, 0x4e, 0x46, 0x4d, 0x45, 0x4d, 0x77, 0x43, 0x51, 0x59, 0x44, 0x56, 0x52, 0x30, 0x54, 0x42, 0x41, 0x49, 0x77, 0x41, 0x44, 0x41, 0x4c, 0x42, 0x67, 0x4e, 0x56, 0x48, 0x51, 0x38, 0x45, 0x42, 0x41, 0x4d, 0x43, 0x42, 0x61, 0x41, 0x77, 0x45, 0x77, 0x59, 0x44, 0x56, 0x52, 0x30, 0x6c, 0x42, 0x41, 0x77, 0x77, 0x43, 0x67, 0x59, 0x49, 0x0a, 0x4b, 0x77, 0x59, 0x42, 0x42, 0x51, 0x55, 0x48, 0x41, 0x77, 0x45, 0x77, 0x46, 0x41, 0x59, 0x44, 0x56, 0x52, 0x30, 0x52, 0x42, 0x41, 0x30, 0x77, 0x43, 0x34, 0x49, 0x4a, 0x62, 0x47, 0x39, 0x6a, 0x59, 0x57, 0x78, 0x6f, 0x62, 0x33, 0x4e, 0x30, 0x4d, 0x41, 0x6f, 0x47, 0x43, 0x43, 0x71, 0x47, 0x53, 0x4d, 0x34, 0x39, 0x42, 0x41, 0x4d, 0x43, 0x41, 0x30, 0x63, 0x41, 0x4d, 0x45, 0x51, 0x43, 0x0a, 0x49, 0x45, 0x7a, 0x72, 0x33, 0x74, 0x2f, 0x6a, 0x65, 0x6a, 0x56, 0x45, 0x39, 0x6f, 0x53, 0x6e, 0x42, 0x70, 0x38, 0x63, 0x33, 0x50, 0x32, 0x70, 0x2b, 0x6c, 0x44, 0x4c, 0x56, 0x52, 0x72, 0x42, 0x38, 0x7a, 0x78, 0x4c, 0x79, 0x6a, 0x5a, 0x76, 0x69, 0x72, 0x55, 0x58, 0x41, 0x69, 0x41, 0x79, 0x51, 0x50, 0x61, 0x45, 0x39, 0x4d, 0x4e, 0x63, 0x4c, 0x38, 0x2f, 0x6e, 0x52, 0x70, 0x75, 0x75, 0x0a, 0x39, 0x39, 0x49, 0x31, 0x65, 0x6e, 0x43, 0x53, 0x6d, 0x57, 0x49, 0x41, 0x4a, 0x35, 0x37, 0x49, 0x77, 0x75, 0x4a, 0x2f, 0x6e, 0x31, 0x64, 0x34, 0x35, 0x51, 0x3d, 0x3d, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a }; #endif #ifndef OPENSSL_NO_DSA /* * -----BEGIN DSA PRIVATE KEY----- * MIIBuwIBAAKBgQDdkFKzNABLOha7Eqj7004+p5fhtR6bxpujToMmSZTYi8igVVXP * Wzf03ULKS5UKjA6WpR6EiZAhm+PdxusZ5xfAuRZLdKy0bgxn1f348Rwh+EQNaEM8 * 0TGcnw5ijwKmSw5yyHPDWdiHzoqEBlhAf8Nl22YTXax/clsc/pu/RRLAdwIVAIEg * QqWRf/1EIZZcgM65Qpd65YuxAoGBAKBauV/RuloFHoSy5iWXESDywiS380tN5974 * GukGwoYdZo5uSIH6ahpeNSef0MbHGAzr7ZVEnhCQfRAwH1gRvSHoq/Rbmcvtd3r+ * QtQHOwvQHgLAynhI4i73c794czHaR+439bmcaSwDnQduRM85Mho/jiiZzAVPxBmG * POIMWNXXAoGAI6Ep5IE7yn3JzkXO9B6tC3bbDM+ZzuuInwZLbtZ8lim7Dsqabg4k * 2YbE4R95Bnfwnjsyl80mq/DbQN5lAHBvjDrkC6ItojBGKI3+iIrqGUEJdxvl4ulj * F0PmSD7zvIG8BfocKOel+EHH0YryExiW6krV1KW2ZRmJrqSFw6KCjV0CFFQFbPfU * xy5PmKytJmXR8BmppkIO * -----END DSA PRIVATE KEY----- */ static const char DSAPrivateKeyPEM[] = { 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x44, 0x53, 0x41, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b, 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x49, 0x49, 0x42, 0x75, 0x77, 0x49, 0x42, 0x41, 0x41, 0x4b, 0x42, 0x67, 0x51, 0x44, 0x64, 0x6b, 0x46, 0x4b, 0x7a, 0x4e, 0x41, 0x42, 0x4c, 0x4f, 0x68, 0x61, 0x37, 0x45, 0x71, 0x6a, 0x37, 0x30, 0x30, 0x34, 0x2b, 0x70, 0x35, 0x66, 0x68, 0x74, 0x52, 0x36, 0x62, 0x78, 0x70, 0x75, 0x6a, 0x54, 0x6f, 0x4d, 0x6d, 0x53, 0x5a, 0x54, 0x59, 0x69, 0x38, 0x69, 0x67, 0x56, 0x56, 0x58, 0x50, 0x0a, 0x57, 0x7a, 0x66, 0x30, 0x33, 0x55, 0x4c, 0x4b, 0x53, 0x35, 0x55, 0x4b, 0x6a, 0x41, 0x36, 0x57, 0x70, 0x52, 0x36, 0x45, 0x69, 0x5a, 0x41, 0x68, 0x6d, 0x2b, 0x50, 0x64, 0x78, 0x75, 0x73, 0x5a, 0x35, 0x78, 0x66, 0x41, 0x75, 0x52, 0x5a, 0x4c, 0x64, 0x4b, 0x79, 0x30, 0x62, 0x67, 0x78, 0x6e, 0x31, 0x66, 0x33, 0x34, 0x38, 0x52, 0x77, 0x68, 0x2b, 0x45, 0x51, 0x4e, 0x61, 0x45, 0x4d, 0x38, 0x0a, 0x30, 0x54, 0x47, 0x63, 0x6e, 0x77, 0x35, 0x69, 0x6a, 0x77, 0x4b, 0x6d, 0x53, 0x77, 0x35, 0x79, 0x79, 0x48, 0x50, 0x44, 0x57, 0x64, 0x69, 0x48, 0x7a, 0x6f, 0x71, 0x45, 0x42, 0x6c, 0x68, 0x41, 0x66, 0x38, 0x4e, 0x6c, 0x32, 0x32, 0x59, 0x54, 0x58, 0x61, 0x78, 0x2f, 0x63, 0x6c, 0x73, 0x63, 0x2f, 0x70, 0x75, 0x2f, 0x52, 0x52, 0x4c, 0x41, 0x64, 0x77, 0x49, 0x56, 0x41, 0x49, 0x45, 0x67, 0x0a, 0x51, 0x71, 0x57, 0x52, 0x66, 0x2f, 0x31, 0x45, 0x49, 0x5a, 0x5a, 0x63, 0x67, 0x4d, 0x36, 0x35, 0x51, 0x70, 0x64, 0x36, 0x35, 0x59, 0x75, 0x78, 0x41, 0x6f, 0x47, 0x42, 0x41, 0x4b, 0x42, 0x61, 0x75, 0x56, 0x2f, 0x52, 0x75, 0x6c, 0x6f, 0x46, 0x48, 0x6f, 0x53, 0x79, 0x35, 0x69, 0x57, 0x58, 0x45, 0x53, 0x44, 0x79, 0x77, 0x69, 0x53, 0x33, 0x38, 0x30, 0x74, 0x4e, 0x35, 0x39, 0x37, 0x34, 0x0a, 0x47, 0x75, 0x6b, 0x47, 0x77, 0x6f, 0x59, 0x64, 0x5a, 0x6f, 0x35, 0x75, 0x53, 0x49, 0x48, 0x36, 0x61, 0x68, 0x70, 0x65, 0x4e, 0x53, 0x65, 0x66, 0x30, 0x4d, 0x62, 0x48, 0x47, 0x41, 0x7a, 0x72, 0x37, 0x5a, 0x56, 0x45, 0x6e, 0x68, 0x43, 0x51, 0x66, 0x52, 0x41, 0x77, 0x48, 0x31, 0x67, 0x52, 0x76, 0x53, 0x48, 0x6f, 0x71, 0x2f, 0x52, 0x62, 0x6d, 0x63, 0x76, 0x74, 0x64, 0x33, 0x72, 0x2b, 0x0a, 0x51, 0x74, 0x51, 0x48, 0x4f, 0x77, 0x76, 0x51, 0x48, 0x67, 0x4c, 0x41, 0x79, 0x6e, 0x68, 0x49, 0x34, 0x69, 0x37, 0x33, 0x63, 0x37, 0x39, 0x34, 0x63, 0x7a, 0x48, 0x61, 0x52, 0x2b, 0x34, 0x33, 0x39, 0x62, 0x6d, 0x63, 0x61, 0x53, 0x77, 0x44, 0x6e, 0x51, 0x64, 0x75, 0x52, 0x4d, 0x38, 0x35, 0x4d, 0x68, 0x6f, 0x2f, 0x6a, 0x69, 0x69, 0x5a, 0x7a, 0x41, 0x56, 0x50, 0x78, 0x42, 0x6d, 0x47, 0x0a, 0x50, 0x4f, 0x49, 0x4d, 0x57, 0x4e, 0x58, 0x58, 0x41, 0x6f, 0x47, 0x41, 0x49, 0x36, 0x45, 0x70, 0x35, 0x49, 0x45, 0x37, 0x79, 0x6e, 0x33, 0x4a, 0x7a, 0x6b, 0x58, 0x4f, 0x39, 0x42, 0x36, 0x74, 0x43, 0x33, 0x62, 0x62, 0x44, 0x4d, 0x2b, 0x5a, 0x7a, 0x75, 0x75, 0x49, 0x6e, 0x77, 0x5a, 0x4c, 0x62, 0x74, 0x5a, 0x38, 0x6c, 0x69, 0x6d, 0x37, 0x44, 0x73, 0x71, 0x61, 0x62, 0x67, 0x34, 0x6b, 0x0a, 0x32, 0x59, 0x62, 0x45, 0x34, 0x52, 0x39, 0x35, 0x42, 0x6e, 0x66, 0x77, 0x6e, 0x6a, 0x73, 0x79, 0x6c, 0x38, 0x30, 0x6d, 0x71, 0x2f, 0x44, 0x62, 0x51, 0x4e, 0x35, 0x6c, 0x41, 0x48, 0x42, 0x76, 0x6a, 0x44, 0x72, 0x6b, 0x43, 0x36, 0x49, 0x74, 0x6f, 0x6a, 0x42, 0x47, 0x4b, 0x49, 0x33, 0x2b, 0x69, 0x49, 0x72, 0x71, 0x47, 0x55, 0x45, 0x4a, 0x64, 0x78, 0x76, 0x6c, 0x34, 0x75, 0x6c, 0x6a, 0x0a, 0x46, 0x30, 0x50, 0x6d, 0x53, 0x44, 0x37, 0x7a, 0x76, 0x49, 0x47, 0x38, 0x42, 0x66, 0x6f, 0x63, 0x4b, 0x4f, 0x65, 0x6c, 0x2b, 0x45, 0x48, 0x48, 0x30, 0x59, 0x72, 0x79, 0x45, 0x78, 0x69, 0x57, 0x36, 0x6b, 0x72, 0x56, 0x31, 0x4b, 0x57, 0x32, 0x5a, 0x52, 0x6d, 0x4a, 0x72, 0x71, 0x53, 0x46, 0x77, 0x36, 0x4b, 0x43, 0x6a, 0x56, 0x30, 0x43, 0x46, 0x46, 0x51, 0x46, 0x62, 0x50, 0x66, 0x55, 0x0a, 0x78, 0x79, 0x35, 0x50, 0x6d, 0x4b, 0x79, 0x74, 0x4a, 0x6d, 0x58, 0x52, 0x38, 0x42, 0x6d, 0x70, 0x70, 0x6b, 0x49, 0x4f, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x44, 0x53, 0x41, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b, 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a }; /* * -----BEGIN CERTIFICATE----- * MIICqTCCAmegAwIBAgIJAILDGUk37fWGMAsGCWCGSAFlAwQDAjASMRAwDgYDVQQK * DAdBY21lIENvMB4XDTE2MTIyNTEzMjUzNloXDTI2MTIyNTEzMjUzNlowEjEQMA4G * A1UECgwHQWNtZSBDbzCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQDdkFKzNABLOha7 * Eqj7004+p5fhtR6bxpujToMmSZTYi8igVVXPWzf03ULKS5UKjA6WpR6EiZAhm+Pd * xusZ5xfAuRZLdKy0bgxn1f348Rwh+EQNaEM80TGcnw5ijwKmSw5yyHPDWdiHzoqE * BlhAf8Nl22YTXax/clsc/pu/RRLAdwIVAIEgQqWRf/1EIZZcgM65Qpd65YuxAoGB * AKBauV/RuloFHoSy5iWXESDywiS380tN5974GukGwoYdZo5uSIH6ahpeNSef0MbH * GAzr7ZVEnhCQfRAwH1gRvSHoq/Rbmcvtd3r+QtQHOwvQHgLAynhI4i73c794czHa * R+439bmcaSwDnQduRM85Mho/jiiZzAVPxBmGPOIMWNXXA4GEAAKBgCOhKeSBO8p9 * yc5FzvQerQt22wzPmc7riJ8GS27WfJYpuw7Kmm4OJNmGxOEfeQZ38J47MpfNJqvw * 20DeZQBwb4w65AuiLaIwRiiN/oiK6hlBCXcb5eLpYxdD5kg+87yBvAX6HCjnpfhB * x9GK8hMYlupK1dSltmUZia6khcOigo1do0UwQzAJBgNVHRMEAjAAMAsGA1UdDwQE * AwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATAUBgNVHREEDTALgglsb2NhbGhvc3Qw * CwYJYIZIAWUDBAMCAy8AMCwCFClxInXTRWNJEWdi5ilNr/fbM1bKAhQy4B7wtmfd * I+zV6g3w9qBkNqStpA== * -----END CERTIFICATE----- */ static const char DSACertPEM[] = { 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x49, 0x49, 0x43, 0x71, 0x54, 0x43, 0x43, 0x41, 0x6d, 0x65, 0x67, 0x41, 0x77, 0x49, 0x42, 0x41, 0x67, 0x49, 0x4a, 0x41, 0x49, 0x4c, 0x44, 0x47, 0x55, 0x6b, 0x33, 0x37, 0x66, 0x57, 0x47, 0x4d, 0x41, 0x73, 0x47, 0x43, 0x57, 0x43, 0x47, 0x53, 0x41, 0x46, 0x6c, 0x41, 0x77, 0x51, 0x44, 0x41, 0x6a, 0x41, 0x53, 0x4d, 0x52, 0x41, 0x77, 0x44, 0x67, 0x59, 0x44, 0x56, 0x51, 0x51, 0x4b, 0x0a, 0x44, 0x41, 0x64, 0x42, 0x59, 0x32, 0x31, 0x6c, 0x49, 0x45, 0x4e, 0x76, 0x4d, 0x42, 0x34, 0x58, 0x44, 0x54, 0x45, 0x32, 0x4d, 0x54, 0x49, 0x79, 0x4e, 0x54, 0x45, 0x7a, 0x4d, 0x6a, 0x55, 0x7a, 0x4e, 0x6c, 0x6f, 0x58, 0x44, 0x54, 0x49, 0x32, 0x4d, 0x54, 0x49, 0x79, 0x4e, 0x54, 0x45, 0x7a, 0x4d, 0x6a, 0x55, 0x7a, 0x4e, 0x6c, 0x6f, 0x77, 0x45, 0x6a, 0x45, 0x51, 0x4d, 0x41, 0x34, 0x47, 0x0a, 0x41, 0x31, 0x55, 0x45, 0x43, 0x67, 0x77, 0x48, 0x51, 0x57, 0x4e, 0x74, 0x5a, 0x53, 0x42, 0x44, 0x62, 0x7a, 0x43, 0x43, 0x41, 0x62, 0x63, 0x77, 0x67, 0x67, 0x45, 0x73, 0x42, 0x67, 0x63, 0x71, 0x68, 0x6b, 0x6a, 0x4f, 0x4f, 0x41, 0x51, 0x42, 0x4d, 0x49, 0x49, 0x42, 0x48, 0x77, 0x4b, 0x42, 0x67, 0x51, 0x44, 0x64, 0x6b, 0x46, 0x4b, 0x7a, 0x4e, 0x41, 0x42, 0x4c, 0x4f, 0x68, 0x61, 0x37, 0x0a, 0x45, 0x71, 0x6a, 0x37, 0x30, 0x30, 0x34, 0x2b, 0x70, 0x35, 0x66, 0x68, 0x74, 0x52, 0x36, 0x62, 0x78, 0x70, 0x75, 0x6a, 0x54, 0x6f, 0x4d, 0x6d, 0x53, 0x5a, 0x54, 0x59, 0x69, 0x38, 0x69, 0x67, 0x56, 0x56, 0x58, 0x50, 0x57, 0x7a, 0x66, 0x30, 0x33, 0x55, 0x4c, 0x4b, 0x53, 0x35, 0x55, 0x4b, 0x6a, 0x41, 0x36, 0x57, 0x70, 0x52, 0x36, 0x45, 0x69, 0x5a, 0x41, 0x68, 0x6d, 0x2b, 0x50, 0x64, 0x0a, 0x78, 0x75, 0x73, 0x5a, 0x35, 0x78, 0x66, 0x41, 0x75, 0x52, 0x5a, 0x4c, 0x64, 0x4b, 0x79, 0x30, 0x62, 0x67, 0x78, 0x6e, 0x31, 0x66, 0x33, 0x34, 0x38, 0x52, 0x77, 0x68, 0x2b, 0x45, 0x51, 0x4e, 0x61, 0x45, 0x4d, 0x38, 0x30, 0x54, 0x47, 0x63, 0x6e, 0x77, 0x35, 0x69, 0x6a, 0x77, 0x4b, 0x6d, 0x53, 0x77, 0x35, 0x79, 0x79, 0x48, 0x50, 0x44, 0x57, 0x64, 0x69, 0x48, 0x7a, 0x6f, 0x71, 0x45, 0x0a, 0x42, 0x6c, 0x68, 0x41, 0x66, 0x38, 0x4e, 0x6c, 0x32, 0x32, 0x59, 0x54, 0x58, 0x61, 0x78, 0x2f, 0x63, 0x6c, 0x73, 0x63, 0x2f, 0x70, 0x75, 0x2f, 0x52, 0x52, 0x4c, 0x41, 0x64, 0x77, 0x49, 0x56, 0x41, 0x49, 0x45, 0x67, 0x51, 0x71, 0x57, 0x52, 0x66, 0x2f, 0x31, 0x45, 0x49, 0x5a, 0x5a, 0x63, 0x67, 0x4d, 0x36, 0x35, 0x51, 0x70, 0x64, 0x36, 0x35, 0x59, 0x75, 0x78, 0x41, 0x6f, 0x47, 0x42, 0x0a, 0x41, 0x4b, 0x42, 0x61, 0x75, 0x56, 0x2f, 0x52, 0x75, 0x6c, 0x6f, 0x46, 0x48, 0x6f, 0x53, 0x79, 0x35, 0x69, 0x57, 0x58, 0x45, 0x53, 0x44, 0x79, 0x77, 0x69, 0x53, 0x33, 0x38, 0x30, 0x74, 0x4e, 0x35, 0x39, 0x37, 0x34, 0x47, 0x75, 0x6b, 0x47, 0x77, 0x6f, 0x59, 0x64, 0x5a, 0x6f, 0x35, 0x75, 0x53, 0x49, 0x48, 0x36, 0x61, 0x68, 0x70, 0x65, 0x4e, 0x53, 0x65, 0x66, 0x30, 0x4d, 0x62, 0x48, 0x0a, 0x47, 0x41, 0x7a, 0x72, 0x37, 0x5a, 0x56, 0x45, 0x6e, 0x68, 0x43, 0x51, 0x66, 0x52, 0x41, 0x77, 0x48, 0x31, 0x67, 0x52, 0x76, 0x53, 0x48, 0x6f, 0x71, 0x2f, 0x52, 0x62, 0x6d, 0x63, 0x76, 0x74, 0x64, 0x33, 0x72, 0x2b, 0x51, 0x74, 0x51, 0x48, 0x4f, 0x77, 0x76, 0x51, 0x48, 0x67, 0x4c, 0x41, 0x79, 0x6e, 0x68, 0x49, 0x34, 0x69, 0x37, 0x33, 0x63, 0x37, 0x39, 0x34, 0x63, 0x7a, 0x48, 0x61, 0x0a, 0x52, 0x2b, 0x34, 0x33, 0x39, 0x62, 0x6d, 0x63, 0x61, 0x53, 0x77, 0x44, 0x6e, 0x51, 0x64, 0x75, 0x52, 0x4d, 0x38, 0x35, 0x4d, 0x68, 0x6f, 0x2f, 0x6a, 0x69, 0x69, 0x5a, 0x7a, 0x41, 0x56, 0x50, 0x78, 0x42, 0x6d, 0x47, 0x50, 0x4f, 0x49, 0x4d, 0x57, 0x4e, 0x58, 0x58, 0x41, 0x34, 0x47, 0x45, 0x41, 0x41, 0x4b, 0x42, 0x67, 0x43, 0x4f, 0x68, 0x4b, 0x65, 0x53, 0x42, 0x4f, 0x38, 0x70, 0x39, 0x0a, 0x79, 0x63, 0x35, 0x46, 0x7a, 0x76, 0x51, 0x65, 0x72, 0x51, 0x74, 0x32, 0x32, 0x77, 0x7a, 0x50, 0x6d, 0x63, 0x37, 0x72, 0x69, 0x4a, 0x38, 0x47, 0x53, 0x32, 0x37, 0x57, 0x66, 0x4a, 0x59, 0x70, 0x75, 0x77, 0x37, 0x4b, 0x6d, 0x6d, 0x34, 0x4f, 0x4a, 0x4e, 0x6d, 0x47, 0x78, 0x4f, 0x45, 0x66, 0x65, 0x51, 0x5a, 0x33, 0x38, 0x4a, 0x34, 0x37, 0x4d, 0x70, 0x66, 0x4e, 0x4a, 0x71, 0x76, 0x77, 0x0a, 0x32, 0x30, 0x44, 0x65, 0x5a, 0x51, 0x42, 0x77, 0x62, 0x34, 0x77, 0x36, 0x35, 0x41, 0x75, 0x69, 0x4c, 0x61, 0x49, 0x77, 0x52, 0x69, 0x69, 0x4e, 0x2f, 0x6f, 0x69, 0x4b, 0x36, 0x68, 0x6c, 0x42, 0x43, 0x58, 0x63, 0x62, 0x35, 0x65, 0x4c, 0x70, 0x59, 0x78, 0x64, 0x44, 0x35, 0x6b, 0x67, 0x2b, 0x38, 0x37, 0x79, 0x42, 0x76, 0x41, 0x58, 0x36, 0x48, 0x43, 0x6a, 0x6e, 0x70, 0x66, 0x68, 0x42, 0x0a, 0x78, 0x39, 0x47, 0x4b, 0x38, 0x68, 0x4d, 0x59, 0x6c, 0x75, 0x70, 0x4b, 0x31, 0x64, 0x53, 0x6c, 0x74, 0x6d, 0x55, 0x5a, 0x69, 0x61, 0x36, 0x6b, 0x68, 0x63, 0x4f, 0x69, 0x67, 0x6f, 0x31, 0x64, 0x6f, 0x30, 0x55, 0x77, 0x51, 0x7a, 0x41, 0x4a, 0x42, 0x67, 0x4e, 0x56, 0x48, 0x52, 0x4d, 0x45, 0x41, 0x6a, 0x41, 0x41, 0x4d, 0x41, 0x73, 0x47, 0x41, 0x31, 0x55, 0x64, 0x44, 0x77, 0x51, 0x45, 0x0a, 0x41, 0x77, 0x49, 0x46, 0x6f, 0x44, 0x41, 0x54, 0x42, 0x67, 0x4e, 0x56, 0x48, 0x53, 0x55, 0x45, 0x44, 0x44, 0x41, 0x4b, 0x42, 0x67, 0x67, 0x72, 0x42, 0x67, 0x45, 0x46, 0x42, 0x51, 0x63, 0x44, 0x41, 0x54, 0x41, 0x55, 0x42, 0x67, 0x4e, 0x56, 0x48, 0x52, 0x45, 0x45, 0x44, 0x54, 0x41, 0x4c, 0x67, 0x67, 0x6c, 0x73, 0x62, 0x32, 0x4e, 0x68, 0x62, 0x47, 0x68, 0x76, 0x63, 0x33, 0x51, 0x77, 0x0a, 0x43, 0x77, 0x59, 0x4a, 0x59, 0x49, 0x5a, 0x49, 0x41, 0x57, 0x55, 0x44, 0x42, 0x41, 0x4d, 0x43, 0x41, 0x79, 0x38, 0x41, 0x4d, 0x43, 0x77, 0x43, 0x46, 0x43, 0x6c, 0x78, 0x49, 0x6e, 0x58, 0x54, 0x52, 0x57, 0x4e, 0x4a, 0x45, 0x57, 0x64, 0x69, 0x35, 0x69, 0x6c, 0x4e, 0x72, 0x2f, 0x66, 0x62, 0x4d, 0x31, 0x62, 0x4b, 0x41, 0x68, 0x51, 0x79, 0x34, 0x42, 0x37, 0x77, 0x74, 0x6d, 0x66, 0x64, 0x0a, 0x49, 0x2b, 0x7a, 0x56, 0x36, 0x67, 0x33, 0x77, 0x39, 0x71, 0x42, 0x6b, 0x4e, 0x71, 0x53, 0x74, 0x70, 0x41, 0x3d, 0x3d, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a }; #endif #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION extern int rand_predictable; #endif #define ENTROPY_NEEDED 32 /* unused, to avoid warning. */ static int idx; int FuzzerInitialize(int *argc, char ***argv) { STACK_OF(SSL_COMP) *comp_methods; OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS | OPENSSL_INIT_ASYNC, NULL); OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL); ERR_get_state(); CRYPTO_free_ex_index(0, -1); idx = SSL_get_ex_data_X509_STORE_CTX_idx(); RAND_add("", 1, ENTROPY_NEEDED); RAND_status(); RSA_get_default_method(); #ifndef OPENSSL_NO_DSA DSA_get_default_method(); #endif #ifndef OPENSSL_NO_EC EC_KEY_get_default_method(); #endif #ifndef OPENSSL_NO_DH DH_get_default_method(); #endif comp_methods = SSL_COMP_get_compression_methods(); OPENSSL_sk_sort((OPENSSL_STACK *)comp_methods); #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION rand_predictable = 1; #endif return 1; } int FuzzerTestOneInput(const uint8_t *buf, size_t len) { SSL *server; BIO *in; BIO *out; BIO *bio_buf; SSL_CTX *ctx; int ret; RSA *privkey; const uint8_t *bufp; EVP_PKEY *pkey; X509 *cert; #ifndef OPENSSL_NO_EC EC_KEY *ecdsakey = NULL; #endif #ifndef OPENSSL_NO_DSA DSA *dsakey = NULL; #endif if (len == 0) return 0; /* * TODO: use the ossltest engine (optionally?) to disable crypto checks. */ /* This only fuzzes the initial flow from the client so far. */ ctx = SSL_CTX_new(SSLv23_method()); /* RSA */ bufp = kRSAPrivateKeyDER; privkey = d2i_RSAPrivateKey(NULL, &bufp, sizeof(kRSAPrivateKeyDER)); OPENSSL_assert(privkey != NULL); pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(pkey, privkey); ret = SSL_CTX_use_PrivateKey(ctx, pkey); OPENSSL_assert(ret == 1); EVP_PKEY_free(pkey); bufp = kCertificateDER; cert = d2i_X509(NULL, &bufp, sizeof(kCertificateDER)); OPENSSL_assert(cert != NULL); ret = SSL_CTX_use_certificate(ctx, cert); OPENSSL_assert(ret == 1); X509_free(cert); #ifndef OPENSSL_NO_EC /* ECDSA */ bio_buf = BIO_new(BIO_s_mem()); OPENSSL_assert((size_t)BIO_write(bio_buf, ECDSAPrivateKeyPEM, sizeof(ECDSAPrivateKeyPEM)) == sizeof(ECDSAPrivateKeyPEM)); ecdsakey = PEM_read_bio_ECPrivateKey(bio_buf, NULL, NULL, NULL); ERR_print_errors_fp(stderr); OPENSSL_assert(ecdsakey != NULL); BIO_free(bio_buf); pkey = EVP_PKEY_new(); EVP_PKEY_assign_EC_KEY(pkey, ecdsakey); ret = SSL_CTX_use_PrivateKey(ctx, pkey); OPENSSL_assert(ret == 1); EVP_PKEY_free(pkey); bio_buf = BIO_new(BIO_s_mem()); OPENSSL_assert((size_t)BIO_write(bio_buf, ECDSACertPEM, sizeof(ECDSACertPEM)) == sizeof(ECDSACertPEM)); cert = PEM_read_bio_X509(bio_buf, NULL, NULL, NULL); OPENSSL_assert(cert != NULL); BIO_free(bio_buf); ret = SSL_CTX_use_certificate(ctx, cert); OPENSSL_assert(ret == 1); X509_free(cert); #endif #ifndef OPENSSL_NO_DSA /* DSA */ bio_buf = BIO_new(BIO_s_mem()); OPENSSL_assert((size_t)BIO_write(bio_buf, DSAPrivateKeyPEM, sizeof(DSAPrivateKeyPEM)) == sizeof(DSAPrivateKeyPEM)); dsakey = PEM_read_bio_DSAPrivateKey(bio_buf, NULL, NULL, NULL); ERR_print_errors_fp(stderr); OPENSSL_assert(dsakey != NULL); BIO_free(bio_buf); pkey = EVP_PKEY_new(); EVP_PKEY_assign_DSA(pkey, dsakey); ret = SSL_CTX_use_PrivateKey(ctx, pkey); OPENSSL_assert(ret == 1); EVP_PKEY_free(pkey); bio_buf = BIO_new(BIO_s_mem()); OPENSSL_assert((size_t)BIO_write(bio_buf, DSACertPEM, sizeof(DSACertPEM)) == sizeof(DSACertPEM)); cert = PEM_read_bio_X509(bio_buf, NULL, NULL, NULL); OPENSSL_assert(cert != NULL); BIO_free(bio_buf); ret = SSL_CTX_use_certificate(ctx, cert); OPENSSL_assert(ret == 1); X509_free(cert); #endif /* TODO: Set up support for SRP and PSK */ server = SSL_new(ctx); ret = SSL_set_cipher_list(server, "ALL:eNULL:@SECLEVEL=0"); OPENSSL_assert(ret == 1); in = BIO_new(BIO_s_mem()); out = BIO_new(BIO_s_mem()); SSL_set_bio(server, in, out); SSL_set_accept_state(server); OPENSSL_assert((size_t)BIO_write(in, buf, len) == len); if (SSL_do_handshake(server) == 1) { /* Keep reading application data until error or EOF. */ uint8_t tmp[1024]; for (;;) { if (SSL_read(server, tmp, sizeof(tmp)) <= 0) { break; } } } SSL_free(server); ERR_clear_error(); SSL_CTX_free(ctx); return 0; } void FuzzerCleanup(void) { }
openssl_openssl
2017-01-26
26a39fa953c11c4257471570655b0193828d4721
crypto/ui/ui_util.c
109
/* * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include "internal/thread_once.h" #include "ui_locl.h" #ifndef BUFSIZ #define BUFSIZ 256 #endif int UI_UTIL_read_pw_string(char *buf, int length, const char *prompt, int verify) { char buff[BUFSIZ]; int ret; ret = UI_UTIL_read_pw(buf, buff, (length > BUFSIZ) ? BUFSIZ : length, prompt, verify); OPENSSL_cleanse(buff, BUFSIZ); return (ret); } int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt, int verify) { int ok = 0; UI *ui; if (size < 1) return -1; ui = UI_new(); if (ui != NULL) { ok = UI_add_input_string(ui, prompt, 0, buf, 0, size - 1); if (ok >= 0 && verify) ok = UI_add_verify_string(ui, prompt, 0, buff, 0, size - 1, buf); if (ok >= 0) ok = UI_process(ui); UI_free(ui); } if (ok > 0) ok = 0; return (ok); } /* * Wrapper around pem_password_cb, a method to help older APIs use newer * ones. */ struct pem_password_cb_data { pem_password_cb *cb; int rwflag; }; static void ui_new_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { /* * Do nothing, the data is allocated externally and assigned later with * CRYPTO_set_ex_data() */ } static int ui_dup_method_data(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, void *from_d, int idx, long argl, void *argp) { void **pptr = (void **)from_d; if (*pptr != NULL) *pptr = OPENSSL_memdup(*pptr, sizeof(struct pem_password_cb_data)); return 1; } static void ui_free_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { OPENSSL_free(ptr); } static CRYPTO_ONCE get_index_once = CRYPTO_ONCE_STATIC_INIT; static int ui_method_data_index = -1; DEFINE_RUN_ONCE_STATIC(ui_method_data_index_init) { ui_method_data_index = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI_METHOD, 0, NULL, ui_new_method_data, ui_dup_method_data, ui_free_method_data); return 1; } static int ui_open(UI *ui) { return 1; } static int ui_read(UI *ui, UI_STRING *uis) { switch (UI_get_string_type(uis)) { case UIT_PROMPT: { char result[PEM_BUFSIZE]; const struct pem_password_cb_data *data = UI_method_get_ex_data(UI_get_method(ui), ui_method_data_index); int maxsize = UI_get_result_maxsize(uis); int len = data->cb(result, maxsize > PEM_BUFSIZE ? PEM_BUFSIZE : maxsize, data->rwflag, UI_get0_user_data(ui)); if (len <= 0) return len; if (UI_set_result(ui, uis, result) >= 0) return 1; return 0; } case UIT_VERIFY: case UIT_NONE: case UIT_BOOLEAN: case UIT_INFO: case UIT_ERROR: break; } return 1; } static int ui_write(UI *ui, UI_STRING *uis) { return 1; } static int ui_close(UI *ui) { return 1; } UI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag) { struct pem_password_cb_data *data = NULL; UI_METHOD *ui_method = NULL; if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL || (ui_method = UI_create_method("PEM password callback wrapper")) == NULL || UI_method_set_opener(ui_method, ui_open) < 0 || UI_method_set_reader(ui_method, ui_read) < 0 || UI_method_set_writer(ui_method, ui_write) < 0 || UI_method_set_closer(ui_method, ui_close) < 0 || !RUN_ONCE(&get_index_once, ui_method_data_index_init) || UI_method_set_ex_data(ui_method, ui_method_data_index, data) < 0) { UI_destroy_method(ui_method); OPENSSL_free(data); return NULL; } data->rwflag = rwflag; data->cb = cb; return ui_method; }
openssl_openssl
2017-01-26
26a39fa953c11c4257471570655b0193828d4721
crypto/poly1305/poly1305_pmeth.c
192
/* * Copyright 2007-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/evp.h> #include "internal/poly1305.h" #include "poly1305_local.h" #include "internal/evp_int.h" /* POLY1305 pkey context structure */ typedef struct { ASN1_OCTET_STRING ktmp; /* Temp storage for key */ POLY1305 ctx; } POLY1305_PKEY_CTX; static int pkey_poly1305_init(EVP_PKEY_CTX *ctx) { POLY1305_PKEY_CTX *pctx; pctx = OPENSSL_zalloc(sizeof(*pctx)); if (pctx == NULL) return 0; pctx->ktmp.type = V_ASN1_OCTET_STRING; EVP_PKEY_CTX_set_data(ctx, pctx); EVP_PKEY_CTX_set0_keygen_info(ctx, NULL, 0); return 1; } static void pkey_poly1305_cleanup(EVP_PKEY_CTX *ctx) { POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); if (pctx != NULL) { OPENSSL_clear_free(pctx->ktmp.data, pctx->ktmp.length); OPENSSL_clear_free(pctx, sizeof(*pctx)); EVP_PKEY_CTX_set_data(ctx, NULL); } } static int pkey_poly1305_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { POLY1305_PKEY_CTX *sctx, *dctx; /* allocate memory for dst->data and a new POLY1305_CTX in dst->data->ctx */ if (!pkey_poly1305_init(dst)) return 0; sctx = EVP_PKEY_CTX_get_data(src); dctx = EVP_PKEY_CTX_get_data(dst); if (ASN1_STRING_get0_data(&sctx->ktmp) != NULL && !ASN1_STRING_copy(&dctx->ktmp, &sctx->ktmp)) { /* cleanup and free the POLY1305_PKEY_CTX in dst->data */ pkey_poly1305_cleanup(dst); return 0; } memcpy(&dctx->ctx, &sctx->ctx, sizeof(POLY1305)); return 1; } static int pkey_poly1305_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { ASN1_OCTET_STRING *key; POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); if (ASN1_STRING_get0_data(&pctx->ktmp) == NULL) return 0; key = ASN1_OCTET_STRING_dup(&pctx->ktmp); if (key == NULL) return 0; return EVP_PKEY_assign_POLY1305(pkey, key); } static int int_update(EVP_MD_CTX *ctx, const void *data, size_t count) { POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(EVP_MD_CTX_pkey_ctx(ctx)); Poly1305_Update(&pctx->ctx, data, count); return 1; } static int poly1305_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) { POLY1305_PKEY_CTX *pctx = ctx->data; ASN1_OCTET_STRING *key = (ASN1_OCTET_STRING *)ctx->pkey->pkey.ptr; if (key->length != POLY1305_KEY_SIZE) return 0; EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT); EVP_MD_CTX_set_update_fn(mctx, int_update); Poly1305_Init(&pctx->ctx, key->data); return 1; } static int poly1305_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, EVP_MD_CTX *mctx) { POLY1305_PKEY_CTX *pctx = ctx->data; *siglen = POLY1305_DIGEST_SIZE; if (sig != NULL) Poly1305_Final(&pctx->ctx, sig); return 1; } static int pkey_poly1305_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); const unsigned char *key; size_t len; switch (type) { case EVP_PKEY_CTRL_MD: /* ignore */ break; case EVP_PKEY_CTRL_SET_MAC_KEY: case EVP_PKEY_CTRL_DIGESTINIT: if (type == EVP_PKEY_CTRL_SET_MAC_KEY) { /* user explicitly setting the key */ key = p2; len = p1; } else { /* user indirectly setting the key via EVP_DigestSignInit */ key = EVP_PKEY_get0_poly1305(EVP_PKEY_CTX_get0_pkey(ctx), &len); } if (key == NULL || len != POLY1305_KEY_SIZE || !ASN1_OCTET_STRING_set(&pctx->ktmp, key, len)) return 0; Poly1305_Init(&pctx->ctx, ASN1_STRING_get0_data(&pctx->ktmp)); break; default: return -2; } return 1; } static int pkey_poly1305_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { if (value == NULL) return 0; if (strcmp(type, "key") == 0) return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value); if (strcmp(type, "hexkey") == 0) return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value); return -2; } const EVP_PKEY_METHOD poly1305_pkey_meth = { EVP_PKEY_POLY1305, EVP_PKEY_FLAG_SIGCTX_CUSTOM, /* we don't deal with a separate MD */ pkey_poly1305_init, pkey_poly1305_copy, pkey_poly1305_cleanup, 0, 0, 0, pkey_poly1305_keygen, 0, 0, 0, 0, 0, 0, poly1305_signctx_init, poly1305_signctx, 0, 0, 0, 0, 0, 0, 0, 0, pkey_poly1305_ctrl, pkey_poly1305_ctrl_str };
openssl_openssl
2017-01-26
26a39fa953c11c4257471570655b0193828d4721
test/uitest.c
141
/* * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/err.h> /* * We know that on VMS, the [.apps] object files are compiled with uppercased * symbols. We must therefore follow suit, or there will be linking errors. * Additionally, the VMS build does stdio via a socketpair. */ #ifdef __VMS # pragma names save # pragma names uppercase, truncated # include "../apps/vms_term_sock.h" #endif #include "../apps/apps.h" #ifdef __VMS # pragma names restore #endif #include "testutil.h" #include "test_main_custom.h" /* apps/apps.c depend on these */ char *default_config_file = NULL; BIO *bio_err = NULL; #ifndef OPENSSL_NO_UI # include <openssl/ui.h> /* Old style PEM password callback */ static int test_pem_password_cb(char *buf, int size, int rwflag, void *userdata) { OPENSSL_strlcpy(buf, (char *)userdata, (size_t)size); return 1; } /* * Test wrapping old style PEM password callback in a UI method through the * use of UI utility functions */ static int test_old() { UI_METHOD *ui_method = NULL; UI *ui = NULL; char defpass[] = "password"; char pass[16]; int ok = 0; if ((ui_method = UI_UTIL_wrap_read_pem_callback(test_pem_password_cb, 0)) == NULL || (ui = UI_new_method(ui_method)) == NULL) goto err; /* The wrapper passes the UI userdata as the callback userdata param */ UI_add_user_data(ui, defpass); if (!UI_add_input_string(ui, "prompt", UI_INPUT_FLAG_DEFAULT_PWD, pass, 0, sizeof(pass) - 1)) goto err; switch (UI_process(ui)) { case -2: BIO_printf(bio_err, "test_old: UI process interrupted or cancelled\n"); /* fall through */ case -1: goto err; default: break; } if (strcmp(pass, defpass) == 0) ok = 1; else BIO_printf(bio_err, "test_old: password failure\n"); err: if (!ok) ERR_print_errors_fp(stderr); UI_free(ui); UI_destroy_method(ui_method); return ok; } /* Test of UI. This uses the UI method defined in apps/apps.c */ static int test_new_ui() { PW_CB_DATA cb_data = { "password", "prompt" }; char pass[16]; int ok = 0; setup_ui_method(); if (password_callback(pass, sizeof(pass), 0, &cb_data) > 0 && strcmp(pass, cb_data.password) == 0) ok = 1; else BIO_printf(bio_err, "test_new: password failure\n"); if (!ok) ERR_print_errors_fp(stderr); destroy_ui_method(); return ok; } #endif int test_main(int argc, char *argv[]) { int ret; bio_err = dup_bio_err(FORMAT_TEXT); #ifndef OPENSSL_NO_UI ADD_TEST(test_old); ADD_TEST(test_new_ui); #endif ret = run_tests(argv[0]); (void)BIO_flush(bio_err); BIO_free(bio_err); return ret; }
openssl_openssl
2017-01-26
26a39fa953c11c4257471570655b0193828d4721
crypto/poly1305/poly1305_ameth.c
67
/* * Copyright 2007-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include "internal/asn1_int.h" #include "internal/poly1305.h" #include "poly1305_local.h" /* * POLY1305 "ASN1" method. This is just here to indicate the maximum * POLY1305 output length and to free up a POLY1305 key. */ static int poly1305_size(const EVP_PKEY *pkey) { return POLY1305_DIGEST_SIZE; } static void poly1305_key_free(EVP_PKEY *pkey) { ASN1_OCTET_STRING *os = EVP_PKEY_get0(pkey); if (os != NULL) { if (os->data != NULL) OPENSSL_cleanse(os->data, os->length); ASN1_OCTET_STRING_free(os); } } static int poly1305_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { /* nothing, (including ASN1_PKEY_CTRL_DEFAULT_MD_NID), is supported */ return -2; } static int poly1305_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b)); } const EVP_PKEY_ASN1_METHOD poly1305_asn1_meth = { EVP_PKEY_POLY1305, EVP_PKEY_POLY1305, 0, "POLY1305", "OpenSSL POLY1305 method", 0, 0, poly1305_pkey_public_cmp, 0, 0, 0, 0, poly1305_size, 0, 0, 0, 0, 0, 0, 0, 0, 0, poly1305_key_free, poly1305_pkey_ctrl, 0, 0 };
openssl_openssl
2017-01-26
26a39fa953c11c4257471570655b0193828d4721
sklearn/tests/test_multioutput.py
126
from __future__ import division import numpy as np import scipy.sparse as sp from sklearn.utils import shuffle from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_raises_regex from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_not_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.exceptions import NotFittedError from sklearn import datasets from sklearn.base import clone from sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier from sklearn.linear_model import Lasso from sklearn.linear_model import SGDClassifier from sklearn.linear_model import SGDRegressor from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC from sklearn.multiclass import OneVsRestClassifier from sklearn.multioutput import MultiOutputRegressor, MultiOutputClassifier def test_multi_target_regression(): X, y = datasets.make_regression(n_targets=3) X_train, y_train = X[:50], y[:50] X_test, y_test = X[50:], y[50:] references = np.zeros_like(y_test) for n in range(3): rgr = GradientBoostingRegressor(random_state=0) rgr.fit(X_train, y_train[:, n]) references[:, n] = rgr.predict(X_test) rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0)) rgr.fit(X_train, y_train) y_pred = rgr.predict(X_test) assert_almost_equal(references, y_pred) def test_multi_target_regression_partial_fit(): X, y = datasets.make_regression(n_targets=3) X_train, y_train = X[:50], y[:50] X_test, y_test = X[50:], y[50:] references = np.zeros_like(y_test) half_index = 25 for n in range(3): sgr = SGDRegressor(random_state=0) sgr.partial_fit(X_train[:half_index], y_train[:half_index, n]) sgr.partial_fit(X_train[half_index:], y_train[half_index:, n]) references[:, n] = sgr.predict(X_test) sgr = MultiOutputRegressor(SGDRegressor(random_state=0)) sgr.partial_fit(X_train[:half_index], y_train[:half_index]) sgr.partial_fit(X_train[half_index:], y_train[half_index:]) y_pred = sgr.predict(X_test) assert_almost_equal(references, y_pred) def test_multi_target_regression_one_target(): # Test multi target regression raises X, y = datasets.make_regression(n_targets=1) rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0)) assert_raises(ValueError, rgr.fit, X, y) def test_multi_target_sparse_regression(): X, y = datasets.make_regression(n_targets=3) X_train, y_train = X[:50], y[:50] X_test = X[50:] for sparse in [sp.csr_matrix, sp.csc_matrix, sp.coo_matrix, sp.dok_matrix, sp.lil_matrix]: rgr = MultiOutputRegressor(Lasso(random_state=0)) rgr_sparse = MultiOutputRegressor(Lasso(random_state=0)) rgr.fit(X_train, y_train) rgr_sparse.fit(sparse(X_train), y_train) assert_almost_equal(rgr.predict(X_test), rgr_sparse.predict(sparse(X_test))) def test_multi_target_sample_weights_api(): X = [[1, 2, 3], [4, 5, 6]] y = [[3.141, 2.718], [2.718, 3.141]] w = [0.8, 0.6] rgr = MultiOutputRegressor(Lasso()) assert_raises_regex(ValueError, "does not support sample weights", rgr.fit, X, y, w) # no exception should be raised if the base estimator supports weights rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0)) rgr.fit(X, y, w) def test_multi_target_sample_weight_partial_fit(): # weighted regressor X = [[1, 2, 3], [4, 5, 6]] y = [[3.141, 2.718], [2.718, 3.141]] w = [2., 1.] rgr_w = MultiOutputRegressor(SGDRegressor(random_state=0)) rgr_w.partial_fit(X, y, w) # weighted with different weights w = [2., 2.] rgr = MultiOutputRegressor(SGDRegressor(random_state=0)) rgr.partial_fit(X, y, w) assert_not_equal(rgr.predict(X)[0][0], rgr_w.predict(X)[0][0]) def test_multi_target_sample_weights(): # weighted regressor Xw = [[1, 2, 3], [4, 5, 6]] yw = [[3.141, 2.718], [2.718, 3.141]] w = [2., 1.] rgr_w = MultiOutputRegressor(GradientBoostingRegressor(random_state=0)) rgr_w.fit(Xw, yw, w) # unweighted, but with repeated samples X = [[1, 2, 3], [1, 2, 3], [4, 5, 6]] y = [[3.141, 2.718], [3.141, 2.718], [2.718, 3.141]] rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0)) rgr.fit(X, y) X_test = [[1.5, 2.5, 3.5], [3.5, 4.5, 5.5]] assert_almost_equal(rgr.predict(X_test), rgr_w.predict(X_test)) # Import the data iris = datasets.load_iris() # create a multiple targets by randomized shuffling and concatenating y. X = iris.data y1 = iris.target y2 = shuffle(y1, random_state=1) y3 = shuffle(y1, random_state=2) y = np.column_stack((y1, y2, y3)) n_samples, n_features = X.shape n_outputs = y.shape[1] n_classes = len(np.unique(y1)) classes = list(map(np.unique, (y1, y2, y3))) def test_multi_output_classification_partial_fit_parallelism(): sgd_linear_clf = SGDClassifier(loss='log', random_state=1) mor = MultiOutputClassifier(sgd_linear_clf, n_jobs=-1) mor.partial_fit(X, y, classes) est1 = mor.estimators_[0] mor.partial_fit(X, y) est2 = mor.estimators_[0] # parallelism requires this to be the case for a sane implementation assert_false(est1 is est2) def test_multi_output_classification_partial_fit(): # test if multi_target initializes correctly with base estimator and fit # assert predictions work as expected for predict sgd_linear_clf = SGDClassifier(loss='log', random_state=1) multi_target_linear = MultiOutputClassifier(sgd_linear_clf) # train the multi_target_linear and also get the predictions. half_index = X.shape[0] // 2 multi_target_linear.partial_fit( X[:half_index], y[:half_index], classes=classes) first_predictions = multi_target_linear.predict(X) assert_equal((n_samples, n_outputs), first_predictions.shape) multi_target_linear.partial_fit(X[half_index:], y[half_index:]) second_predictions = multi_target_linear.predict(X) assert_equal((n_samples, n_outputs), second_predictions.shape) # train the linear classification with each column and assert that # predictions are equal after first partial_fit and second partial_fit for i in range(3): # create a clone with the same state sgd_linear_clf = clone(sgd_linear_clf) sgd_linear_clf.partial_fit( X[:half_index], y[:half_index, i], classes=classes[i]) assert_array_equal(sgd_linear_clf.predict(X), first_predictions[:, i]) sgd_linear_clf.partial_fit(X[half_index:], y[half_index:, i]) assert_array_equal(sgd_linear_clf.predict(X), second_predictions[:, i]) def test_mutli_output_classifiation_partial_fit_no_first_classes_exception(): sgd_linear_clf = SGDClassifier(loss='log', random_state=1) multi_target_linear = MultiOutputClassifier(sgd_linear_clf) assert_raises_regex(ValueError, "classes must be passed on the first call " "to partial_fit.", multi_target_linear.partial_fit, X, y) def test_multi_output_classification(): # test if multi_target initializes correctly with base estimator and fit # assert predictions work as expected for predict, prodict_proba and score forest = RandomForestClassifier(n_estimators=10, random_state=1) multi_target_forest = MultiOutputClassifier(forest) # train the multi_target_forest and also get the predictions. multi_target_forest.fit(X, y) predictions = multi_target_forest.predict(X) assert_equal((n_samples, n_outputs), predictions.shape) predict_proba = multi_target_forest.predict_proba(X) assert len(predict_proba) == n_outputs for class_probabilities in predict_proba: assert_equal((n_samples, n_classes), class_probabilities.shape) assert_array_equal(np.argmax(np.dstack(predict_proba), axis=1), predictions) # train the forest with each column and assert that predictions are equal for i in range(3): forest_ = clone(forest) # create a clone with the same state forest_.fit(X, y[:, i]) assert_equal(list(forest_.predict(X)), list(predictions[:, i])) assert_array_equal(list(forest_.predict_proba(X)), list(predict_proba[i])) def test_multiclass_multioutput_estimator(): # test to check meta of meta estimators svc = LinearSVC(random_state=0) multi_class_svc = OneVsRestClassifier(svc) multi_target_svc = MultiOutputClassifier(multi_class_svc) multi_target_svc.fit(X, y) predictions = multi_target_svc.predict(X) assert_equal((n_samples, n_outputs), predictions.shape) # train the forest with each column and assert that predictions are equal for i in range(3): multi_class_svc_ = clone(multi_class_svc) # create a clone multi_class_svc_.fit(X, y[:, i]) assert_equal(list(multi_class_svc_.predict(X)), list(predictions[:, i])) def test_multiclass_multioutput_estimator_predict_proba(): seed = 542 # make test deterministic rng = np.random.RandomState(seed) # random features X = rng.normal(size=(5, 5)) # random labels y1 = np.array(['b', 'a', 'a', 'b', 'a']).reshape(5, 1) # 2 classes y2 = np.array(['d', 'e', 'f', 'e', 'd']).reshape(5, 1) # 3 classes Y = np.concatenate([y1, y2], axis=1) clf = MultiOutputClassifier(LogisticRegression(random_state=seed)) clf.fit(X, Y) y_result = clf.predict_proba(X) y_actual = [np.array([[0.23481764, 0.76518236], [0.67196072, 0.32803928], [0.54681448, 0.45318552], [0.34883923, 0.65116077], [0.73687069, 0.26312931]]), np.array([[0.5171785, 0.23878628, 0.24403522], [0.22141451, 0.64102704, 0.13755846], [0.16751315, 0.18256843, 0.64991843], [0.27357372, 0.55201592, 0.17441036], [0.65745193, 0.26062899, 0.08191907]])] for i in range(len(y_actual)): assert_almost_equal(y_result[i], y_actual[i]) def test_multi_output_classification_sample_weights(): # weighted classifier Xw = [[1, 2, 3], [4, 5, 6]] yw = [[3, 2], [2, 3]] w = np.asarray([2., 1.]) forest = RandomForestClassifier(n_estimators=10, random_state=1) clf_w = MultiOutputClassifier(forest) clf_w.fit(Xw, yw, w) # unweighted, but with repeated samples X = [[1, 2, 3], [1, 2, 3], [4, 5, 6]] y = [[3, 2], [3, 2], [2, 3]] forest = RandomForestClassifier(n_estimators=10, random_state=1) clf = MultiOutputClassifier(forest) clf.fit(X, y) X_test = [[1.5, 2.5, 3.5], [3.5, 4.5, 5.5]] assert_almost_equal(clf.predict(X_test), clf_w.predict(X_test)) def test_multi_output_classification_partial_fit_sample_weights(): # weighted classifier Xw = [[1, 2, 3], [4, 5, 6], [1.5, 2.5, 3.5]] yw = [[3, 2], [2, 3], [3, 2]] w = np.asarray([2., 1., 1.]) sgd_linear_clf = SGDClassifier(random_state=1) clf_w = MultiOutputClassifier(sgd_linear_clf) clf_w.fit(Xw, yw, w) # unweighted, but with repeated samples X = [[1, 2, 3], [1, 2, 3], [4, 5, 6], [1.5, 2.5, 3.5]] y = [[3, 2], [3, 2], [2, 3], [3, 2]] sgd_linear_clf = SGDClassifier(random_state=1) clf = MultiOutputClassifier(sgd_linear_clf) clf.fit(X, y) X_test = [[1.5, 2.5, 3.5]] assert_array_almost_equal(clf.predict(X_test), clf_w.predict(X_test)) def test_multi_output_exceptions(): # NotFittedError when fit is not done but score, predict and # and predict_proba are called moc = MultiOutputClassifier(LinearSVC(random_state=0)) assert_raises(NotFittedError, moc.predict, y) assert_raises(NotFittedError, moc.predict_proba, y) assert_raises(NotFittedError, moc.score, X, y) # ValueError when number of outputs is different # for fit and score y_new = np.column_stack((y1, y2)) moc.fit(X, y) assert_raises(ValueError, moc.score, X, y_new)
scikit-learn_scikit-learn
2017-01-26
9f6b849c3523faf2271dea105e4129cb1e1a1cb8
build_tools/circle/checkout_merge_commit.sh
29
#!/bin/bash # Add `master` branch to the update list. # Otherwise CircleCI will give us a cached one. FETCH_REFS="+master:master" # Update PR refs for testing. if [[ -n "${CIRCLE_PR_NUMBER}" ]] then FETCH_REFS="${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/head:pr/${CIRCLE_PR_NUMBER}/head" FETCH_REFS="${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/merge:pr/${CIRCLE_PR_NUMBER}/merge" fi # Retrieve the refs. git fetch -u origin ${FETCH_REFS} # Checkout the PR merge ref. if [[ -n "${CIRCLE_PR_NUMBER}" ]] then git checkout -qf "pr/${CIRCLE_PR_NUMBER}/merge" fi # Check for merge conflicts. if [[ -n "${CIRCLE_PR_NUMBER}" ]] then git branch --merged | grep master > /dev/null git branch --merged | grep "pr/${CIRCLE_PR_NUMBER}/head" > /dev/null fi
scikit-learn_scikit-learn
2017-01-26
9f6b849c3523faf2271dea105e4129cb1e1a1cb8
doc/sphinxext/sphinx_gallery/notebook.py
106
# -*- coding: utf-8 -*- r""" ============================ Parser for Jupyter notebooks ============================ Class that holds the Jupyter notebook information """ # Author: Óscar Nájera # License: 3-clause BSD from __future__ import division, absolute_import, print_function from functools import partial import argparse import json import re import sys from .py_source_parser import split_code_and_text_blocks def text2string(content): """Returns a string without the extra triple quotes""" try: return ast.literal_eval(content) + '\n' except Exception: return content + '\n' def jupyter_notebook_skeleton(): """Returns a dictionary with the elements of a Jupyter notebook""" py_version = sys.version_info notebook_skeleton = { "cells": [], "metadata": { "kernelspec": { "display_name": "Python " + str(py_version[0]), "language": "python", "name": "python" + str(py_version[0]) }, "language_info": { "codemirror_mode": { "name": "ipython", "version": py_version[0] }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython" + str(py_version[0]), "version": '{0}.{1}.{2}'.format(*sys.version_info[:3]) } }, "nbformat": 4, "nbformat_minor": 0 } return notebook_skeleton def directive_fun(match, directive): """Helper to fill in directives""" directive_to_alert = dict(note="info", warning="danger") return ('<div class="alert alert-{0}"><h4>{1}</h4><p>{2}</p></div>' .format(directive_to_alert[directive], directive.capitalize(), match.group(1).strip())) def rst2md(text): """Converts the RST text from the examples docstrigs and comments into markdown text for the Jupyter notebooks""" top_heading = re.compile(r'^=+$\s^([\w\s-]+)^=+$', flags=re.M) text = re.sub(top_heading, r'# \1', text) math_eq = re.compile(r'^\.\. math::((?:.+)?(?:\n+^ .+)*)', flags=re.M) text = re.sub(math_eq, lambda match: r'\begin{{align}}{0}\end{{align}}'.format( match.group(1).strip()), text) inline_math = re.compile(r':math:`(.+?)`', re.DOTALL) text = re.sub(inline_math, r'$\1$', text) directives = ('warning', 'note') for directive in directives: directive_re = re.compile(r'^\.\. %s::((?:.+)?(?:\n+^ .+)*)' % directive, flags=re.M) text = re.sub(directive_re, partial(directive_fun, directive=directive), text) links = re.compile(r'^ *\.\. _.*:.*$\n', flags=re.M) text = re.sub(links, '', text) refs = re.compile(r':ref:`') text = re.sub(refs, '`', text) contents = re.compile(r'^\s*\.\. contents::.*$(\n +:\S+: *$)*\n', flags=re.M) text = re.sub(contents, '', text) images = re.compile( r'^\.\. image::(.*$)(?:\n *:alt:(.*$)\n)?(?: +:\S+:.*$\n)*', flags=re.M) text = re.sub( images, lambda match: '![{1}]({0})\n'.format( match.group(1).strip(), (match.group(2) or '').strip()), text) return text def jupyter_notebook(script_blocks): """Generate a Jupyter notebook file cell-by-cell Parameters ---------- script_blocks: list script execution cells """ work_notebook = jupyter_notebook_skeleton() add_code_cell(work_notebook, "%matplotlib inline") fill_notebook(work_notebook, script_blocks) return work_notebook def add_code_cell(work_notebook, code): """Add a code cell to the notebook Parameters ---------- code : str Cell content """ code_cell = { "cell_type": "code", "execution_count": None, "metadata": {"collapsed": False}, "outputs": [], "source": [code.strip()] } work_notebook["cells"].append(code_cell) def add_markdown_cell(work_notebook, text): """Add a markdown cell to the notebook Parameters ---------- code : str Cell content """ markdown_cell = { "cell_type": "markdown", "metadata": {}, "source": [rst2md(text)] } work_notebook["cells"].append(markdown_cell) def fill_notebook(work_notebook, script_blocks): """Writes the Jupyter notebook cells Parameters ---------- script_blocks : list of tuples """ for blabel, bcontent in script_blocks: if blabel == 'code': add_code_cell(work_notebook, bcontent) else: add_markdown_cell(work_notebook, text2string(bcontent)) def save_notebook(work_notebook, write_file): """Saves the Jupyter work_notebook to write_file""" with open(write_file, 'w') as out_nb: json.dump(work_notebook, out_nb, indent=2) ############################################################################### # Notebook shell utility def python_to_jupyter_cli(args=None, namespace=None): """Exposes the jupyter notebook renderer to the command line Takes the same arguments as ArgumentParser.parse_args """ parser = argparse.ArgumentParser( description='Sphinx-Gallery Notebook converter') parser.add_argument('python_src_file', nargs='+', help='Input Python file script to convert. ' 'Supports multiple files and shell wildcards' ' (e.g. *.py)') args = parser.parse_args(args, namespace) for src_file in args.python_src_file: blocks = split_code_and_text_blocks(src_file) print('Converting {0}'.format(src_file)) example_nb = jupyter_notebook(blocks) save_notebook(example_nb, src_file.replace('.py', '.ipynb'))
scikit-learn_scikit-learn
2017-01-26
9f6b849c3523faf2271dea105e4129cb1e1a1cb8
doc/sphinxext/sphinx_gallery/py_source_parser.py
88
# -*- coding: utf-8 -*- r""" Parser for python source files ============================== """ # Created Sun Nov 27 14:03:07 2016 # Author: Óscar Nájera from __future__ import division, absolute_import, print_function import ast import re from textwrap import dedent def get_docstring_and_rest(filename): """Separate `filename` content between docstring and the rest Strongly inspired from ast.get_docstring. Returns ------- docstring: str docstring of `filename` rest: str `filename` content without the docstring """ # can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't # seem to work with unicode strings in Python2.7 # "SyntaxError: encoding declaration in Unicode string" with open(filename, 'rb') as f: content = f.read() # change from Windows format to UNIX for uniformity content = content.replace(b'\r\n', b'\n') node = ast.parse(content) if not isinstance(node, ast.Module): raise TypeError("This function only supports modules. " "You provided {0}".format(node.__class__.__name__)) if node.body and isinstance(node.body[0], ast.Expr) and \ isinstance(node.body[0].value, ast.Str): docstring_node = node.body[0] docstring = docstring_node.value.s if hasattr(docstring, 'decode'): # python2.7 docstring = docstring.decode('utf-8') # This get the content of the file after the docstring last line # Note: 'maxsplit' argument is not a keyword argument in python2 rest = content.decode('utf-8').split('\n', docstring_node.lineno)[-1] return docstring, rest else: raise ValueError(('Could not find docstring in file "{0}". ' 'A docstring is required by sphinx-gallery') .format(filename)) def split_code_and_text_blocks(source_file): """Return list with source file separated into code and text blocks. Returns ------- blocks : list of (label, content) List where each element is a tuple with the label ('text' or 'code'), and content string of block. """ docstring, rest_of_content = get_docstring_and_rest(source_file) blocks = [('text', docstring)] pattern = re.compile( r'(?P<header_line>^#{20,}.*)\s(?P<text_content>(?:^#.*\s)*)', flags=re.M) pos_so_far = 0 for match in re.finditer(pattern, rest_of_content): match_start_pos, match_end_pos = match.span() code_block_content = rest_of_content[pos_so_far:match_start_pos] text_content = match.group('text_content') sub_pat = re.compile('^#', flags=re.M) text_block_content = dedent(re.sub(sub_pat, '', text_content)).lstrip() if code_block_content.strip(): blocks.append(('code', code_block_content)) if text_block_content.strip(): blocks.append(('text', text_block_content)) pos_so_far = match_end_pos remaining_content = rest_of_content[pos_so_far:] if remaining_content.strip(): blocks.append(('code', remaining_content)) return blocks
scikit-learn_scikit-learn
2017-01-26
9f6b849c3523faf2271dea105e4129cb1e1a1cb8
doc/themes/scikit-learn/static/jquery.js
4
/*! jQuery v3.1.1 | (c) jQuery Foundation | jquery.org/license */ !function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.1.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c<b?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:h,sort:c.sort,splice:c.splice},r.extend=r.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||r.isFunction(g)||(g={}),h===i&&(g=this,h--);h<i;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(r.isPlainObject(d)||(e=r.isArray(d)))?(e?(e=!1,f=c&&r.isArray(c)?c:[]):f=c&&r.isPlainObject(c)?c:{},g[b]=r.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},r.extend({expando:"jQuery"+(q+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===r.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=r.type(a);return("number"===b||"string"===b)&&!isNaN(a-parseFloat(a))},isPlainObject:function(a){var b,c;return!(!a||"[object Object]"!==k.call(a))&&(!(b=e(a))||(c=l.call(b,"constructor")&&b.constructor,"function"==typeof c&&m.call(c)===n))},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?j[k.call(a)]||"object":typeof a},globalEval:function(a){p(a)},camelCase:function(a){return a.replace(t,"ms-").replace(u,v)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(w(a)){for(c=a.length;d<c;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(s,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(w(Object(a))?r.merge(c,"string"==typeof a?[a]:a):h.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:i.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;d<c;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;f<g;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,f=0,h=[];if(w(a))for(d=a.length;f<d;f++)e=b(a[f],f,c),null!=e&&h.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&h.push(e);return g.apply([],h)},guid:1,proxy:function(a,b){var c,d,e;if("string"==typeof b&&(c=a[b],b=a,a=c),r.isFunction(a))return d=f.call(arguments,2),e=function(){return a.apply(b||this,d.concat(f.call(arguments)))},e.guid=a.guid=a.guid||r.guid++,e},now:Date.now,support:o}),"function"==typeof Symbol&&(r.fn[Symbol.iterator]=c[Symbol.iterator]),r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){j["[object "+b+"]"]=b.toLowerCase()});function w(a){var b=!!a&&"length"in a&&a.length,c=r.type(a);return"function"!==c&&!r.isWindow(a)&&("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",M="\\["+K+"*("+L+")(?:"+K+"*([*^$|!~]?=)"+K+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+L+"))|)"+K+"*\\]",N=":("+L+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(K+"+","g"),P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c<b;c+=2)a.push(c);return a}),odd:pa(function(a,b){for(var c=1;c<b;c+=2)a.push(c);return a}),lt:pa(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function ra(){}ra.prototype=d.filters=d.pseudos,d.setFilters=new ra,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=Q.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function sa(a){for(var b=0,c=a.length,d="";b<c;b++)d+=a[b].value;return d}function ta(a,b,c){var d=b.dir,e=b.next,f=e||d,g=c&&"parentNode"===f,h=x++;return b.first?function(b,c,e){while(b=b[d])if(1===b.nodeType||g)return a(b,c,e);return!1}:function(b,c,i){var j,k,l,m=[w,h];if(i){while(b=b[d])if((1===b.nodeType||g)&&a(b,c,i))return!0}else while(b=b[d])if(1===b.nodeType||g)if(l=b[u]||(b[u]={}),k=l[b.uniqueID]||(l[b.uniqueID]={}),e&&e===b.nodeName.toLowerCase())b=b[d]||b;else{if((j=k[f])&&j[0]===w&&j[1]===h)return m[2]=j[2];if(k[f]=m,m[2]=a(b,c,i))return!0}return!1}}function ua(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d<e;d++)ga(a,b[d],c);return c}function wa(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;h<i;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function xa(a,b,c,d,e,f){return d&&!d[u]&&(d=xa(d)),e&&!e[u]&&(e=xa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||va(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:wa(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=wa(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i<f;i++)if(c=d.relative[a[i].type])m=[ta(ua(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;e<f;e++)if(d.relative[a[e].type])break;return xa(i>1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i<e&&ya(a.slice(i,e)),e<f&&ya(a=a.slice(e)),e<f&&sa(a))}m.push(c)}return ua(m)}function za(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext,B=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,C=/^.[^:#\[\.,]*$/;function D(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):C.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b<d;b++)if(r.contains(e[b],this))return!0}));for(c=this.pushStack([]),b=0;b<d;b++)r.find(a,e[b],c);return d>1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(D(this,a||[],!1))},not:function(a){return this.pushStack(D(this,a||[],!0))},is:function(a){return!!D(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var E,F=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,G=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||E,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:F.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),B.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};G.prototype=r.fn,E=r(d);var H=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a<c;a++)if(r.contains(this,b[a]))return!0})},closest:function(a,b){var c,d=0,e=this.length,f=[],g="string"!=typeof a&&r(a);if(!A.test(a))for(;d<e;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function J(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return J(a,"nextSibling")},prev:function(a){return J(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return a.contentDocument||r.merge([],a.childNodes)}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(I[a]||r.uniqueSort(e),H.test(a)&&e.reverse()),this.pushStack(e)}});var K=/[^\x20\t\r\n\f]+/g;function L(a){var b={};return r.each(a.match(K)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?L(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){r.each(b,function(b,c){r.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==r.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return r.each(arguments,function(a,b){var c;while((c=r.inArray(b,f,c))>-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function M(a){return a}function N(a){throw a}function O(a,b,c){var d;try{a&&r.isFunction(d=a.promise)?d.call(a).done(b).fail(c):a&&r.isFunction(d=a.then)?d.call(a,b,c):b.call(void 0,a)}catch(a){c.call(void 0,a)}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b<f)){if(a=d.apply(h,i),a===c.promise())throw new TypeError("Thenable self-resolution");j=a&&("object"==typeof a||"function"==typeof a)&&a.then,r.isFunction(j)?e?j.call(a,g(f,c,M,e),g(f,c,N,e)):(f++,j.call(a,g(f,c,M,e),g(f,c,N,e),g(f,c,M,c.notifyWith))):(d!==M&&(h=void 0,i=[a]),(e||c.resolveWith)(h,i))}},k=e?j:function(){try{j()}catch(a){r.Deferred.exceptionHook&&r.Deferred.exceptionHook(a,k.stackTrace),b+1>=f&&(d!==N&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:M,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:M)),c[2][3].add(g(0,a,r.isFunction(d)?d:N))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(O(a,g.done(h(c)).resolve,g.reject),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)O(e[c],h(c),g.reject);return g.promise()}});var P=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&P.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var Q=r.Deferred();r.fn.ready=function(a){return Q.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,holdReady:function(a){a?r.readyWait++:r.ready(!0)},ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||Q.resolveWith(d,[r]))}}),r.ready.then=Q.then;function R(){d.removeEventListener("DOMContentLoaded",R), a.removeEventListener("load",R),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",R),a.addEventListener("load",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h<i;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},T=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function U(){this.expando=r.expando+U.uid++}U.uid=1,U.prototype={cache:function(a){var b=a[this.expando];return b||(b={},T(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[r.camelCase(b)]=c;else for(d in b)e[r.camelCase(d)]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][r.camelCase(b)]},access:function(a,b,c){return void 0===b||b&&"string"==typeof b&&void 0===c?this.get(a,b):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d=a[this.expando];if(void 0!==d){if(void 0!==b){r.isArray(b)?b=b.map(r.camelCase):(b=r.camelCase(b),b=b in d?[b]:b.match(K)||[]),c=b.length;while(c--)delete d[b[c]]}(void 0===b||r.isEmptyObject(d))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!r.isEmptyObject(b)}};var V=new U,W=new U,X=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Y=/[A-Z]/g;function Z(a){return"true"===a||"false"!==a&&("null"===a?null:a===+a+""?+a:X.test(a)?JSON.parse(a):a)}function $(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Y,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c=Z(c)}catch(e){}W.set(a,b,c)}else c=void 0;return c}r.extend({hasData:function(a){return W.hasData(a)||V.hasData(a)},data:function(a,b,c){return W.access(a,b,c)},removeData:function(a,b){W.remove(a,b)},_data:function(a,b,c){return V.access(a,b,c)},_removeData:function(a,b){V.remove(a,b)}}),r.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=W.get(f),1===f.nodeType&&!V.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=r.camelCase(d.slice(5)),$(f,d,e[d])));V.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){W.set(this,a)}):S(this,function(b){var c;if(f&&void 0===b){if(c=W.get(f,a),void 0!==c)return c;if(c=$(f,a),void 0!==c)return c}else this.each(function(){W.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks("once memory").add(function(){V.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?r.queue(this[0],a):void 0===b?this:this.each(function(){var c=r.queue(this,a,b);r._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&r.dequeue(this,a)})},dequeue:function(a){return this.each(function(){r.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=r.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=V.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var _=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,aa=new RegExp("^(?:([+-])=|)("+_+")([a-z%]*)$","i"),ba=["Top","Right","Bottom","Left"],ca=function(a,b){return a=b||a,"none"===a.style.display||""===a.style.display&&r.contains(a.ownerDocument,a)&&"none"===r.css(a,"display")},da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};function ea(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return r.css(a,b,"")},i=h(),j=c&&c[3]||(r.cssNumber[b]?"":"px"),k=(r.cssNumber[b]||"px"!==j&&+i)&&aa.exec(r.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,r.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var fa={};function ga(a){var b,c=a.ownerDocument,d=a.nodeName,e=fa[d];return e?e:(b=c.body.appendChild(c.createElement(d)),e=r.css(b,"display"),b.parentNode.removeChild(b),"none"===e&&(e="block"),fa[d]=e,e)}function ha(a,b){for(var c,d,e=[],f=0,g=a.length;f<g;f++)d=a[f],d.style&&(c=d.style.display,b?("none"===c&&(e[f]=V.get(d,"display")||null,e[f]||(d.style.display="")),""===d.style.display&&ca(d)&&(e[f]=ga(d))):"none"!==c&&(e[f]="none",V.set(d,"display",c)));for(f=0;f<g;f++)null!=e[f]&&(a[f].style.display=e[f]);return a}r.fn.extend({show:function(){return ha(this,!0)},hide:function(){return ha(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){ca(this)?r(this).show():r(this).hide()})}});var ia=/^(?:checkbox|radio)$/i,ja=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,ka=/^$|\/(?:java|ecma)script/i,la={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};la.optgroup=la.option,la.tbody=la.tfoot=la.colgroup=la.caption=la.thead,la.th=la.td;function ma(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&r.nodeName(a,b)?r.merge([a],c):c}function na(a,b){for(var c=0,d=a.length;c<d;c++)V.set(a[c],"globalEval",!b||V.get(b[c],"globalEval"))}var oa=/<|&#?\w+;/;function pa(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],n=0,o=a.length;n<o;n++)if(f=a[n],f||0===f)if("object"===r.type(f))r.merge(m,f.nodeType?[f]:f);else if(oa.test(f)){g=g||l.appendChild(b.createElement("div")),h=(ja.exec(f)||["",""])[1].toLowerCase(),i=la[h]||la._default,g.innerHTML=i[1]+r.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;r.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",n=0;while(f=m[n++])if(d&&r.inArray(f,d)>-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=ma(l.appendChild(f),"script"),j&&na(g),c){k=0;while(f=g[k++])ka.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var qa=d.documentElement,ra=/^key/,sa=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ta=/^([^.]*)(?:\.(.+)|)/;function ua(){return!0}function va(){return!1}function wa(){try{return d.activeElement}catch(a){}}function xa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)xa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=va;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(qa,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(K)||[""],j=b.length;while(j--)h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.hasData(a)&&V.get(a);if(q&&(i=q.events)){b=(b||"").match(K)||[""],j=b.length;while(j--)if(h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&V.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(V.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c<arguments.length;c++)i[c]=arguments[c];if(b.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,b)!==!1){h=r.event.handlers.call(this,b,j),c=0;while((f=h[c++])&&!b.isPropagationStopped()){b.currentTarget=f.elem,d=0;while((g=f.handlers[d++])&&!b.isImmediatePropagationStopped())b.rnamespace&&!b.rnamespace.test(g.namespace)||(b.handleObj=g,b.data=g.data,e=((r.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(b.result=e)===!1&&(b.preventDefault(),b.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,b),b.result}},handlers:function(a,b){var c,d,e,f,g,h=[],i=b.delegateCount,j=a.target;if(i&&j.nodeType&&!("click"===a.type&&a.button>=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c<i;c++)d=b[c],e=d.selector+" ",void 0===g[e]&&(g[e]=d.needsContext?r(e,this).index(j)>-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i<b.length&&h.push({elem:j,handlers:b.slice(i)}),h},addProp:function(a,b){Object.defineProperty(r.Event.prototype,a,{enumerable:!0,configurable:!0,get:r.isFunction(b)?function(){if(this.originalEvent)return b(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[a]},set:function(b){Object.defineProperty(this,a,{enumerable:!0,configurable:!0,writable:!0,value:b})}})},fix:function(a){return a[r.expando]?a:new r.Event(a)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==wa()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===wa()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&r.nodeName(this,"input"))return this.click(),!1},_default:function(a){return r.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},r.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},r.Event=function(a,b){return this instanceof r.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ua:va,this.target=a.target&&3===a.target.nodeType?a.target.parentNode:a.target,this.currentTarget=a.currentTarget,this.relatedTarget=a.relatedTarget):this.type=a,b&&r.extend(this,b),this.timeStamp=a&&a.timeStamp||r.now(),void(this[r.expando]=!0)):new r.Event(a,b)},r.Event.prototype={constructor:r.Event,isDefaultPrevented:va,isPropagationStopped:va,isImmediatePropagationStopped:va,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ua,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ua,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ua,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},r.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(a){var b=a.button;return null==a.which&&ra.test(a.type)?null!=a.charCode?a.charCode:a.keyCode:!a.which&&void 0!==b&&sa.test(a.type)?1&b?1:2&b?3:4&b?2:0:a.which}},r.event.addProp),r.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){r.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||r.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),r.fn.extend({on:function(a,b,c,d){return xa(this,a,b,c,d)},one:function(a,b,c,d){return xa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,r(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=va),this.each(function(){r.event.remove(this,a,c,b)})}});var ya=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,za=/<script|<style|<link/i,Aa=/checked\s*(?:[^=]|=\s*.checked.)/i,Ba=/^true\/(.*)/,Ca=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Da(a,b){return r.nodeName(a,"table")&&r.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a:a}function Ea(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Fa(a){var b=Ba.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ga(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(V.hasData(a)&&(f=V.access(a),g=V.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c<d;c++)r.event.add(b,e,j[e][c])}W.hasData(a)&&(h=W.access(a),i=r.extend({},h),W.set(b,i))}}function Ha(a,b){var c=b.nodeName.toLowerCase();"input"===c&&ia.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function Ia(a,b,c,d){b=g.apply([],b);var e,f,h,i,j,k,l=0,m=a.length,n=m-1,q=b[0],s=r.isFunction(q);if(s||m>1&&"string"==typeof q&&!o.checkClone&&Aa.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ia(f,b,c,d)});if(m&&(e=pa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(ma(e,"script"),Ea),i=h.length;l<m;l++)j=e,l!==n&&(j=r.clone(j,!0,!0),i&&r.merge(h,ma(j,"script"))),c.call(a[l],j,l);if(i)for(k=h[h.length-1].ownerDocument,r.map(h,Fa),l=0;l<i;l++)j=h[l],ka.test(j.type||"")&&!V.access(j,"globalEval")&&r.contains(k,j)&&(j.src?r._evalUrl&&r._evalUrl(j.src):p(j.textContent.replace(Ca,""),k))}return a}function Ja(a,b,c){for(var d,e=b?r.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||r.cleanData(ma(d)),d.parentNode&&(c&&r.contains(d.ownerDocument,d)&&na(ma(d,"script")),d.parentNode.removeChild(d));return a}r.extend({htmlPrefilter:function(a){return a.replace(ya,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=ma(h),f=ma(a),d=0,e=f.length;d<e;d++)Ha(f[d],g[d]);if(b)if(c)for(f=f||ma(a),g=g||ma(h),d=0,e=f.length;d<e;d++)Ga(f[d],g[d]);else Ga(a,h);return g=ma(h,"script"),g.length>0&&na(g,!i&&ma(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(T(c)){if(b=c[V.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[V.expando]=void 0}c[W.expando]&&(c[W.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ja(this,a,!0)},remove:function(a){return Ja(this,a)},text:function(a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.appendChild(a)}})},prepend:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(ma(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return S(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!za.test(a)&&!la[(ja.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c<d;c++)b=this[c]||{},1===b.nodeType&&(r.cleanData(ma(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ia(this,arguments,function(b){var c=this.parentNode;r.inArray(this,a)<0&&(r.cleanData(ma(this)),c&&c.replaceChild(b,this))},a)}}),r.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){r.fn[a]=function(a){for(var c,d=[],e=r(a),f=e.length-1,g=0;g<=f;g++)c=g===f?this:this.clone(!0),r(e[g])[b](c),h.apply(d,c.get());return this.pushStack(d)}});var Ka=/^margin/,La=new RegExp("^("+_+")(?!px)[a-z%]+$","i"),Ma=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)};!function(){function b(){if(i){i.style.cssText="box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",i.innerHTML="",qa.appendChild(h);var b=a.getComputedStyle(i);c="1%"!==b.top,g="2px"===b.marginLeft,e="4px"===b.width,i.style.marginRight="50%",f="4px"===b.marginRight,qa.removeChild(h),i=null}}var c,e,f,g,h=d.createElement("div"),i=d.createElement("div");i.style&&(i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",o.clearCloneStyle="content-box"===i.style.backgroundClip,h.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",h.appendChild(i),r.extend(o,{pixelPosition:function(){return b(),c},boxSizingReliable:function(){return b(),e},pixelMarginRight:function(){return b(),f},reliableMarginLeft:function(){return b(),g}}))}();function Na(a,b,c){var d,e,f,g,h=a.style;return c=c||Ma(a),c&&(g=c.getPropertyValue(b)||c[b],""!==g||r.contains(a.ownerDocument,a)||(g=r.style(a,b)),!o.pixelMarginRight()&&La.test(g)&&Ka.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function Oa(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Pa=/^(none|table(?!-c[ea]).+)/,Qa={position:"absolute",visibility:"hidden",display:"block"},Ra={letterSpacing:"0",fontWeight:"400"},Sa=["Webkit","Moz","ms"],Ta=d.createElement("div").style;function Ua(a){if(a in Ta)return a;var b=a[0].toUpperCase()+a.slice(1),c=Sa.length;while(c--)if(a=Sa[c]+b,a in Ta)return a}function Va(a,b,c){var d=aa.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Wa(a,b,c,d,e){var f,g=0;for(f=c===(d?"border":"content")?4:"width"===b?1:0;f<4;f+=2)"margin"===c&&(g+=r.css(a,c+ba[f],!0,e)),d?("content"===c&&(g-=r.css(a,"padding"+ba[f],!0,e)),"margin"!==c&&(g-=r.css(a,"border"+ba[f]+"Width",!0,e))):(g+=r.css(a,"padding"+ba[f],!0,e),"padding"!==c&&(g+=r.css(a,"border"+ba[f]+"Width",!0,e)));return g}function Xa(a,b,c){var d,e=!0,f=Ma(a),g="border-box"===r.css(a,"boxSizing",!1,f);if(a.getClientRects().length&&(d=a.getBoundingClientRect()[b]),d<=0||null==d){if(d=Na(a,b,f),(d<0||null==d)&&(d=a.style[b]),La.test(d))return d;e=g&&(o.boxSizingReliable()||d===a.style[b]),d=parseFloat(d)||0}return d+Wa(a,b,c||(g?"border":"content"),e,f)+"px"}r.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Na(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=r.camelCase(b),i=a.style;return b=r.cssProps[h]||(r.cssProps[h]=Ua(h)||h),g=r.cssHooks[b]||r.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=aa.exec(c))&&e[1]&&(c=ea(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(r.cssNumber[h]?"":"px")),o.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=r.camelCase(b);return b=r.cssProps[h]||(r.cssProps[h]=Ua(h)||h),g=r.cssHooks[b]||r.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Na(a,b,d)),"normal"===e&&b in Ra&&(e=Ra[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),r.each(["height","width"],function(a,b){r.cssHooks[b]={get:function(a,c,d){if(c)return!Pa.test(r.css(a,"display"))||a.getClientRects().length&&a.getBoundingClientRect().width?Xa(a,b,d):da(a,Qa,function(){return Xa(a,b,d)})},set:function(a,c,d){var e,f=d&&Ma(a),g=d&&Wa(a,b,d,"border-box"===r.css(a,"boxSizing",!1,f),f);return g&&(e=aa.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=r.css(a,b)),Va(a,c,g)}}}),r.cssHooks.marginLeft=Oa(o.reliableMarginLeft,function(a,b){if(b)return(parseFloat(Na(a,"marginLeft"))||a.getBoundingClientRect().left-da(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px"}),r.each({margin:"",padding:"",border:"Width"},function(a,b){r.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];d<4;d++)e[a+ba[d]+b]=f[d]||f[d-2]||f[0];return e}},Ka.test(a)||(r.cssHooks[a+b].set=Va)}),r.fn.extend({css:function(a,b){return S(this,function(a,b,c){var d,e,f={},g=0;if(r.isArray(b)){for(d=Ma(a),e=b.length;g<e;g++)f[b[g]]=r.css(a,b[g],!1,d);return f}return void 0!==c?r.style(a,b,c):r.css(a,b)},a,b,arguments.length>1)}});function Ya(a,b,c,d,e){return new Ya.prototype.init(a,b,c,d,e)}r.Tween=Ya,Ya.prototype={constructor:Ya,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=Ya.propHooks[this.prop];return a&&a.get?a.get(this):Ya.propHooks._default.get(this)},run:function(a){var b,c=Ya.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ya.propHooks._default.set(this),this}},Ya.prototype.init.prototype=Ya.prototype,Ya.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},Ya.propHooks.scrollTop=Ya.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=Ya.prototype.init,r.fx.step={};var Za,$a,_a=/^(?:toggle|show|hide)$/,ab=/queueHooks$/;function bb(){$a&&(a.requestAnimationFrame(bb),r.fx.tick())}function cb(){return a.setTimeout(function(){Za=void 0}),Za=r.now()}function db(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ba[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function eb(a,b,c){for(var d,e=(hb.tweeners[b]||[]).concat(hb.tweeners["*"]),f=0,g=e.length;f<g;f++)if(d=e[f].call(c,b,a))return d}function fb(a,b,c){var d,e,f,g,h,i,j,k,l="width"in b||"height"in b,m=this,n={},o=a.style,p=a.nodeType&&ca(a),q=V.get(a,"fxshow");c.queue||(g=r._queueHooks(a,"fx"),null==g.unqueued&&(g.unqueued=0,h=g.empty.fire,g.empty.fire=function(){g.unqueued||h()}),g.unqueued++,m.always(function(){m.always(function(){g.unqueued--,r.queue(a,"fx").length||g.empty.fire()})}));for(d in b)if(e=b[d],_a.test(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||r.style(a,d)}if(i=!r.isEmptyObject(b),i||!r.isEmptyObject(n)){l&&1===a.nodeType&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=q&&q.display,null==j&&(j=V.get(a,"display")),k=r.css(a,"display"),"none"===k&&(j?k=j:(ha([a],!0),j=a.style.display||j,k=r.css(a,"display"),ha([a]))),("inline"===k||"inline-block"===k&&null!=j)&&"none"===r.css(a,"float")&&(i||(m.done(function(){o.display=j}),null==j&&(k=o.display,j="none"===k?"":k)),o.display="inline-block")),c.overflow&&(o.overflow="hidden",m.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]})),i=!1;for(d in n)i||(q?"hidden"in q&&(p=q.hidden):q=V.access(a,"fxshow",{display:j}),f&&(q.hidden=!p),p&&ha([a],!0),m.done(function(){p||ha([a]),V.remove(a,"fxshow");for(d in n)r.style(a,d,n[d])})),i=eb(p?q[d]:0,d,m),d in q||(q[d]=i.start,p&&(i.end=i.start,i.start=0))}}function gb(a,b){var c,d,e,f,g;for(c in a)if(d=r.camelCase(c),e=b[d],f=a[c],r.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=r.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function hb(a,b,c){var d,e,f=0,g=hb.prefilters.length,h=r.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Za||cb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;g<i;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),f<1&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:r.extend({},b),opts:r.extend(!0,{specialEasing:{},easing:r.easing._default},c),originalProperties:b,originalOptions:c,startTime:Za||cb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=r.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;c<d;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(gb(k,j.opts.specialEasing);f<g;f++)if(d=hb.prefilters[f].call(j,a,k,j.opts))return r.isFunction(d.stop)&&(r._queueHooks(j.elem,j.opts.queue).stop=r.proxy(d.stop,d)),d;return r.map(k,eb,j),r.isFunction(j.opts.start)&&j.opts.start.call(a,j),r.fx.timer(r.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}r.Animation=r.extend(hb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return ea(c.elem,a,aa.exec(b),c),c}]},tweener:function(a,b){r.isFunction(a)?(b=a,a=["*"]):a=a.match(K);for(var c,d=0,e=a.length;d<e;d++)c=a[d],hb.tweeners[c]=hb.tweeners[c]||[],hb.tweeners[c].unshift(b)},prefilters:[fb],prefilter:function(a,b){b?hb.prefilters.unshift(a):hb.prefilters.push(a)}}),r.speed=function(a,b,c){var e=a&&"object"==typeof a?r.extend({},a):{complete:c||!c&&b||r.isFunction(a)&&a,duration:a,easing:c&&b||b&&!r.isFunction(b)&&b};return r.fx.off||d.hidden?e.duration=0:"number"!=typeof e.duration&&(e.duration in r.fx.speeds?e.duration=r.fx.speeds[e.duration]:e.duration=r.fx.speeds._default),null!=e.queue&&e.queue!==!0||(e.queue="fx"),e.old=e.complete,e.complete=function(){r.isFunction(e.old)&&e.old.call(this),e.queue&&r.dequeue(this,e.queue)},e},r.fn.extend({fadeTo:function(a,b,c,d){return this.filter(ca).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=r.isEmptyObject(a),f=r.speed(b,c,d),g=function(){var b=hb(this,r.extend({},a),f);(e||V.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=r.timers,g=V.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&ab.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||r.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=V.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=r.timers,g=d?d.length:0;for(c.finish=!0,r.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;b<g;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),r.each(["toggle","show","hide"],function(a,b){var c=r.fn[b];r.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(db(b,!0),a,d,e)}}),r.each({slideDown:db("show"),slideUp:db("hide"),slideToggle:db("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){r.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),r.timers=[],r.fx.tick=function(){var a,b=0,c=r.timers;for(Za=r.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||r.fx.stop(),Za=void 0},r.fx.timer=function(a){r.timers.push(a),a()?r.fx.start():r.timers.pop()},r.fx.interval=13,r.fx.start=function(){$a||($a=a.requestAnimationFrame?a.requestAnimationFrame(bb):a.setInterval(r.fx.tick,r.fx.interval))},r.fx.stop=function(){a.cancelAnimationFrame?a.cancelAnimationFrame($a):a.clearInterval($a),$a=null},r.fx.speeds={slow:600,fast:200,_default:400},r.fn.delay=function(b,c){return b=r.fx?r.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",o.checkOn=""!==a.value,o.optSelected=c.selected,a=d.createElement("input"),a.value="t",a.type="radio",o.radioValue="t"===a.value}();var ib,jb=r.expr.attrHandle;r.fn.extend({attr:function(a,b){return S(this,r.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?ib:void 0)), void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&r.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),ib={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=jb[b]||r.find.attr;jb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=jb[g],jb[g]=e,e=null!=c(a,b,d)?g:null,jb[g]=f),e}});var kb=/^(?:input|select|textarea|button)$/i,lb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):kb.test(a.nodeName)||lb.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function mb(a){var b=a.match(K)||[];return b.join(" ")}function nb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,nb(this)))});if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,nb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,nb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=nb(this),b&&V.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":V.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+mb(nb(c))+" ").indexOf(b)>-1)return!0;return!1}});var ob=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":r.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(ob,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:mb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d<i;d++)if(c=e[d],(c.selected||d===f)&&!c.disabled&&(!c.parentNode.disabled||!r.nodeName(c.parentNode,"optgroup"))){if(b=r(c).val(),g)return b;h.push(b)}return h},set:function(a,b){var c,d,e=a.options,f=r.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=r.inArray(r.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(r.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!pb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,pb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(V.get(h,"events")||{})[b.type]&&V.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&T(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!T(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=V.access(d,b);e||d.addEventListener(a,c,!0),V.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=V.access(d,b)-1;e?V.access(d,b,e):(d.removeEventListener(a,c,!0),V.remove(d,b))}}});var qb=a.location,rb=r.now(),sb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var tb=/\[\]$/,ub=/\r?\n/g,vb=/^(?:submit|button|image|reset|file)$/i,wb=/^(?:input|select|textarea|keygen)/i;function xb(a,b,c,d){var e;if(r.isArray(b))r.each(b,function(b,e){c||tb.test(a)?d(a,e):xb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)xb(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(r.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)xb(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&wb.test(this.nodeName)&&!vb.test(a)&&(this.checked||!ia.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:r.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(ub,"\r\n")}}):{name:b.name,value:c.replace(ub,"\r\n")}}).get()}});var yb=/%20/g,zb=/#.*$/,Ab=/([?&])_=[^&]*/,Bb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Cb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Db=/^(?:GET|HEAD)$/,Eb=/^\/\//,Fb={},Gb={},Hb="*/".concat("*"),Ib=d.createElement("a");Ib.href=qb.href;function Jb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(K)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Kb(a,b,c,d){var e={},f=a===Gb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Lb(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Mb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Nb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qb.href,type:"GET",isLocal:Cb.test(qb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Hb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Lb(Lb(a,r.ajaxSettings),b):Lb(r.ajaxSettings,a)},ajaxPrefilter:Jb(Fb),ajaxTransport:Jb(Gb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Bb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||qb.href)+"").replace(Eb,qb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(K)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Ib.protocol+"//"+Ib.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Kb(Fb,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Db.test(o.type),f=o.url.replace(zb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(yb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(sb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Ab,"$1"),n=(sb.test(f)?"&":"?")+"_="+rb++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Hb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Kb(Gb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Mb(o,y,d)),v=Nb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Ob={0:200,1223:204},Pb=r.ajaxSettings.xhr();o.cors=!!Pb&&"withCredentials"in Pb,o.ajax=Pb=!!Pb,r.ajaxTransport(function(b){var c,d;if(o.cors||Pb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Ob[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Qb=[],Rb=/(=)\?(?=&|$)|\?\?/;r.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Qb.pop()||r.expando+"_"+rb++;return this[a]=!0,a}}),r.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Rb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Rb.test(b.data)&&"data");if(h||"jsonp"===b.dataTypes[0])return e=b.jsonpCallback=r.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Rb,"$1"+e):b.jsonp!==!1&&(b.url+=(sb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||r.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?r(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Qb.push(e)),g&&r.isFunction(f)&&f(g[0]),g=f=void 0}),"script"}),o.createHTMLDocument=function(){var a=d.implementation.createHTMLDocument("").body;return a.innerHTML="<form></form><form></form>",2===a.childNodes.length}(),r.parseHTML=function(a,b,c){if("string"!=typeof a)return[];"boolean"==typeof b&&(c=b,b=!1);var e,f,g;return b||(o.createHTMLDocument?(b=d.implementation.createHTMLDocument(""),e=b.createElement("base"),e.href=d.location.href,b.head.appendChild(e)):b=d),f=B.exec(a),g=!c&&[],f?[b.createElement(f[1])]:(f=pa([a],b,g),g&&g.length&&r(g).remove(),r.merge([],f.childNodes))},r.fn.load=function(a,b,c){var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=mb(a.slice(h)),a=a.slice(0,h)),r.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&r.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?r("<div>").append(r.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},r.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){r.fn[b]=function(a){return this.on(b,a)}}),r.expr.pseudos.animated=function(a){return r.grep(r.timers,function(b){return a===b.elem}).length};function Sb(a){return r.isWindow(a)?a:9===a.nodeType&&a.defaultView}r.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=r.css(a,"position"),l=r(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=r.css(a,"top"),i=r.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),r.isFunction(b)&&(b=b.call(a,c,r.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},r.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){r.offset.setOffset(this,a,b)});var b,c,d,e,f=this[0];if(f)return f.getClientRects().length?(d=f.getBoundingClientRect(),d.width||d.height?(e=f.ownerDocument,c=Sb(e),b=e.documentElement,{top:d.top+c.pageYOffset-b.clientTop,left:d.left+c.pageXOffset-b.clientLeft}):d):{top:0,left:0}},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===r.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),r.nodeName(a[0],"html")||(d=a.offset()),d={top:d.top+r.css(a[0],"borderTopWidth",!0),left:d.left+r.css(a[0],"borderLeftWidth",!0)}),{top:b.top-d.top-r.css(c,"marginTop",!0),left:b.left-d.left-r.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===r.css(a,"position"))a=a.offsetParent;return a||qa})}}),r.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;r.fn[a]=function(d){return S(this,function(a,d,e){var f=Sb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),r.each(["top","left"],function(a,b){r.cssHooks[b]=Oa(o.pixelPosition,function(a,c){if(c)return c=Na(a,b),La.test(c)?r(a).position()[b]+"px":c})}),r.each({Height:"height",Width:"width"},function(a,b){r.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){r.fn[d]=function(e,f){var g=arguments.length&&(c||"boolean"!=typeof e),h=c||(e===!0||f===!0?"margin":"border");return S(this,function(b,c,e){var f;return r.isWindow(b)?0===d.indexOf("outer")?b["inner"+a]:b.document.documentElement["client"+a]:9===b.nodeType?(f=b.documentElement,Math.max(b.body["scroll"+a],f["scroll"+a],b.body["offset"+a],f["offset"+a],f["client"+a])):void 0===e?r.css(b,c,h):r.style(b,c,e,h)},b,g?e:void 0,g)}})}),r.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),r.parseJSON=JSON.parse,"function"==typeof define&&define.amd&&define("jquery",[],function(){return r});var Tb=a.jQuery,Ub=a.$;return r.noConflict=function(b){return a.$===r&&(a.$=Ub),b&&a.jQuery===r&&(a.jQuery=Tb),r},b||(a.jQuery=a.$=r),r});
scikit-learn_scikit-learn
2017-01-26
9f6b849c3523faf2271dea105e4129cb1e1a1cb8
src/platforms/weex/framework.js
416
import TextNode from 'weex/runtime/text-node' // this will be preserved during build const VueFactory = require('./factory') const instances = {} const modules = {} const components = {} const renderer = { TextNode, instances, modules, components } /** * Prepare framework config, basically about the virtual-DOM and JS bridge. * @param {object} cfg */ export function init (cfg) { renderer.Document = cfg.Document renderer.Element = cfg.Element renderer.Comment = cfg.Comment renderer.sendTasks = cfg.sendTasks } /** * Reset framework config and clear all registrations. */ export function reset () { clear(instances) clear(modules) clear(components) delete renderer.Document delete renderer.Element delete renderer.Comment delete renderer.sendTasks } /** * Delete all keys of an object. * @param {object} obj */ function clear (obj) { for (const key in obj) { delete obj[key] } } /** * Create an instance with id, code, config and external data. * @param {string} instanceId * @param {string} appCode * @param {object} config * @param {object} data * @param {object} env { info, config, services } */ export function createInstance ( instanceId, appCode = '', config = {}, data, env = {} ) { // Virtual-DOM object. const document = new renderer.Document(instanceId, config.bundleUrl) // All function/callback of parameters before sent to native // will be converted as an id. So `callbacks` is used to store // these real functions. When a callback invoked and won't be // called again, it should be removed from here automatically. const callbacks = [] // The latest callback id, incremental. const callbackId = 1 const instance = instances[instanceId] = { instanceId, config, data, document, callbacks, callbackId } // Prepare native module getter and HTML5 Timer APIs. const moduleGetter = genModuleGetter(instanceId) const timerAPIs = getInstanceTimer(instanceId, moduleGetter) // Prepare `weex` instance variable. const weexInstanceVar = { config, document, requireModule: moduleGetter } Object.freeze(weexInstanceVar) // Each instance has a independent `Vue` mdoule instance const Vue = instance.Vue = createVueModuleInstance(instanceId, moduleGetter) // The function which create a closure the JS Bundle will run in. // It will declare some instance variables like `Vue`, HTML5 Timer APIs etc. const instanceVars = Object.assign({ Vue, weex: weexInstanceVar, __weex_require_module__: weexInstanceVar.requireModule // deprecated }, timerAPIs) callFunction(instanceVars, appCode) // Send `createFinish` signal to native. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'createFinish', args: [] }], -1) } /** * Destroy an instance with id. It will make sure all memory of * this instance released and no more leaks. * @param {string} instanceId */ export function destroyInstance (instanceId) { const instance = instances[instanceId] if (instance && instance.app instanceof instance.Vue) { instance.app.$destroy() } delete instances[instanceId] } /** * Refresh an instance with id and new top-level component data. * It will use `Vue.set` on all keys of the new data. So it's better * define all possible meaningful keys when instance created. * @param {string} instanceId * @param {object} data */ export function refreshInstance (instanceId, data) { const instance = instances[instanceId] if (!instance || !(instance.app instanceof instance.Vue)) { return new Error(`refreshInstance: instance ${instanceId} not found!`) } for (const key in data) { instance.Vue.set(instance.app, key, data[key]) } // Finally `refreshFinish` signal needed. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'refreshFinish', args: [] }], -1) } /** * Get the JSON object of the root element. * @param {string} instanceId */ export function getRoot (instanceId) { const instance = instances[instanceId] if (!instance || !(instance.app instanceof instance.Vue)) { return new Error(`getRoot: instance ${instanceId} not found!`) } return instance.app.$el.toJSON() } /** * Receive tasks from native. Generally there are two types of tasks: * 1. `fireEvent`: an device actions or user actions from native. * 2. `callback`: invoke function which sent to native as a parameter before. * @param {string} instanceId * @param {array} tasks */ export function receiveTasks (instanceId, tasks) { const instance = instances[instanceId] if (!instance || !(instance.app instanceof instance.Vue)) { return new Error(`receiveTasks: instance ${instanceId} not found!`) } const { callbacks, document } = instance tasks.forEach(task => { // `fireEvent` case: find the event target and fire. if (task.method === 'fireEvent') { const [nodeId, type, e, domChanges] = task.args const el = document.getRef(nodeId) document.fireEvent(el, type, e, domChanges) } // `callback` case: find the callback by id and call it. if (task.method === 'callback') { const [callbackId, data, ifKeepAlive] = task.args const callback = callbacks[callbackId] if (typeof callback === 'function') { callback(data) // Remove the callback from `callbacks` if it won't called again. if (typeof ifKeepAlive === 'undefined' || ifKeepAlive === false) { callbacks[callbackId] = undefined } } } }) // Finally `updateFinish` signal needed. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'updateFinish', args: [] }], -1) } /** * Register native modules information. * @param {object} newModules */ export function registerModules (newModules) { for (const name in newModules) { if (!modules[name]) { modules[name] = {} } newModules[name].forEach(method => { if (typeof method === 'string') { modules[name][method] = true } else { modules[name][method.name] = method.args } }) } } /** * Register native components information. * @param {array} newComponents */ export function registerComponents (newComponents) { if (Array.isArray(newComponents)) { newComponents.forEach(component => { if (!component) { return } if (typeof component === 'string') { components[component] = true } else if (typeof component === 'object' && typeof component.type === 'string') { components[component.type] = component } }) } } /** * Create a fresh instance of Vue for each Weex instance. */ function createVueModuleInstance (instanceId, moduleGetter) { const exports = {} VueFactory(exports, renderer) const Vue = exports.Vue const instance = instances[instanceId] // patch reserved tag detection to account for dynamically registered // components const isReservedTag = Vue.config.isReservedTag || (() => false) Vue.config.isReservedTag = name => { return components[name] || isReservedTag(name) } // expose weex-specific info Vue.prototype.$instanceId = instanceId Vue.prototype.$document = instance.document // expose weex native module getter on subVue prototype so that // vdom runtime modules can access native modules via vnode.context Vue.prototype.$requireWeexModule = moduleGetter // Hack `Vue` behavior to handle instance information and data // before root component created. Vue.mixin({ beforeCreate () { const options = this.$options // root component (vm) if (options.el) { // set external data of instance const dataOption = options.data const internalData = (typeof dataOption === 'function' ? dataOption() : dataOption) || {} options.data = Object.assign(internalData, instance.data) // record instance by id instance.app = this } } }) /** * @deprecated Just instance variable `weex.config` * Get instance config. * @return {object} */ Vue.prototype.$getConfig = function () { if (instance.app instanceof Vue) { return instance.config } } return Vue } /** * Generate native module getter. Each native module has several * methods to call. And all the hebaviors is instance-related. So * this getter will return a set of methods which additionally * send current instance id to native when called. Also the args * will be normalized into "safe" value. For example function arg * will be converted into a callback id. * @param {string} instanceId * @return {function} */ function genModuleGetter (instanceId) { const instance = instances[instanceId] return function (name) { const nativeModule = modules[name] || [] const output = {} for (const methodName in nativeModule) { output[methodName] = (...args) => { const finalArgs = args.map(value => { return normalize(value, instance) }) renderer.sendTasks(instanceId + '', [{ module: name, method: methodName, args: finalArgs }], -1) } } return output } } /** * Generate HTML5 Timer APIs. An important point is that the callback * will be converted into callback id when sent to native. So the * framework can make sure no side effect of the callabck happened after * an instance destroyed. * @param {[type]} instanceId [description] * @param {[type]} moduleGetter [description] * @return {[type]} [description] */ function getInstanceTimer (instanceId, moduleGetter) { const instance = instances[instanceId] const timer = moduleGetter('timer') const timerAPIs = { setTimeout: (...args) => { const handler = function () { args[0](...args.slice(2)) } timer.setTimeout(handler, args[1]) return instance.callbackId.toString() }, setInterval: (...args) => { const handler = function () { args[0](...args.slice(2)) } timer.setInterval(handler, args[1]) return instance.callbackId.toString() }, clearTimeout: (n) => { timer.clearTimeout(n) }, clearInterval: (n) => { timer.clearInterval(n) } } return timerAPIs } /** * Call a new function body with some global objects. * @param {object} globalObjects * @param {string} code * @return {any} */ function callFunction (globalObjects, body) { const globalKeys = [] const globalValues = [] for (const key in globalObjects) { globalKeys.push(key) globalValues.push(globalObjects[key]) } globalKeys.push(body) const result = new Function(...globalKeys) return result(...globalValues) } /** * Convert all type of values into "safe" format to send to native. * 1. A `function` will be converted into callback id. * 2. An `Element` object will be converted into `ref`. * The `instance` param is used to generate callback id and store * function if necessary. * @param {any} v * @param {object} instance * @return {any} */ function normalize (v, instance) { const type = typof(v) switch (type) { case 'undefined': case 'null': return '' case 'regexp': return v.toString() case 'date': return v.toISOString() case 'number': case 'string': case 'boolean': case 'array': case 'object': if (v instanceof renderer.Element) { return v.ref } return v case 'function': instance.callbacks[++instance.callbackId] = v return instance.callbackId.toString() default: return JSON.stringify(v) } } /** * Get the exact type of an object by `toString()`. For example call * `toString()` on an array will be returned `[object Array]`. * @param {any} v * @return {string} */ function typof (v) { const s = Object.prototype.toString.call(v) return s.substring(8, s.length - 1).toLowerCase() }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3