text
stringlengths 3
1.05M
|
|---|
if (self.CavalryLogger) { CavalryLogger.start_js(["TYAI+"]); }
__d("GroupSellProductDetailsEvent",[],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();f.exports={PHOTO_CLICK:"photo_click",SHOW_DIALOG:"show_dialog",HIDE_DIALOG:"hide_dialog",PROFILE_LINK_CLICK:"profile_link_click",GROUP_LINK_CLICK:"group_link_click",PERMALINK_CLICK:"permalink_click",ASYNC_DATA_REQUEST_FAIL:"async_data_request_fail",DIALOG_INSTANCE_NULL:"dialog_instance_null",MESSAGE_SELLER_CLICK:"message_seller_click",UFI_CLICK:"ufi_click",MARK_AS_SOLD_CLICK:"mark_as_sold_click",FAILED_SALE_POST_GEN:"failed_sale_post_gen",PHOTO_SWIPE:"photo_swipe",GROUP_POST_LIKE:"group_post_like",GROUP_POST_COMMENT:"group_post_comment",SUGGESTED_ITEM_VPV:"suggested_item_vpv",SUGGESTED_ITEM_CLICK:"suggested_item_click",GROUP_POST_COMMENT_ERROR:"group_post_comment_error",GROUP_POST_COMMENT_TEXT_ENTERED:"group_post_comment_text_entered",GROUP_POST_COMMENT_INPUT_FOCUS:"group_post_comment_input_focus",GROUP_POST_COMMENT_WITH_PHOTO:"group_post_comment_with_photo",GROUP_POST_COMMENT_INPUT_PREDICTIVE_TEXT_PRESS:"group_post_comment_input_predictive_text_press",GROUP_POST_SHARE_CLICK:"group_post_share_click",PDP_INITIAL_LOAD:"pdp_initial_load",PDP_NETWORK_FAILURE:"pdp_network_failure"};}),null);
__d("GroupSellProductDetailsImageAspect",[],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();f.exports={HORIZONTAL:"horizontal",VERTICAL:"vertical",WIDE_HORIZONTAL:"wide_horizontal",WIDE_VERTICAL:"wide_vertical",SQUARE:"square",HEIGHT_BOUND:"height_bound"};}),null);
__d("SphericalPhotoViewerLogEvents",[],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();f.exports={TAP_HEADING_INDICATOR:"spherical_photo_tap_heading_indicator",ZOOM_START:"spherical_photo_zoom_start",DRAG_START:"spherical_photo_drag_start",SIGNIFICANT_MOVEMENT:"spherical_photo_significant_movement",SHOW_VIEW_IN_VR:"spherical_photo_show_view_in_vr",TAP_VIEW_IN_VR:"spherical_photo_tap_view_in_vr",PHONE_PAN_ANIMATION:"spherical_photo_phone_pan_animation",DRAG_MOUSE_ANIMATION:"spherical_photo_drag_mouse_animation",MOUSEOVER_START:"spherical_photo_mouseover_start",WWW_GYRO_START:"spherical_photo_www_gyro_start",WWW_ENTER_SNOWLIFT:"spherical_photo_www_enter_snowlift",WWW_EXIT_SNOWLIFT:"spherical_photo_www_exit_snowlift",ENTER_FULLSCREEN:"spherical_photo_tap_feed_to_fullscreen",EXIT_FULLSCREEN:"spherical_photo_fullscreen_exited",CDN_IMAGE_FAILURE:"spherical_photo_cdn_image_failure",WEBGL_INIT_FAILURE:"spherical_photo_webgl_init_failure",FEED_VP_ENTERED:"spherical_photo_feed_vp_entered",FEED_VP_EXITED:"spherical_photo_feed_vp_exited",CUBE_LOAD_TIME:"spherical_photo_cube_load_time",RENDER_FRAME_RATE:"spherical_photo_render_frame_rate",FALLBACK_PREVIEW:"spherical_photo_fallback_preview",FALLBACK_LEARNMORE:"spherical_photo_fallback_learnmore",LOADED:"spherical_photo_loaded",TOGGLE_ON:"spherical_photo_toggle_on",TOGGLE_OFF:"spherical_photo_toggle_off",POST_EVENT:"spherical_photo_post_event",TAP_HEADING_INDICATOR_DEPRECATED:"tap_360_photo_heading_indicator",ZOOM_START_DEPRECATED:"zoom_start_360_photo",DRAG_START_DEPRECATED:"drag_start_360_photo",SIGNIFICANT_MOVEMENT_DEPRECATED:"significant_movement_360_photo",SHOW_VIEW_IN_VR_DEPRECATED:"show_360_photo_view_in_vr",TAP_VIEW_IN_VR_DEPRECATED:"tap_360_photo_view_in_vr",PHONE_PAN_ANIMATION_DEPRECATED:"phone_pan_animation_360_photo",TAP_FEED_TO_FULLSCREEN_DEPRECATED:"tap_360_photo_feed_to_fullscreen"};}),null);
__d("VideoProjection",[],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();f.exports={FLAT:"flat",EQUIRECTANGULAR:"equirectangular",CUBEMAP:"cubemap",UNPADDED_CUBEMAP:"unpadded_cubemap",UNPADDED_CUBESTRIP:"unpadded_cubestrip",OFFSET_CUBEMAP:"offset_cubemap",ROTATED_CUBEMAP:"rotated_cubemap",PYRAMID:"pyramid",STRETCHED_CUBEMAP:"stretched_cubemap"};}),null);
__d('GroupSellProductDetailActionsTypedLogger',['Banzai','GeneratedLoggerUtils','nullthrows'],(function a(b,c,d,e,f,g){'use strict';if(c.__markCompiled)c.__markCompiled();function h(){this.clear();}h.prototype.log=function(){c('GeneratedLoggerUtils').log('logger:GroupSellProductDetailActionsLoggerConfig',this.$GroupSellProductDetailActionsTypedLogger1,c('Banzai').BASIC);};h.prototype.logVital=function(){c('GeneratedLoggerUtils').log('logger:GroupSellProductDetailActionsLoggerConfig',this.$GroupSellProductDetailActionsTypedLogger1,c('Banzai').VITAL);};h.prototype.clear=function(){this.$GroupSellProductDetailActionsTypedLogger1={};return this;};h.prototype.updateData=function(j){this.$GroupSellProductDetailActionsTypedLogger1=babelHelpers['extends']({},this.$GroupSellProductDetailActionsTypedLogger1,j);return this;};h.prototype.setClientTimeStr=function(j){this.$GroupSellProductDetailActionsTypedLogger1.client_time_str=j;return this;};h.prototype.setEvent=function(j){this.$GroupSellProductDetailActionsTypedLogger1.event=j;return this;};h.prototype.setExceptionMessage=function(j){this.$GroupSellProductDetailActionsTypedLogger1.exception_message=j;return this;};h.prototype.setGroupID=function(j){this.$GroupSellProductDetailActionsTypedLogger1.group_id=j;return this;};h.prototype.setIsEmployee=function(j){this.$GroupSellProductDetailActionsTypedLogger1.is_employee=j;return this;};h.prototype.setReferralSurface=function(j){this.$GroupSellProductDetailActionsTypedLogger1.referral_surface=j;return this;};h.prototype.setStoryID=function(j){this.$GroupSellProductDetailActionsTypedLogger1.story_id=j;return this;};h.prototype.setSurface=function(j){this.$GroupSellProductDetailActionsTypedLogger1.surface=j;return this;};h.prototype.setVC=function(j){this.$GroupSellProductDetailActionsTypedLogger1.vc=j;return this;};var i={client_time_str:true,event:true,exception_message:true,group_id:true,is_employee:true,referral_surface:true,story_id:true,surface:true,vc:true};f.exports=h;}),null);
__d('GroupCommerceProductDetailImageContainer.react',['cx','DOM','Event','GroupSellProductDetailActionsTypedLogger','GroupSellProductDetailsEvent','GroupSellProductDetailsImageAspect','Image.react','React','ScrollableArea.react','Style','Vector'],(function a(b,c,d,e,f,g,h){'use strict';var i,j;if(c.__markCompiled)c.__markCompiled();var k=c('React').PropTypes,l=38,m=483;i=babelHelpers.inherits(n,c('React').Component);j=i&&i.prototype;function n(o,p){j.constructor.call(this,o,p);this.$GroupCommerceProductDetailImageContainer6=function(event){switch(event.keyCode){case 37:case 38:event.stopPropagation();this.$GroupCommerceProductDetailImageContainer9();break;case 39:case 40:event.stopPropagation();this.$GroupCommerceProductDetailImageContainer10();break;}}.bind(this);this.$GroupCommerceProductDetailImageContainer11=function(q){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').PHOTO_CLICK).setStoryID(this.props.storyID).setGroupID(this.props.group.id).log();this.$GroupCommerceProductDetailImageContainer7(q,this.props.media);this.setState({currentIndex:q});}.bind(this);this.state={currentIndex:0,stageWidth:m,stageHeight:558};}n.prototype.render=function(){return c('React').createElement('div',null,c('React').createElement('div',{className:"_57xm"},this.$GroupCommerceProductDetailImageContainer2()),c('React').createElement('div',{className:"_57xn"},this.props.media.length==0?this.$GroupCommerceProductDetailImageContainer3():this.$GroupCommerceProductDetailImageContainer4()));};n.prototype.componentDidUpdate=function(o,p){if(this.props.media&&this.props.media.length>1&&this.props.media!==o.media){this.$GroupCommerceProductDetailImageContainer5();this.$GroupCommerceProductDetailImageContainer1=c('Event').listen(document.body,'keydown',this.$GroupCommerceProductDetailImageContainer6);}else if(!this.props.media||this.props.media.length<1)this.$GroupCommerceProductDetailImageContainer5();};n.prototype.componentWillUnmount=function(){this.$GroupCommerceProductDetailImageContainer5();};n.prototype.componentWillReceiveProps=function(o){var p,q=this;if(this.props.media!==o.media){var r=0;if(o.media.length<1){this.setState({stageWidth:m});}else (function(){var s=q.props.query;if(s&&s.fbid){r=o.media.findIndex(function(t){return t.id.toString()===s.fbid;});if(r==-1)r=0;}q.$GroupCommerceProductDetailImageContainer7(r,o.media);})();this.setState({currentIndex:r});}};n.prototype.$GroupCommerceProductDetailImageContainer3=function(){var o=this.props.elem;if(!o)return null;var p=c('DOM').scry(o,'img')[0],q=c('DOM').scry(o,'i')[0],r=null,s=null;if(p){r=p.src;s=c('Vector').from(p.naturalWidth,p.naturalHeight);}else if(q){r=c('Style').get(q,'backgroundImage').replace(/.*url\("?([^"]*)"?\).*/,'$1');s=c('Vector').from(p.naturalWidth,p.naturalHeight);}else return null;if(!s.x||!s.y||!r)return null;return c('React').createElement(c('Image.react'),{className:"_580_",width:s.x,height:s.y,src:r,style:this.$GroupCommerceProductDetailImageContainer8(s.x,s.y)});};n.prototype.$GroupCommerceProductDetailImageContainer5=function(){if(this.$GroupCommerceProductDetailImageContainer1){this.$GroupCommerceProductDetailImageContainer1.remove();this.$GroupCommerceProductDetailImageContainer1=null;}};n.prototype.$GroupCommerceProductDetailImageContainer7=function(o,p){var q=p[o],r=this.state.stageWidth;switch(q.aspect){case c('GroupSellProductDetailsImageAspect').HORIZONTAL:case c('GroupSellProductDetailsImageAspect').WIDE_HORIZONTAL:r=744;break;case c('GroupSellProductDetailsImageAspect').WIDE_VERTICAL:r=314;break;case c('GroupSellProductDetailsImageAspect').VERTICAL:r=419;break;case c('GroupSellProductDetailsImageAspect').SQUARE:r=558;break;case c('GroupSellProductDetailsImageAspect').HEIGHT_BOUND:r=q.width;break;}this.props.onResize(q.aspect,r);this.setState({stageWidth:r});};n.prototype.$GroupCommerceProductDetailImageContainer10=function(){var o=this.state.currentIndex+1,p=this.props.media.length-1;if(o>p)o=0;this.$GroupCommerceProductDetailImageContainer11(o);};n.prototype.$GroupCommerceProductDetailImageContainer9=function(){var o=this.state.currentIndex-1,p=this.props.media.length-1;if(o<0)o=p;this.$GroupCommerceProductDetailImageContainer11(o);};n.prototype.$GroupCommerceProductDetailImageContainer4=function(){var o=[],p=this.props.media.length;for(var q=0;q<p;q++){var r=this.props.media[q];o.push(c('React').createElement(c('Image.react'),{className:(this.state.currentIndex!=q?"_5810":'')+(' '+"_580_"),width:r.width,height:r.height,src:r.uri,key:'stage'+r.id,style:this.$GroupCommerceProductDetailImageContainer8(r.width,r.height)}));}return o;};n.prototype.$GroupCommerceProductDetailImageContainer8=function(o,p){var q=0;if(o>this.state.stageWidth){q=this.state.stageWidth/o;o*=q;p*=q;}if(p>this.state.stageHeight){q=this.state.stageHeight/p;o*=q;p*=q;}return {paddingTop:(this.state.stageHeight-p)/2+'px',paddingLeft:(this.state.stageWidth-o)/2+'px',maxWidth:this.state.stageWidth,maxHeight:this.state.stageHeight};};n.prototype.$GroupCommerceProductDetailImageContainer2=function(){var o=[],p=this.props.media.length;for(var q=0;q<p;q++){var r=this.props.media[q];o.push(c('React').createElement(c('Image.react'),{className:"_5811"+(this.state.currentIndex==q?' '+"_5812":''),width:l,height:l,src:r.uriThumb,onClick:this.$GroupCommerceProductDetailImageContainer11.bind(this,q),key:'thumbnail'+r.id}));}return (c('React').createElement('div',null,c('React').createElement(c('ScrollableArea.react'),{height:this.props.maxHeight,shadow:false},o),c('React').createElement('div',{className:"_2dh4",style:{width:l}})));};n.propTypes={group:k.object.isRequired,media:k.any.isRequired,onResize:k.func.isRequired,maxHeight:k.number.isRequired,storyID:k.string,query:k.object,elem:k.object};f.exports=n;}),null);
__d('GroupCommerceProductDetailPivotItem.react',['cx','Image.react','Link.react','React','Relay','Tooltip.react','XUICard.react','XUICardSection.react','XUIText.react'],(function a(b,c,d,e,f,g,h){'use strict';var i,j;if(c.__markCompiled)c.__markCompiled();var k=148;i=babelHelpers.inherits(l,c('React').Component);j=i&&i.prototype;l.prototype.render=function(){var m=this.props.pivotItem.primary_photo,n=m?this.props.pivotItem.snowlift_uri:null,o=m?null:this.props.pivotItem.story.url,p=m?'theater':undefined;return (c('React').createElement('div',{className:"_179c"},c('React').createElement(c('Link.react'),{ajaxify:n,href:o,rel:p},c('React').createElement(c('XUICard.react'),{className:"_3-8h",style:{width:k}},this.renderImage(),c('React').createElement(c('XUICardSection.react'),{className:"_2pi8 _2pi2 _4bqg"},c('React').createElement(c('XUIText.react'),{className:"_4bqh",display:'block',weight:'bold',size:'small'},this.props.pivotItem.group_commerce_item_title),c('React').createElement(c('XUIText.react'),{className:"_179d _4bqh",display:'block',size:'small'},this.props.pivotItem.formatted_price.text))))));};l.prototype.renderImage=function(){if(this.props.pivotItem.primary_photo)return (c('React').createElement(c('Image.react'),{width:k,height:k,src:this.props.pivotItem.primary_photo.image.uri}));return (c('React').createElement('div',{className:"_5xvt",style:{width:k,height:k}}));};function l(){i.apply(this,arguments);}f.exports=c('Relay').createContainer(l,{initialVariables:{image_size:k},fragments:{pivotItem:function m(){return function(){return {children:[{fieldName:'group_commerce_item_title',kind:'Field',metadata:{},type:'String'},{children:[{fieldName:'text',kind:'Field',metadata:{},type:'String'}],fieldName:'formatted_price',kind:'Field',metadata:{canHaveSubselections:true},type:'TextWithEntities'},{children:[{calls:[{kind:'Call',metadata:{},name:'width',value:{kind:'CallVariable',callVariableName:'image_size'}},{kind:'Call',metadata:{},name:'height',value:{kind:'CallVariable',callVariableName:'image_size'}},{kind:'Call',metadata:{},name:'sizing',value:{kind:'CallValue',callValue:'cover-fill'}}],children:[{fieldName:'uri',kind:'Field',metadata:{},type:'Url'}],fieldName:'image',kind:'Field',metadata:{canHaveSubselections:true},type:'Image'},{fieldName:'id',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'ID'}],fieldName:'primary_photo',kind:'Field',metadata:{canHaveSubselections:true,inferredRootCallName:'node',inferredPrimaryKey:'id'},type:'Photo'},{fieldName:'snowlift_uri',kind:'Field',metadata:{},type:'Url'},{children:[{fieldName:'url',kind:'Field',metadata:{},type:'Url'},{fieldName:'id',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'ID'}],fieldName:'story',kind:'Field',metadata:{canHaveSubselections:true,inferredRootCallName:'node',inferredPrimaryKey:'id'},type:'Story'},{fieldName:'id',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'ID'}],id:c('Relay').QL.__id(),kind:'Fragment',metadata:{},name:'GroupCommerceProductDetailPivotItem_react_PivotItemRelayQL',type:'GroupCommerceProductItem'};}();}}});}),null);
__d('GroupCommerceProductDetailPivots.react',['cx','fbt','ix','GroupCommerceProductDetailPivotItem.react','Image.react','Layout.react','React','Relay','XUICarousel.react','XUICarouselAnimator','XUICarouselArrow.react','XUICarouselItem.react','XUIGrayText.react'],(function a(b,c,d,e,f,g,h,i,j){'use strict';var k,l;if(c.__markCompiled)c.__markCompiled();var m=c('Layout.react').Column,n=c('React').PropTypes,o=12,p=8;k=babelHelpers.inherits(q,c('React').Component);l=k&&k.prototype;q.prototype.render=function(){if(!this.props.groupCommerceProductItem||!this.props.groupCommerceProductItem.top_related_products||!this.props.groupCommerceProductItem.top_related_products.edges||this.props.groupCommerceProductItem.top_related_products.edges.length<o)return null;var r=this.props.groupCommerceProductItem.top_related_products.edges.map(function(u){return (c('React').createElement(c('XUICarouselItem.react'),{className:"_3-8_",key:u.node.id},c('React').createElement(c('GroupCommerceProductDetailPivotItem.react'),{pivotItem:u.node})));}),s=c('React').createElement(c('XUICarouselArrow.react'),null,c('React').createElement(c('Image.react'),{alt:i._("Tr\u01b0\u1edbc"),src:j('/images/vault/arrow_left.png')})),t=c('React').createElement(c('XUICarouselArrow.react'),null,c('React').createElement(c('Image.react'),{alt:i._("Ti\u1ebfp"),src:j('/images/vault/arrow_right.png')}));return (c('React').createElement('div',{className:"_2pie _39ha"},c('React').createElement(c('XUIGrayText.react'),{className:"_3-94",shade:'light',size:'small',weight:'bold',display:'block'},i._("XEM TH\u00caM M\u1eb6T H\u00c0NG")),c('React').createElement(c('XUICarousel.react'),{animator:new (c('XUICarouselAnimator'))({type:'horizontal',centered:false,firstAndLastAligned:true}),arrows:[s,t],initialAutoplay:false,viewportWidth:this.props.width-p*2,wrapAround:false},r)));};function q(){k.apply(this,arguments);}q.propTypes={width:n.number.isRequired};f.exports=c('Relay').createContainer(q,{initialVariables:{count:o},fragments:{groupCommerceProductItem:function r(){return function(s){return {children:[{fieldName:'id',kind:'Field',metadata:{isRequisite:true},type:'ID'},{calls:[{kind:'Call',metadata:{},name:'first',value:{kind:'CallVariable',callVariableName:'count'}}],children:[{fieldName:'count',kind:'Field',metadata:{},type:'Int'},{children:[{children:[].concat.apply([],[{fieldName:'id',kind:'Field',metadata:{isRequisite:true},type:'ID'},c('Relay').QL.__frag(s)]),fieldName:'node',kind:'Field',metadata:{canHaveSubselections:true,inferredRootCallName:'node',inferredPrimaryKey:'id',isRequisite:true},type:'GroupCommerceProductItem'},{fieldName:'cursor',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'ID'}],fieldName:'edges',kind:'Field',metadata:{canHaveSubselections:true,isPlural:true},type:'ProductToTopRelatedProductsEdge'},{children:[{fieldName:'has_next_page',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'Boolean'},{fieldName:'has_previous_page',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'Boolean'}],fieldName:'page_info',kind:'Field',metadata:{canHaveSubselections:true,isGenerated:true,isRequisite:true},type:'PageInfo'}],fieldName:'top_related_products',kind:'Field',metadata:{canHaveSubselections:true,isConnection:true,isFindable:true},type:'ProductToTopRelatedProductsConnection'}],id:c('Relay').QL.__id(),kind:'Fragment',metadata:{},name:'GroupCommerceProductDetailPivots_react_GroupCommerceProductItemRelayQL',type:'GroupCommerceProductItem'};}(c('GroupCommerceProductDetailPivotItem.react').getFragment('pivotItem'));}}});}),null);
__d('GroupCommerceProductDetailPivotsRoute',['Relay'],(function a(b,c,d,e,f,g){'use strict';var h,i;if(c.__markCompiled)c.__markCompiled();h=babelHelpers.inherits(j,c('Relay').Route);i=h&&h.prototype;function j(){h.apply(this,arguments);}j.routeName='GroupCommerceProductDetailPivotsRoute';j.path='/product_details/top_related_products/{id}';j.paramDefinitions={id:{type:'Number',required:true}};j.queries={groupCommerceProductItem:function k(l){return function(m){return {calls:[{kind:'Call',metadata:{type:'ID!'},name:'id',value:{kind:'CallVariable',callVariableName:'id'}}],children:[].concat.apply([],[{fieldName:'id',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'ID'},{fieldName:'__typename',kind:'Field',metadata:{isGenerated:true,isRequisite:true},type:'String'},c('Relay').QL.__frag(m)]),fieldName:'node',kind:'Query',metadata:{isAbstract:true,identifyingArgName:'id',identifyingArgType:'ID!'},name:'GroupCommerceProductDetailPivotsRoute',type:'Node'};}(l.getFragment('groupCommerceProductItem'));}};f.exports=j;}),null);
__d('GroupCommerceProductDetailPivotsRelayContainer.react',['GroupCommerceProductDetailPivots.react','GroupCommerceProductDetailPivotsRoute','React','RelayRootContainer'],(function a(b,c,d,e,f,g){'use strict';var h,i;if(c.__markCompiled)c.__markCompiled();var j=c('React').PropTypes;h=babelHelpers.inherits(k,c('React').Component);i=h&&h.prototype;k.prototype.render=function(){var l=new (c('GroupCommerceProductDetailPivotsRoute'))({id:this.props.groupCommerceProductID});return (c('React').createElement(c('RelayRootContainer'),{Component:c('GroupCommerceProductDetailPivots.react'),route:l,renderFetched:function(m){return (c('React').createElement(c('GroupCommerceProductDetailPivots.react'),babelHelpers['extends']({},m,{width:this.props.width})));}.bind(this)}));};function k(){h.apply(this,arguments);}k.propTypes={groupCommerceProductID:j.number.isRequired,width:j.number.isRequired};f.exports=k;}),null);
__d('GroupCommerceProductDetailRHCContent.react',['cx','ix','GroupSellProductDetailActionsTypedLogger','GroupSellProductDetailsEvent','Image.react','Link.react','React','XUIText.react'],(function a(b,c,d,e,f,g,h,i){'use strict';var j,k;if(c.__markCompiled)c.__markCompiled();var l=c('React').PropTypes;j=babelHelpers.inherits(m,c('React').Component);k=j&&j.prototype;m.prototype.render=function(){var n=this.$GroupCommerceProductDetailRHCContent1(),o=this.$GroupCommerceProductDetailRHCContent2();return (c('React').createElement('div',{className:"_4g63"+(!this.props.actor.profilePicURI?' '+"_34xy":'')},c('React').createElement('div',{className:"_4g65"},o,n,c('React').createElement(c('XUIText.react'),{className:"_4g66"},this.props.product.price),c('React').createElement('div',{className:"_4g67"},this.props.description),c('React').createElement('div',{className:"_4g68"},this.props.actionButton)),c('React').createElement('div',{className:"_4g6d",ref:'ufi',onClick:function(){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').UFI_CLICK).setStoryID(this.props.storyID).setGroupID(this.props.group.id).log();}.bind(this)},this.props.ufi)));};m.prototype.$GroupCommerceProductDetailRHCContent2=function(){var n=this.props.product.statusText?this.props.product.statusText+' '+this.props.product.title:this.props.product.title;return (c('React').createElement(c('XUIText.react'),{id:this.props.titleID,className:"_4g6e"},n));};m.prototype.$GroupCommerceProductDetailRHCContent1=function(){var n=!this.props.product.deliveryNote?null:c('React').createElement(c('XUIText.react'),{display:'inline'},this.props.product.deliveryNote),o=n?c('React').createElement(c('Image.react'),{className:"_4g6g",src:i('images/groups/sell/place_icon_sell.png')}):null;return (c('React').createElement('div',{className:"_4g6h"},o,c('React').createElement(c('XUIText.react'),null,n)));};function m(){j.apply(this,arguments);}m.propTypes={actor:l.object.isRequired,product:l.object.isRequired,group:l.object.isRequired,feedback:l.object.isRequired,ufi:l.any.isRequired,actionButton:l.any.isRequired,storyID:l.string,description:l.any.isRequired,titleID:l.string};f.exports=m;}),null);
__d('GroupCommerceProductDetailRHCFooter.react',['cx','Event','MentionsInputTypeaheadView.react','React','ReactDOM','UFIAddCommentController','UFIMentionsInputProxy.react'],(function a(b,c,d,e,f,g,h){'use strict';var i,j;if(c.__markCompiled)c.__markCompiled();var k=c('React').PropTypes;i=babelHelpers.inherits(l,c('React').Component);j=i&&i.prototype;l.prototype.componentDidMount=function(){this.$GroupCommerceProductDetailRHCFooter1=c('Event').listen(c('ReactDOM').findDOMNode(this.refs.ufiAddComment),'keydown',this.$GroupCommerceProductDetailRHCFooter2);};l.prototype.createUFIAddComment=function(m){if(m.ufi&&m.ufi.params){m.ufi.params.mentionsinput={inputComponent:c('UFIMentionsInputProxy.react'),viewComponent:c('MentionsInputTypeaheadView.react')};new (c('UFIAddCommentController'))(c('ReactDOM').findDOMNode(this.refs.ufiAddComment),m.ufi.params).render();}};l.prototype.componentWillUnmount=function(){if(this.$GroupCommerceProductDetailRHCFooter1){this.$GroupCommerceProductDetailRHCFooter1.remove();this.$GroupCommerceProductDetailRHCFooter1=null;}};l.prototype.render=function(){return (c('React').createElement('div',{className:"_3g6i"+(!this.props.actor.profilePicURI?' '+"_34xy":''),key:this.props.ufiInstanceID,ref:'ufiAddComment'}));};l.prototype.$GroupCommerceProductDetailRHCFooter2=function(event){switch(event.keyCode){case 37:case 38:case 39:case 40:event.stopPropagation();break;}};function l(){i.apply(this,arguments);}l.propTypes={ufiInstanceID:k.string.isRequired,ufi:k.object.isRequired,actor:k.object.isRequired};f.exports=l;}),null);
__d('GroupCommerceProductDetailRHCHeader.react',['cx','ix','GroupSellProductDetailActionsTypedLogger','GroupSellProductDetailsEvent','Image.react','Link.react','React','ReactLayeredComponentMixin_DEPRECATED','XUIContextualDialog.react','XUIContextualDialogBody.react','classWithMixins','isEmpty','mixin'],(function a(b,c,d,e,f,g,h,i){'use strict';var j,k;if(c.__markCompiled)c.__markCompiled();var l=c('React').PropTypes,m=104,n=40;j=babelHelpers.inherits(o,c('classWithMixins')(c('React').Component,c('mixin')(c('ReactLayeredComponentMixin_DEPRECATED'))));k=j&&j.prototype;o.prototype.renderLayers=function(){return {actorDialog:c('React').createElement(c('XUIContextualDialog.react'),{contextRef:function(){return this.refs.actorName;}.bind(this),shown:true,hoverContextRef:function(){return this.refs.actorName;}.bind(this),hideOnEscape:true,hoverHideDelay:0,hoverShowDelay:500,autoFocus:false,width:c('XUIContextualDialog.react').WIDTH.WIDE,position:'below'},c('React').createElement(c('XUIContextualDialogBody.react'),null,c('React').createElement('div',{id:this.props.actorHoverID}))),actorImageDialog:c('React').createElement(c('XUIContextualDialog.react'),{contextRef:function(){return this.refs.actorImage;}.bind(this),shown:true,hoverContextRef:function(){return this.refs.actorImage;}.bind(this),hideOnEscape:true,hoverHideDelay:0,hoverShowDelay:500,autoFocus:false,width:c('XUIContextualDialog.react').WIDTH.WIDE,position:'below'},c('React').createElement(c('XUIContextualDialogBody.react'),null,c('React').createElement('div',{id:this.props.actorImageHoverID}))),groupDialog:c('React').createElement(c('XUIContextualDialog.react'),{contextRef:function(){return this.refs.groupName;}.bind(this),shown:true,hoverContextRef:function(){return this.refs.groupName;}.bind(this),hideOnEscape:true,hoverHideDelay:0,hoverShowDelay:500,autoFocus:false,width:c('XUIContextualDialog.react').WIDTH.WIDE,position:'below'},c('React').createElement(c('XUIContextualDialogBody.react'),null,c('React').createElement('div',{id:this.props.groupHoverID})))};};o.prototype.render=function(){return (c('React').createElement('div',{className:"_34xx"+(!this.props.actor.profilePicURI?' '+"_34xy":'')},c('React').createElement(c('Image.react'),{className:"_34xz",width:n,height:n,src:this.props.actor.profilePicURI,ref:'actorImage'}),c('React').createElement('div',{className:"_34x-"},c('React').createElement('div',{className:"_34x_"},c('React').createElement('div',{ref:'actorName',className:"_34y0"},c('React').createElement(c('Link.react'),{href:this.props.actor.uri,onClick:function(){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').PROFILE_LINK_CLICK).setStoryID(this.props.storyID).setGroupID(this.props.group.id).log();this.props.hideDialog();}.bind(this)},this.props.actor.name)),!c('isEmpty')(this.props.group)?c('React').createElement(c('Image.react'),{className:"_34y1",src:i('images/icons/wall_arrow.gif')}):null,c('React').createElement('div',{ref:'groupName',className:"_34y0"},c('React').createElement(c('Link.react'),{href:this.props.group.uri,onClick:function(){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').GROUP_LINK_CLICK).setStoryID(this.props.storyID).setGroupID(this.props.group.id).log();this.props.hideDialog();}.bind(this)},this.props.group.name))),c('React').createElement('div',{className:"_4g6i"},c('React').createElement(c('Link.react'),{href:this.props.product.uri,onClick:function(){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').PERMALINK_CLICK).setStoryID(this.props.storyID).setGroupID(this.props.group.id).log();this.props.hideDialog();}.bind(this)},this.props.timestamp))),c('React').createElement('div',{id:this.props.chevronID})));};o.prototype.componentDidUpdate=function(p,q){var r=this.refs.actorName.offsetWidth,s=m-r;this.refs.groupName.style.maxWidth=m+s+'px';};function o(){j.apply(this,arguments);}o.propTypes={actor:l.object.isRequired,group:l.object.isRequired,storyID:l.string,actorHoverID:l.string.isRequired,actorImageHoverID:l.string.isRequired,groupHoverID:l.string.isRequired,chevronID:l.string.isRequired,product:l.object.isRequired,timestamp:l.any.isRequired};f.exports=o;}),null);
__d("XGroupCommerceMarketplaceProductDetailController",["XController"],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();f.exports=c("XController").create("\/marketplace\/product_detail\/",{sale_post_id:{type:"FBID",required:true},ufi_id:{type:"String",required:true},date_time_id:{type:"String",required:true},action_button_id:{type:"String",required:true},actor_dialog_id:{type:"String",required:true},actor_image_dialog_id:{type:"String",required:true},description_id:{type:"String",required:true},title_id:{type:"String",required:true},group_hover_id:{type:"String",required:true},ufi_instance_id:{type:"String",required:true},chevron_id:{type:"String",required:true}});}),null);
__d("XGroupCommerceMarketplaceSimilarProductsController",["XController"],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();f.exports=c("XController").create("\/marketplace\/similar_products\/",{rid:{type:"Int"},rt:{type:"Enum",enumType:0},location:{type:"Enum",enumType:1},share_id:{type:"Int"},sale_post_id:{type:"FBID",required:true},post_dom_id:{type:"String",required:true},render_location:{type:"Enum",required:true,enumType:1}});}),null);
__d('GroupCommerceProductDetail.react',['csx','cx','fbt','Arbiter','AsyncRequest','GroupSellProductDetailActionsTypedLogger','GroupSellProductDetailsEvent','GroupSellProductDetailsImageAspect','LayerFadeOnHide','LayerHideOnEscape','LeftRight.react','GroupCommerceProductDetailPivotsRelayContainer.react','GroupCommerceProductDetailRHCHeader.react','GroupCommerceProductDetailImageContainer.react','GroupCommerceProductDetailRHCContent.react','GroupCommerceProductDetailRHCFooter.react','Parent','React','ReactRenderer','ResponsiveBlock.react','ScrollableArea.react','XGroupCommerceMarketplaceProductDetailController','XGroupCommerceMarketplaceSimilarProductsController','XUIDialog.react','XUIDialogTitle.react','XUIDialogBody.react','guid'],(function a(b,c,d,e,f,g,h,i,j){'use strict';var k,l;if(c.__markCompiled)c.__markCompiled();var m=495,n=530,o=891;k=babelHelpers.inherits(p,c('React').Component);l=k&&k.prototype;function p(q,r){l.constructor.call(this,q,r);var s=this;s.hideDialog=this.hideDialog.bind(this);s.showDialog=this.showDialog.bind(this);s.$GroupCommerceProductDetail3=this.$GroupCommerceProductDetail3.bind(this);s.$GroupCommerceProductDetail4=this.$GroupCommerceProductDetail4.bind(this);s.$GroupCommerceProductDetail5=this.$GroupCommerceProductDetail5.bind(this);s.$GroupCommerceProductDetail6=this.$GroupCommerceProductDetail6.bind(this);this.$GroupCommerceProductDetail2={};this.state={isDialogShown:false,width:o,rhcHeight:200,payload:this.$GroupCommerceProductDetail7(),ufiID:'ufi_detail_'+c('guid')(),datetimeID:'datetime_'+c('guid')(),actionButtonID:'actionButton'+c('guid')(),actorHoverID:'actorHoverID'+c('guid')(),actorImageHoverID:'actorImageHoverID'+c('guid')(),descriptionID:'descriptionID'+c('guid')(),titleID:'titleID'+c('guid')(),groupHoverID:'groupHoverID'+c('guid')(),ufiInstanceID:'ufiInstanceID'+c('guid')(),chevronID:'chevronID'+c('guid')(),query:null,elem:null,salePostID:null};}p.prototype.componentDidMount=function(){this.$GroupCommerceProductDetail1=c('Arbiter').subscribe('XComposerEditDialog/doneEditing',function(){this.$GroupCommerceProductDetail8(this.state.salePostID);}.bind(this));};p.prototype.componentWillUnmount=function(){var q=this.refs.modal;if(q!=null)q.layer.hide();p.$GroupCommerceProductDetail9=null;this.$GroupCommerceProductDetail1&&this.$GroupCommerceProductDetail1.unsubscribe();this.$GroupCommerceProductDetail1=null;};p.prototype.render=function(){var q=c('React').createElement('span',{id:this.state.datetimeID}),r=c('React').createElement('div',{id:this.state.ufiID}),s=c('React').createElement('div',{id:this.state.actionButtonID}),t=c('React').createElement('div',{className:"_3g5q",id:this.state.descriptionID});return (c('React').createElement(c('XUIDialog.react'),{className:"_5p3y",shown:this.state.isDialogShown,onToggle:this.$GroupCommerceProductDetail3,ref:'modal',width:this.state.width,behaviors:{LayerFadeOnHide:c('LayerFadeOnHide'),LayerHideOnEscape:c('LayerHideOnEscape')}},c('React').createElement(c('XUIDialogTitle.react'),null,j._("Chi ti\u1ebft m\u1eb7t h\u00e0ng")),c('React').createElement(c('XUIDialogBody.react'),null,c('React').createElement('div',{className:"_3g6d"},c('React').createElement(c('LeftRight.react'),null,c('React').createElement('div',{className:"_3g6e"},c('React').createElement(c('GroupCommerceProductDetailImageContainer.react'),{group:this.state.payload.group,media:this.state.payload.media,maxHeight:n,storyID:this.state.payload.storyID,query:this.state.query,elem:this.state.elem,onResize:this.$GroupCommerceProductDetail6})),c('React').createElement('div',{className:"_3g6f"},c('React').createElement(c('ScrollableArea.react'),{className:"_3g6g",height:this.state.rhcHeight},c('React').createElement(c('ResponsiveBlock.react'),{className:"_3g6h",onResize:this.$GroupCommerceProductDetail4},c('React').createElement(c('GroupCommerceProductDetailRHCHeader.react'),{actor:this.state.payload.actor,group:this.state.payload.group,hideDialog:this.hideDialog,storyID:this.state.payload.storyID,actorHoverID:this.state.actorHoverID,actorImageHoverID:this.state.actorImageHoverID,groupHoverID:this.state.groupHoverID,chevronID:this.state.chevronID,product:this.state.payload.product,timestamp:q}),c('React').createElement(c('GroupCommerceProductDetailRHCContent.react'),{actor:this.state.payload.actor,product:this.state.payload.product,group:this.state.payload.group,feedback:this.state.payload.feedback,actionButton:s,ufi:r,hideDialog:this.hideDialog,storyID:this.state.payload.storyID,description:t,titleID:this.state.titleID}))),c('React').createElement(c('GroupCommerceProductDetailRHCFooter.react'),{actor:this.state.payload.actor,ref:'rhcFooter',className:"_3g6i",ufiInstanceID:this.state.ufiInstanceID,ufi:this.state.payload.ufi}))),this.$GroupCommerceProductDetail10()))));};p.prototype.showDialog=function(q,r,s){this.$GroupCommerceProductDetail8(q);this.setState({payload:this.$GroupCommerceProductDetail7(),salePostID:q,query:r,elem:s,isDialogShown:true,width:o});this.$GroupCommerceProductDetail11(q,s);};p.prototype.$GroupCommerceProductDetail10=function(){var q=this.state.payload.product;if(!q.id||!q.showPivots)return null;return (c('React').createElement(c('GroupCommerceProductDetailPivotsRelayContainer.react'),{groupCommerceProductID:q.id,width:this.state.width}));};p.prototype.$GroupCommerceProductDetail8=function(q){var r=c('XGroupCommerceMarketplaceProductDetailController').getURIBuilder().setFBID('sale_post_id',q).setString('ufi_id',this.state.ufiID).setString('date_time_id',this.state.datetimeID).setString('action_button_id',this.state.actionButtonID).setString('actor_dialog_id',this.state.actorHoverID).setString('actor_image_dialog_id',this.state.actorImageHoverID).setString('description_id',this.state.descriptionID).setString('title_id',this.state.titleID).setString('group_hover_id',this.state.groupHoverID).setString('ufi_instance_id',this.state.ufiInstanceID).setString('chevron_id',this.state.chevronID).getURI();new (c('AsyncRequest'))().setURI(r).setMethod('GET').setHandler(this.$GroupCommerceProductDetail5).setErrorHandler(function(s){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').ASYNC_DATA_REQUEST_FAIL).setStoryID(q.toString()).log();}).setReadOnly(true).send();};p.prototype.$GroupCommerceProductDetail11=function(q,r){var s=r&&c('Parent').bySelector(r,"._4-u2");if(!r||!r.dataset.renderLocation||!s)return;var t=s.id;if(!t||this.$GroupCommerceProductDetail2[t])return;this.$GroupCommerceProductDetail2[t]=true;var u=c('XGroupCommerceMarketplaceSimilarProductsController').getURIBuilder().setFBID('sale_post_id',q).setString('post_dom_id',t).setEnum('render_location',r.dataset.renderLocation).getURI();new (c('AsyncRequest'))().setURI(u).setMethod('GET').setHandler(this.$GroupCommerceProductDetail12).setErrorHandler(function(v){}).setReadOnly(true).send();};p.prototype.$GroupCommerceProductDetail12=function(q){var r=q.getPayload();if(!r||!r.length)return;};p.prototype.hideDialog=function(){this.$GroupCommerceProductDetail3(false);};p.prototype.$GroupCommerceProductDetail6=function(q,r){var s=this.state.width;switch(q){case c('GroupSellProductDetailsImageAspect').HORIZONTAL:case c('GroupSellProductDetailsImageAspect').WIDE_HORIZONTAL:s=1153;break;case c('GroupSellProductDetailsImageAspect').WIDE_VERTICAL:s=723;break;case c('GroupSellProductDetailsImageAspect').VERTICAL:s=828;break;case c('GroupSellProductDetailsImageAspect').SQUARE:s=967;break;case c('GroupSellProductDetailsImageAspect').HEIGHT_BOUND:s=r+409;break;}this.setState({width:s});};p.prototype.$GroupCommerceProductDetail4=function(q,r){if(r>m)r=m;this.setState({rhcHeight:r});};p.prototype.$GroupCommerceProductDetail3=function(q){if(p.$GroupCommerceProductDetail9!==null)this.setState({isDialogShown:q});if(!q){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').HIDE_DIALOG).setStoryID(this.state.payload.storyID).setGroupID(this.state.payload.group.id).log();if(p.$GroupCommerceProductDetail9!==null)setTimeout(function(){this.setState({payload:this.$GroupCommerceProductDetail7(),query:null,elem:null});}.bind(this));}};p.prototype.$GroupCommerceProductDetail7=function(){return {actor:{profilePicURI:null},group:{},product:{},feedback:{},media:[],ufi:{}};};p.prototype.$GroupCommerceProductDetail5=function(q){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').SHOW_DIALOG).setStoryID(q.payload.storyID).setGroupID(q.payload.group.id).log();this.setState({payload:q.payload,isDialogShown:true});};p.init=function(q){var r=c('ReactRenderer').constructAndRenderComponent(p,{},q);p.$GroupCommerceProductDetail13=q;p.$GroupCommerceProductDetail9=r;if(p.$GroupCommerceProductDetail14){p.showDialog(p.$GroupCommerceProductDetail14,p.$GroupCommerceProductDetail15,p.$GroupCommerceProductDetail16);p.$GroupCommerceProductDetail14=null;p.$GroupCommerceProductDetail15=null;p.$GroupCommerceProductDetail16=null;}};p.showDialog=function(q,r,s){if(!p.$GroupCommerceProductDetail9){if(!p.$GroupCommerceProductDetail13){p.$GroupCommerceProductDetail14=q;p.$GroupCommerceProductDetail15=r;p.$GroupCommerceProductDetail16=s;return;}p.init(p.$GroupCommerceProductDetail13);}if(!p.$GroupCommerceProductDetail9){new (c('GroupSellProductDetailActionsTypedLogger'))().setEvent(c('GroupSellProductDetailsEvent').DIALOG_INSTANCE_NULL).setStoryID(q.toString()).log();return;}p.$GroupCommerceProductDetail9.showDialog(q,r,s);};p.$GroupCommerceProductDetail9=null;p.$GroupCommerceProductDetail14=null;p.$GroupCommerceProductDetail13=null;p.$GroupCommerceProductDetail16=null;p.$GroupCommerceProductDetail15=null;f.exports=p;}),null);
__d('SphericalPhotoViewerTypedLogger',['Banzai','GeneratedLoggerUtils','nullthrows'],(function a(b,c,d,e,f,g){'use strict';if(c.__markCompiled)c.__markCompiled();function h(){this.clear();}h.prototype.log=function(){c('GeneratedLoggerUtils').log('spherical_photo_viewer_log:SphericalPhotoViewerLoggerConfig',this.$SphericalPhotoViewerTypedLogger1,c('Banzai').BASIC);};h.prototype.logVital=function(){c('GeneratedLoggerUtils').log('spherical_photo_viewer_log:SphericalPhotoViewerLoggerConfig',this.$SphericalPhotoViewerTypedLogger1,c('Banzai').VITAL);};h.prototype.clear=function(){this.$SphericalPhotoViewerTypedLogger1={};return this;};h.prototype.updateData=function(j){this.$SphericalPhotoViewerTypedLogger1=babelHelpers['extends']({},this.$SphericalPhotoViewerTypedLogger1,j);return this;};h.prototype.setComposerSessionID=function(j){this.$SphericalPhotoViewerTypedLogger1.composer_session_id=j;return this;};h.prototype.setEventType=function(j){this.$SphericalPhotoViewerTypedLogger1.event_type=j;return this;};h.prototype.setFallbackUI=function(j){this.$SphericalPhotoViewerTypedLogger1.fallback_ui=j;return this;};h.prototype.setName=function(j){this.$SphericalPhotoViewerTypedLogger1.name=j;return this;};h.prototype.setNumberOfSphericalPhoto=function(j){this.$SphericalPhotoViewerTypedLogger1.number_of_spherical_photo=j;return this;};h.prototype.setPhotoID=function(j){this.$SphericalPhotoViewerTypedLogger1.photo_id=j;return this;};h.prototype.setSphericalPhotoSessionID=function(j){this.$SphericalPhotoViewerTypedLogger1.spherical_photo_session_id=j;return this;};h.prototype.setSurface=function(j){this.$SphericalPhotoViewerTypedLogger1.surface=j;return this;};var i={composer_session_id:true,event_type:true,fallback_ui:true,name:true,number_of_spherical_photo:true,photo_id:true,spherical_photo_session_id:true,surface:true};f.exports=h;}),null);
__d('SphericalPhotoViewerLoggerUtil',['CSS','FullScreen','SphericalPhotoViewerLogEvents','ProfileTabUtils','SphericalPhotoViewerTypedLogger','TimelineURI','URI','SphericalMediaConstants'],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h='timelineLayout',i=c('SphericalMediaConstants').LOGGER_SURFACES,j=function l(){if(c('FullScreen').isFullScreen())return i.fullpage;var m=c('URI').getMostRecentURI();if(m.getQueryData().hasOwnProperty('theater'))return i.snowlift;if(m.getPath()==='/'||m.getPath()==='/home.php')return i.newsfeed;var n=c('TimelineURI').getTabKeyFromURI(m),o=c('TimelineURI').getVanityFromURI(m);if(o&&c('ProfileTabUtils').isTimelineTab(n)&&c('CSS').hasClass(document.body,h))return i.timeline;return i.other;},k={logTapHeadingIndicator:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').TAP_HEADING_INDICATOR,m);},logDragStart:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').DRAG_START,m);},logMouseOverStart:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').MOUSEOVER_START,m);},logWWWGyroStart:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').WWW_GYRO_START,m);},logZoomStart:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').ZOOM_START,m);},logDragMouseAnimation:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').DRAG_MOUSE_ANIMATION,m);},logEnterSnowlift:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').WWW_ENTER_SNOWLIFT,m);},logExitSnowlift:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').WWW_EXIT_SNOWLIFT,m);},logEnterFullScreen:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').ENTER_FULLSCREEN,m);},logExitFullScreen:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').EXIT_FULLSCREEN,m);},logSignificantMovement:function l(){var m=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];k._log(c('SphericalPhotoViewerLogEvents').SIGNIFICANT_MOVEMENT,m);},_log:function l(m,n){n.surface=n.surface||j();new (c('SphericalPhotoViewerTypedLogger'))().setName(m).setPhotoID(n.photoID).setSphericalPhotoSessionID(n.sessionID).setSurface(n.surface).log();}};f.exports=k;}),null);
__d("gl-matrix-common",[],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();var h={};h.EPSILON=1e-06;h.ARRAY_TYPE=(typeof Float32Array!=='undefined')?Float32Array:Array;h.RANDOM=Math.random;h.ENABLE_SIMD=false;h.SIMD_AVAILABLE=(h.ARRAY_TYPE===this.Float32Array)&&('SIMD' in this);h.USE_SIMD=h.ENABLE_SIMD&&h.SIMD_AVAILABLE;h.setMatrixArrayType=function(j){h.ARRAY_TYPE=j;};var i=Math.PI/180;h.toRadian=function(j){return j*i;};h.equals=function(j,k){return Math.abs(j-k)<=h.EPSILON*Math.max(1,Math.abs(j),Math.abs(k));};f.exports=h;}),null);
__d("gl-matrix-mat4",["gl-matrix-common"],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();var h=c("gl-matrix-common"),i={scalar:{},SIMD:{}};i.create=function(){var j=new h.ARRAY_TYPE(16);j[0]=1;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=1;j[6]=0;j[7]=0;j[8]=0;j[9]=0;j[10]=1;j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.clone=function(j){var k=new h.ARRAY_TYPE(16);k[0]=j[0];k[1]=j[1];k[2]=j[2];k[3]=j[3];k[4]=j[4];k[5]=j[5];k[6]=j[6];k[7]=j[7];k[8]=j[8];k[9]=j[9];k[10]=j[10];k[11]=j[11];k[12]=j[12];k[13]=j[13];k[14]=j[14];k[15]=j[15];return k;};i.copy=function(j,k){j[0]=k[0];j[1]=k[1];j[2]=k[2];j[3]=k[3];j[4]=k[4];j[5]=k[5];j[6]=k[6];j[7]=k[7];j[8]=k[8];j[9]=k[9];j[10]=k[10];j[11]=k[11];j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];return j;};i.fromValues=function(j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y){var z=new h.ARRAY_TYPE(16);z[0]=j;z[1]=k;z[2]=l;z[3]=m;z[4]=n;z[5]=o;z[6]=p;z[7]=q;z[8]=r;z[9]=s;z[10]=t;z[11]=u;z[12]=v;z[13]=w;z[14]=x;z[15]=y;return z;};i.set=function(j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){j[0]=k;j[1]=l;j[2]=m;j[3]=n;j[4]=o;j[5]=p;j[6]=q;j[7]=r;j[8]=s;j[9]=t;j[10]=u;j[11]=v;j[12]=w;j[13]=x;j[14]=y;j[15]=z;return j;};i.identity=function(j){j[0]=1;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=1;j[6]=0;j[7]=0;j[8]=0;j[9]=0;j[10]=1;j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.scalar.transpose=function(j,k){if(j===k){var l=k[1],m=k[2],n=k[3],o=k[6],p=k[7],q=k[11];j[1]=k[4];j[2]=k[8];j[3]=k[12];j[4]=l;j[6]=k[9];j[7]=k[13];j[8]=m;j[9]=o;j[11]=k[14];j[12]=n;j[13]=p;j[14]=q;}else{j[0]=k[0];j[1]=k[4];j[2]=k[8];j[3]=k[12];j[4]=k[1];j[5]=k[5];j[6]=k[9];j[7]=k[13];j[8]=k[2];j[9]=k[6];j[10]=k[10];j[11]=k[14];j[12]=k[3];j[13]=k[7];j[14]=k[11];j[15]=k[15];}return j;};i.SIMD.transpose=function(j,k){var l,m,n,o,p,q,r,s,t,u;l=SIMD.Float32x4.load(k,0);m=SIMD.Float32x4.load(k,4);n=SIMD.Float32x4.load(k,8);o=SIMD.Float32x4.load(k,12);p=SIMD.Float32x4.shuffle(l,m,0,1,4,5);q=SIMD.Float32x4.shuffle(n,o,0,1,4,5);r=SIMD.Float32x4.shuffle(p,q,0,2,4,6);s=SIMD.Float32x4.shuffle(p,q,1,3,5,7);SIMD.Float32x4.store(j,0,r);SIMD.Float32x4.store(j,4,s);p=SIMD.Float32x4.shuffle(l,m,2,3,6,7);q=SIMD.Float32x4.shuffle(n,o,2,3,6,7);t=SIMD.Float32x4.shuffle(p,q,0,2,4,6);u=SIMD.Float32x4.shuffle(p,q,1,3,5,7);SIMD.Float32x4.store(j,8,t);SIMD.Float32x4.store(j,12,u);return j;};i.transpose=h.USE_SIMD?i.SIMD.transpose:i.scalar.transpose;i.scalar.invert=function(j,k){var l=k[0],m=k[1],n=k[2],o=k[3],p=k[4],q=k[5],r=k[6],s=k[7],t=k[8],u=k[9],v=k[10],w=k[11],x=k[12],y=k[13],z=k[14],aa=k[15],ba=l*q-m*p,ca=l*r-n*p,da=l*s-o*p,ea=m*r-n*q,fa=m*s-o*q,ga=n*s-o*r,ha=t*y-u*x,ia=t*z-v*x,ja=t*aa-w*x,ka=u*z-v*y,la=u*aa-w*y,ma=v*aa-w*z,na=ba*ma-ca*la+da*ka+ea*ja-fa*ia+ga*ha;if(!na)return null;na=1/na;j[0]=(q*ma-r*la+s*ka)*na;j[1]=(n*la-m*ma-o*ka)*na;j[2]=(y*ga-z*fa+aa*ea)*na;j[3]=(v*fa-u*ga-w*ea)*na;j[4]=(r*ja-p*ma-s*ia)*na;j[5]=(l*ma-n*ja+o*ia)*na;j[6]=(z*da-x*ga-aa*ca)*na;j[7]=(t*ga-v*da+w*ca)*na;j[8]=(p*la-q*ja+s*ha)*na;j[9]=(m*ja-l*la-o*ha)*na;j[10]=(x*fa-y*da+aa*ba)*na;j[11]=(u*da-t*fa-w*ba)*na;j[12]=(q*ia-p*ka-r*ha)*na;j[13]=(l*ka-m*ia+n*ha)*na;j[14]=(y*ca-x*ea-z*ba)*na;j[15]=(t*ea-u*ca+v*ba)*na;return j;};i.SIMD.invert=function(j,k){var l,m,n,o,p,q,r,s,t,u,v=SIMD.Float32x4.load(k,0),w=SIMD.Float32x4.load(k,4),x=SIMD.Float32x4.load(k,8),y=SIMD.Float32x4.load(k,12);p=SIMD.Float32x4.shuffle(v,w,0,1,4,5);m=SIMD.Float32x4.shuffle(x,y,0,1,4,5);l=SIMD.Float32x4.shuffle(p,m,0,2,4,6);m=SIMD.Float32x4.shuffle(m,p,1,3,5,7);p=SIMD.Float32x4.shuffle(v,w,2,3,6,7);o=SIMD.Float32x4.shuffle(x,y,2,3,6,7);n=SIMD.Float32x4.shuffle(p,o,0,2,4,6);o=SIMD.Float32x4.shuffle(o,p,1,3,5,7);p=SIMD.Float32x4.mul(n,o);p=SIMD.Float32x4.swizzle(p,1,0,3,2);q=SIMD.Float32x4.mul(m,p);r=SIMD.Float32x4.mul(l,p);p=SIMD.Float32x4.swizzle(p,2,3,0,1);q=SIMD.Float32x4.sub(SIMD.Float32x4.mul(m,p),q);r=SIMD.Float32x4.sub(SIMD.Float32x4.mul(l,p),r);r=SIMD.Float32x4.swizzle(r,2,3,0,1);p=SIMD.Float32x4.mul(m,n);p=SIMD.Float32x4.swizzle(p,1,0,3,2);q=SIMD.Float32x4.add(SIMD.Float32x4.mul(o,p),q);t=SIMD.Float32x4.mul(l,p);p=SIMD.Float32x4.swizzle(p,2,3,0,1);q=SIMD.Float32x4.sub(q,SIMD.Float32x4.mul(o,p));t=SIMD.Float32x4.sub(SIMD.Float32x4.mul(l,p),t);t=SIMD.Float32x4.swizzle(t,2,3,0,1);p=SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(m,2,3,0,1),o);p=SIMD.Float32x4.swizzle(p,1,0,3,2);n=SIMD.Float32x4.swizzle(n,2,3,0,1);q=SIMD.Float32x4.add(SIMD.Float32x4.mul(n,p),q);s=SIMD.Float32x4.mul(l,p);p=SIMD.Float32x4.swizzle(p,2,3,0,1);q=SIMD.Float32x4.sub(q,SIMD.Float32x4.mul(n,p));s=SIMD.Float32x4.sub(SIMD.Float32x4.mul(l,p),s);s=SIMD.Float32x4.swizzle(s,2,3,0,1);p=SIMD.Float32x4.mul(l,m);p=SIMD.Float32x4.swizzle(p,1,0,3,2);s=SIMD.Float32x4.add(SIMD.Float32x4.mul(o,p),s);t=SIMD.Float32x4.sub(SIMD.Float32x4.mul(n,p),t);p=SIMD.Float32x4.swizzle(p,2,3,0,1);s=SIMD.Float32x4.sub(SIMD.Float32x4.mul(o,p),s);t=SIMD.Float32x4.sub(t,SIMD.Float32x4.mul(n,p));p=SIMD.Float32x4.mul(l,o);p=SIMD.Float32x4.swizzle(p,1,0,3,2);r=SIMD.Float32x4.sub(r,SIMD.Float32x4.mul(n,p));s=SIMD.Float32x4.add(SIMD.Float32x4.mul(m,p),s);p=SIMD.Float32x4.swizzle(p,2,3,0,1);r=SIMD.Float32x4.add(SIMD.Float32x4.mul(n,p),r);s=SIMD.Float32x4.sub(s,SIMD.Float32x4.mul(m,p));p=SIMD.Float32x4.mul(l,n);p=SIMD.Float32x4.swizzle(p,1,0,3,2);r=SIMD.Float32x4.add(SIMD.Float32x4.mul(o,p),r);t=SIMD.Float32x4.sub(t,SIMD.Float32x4.mul(m,p));p=SIMD.Float32x4.swizzle(p,2,3,0,1);r=SIMD.Float32x4.sub(r,SIMD.Float32x4.mul(o,p));t=SIMD.Float32x4.add(SIMD.Float32x4.mul(m,p),t);u=SIMD.Float32x4.mul(l,q);u=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(u,2,3,0,1),u);u=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(u,1,0,3,2),u);p=SIMD.Float32x4.reciprocalApproximation(u);u=SIMD.Float32x4.sub(SIMD.Float32x4.add(p,p),SIMD.Float32x4.mul(u,SIMD.Float32x4.mul(p,p)));u=SIMD.Float32x4.swizzle(u,0,0,0,0);if(!u)return null;SIMD.Float32x4.store(j,0,SIMD.Float32x4.mul(u,q));SIMD.Float32x4.store(j,4,SIMD.Float32x4.mul(u,r));SIMD.Float32x4.store(j,8,SIMD.Float32x4.mul(u,s));SIMD.Float32x4.store(j,12,SIMD.Float32x4.mul(u,t));return j;};i.invert=h.USE_SIMD?i.SIMD.invert:i.scalar.invert;i.scalar.adjoint=function(j,k){var l=k[0],m=k[1],n=k[2],o=k[3],p=k[4],q=k[5],r=k[6],s=k[7],t=k[8],u=k[9],v=k[10],w=k[11],x=k[12],y=k[13],z=k[14],aa=k[15];j[0]=(q*(v*aa-w*z)-u*(r*aa-s*z)+y*(r*w-s*v));j[1]=-(m*(v*aa-w*z)-u*(n*aa-o*z)+y*(n*w-o*v));j[2]=(m*(r*aa-s*z)-q*(n*aa-o*z)+y*(n*s-o*r));j[3]=-(m*(r*w-s*v)-q*(n*w-o*v)+u*(n*s-o*r));j[4]=-(p*(v*aa-w*z)-t*(r*aa-s*z)+x*(r*w-s*v));j[5]=(l*(v*aa-w*z)-t*(n*aa-o*z)+x*(n*w-o*v));j[6]=-(l*(r*aa-s*z)-p*(n*aa-o*z)+x*(n*s-o*r));j[7]=(l*(r*w-s*v)-p*(n*w-o*v)+t*(n*s-o*r));j[8]=(p*(u*aa-w*y)-t*(q*aa-s*y)+x*(q*w-s*u));j[9]=-(l*(u*aa-w*y)-t*(m*aa-o*y)+x*(m*w-o*u));j[10]=(l*(q*aa-s*y)-p*(m*aa-o*y)+x*(m*s-o*q));j[11]=-(l*(q*w-s*u)-p*(m*w-o*u)+t*(m*s-o*q));j[12]=-(p*(u*z-v*y)-t*(q*z-r*y)+x*(q*v-r*u));j[13]=(l*(u*z-v*y)-t*(m*z-n*y)+x*(m*v-n*u));j[14]=-(l*(q*z-r*y)-p*(m*z-n*y)+x*(m*r-n*q));j[15]=(l*(q*v-r*u)-p*(m*v-n*u)+t*(m*r-n*q));return j;};i.SIMD.adjoint=function(j,k){var l,m,n,o,p,q,r,s,t,u,v,w,x;l=SIMD.Float32x4.load(k,0);m=SIMD.Float32x4.load(k,4);n=SIMD.Float32x4.load(k,8);o=SIMD.Float32x4.load(k,12);t=SIMD.Float32x4.shuffle(l,m,0,1,4,5);q=SIMD.Float32x4.shuffle(n,o,0,1,4,5);p=SIMD.Float32x4.shuffle(t,q,0,2,4,6);q=SIMD.Float32x4.shuffle(q,t,1,3,5,7);t=SIMD.Float32x4.shuffle(l,m,2,3,6,7);s=SIMD.Float32x4.shuffle(n,o,2,3,6,7);r=SIMD.Float32x4.shuffle(t,s,0,2,4,6);s=SIMD.Float32x4.shuffle(s,t,1,3,5,7);t=SIMD.Float32x4.mul(r,s);t=SIMD.Float32x4.swizzle(t,1,0,3,2);u=SIMD.Float32x4.mul(q,t);v=SIMD.Float32x4.mul(p,t);t=SIMD.Float32x4.swizzle(t,2,3,0,1);u=SIMD.Float32x4.sub(SIMD.Float32x4.mul(q,t),u);v=SIMD.Float32x4.sub(SIMD.Float32x4.mul(p,t),v);v=SIMD.Float32x4.swizzle(v,2,3,0,1);t=SIMD.Float32x4.mul(q,r);t=SIMD.Float32x4.swizzle(t,1,0,3,2);u=SIMD.Float32x4.add(SIMD.Float32x4.mul(s,t),u);x=SIMD.Float32x4.mul(p,t);t=SIMD.Float32x4.swizzle(t,2,3,0,1);u=SIMD.Float32x4.sub(u,SIMD.Float32x4.mul(s,t));x=SIMD.Float32x4.sub(SIMD.Float32x4.mul(p,t),x);x=SIMD.Float32x4.swizzle(x,2,3,0,1);t=SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(q,2,3,0,1),s);t=SIMD.Float32x4.swizzle(t,1,0,3,2);r=SIMD.Float32x4.swizzle(r,2,3,0,1);u=SIMD.Float32x4.add(SIMD.Float32x4.mul(r,t),u);w=SIMD.Float32x4.mul(p,t);t=SIMD.Float32x4.swizzle(t,2,3,0,1);u=SIMD.Float32x4.sub(u,SIMD.Float32x4.mul(r,t));w=SIMD.Float32x4.sub(SIMD.Float32x4.mul(p,t),w);w=SIMD.Float32x4.swizzle(w,2,3,0,1);t=SIMD.Float32x4.mul(p,q);t=SIMD.Float32x4.swizzle(t,1,0,3,2);w=SIMD.Float32x4.add(SIMD.Float32x4.mul(s,t),w);x=SIMD.Float32x4.sub(SIMD.Float32x4.mul(r,t),x);t=SIMD.Float32x4.swizzle(t,2,3,0,1);w=SIMD.Float32x4.sub(SIMD.Float32x4.mul(s,t),w);x=SIMD.Float32x4.sub(x,SIMD.Float32x4.mul(r,t));t=SIMD.Float32x4.mul(p,s);t=SIMD.Float32x4.swizzle(t,1,0,3,2);v=SIMD.Float32x4.sub(v,SIMD.Float32x4.mul(r,t));w=SIMD.Float32x4.add(SIMD.Float32x4.mul(q,t),w);t=SIMD.Float32x4.swizzle(t,2,3,0,1);v=SIMD.Float32x4.add(SIMD.Float32x4.mul(r,t),v);w=SIMD.Float32x4.sub(w,SIMD.Float32x4.mul(q,t));t=SIMD.Float32x4.mul(p,r);t=SIMD.Float32x4.swizzle(t,1,0,3,2);v=SIMD.Float32x4.add(SIMD.Float32x4.mul(s,t),v);x=SIMD.Float32x4.sub(x,SIMD.Float32x4.mul(q,t));t=SIMD.Float32x4.swizzle(t,2,3,0,1);v=SIMD.Float32x4.sub(v,SIMD.Float32x4.mul(s,t));x=SIMD.Float32x4.add(SIMD.Float32x4.mul(q,t),x);SIMD.Float32x4.store(j,0,u);SIMD.Float32x4.store(j,4,v);SIMD.Float32x4.store(j,8,w);SIMD.Float32x4.store(j,12,x);return j;};i.adjoint=h.USE_SIMD?i.SIMD.adjoint:i.scalar.adjoint;i.determinant=function(j){var k=j[0],l=j[1],m=j[2],n=j[3],o=j[4],p=j[5],q=j[6],r=j[7],s=j[8],t=j[9],u=j[10],v=j[11],w=j[12],x=j[13],y=j[14],z=j[15],aa=k*p-l*o,ba=k*q-m*o,ca=k*r-n*o,da=l*q-m*p,ea=l*r-n*p,fa=m*r-n*q,ga=s*x-t*w,ha=s*y-u*w,ia=s*z-v*w,ja=t*y-u*x,ka=t*z-v*x,la=u*z-v*y;return aa*la-ba*ka+ca*ja+da*ia-ea*ha+fa*ga;};i.SIMD.multiply=function(j,k,l){var m=SIMD.Float32x4.load(k,0),n=SIMD.Float32x4.load(k,4),o=SIMD.Float32x4.load(k,8),p=SIMD.Float32x4.load(k,12),q=SIMD.Float32x4.load(l,0),r=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(q,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(q,1,1,1,1),n),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(q,2,2,2,2),o),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(q,3,3,3,3),p))));SIMD.Float32x4.store(j,0,r);var s=SIMD.Float32x4.load(l,4),t=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s,1,1,1,1),n),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s,2,2,2,2),o),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s,3,3,3,3),p))));SIMD.Float32x4.store(j,4,t);var u=SIMD.Float32x4.load(l,8),v=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(u,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(u,1,1,1,1),n),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(u,2,2,2,2),o),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(u,3,3,3,3),p))));SIMD.Float32x4.store(j,8,v);var w=SIMD.Float32x4.load(l,12),x=SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(w,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(w,1,1,1,1),n),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(w,2,2,2,2),o),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(w,3,3,3,3),p))));SIMD.Float32x4.store(j,12,x);return j;};i.scalar.multiply=function(j,k,l){var m=k[0],n=k[1],o=k[2],p=k[3],q=k[4],r=k[5],s=k[6],t=k[7],u=k[8],v=k[9],w=k[10],x=k[11],y=k[12],z=k[13],aa=k[14],ba=k[15],ca=l[0],da=l[1],ea=l[2],fa=l[3];j[0]=ca*m+da*q+ea*u+fa*y;j[1]=ca*n+da*r+ea*v+fa*z;j[2]=ca*o+da*s+ea*w+fa*aa;j[3]=ca*p+da*t+ea*x+fa*ba;ca=l[4];da=l[5];ea=l[6];fa=l[7];j[4]=ca*m+da*q+ea*u+fa*y;j[5]=ca*n+da*r+ea*v+fa*z;j[6]=ca*o+da*s+ea*w+fa*aa;j[7]=ca*p+da*t+ea*x+fa*ba;ca=l[8];da=l[9];ea=l[10];fa=l[11];j[8]=ca*m+da*q+ea*u+fa*y;j[9]=ca*n+da*r+ea*v+fa*z;j[10]=ca*o+da*s+ea*w+fa*aa;j[11]=ca*p+da*t+ea*x+fa*ba;ca=l[12];da=l[13];ea=l[14];fa=l[15];j[12]=ca*m+da*q+ea*u+fa*y;j[13]=ca*n+da*r+ea*v+fa*z;j[14]=ca*o+da*s+ea*w+fa*aa;j[15]=ca*p+da*t+ea*x+fa*ba;return j;};i.multiply=h.USE_SIMD?i.SIMD.multiply:i.scalar.multiply;i.mul=i.multiply;i.scalar.translate=function(j,k,l){var m=l[0],n=l[1],o=l[2],p,q,r,s,t,u,v,w,x,y,z,aa;if(k===j){j[12]=k[0]*m+k[4]*n+k[8]*o+k[12];j[13]=k[1]*m+k[5]*n+k[9]*o+k[13];j[14]=k[2]*m+k[6]*n+k[10]*o+k[14];j[15]=k[3]*m+k[7]*n+k[11]*o+k[15];}else{p=k[0];q=k[1];r=k[2];s=k[3];t=k[4];u=k[5];v=k[6];w=k[7];x=k[8];y=k[9];z=k[10];aa=k[11];j[0]=p;j[1]=q;j[2]=r;j[3]=s;j[4]=t;j[5]=u;j[6]=v;j[7]=w;j[8]=x;j[9]=y;j[10]=z;j[11]=aa;j[12]=p*m+t*n+x*o+k[12];j[13]=q*m+u*n+y*o+k[13];j[14]=r*m+v*n+z*o+k[14];j[15]=s*m+w*n+aa*o+k[15];}return j;};i.SIMD.translate=function(j,k,l){var m=SIMD.Float32x4.load(k,0),n=SIMD.Float32x4.load(k,4),o=SIMD.Float32x4.load(k,8),p=SIMD.Float32x4.load(k,12),q=SIMD.Float32x4(l[0],l[1],l[2],0);if(k!==j){j[0]=k[0];j[1]=k[1];j[2]=k[2];j[3]=k[3];j[4]=k[4];j[5]=k[5];j[6]=k[6];j[7]=k[7];j[8]=k[8];j[9]=k[9];j[10]=k[10];j[11]=k[11];}m=SIMD.Float32x4.mul(m,SIMD.Float32x4.swizzle(q,0,0,0,0));n=SIMD.Float32x4.mul(n,SIMD.Float32x4.swizzle(q,1,1,1,1));o=SIMD.Float32x4.mul(o,SIMD.Float32x4.swizzle(q,2,2,2,2));var r=SIMD.Float32x4.add(m,SIMD.Float32x4.add(n,SIMD.Float32x4.add(o,p)));SIMD.Float32x4.store(j,12,r);return j;};i.translate=h.USE_SIMD?i.SIMD.translate:i.scalar.translate;i.scalar.scale=function(j,k,l){var m=l[0],n=l[1],o=l[2];j[0]=k[0]*m;j[1]=k[1]*m;j[2]=k[2]*m;j[3]=k[3]*m;j[4]=k[4]*n;j[5]=k[5]*n;j[6]=k[6]*n;j[7]=k[7]*n;j[8]=k[8]*o;j[9]=k[9]*o;j[10]=k[10]*o;j[11]=k[11]*o;j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];return j;};i.SIMD.scale=function(j,k,l){var m,n,o,p=SIMD.Float32x4(l[0],l[1],l[2],0);m=SIMD.Float32x4.load(k,0);SIMD.Float32x4.store(j,0,SIMD.Float32x4.mul(m,SIMD.Float32x4.swizzle(p,0,0,0,0)));n=SIMD.Float32x4.load(k,4);SIMD.Float32x4.store(j,4,SIMD.Float32x4.mul(n,SIMD.Float32x4.swizzle(p,1,1,1,1)));o=SIMD.Float32x4.load(k,8);SIMD.Float32x4.store(j,8,SIMD.Float32x4.mul(o,SIMD.Float32x4.swizzle(p,2,2,2,2)));j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];return j;};i.scale=h.USE_SIMD?i.SIMD.scale:i.scalar.scale;i.rotate=function(j,k,l,m){var n=m[0],o=m[1],p=m[2],q=Math.sqrt(n*n+o*o+p*p),r,s,t,u,v,w,x,y,z,aa,ba,ca,da,ea,fa,ga,ha,ia,ja,ka,la,ma,na,oa;if(Math.abs(q)<h.EPSILON)return null;q=1/q;n*=q;o*=q;p*=q;r=Math.sin(l);s=Math.cos(l);t=1-s;u=k[0];v=k[1];w=k[2];x=k[3];y=k[4];z=k[5];aa=k[6];ba=k[7];ca=k[8];da=k[9];ea=k[10];fa=k[11];ga=n*n*t+s;ha=o*n*t+p*r;ia=p*n*t-o*r;ja=n*o*t-p*r;ka=o*o*t+s;la=p*o*t+n*r;ma=n*p*t+o*r;na=o*p*t-n*r;oa=p*p*t+s;j[0]=u*ga+y*ha+ca*ia;j[1]=v*ga+z*ha+da*ia;j[2]=w*ga+aa*ha+ea*ia;j[3]=x*ga+ba*ha+fa*ia;j[4]=u*ja+y*ka+ca*la;j[5]=v*ja+z*ka+da*la;j[6]=w*ja+aa*ka+ea*la;j[7]=x*ja+ba*ka+fa*la;j[8]=u*ma+y*na+ca*oa;j[9]=v*ma+z*na+da*oa;j[10]=w*ma+aa*na+ea*oa;j[11]=x*ma+ba*na+fa*oa;if(k!==j){j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];}return j;};i.scalar.rotateX=function(j,k,l){var m=Math.sin(l),n=Math.cos(l),o=k[4],p=k[5],q=k[6],r=k[7],s=k[8],t=k[9],u=k[10],v=k[11];if(k!==j){j[0]=k[0];j[1]=k[1];j[2]=k[2];j[3]=k[3];j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];}j[4]=o*n+s*m;j[5]=p*n+t*m;j[6]=q*n+u*m;j[7]=r*n+v*m;j[8]=s*n-o*m;j[9]=t*n-p*m;j[10]=u*n-q*m;j[11]=v*n-r*m;return j;};i.SIMD.rotateX=function(j,k,l){var m=SIMD.Float32x4.splat(Math.sin(l)),n=SIMD.Float32x4.splat(Math.cos(l));if(k!==j){j[0]=k[0];j[1]=k[1];j[2]=k[2];j[3]=k[3];j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];}var o=SIMD.Float32x4.load(k,4),p=SIMD.Float32x4.load(k,8);SIMD.Float32x4.store(j,4,SIMD.Float32x4.add(SIMD.Float32x4.mul(o,n),SIMD.Float32x4.mul(p,m)));SIMD.Float32x4.store(j,8,SIMD.Float32x4.sub(SIMD.Float32x4.mul(p,n),SIMD.Float32x4.mul(o,m)));return j;};i.rotateX=h.USE_SIMD?i.SIMD.rotateX:i.scalar.rotateX;i.scalar.rotateY=function(j,k,l){var m=Math.sin(l),n=Math.cos(l),o=k[0],p=k[1],q=k[2],r=k[3],s=k[8],t=k[9],u=k[10],v=k[11];if(k!==j){j[4]=k[4];j[5]=k[5];j[6]=k[6];j[7]=k[7];j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];}j[0]=o*n-s*m;j[1]=p*n-t*m;j[2]=q*n-u*m;j[3]=r*n-v*m;j[8]=o*m+s*n;j[9]=p*m+t*n;j[10]=q*m+u*n;j[11]=r*m+v*n;return j;};i.SIMD.rotateY=function(j,k,l){var m=SIMD.Float32x4.splat(Math.sin(l)),n=SIMD.Float32x4.splat(Math.cos(l));if(k!==j){j[4]=k[4];j[5]=k[5];j[6]=k[6];j[7]=k[7];j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];}var o=SIMD.Float32x4.load(k,0),p=SIMD.Float32x4.load(k,8);SIMD.Float32x4.store(j,0,SIMD.Float32x4.sub(SIMD.Float32x4.mul(o,n),SIMD.Float32x4.mul(p,m)));SIMD.Float32x4.store(j,8,SIMD.Float32x4.add(SIMD.Float32x4.mul(o,m),SIMD.Float32x4.mul(p,n)));return j;};i.rotateY=h.USE_SIMD?i.SIMD.rotateY:i.scalar.rotateY;i.scalar.rotateZ=function(j,k,l){var m=Math.sin(l),n=Math.cos(l),o=k[0],p=k[1],q=k[2],r=k[3],s=k[4],t=k[5],u=k[6],v=k[7];if(k!==j){j[8]=k[8];j[9]=k[9];j[10]=k[10];j[11]=k[11];j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];}j[0]=o*n+s*m;j[1]=p*n+t*m;j[2]=q*n+u*m;j[3]=r*n+v*m;j[4]=s*n-o*m;j[5]=t*n-p*m;j[6]=u*n-q*m;j[7]=v*n-r*m;return j;};i.SIMD.rotateZ=function(j,k,l){var m=SIMD.Float32x4.splat(Math.sin(l)),n=SIMD.Float32x4.splat(Math.cos(l));if(k!==j){j[8]=k[8];j[9]=k[9];j[10]=k[10];j[11]=k[11];j[12]=k[12];j[13]=k[13];j[14]=k[14];j[15]=k[15];}var o=SIMD.Float32x4.load(k,0),p=SIMD.Float32x4.load(k,4);SIMD.Float32x4.store(j,0,SIMD.Float32x4.add(SIMD.Float32x4.mul(o,n),SIMD.Float32x4.mul(p,m)));SIMD.Float32x4.store(j,4,SIMD.Float32x4.sub(SIMD.Float32x4.mul(p,n),SIMD.Float32x4.mul(o,m)));return j;};i.rotateZ=h.USE_SIMD?i.SIMD.rotateZ:i.scalar.rotateZ;i.fromTranslation=function(j,k){j[0]=1;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=1;j[6]=0;j[7]=0;j[8]=0;j[9]=0;j[10]=1;j[11]=0;j[12]=k[0];j[13]=k[1];j[14]=k[2];j[15]=1;return j;};i.fromScaling=function(j,k){j[0]=k[0];j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=k[1];j[6]=0;j[7]=0;j[8]=0;j[9]=0;j[10]=k[2];j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.fromRotation=function(j,k,l){var m=l[0],n=l[1],o=l[2],p=Math.sqrt(m*m+n*n+o*o),q,r,s;if(Math.abs(p)<h.EPSILON)return null;p=1/p;m*=p;n*=p;o*=p;q=Math.sin(k);r=Math.cos(k);s=1-r;j[0]=m*m*s+r;j[1]=n*m*s+o*q;j[2]=o*m*s-n*q;j[3]=0;j[4]=m*n*s-o*q;j[5]=n*n*s+r;j[6]=o*n*s+m*q;j[7]=0;j[8]=m*o*s+n*q;j[9]=n*o*s-m*q;j[10]=o*o*s+r;j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.fromXRotation=function(j,k){var l=Math.sin(k),m=Math.cos(k);j[0]=1;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=m;j[6]=l;j[7]=0;j[8]=0;j[9]=-l;j[10]=m;j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.fromYRotation=function(j,k){var l=Math.sin(k),m=Math.cos(k);j[0]=m;j[1]=0;j[2]=-l;j[3]=0;j[4]=0;j[5]=1;j[6]=0;j[7]=0;j[8]=l;j[9]=0;j[10]=m;j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.fromZRotation=function(j,k){var l=Math.sin(k),m=Math.cos(k);j[0]=m;j[1]=l;j[2]=0;j[3]=0;j[4]=-l;j[5]=m;j[6]=0;j[7]=0;j[8]=0;j[9]=0;j[10]=1;j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.fromRotationTranslation=function(j,k,l){var m=k[0],n=k[1],o=k[2],p=k[3],q=m+m,r=n+n,s=o+o,t=m*q,u=m*r,v=m*s,w=n*r,x=n*s,y=o*s,z=p*q,aa=p*r,ba=p*s;j[0]=1-(w+y);j[1]=u+ba;j[2]=v-aa;j[3]=0;j[4]=u-ba;j[5]=1-(t+y);j[6]=x+z;j[7]=0;j[8]=v+aa;j[9]=x-z;j[10]=1-(t+w);j[11]=0;j[12]=l[0];j[13]=l[1];j[14]=l[2];j[15]=1;return j;};i.getTranslation=function(j,k){j[0]=k[12];j[1]=k[13];j[2]=k[14];return j;};i.getRotation=function(j,k){var l=k[0]+k[5]+k[10],m=0;if(l>0){m=Math.sqrt(l+1)*2;j[3]=.25*m;j[0]=(k[6]-k[9])/m;j[1]=(k[8]-k[2])/m;j[2]=(k[1]-k[4])/m;}else if((k[0]>k[5])&(k[0]>k[10])){m=Math.sqrt(1+k[0]-k[5]-k[10])*2;j[3]=(k[6]-k[9])/m;j[0]=.25*m;j[1]=(k[1]+k[4])/m;j[2]=(k[8]+k[2])/m;}else if(k[5]>k[10]){m=Math.sqrt(1+k[5]-k[0]-k[10])*2;j[3]=(k[8]-k[2])/m;j[0]=(k[1]+k[4])/m;j[1]=.25*m;j[2]=(k[6]+k[9])/m;}else{m=Math.sqrt(1+k[10]-k[0]-k[5])*2;j[3]=(k[1]-k[4])/m;j[0]=(k[8]+k[2])/m;j[1]=(k[6]+k[9])/m;j[2]=.25*m;}return j;};i.fromRotationTranslationScale=function(j,k,l,m){var n=k[0],o=k[1],p=k[2],q=k[3],r=n+n,s=o+o,t=p+p,u=n*r,v=n*s,w=n*t,x=o*s,y=o*t,z=p*t,aa=q*r,ba=q*s,ca=q*t,da=m[0],ea=m[1],fa=m[2];j[0]=(1-(x+z))*da;j[1]=(v+ca)*da;j[2]=(w-ba)*da;j[3]=0;j[4]=(v-ca)*ea;j[5]=(1-(u+z))*ea;j[6]=(y+aa)*ea;j[7]=0;j[8]=(w+ba)*fa;j[9]=(y-aa)*fa;j[10]=(1-(u+x))*fa;j[11]=0;j[12]=l[0];j[13]=l[1];j[14]=l[2];j[15]=1;return j;};i.fromRotationTranslationScaleOrigin=function(j,k,l,m,n){var o=k[0],p=k[1],q=k[2],r=k[3],s=o+o,t=p+p,u=q+q,v=o*s,w=o*t,x=o*u,y=p*t,z=p*u,aa=q*u,ba=r*s,ca=r*t,da=r*u,ea=m[0],fa=m[1],ga=m[2],ha=n[0],ia=n[1],ja=n[2];j[0]=(1-(y+aa))*ea;j[1]=(w+da)*ea;j[2]=(x-ca)*ea;j[3]=0;j[4]=(w-da)*fa;j[5]=(1-(v+aa))*fa;j[6]=(z+ba)*fa;j[7]=0;j[8]=(x+ca)*ga;j[9]=(z-ba)*ga;j[10]=(1-(v+y))*ga;j[11]=0;j[12]=l[0]+ha-(j[0]*ha+j[4]*ia+j[8]*ja);j[13]=l[1]+ia-(j[1]*ha+j[5]*ia+j[9]*ja);j[14]=l[2]+ja-(j[2]*ha+j[6]*ia+j[10]*ja);j[15]=1;return j;};i.fromQuat=function(j,k){var l=k[0],m=k[1],n=k[2],o=k[3],p=l+l,q=m+m,r=n+n,s=l*p,t=m*p,u=m*q,v=n*p,w=n*q,x=n*r,y=o*p,z=o*q,aa=o*r;j[0]=1-u-x;j[1]=t+aa;j[2]=v-z;j[3]=0;j[4]=t-aa;j[5]=1-s-x;j[6]=w+y;j[7]=0;j[8]=v+z;j[9]=w-y;j[10]=1-s-u;j[11]=0;j[12]=0;j[13]=0;j[14]=0;j[15]=1;return j;};i.frustum=function(j,k,l,m,n,o,p){var q=1/(l-k),r=1/(n-m),s=1/(o-p);j[0]=(o*2)*q;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=(o*2)*r;j[6]=0;j[7]=0;j[8]=(l+k)*q;j[9]=(n+m)*r;j[10]=(p+o)*s;j[11]=-1;j[12]=0;j[13]=0;j[14]=(p*o*2)*s;j[15]=0;return j;};i.perspective=function(j,k,l,m,n){var o=1/Math.tan(k/2),p=1/(m-n);j[0]=o/l;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=o;j[6]=0;j[7]=0;j[8]=0;j[9]=0;j[10]=(n+m)*p;j[11]=-1;j[12]=0;j[13]=0;j[14]=(2*n*m)*p;j[15]=0;return j;};i.perspectiveFromFieldOfView=function(j,k,l,m){var n=Math.tan(k.upDegrees*Math.PI/180),o=Math.tan(k.downDegrees*Math.PI/180),p=Math.tan(k.leftDegrees*Math.PI/180),q=Math.tan(k.rightDegrees*Math.PI/180),r=2/(p+q),s=2/(n+o);j[0]=r;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=s;j[6]=0;j[7]=0;j[8]=-((p-q)*r*.5);j[9]=((n-o)*s*.5);j[10]=m/(l-m);j[11]=-1;j[12]=0;j[13]=0;j[14]=(m*l)/(l-m);j[15]=0;return j;};i.ortho=function(j,k,l,m,n,o,p){var q=1/(k-l),r=1/(m-n),s=1/(o-p);j[0]=-2*q;j[1]=0;j[2]=0;j[3]=0;j[4]=0;j[5]=-2*r;j[6]=0;j[7]=0;j[8]=0;j[9]=0;j[10]=2*s;j[11]=0;j[12]=(k+l)*q;j[13]=(n+m)*r;j[14]=(p+o)*s;j[15]=1;return j;};i.lookAt=function(j,k,l,m){var n,o,p,q,r,s,t,u,v,w,x=k[0],y=k[1],z=k[2],aa=m[0],ba=m[1],ca=m[2],da=l[0],ea=l[1],fa=l[2];if(Math.abs(x-da)<h.EPSILON&&Math.abs(y-ea)<h.EPSILON&&Math.abs(z-fa)<h.EPSILON)return i.identity(j);t=x-da;u=y-ea;v=z-fa;w=1/Math.sqrt(t*t+u*u+v*v);t*=w;u*=w;v*=w;n=ba*v-ca*u;o=ca*t-aa*v;p=aa*u-ba*t;w=Math.sqrt(n*n+o*o+p*p);if(!w){n=0;o=0;p=0;}else{w=1/w;n*=w;o*=w;p*=w;}q=u*p-v*o;r=v*n-t*p;s=t*o-u*n;w=Math.sqrt(q*q+r*r+s*s);if(!w){q=0;r=0;s=0;}else{w=1/w;q*=w;r*=w;s*=w;}j[0]=n;j[1]=q;j[2]=t;j[3]=0;j[4]=o;j[5]=r;j[6]=u;j[7]=0;j[8]=p;j[9]=s;j[10]=v;j[11]=0;j[12]=-(n*x+o*y+p*z);j[13]=-(q*x+r*y+s*z);j[14]=-(t*x+u*y+v*z);j[15]=1;return j;};i.str=function(j){return 'mat4('+j[0]+', '+j[1]+', '+j[2]+', '+j[3]+', '+j[4]+', '+j[5]+', '+j[6]+', '+j[7]+', '+j[8]+', '+j[9]+', '+j[10]+', '+j[11]+', '+j[12]+', '+j[13]+', '+j[14]+', '+j[15]+')';};i.frob=function(j){return (Math.sqrt(Math.pow(j[0],2)+Math.pow(j[1],2)+Math.pow(j[2],2)+Math.pow(j[3],2)+Math.pow(j[4],2)+Math.pow(j[5],2)+Math.pow(j[6],2)+Math.pow(j[7],2)+Math.pow(j[8],2)+Math.pow(j[9],2)+Math.pow(j[10],2)+Math.pow(j[11],2)+Math.pow(j[12],2)+Math.pow(j[13],2)+Math.pow(j[14],2)+Math.pow(j[15],2)));};i.add=function(j,k,l){j[0]=k[0]+l[0];j[1]=k[1]+l[1];j[2]=k[2]+l[2];j[3]=k[3]+l[3];j[4]=k[4]+l[4];j[5]=k[5]+l[5];j[6]=k[6]+l[6];j[7]=k[7]+l[7];j[8]=k[8]+l[8];j[9]=k[9]+l[9];j[10]=k[10]+l[10];j[11]=k[11]+l[11];j[12]=k[12]+l[12];j[13]=k[13]+l[13];j[14]=k[14]+l[14];j[15]=k[15]+l[15];return j;};i.subtract=function(j,k,l){j[0]=k[0]-l[0];j[1]=k[1]-l[1];j[2]=k[2]-l[2];j[3]=k[3]-l[3];j[4]=k[4]-l[4];j[5]=k[5]-l[5];j[6]=k[6]-l[6];j[7]=k[7]-l[7];j[8]=k[8]-l[8];j[9]=k[9]-l[9];j[10]=k[10]-l[10];j[11]=k[11]-l[11];j[12]=k[12]-l[12];j[13]=k[13]-l[13];j[14]=k[14]-l[14];j[15]=k[15]-l[15];return j;};i.sub=i.subtract;i.multiplyScalar=function(j,k,l){j[0]=k[0]*l;j[1]=k[1]*l;j[2]=k[2]*l;j[3]=k[3]*l;j[4]=k[4]*l;j[5]=k[5]*l;j[6]=k[6]*l;j[7]=k[7]*l;j[8]=k[8]*l;j[9]=k[9]*l;j[10]=k[10]*l;j[11]=k[11]*l;j[12]=k[12]*l;j[13]=k[13]*l;j[14]=k[14]*l;j[15]=k[15]*l;return j;};i.multiplyScalarAndAdd=function(j,k,l,m){j[0]=k[0]+(l[0]*m);j[1]=k[1]+(l[1]*m);j[2]=k[2]+(l[2]*m);j[3]=k[3]+(l[3]*m);j[4]=k[4]+(l[4]*m);j[5]=k[5]+(l[5]*m);j[6]=k[6]+(l[6]*m);j[7]=k[7]+(l[7]*m);j[8]=k[8]+(l[8]*m);j[9]=k[9]+(l[9]*m);j[10]=k[10]+(l[10]*m);j[11]=k[11]+(l[11]*m);j[12]=k[12]+(l[12]*m);j[13]=k[13]+(l[13]*m);j[14]=k[14]+(l[14]*m);j[15]=k[15]+(l[15]*m);return j;};i.exactEquals=function(j,k){return j[0]===k[0]&&j[1]===k[1]&&j[2]===k[2]&&j[3]===k[3]&&j[4]===k[4]&&j[5]===k[5]&&j[6]===k[6]&&j[7]===k[7]&&j[8]===k[8]&&j[9]===k[9]&&j[10]===k[10]&&j[11]===k[11]&&j[12]===k[12]&&j[13]===k[13]&&j[14]===k[14]&&j[15]===k[15];};i.equals=function(j,k){var l=j[0],m=j[1],n=j[2],o=j[3],p=j[4],q=j[5],r=j[6],s=j[7],t=j[8],u=j[9],v=j[10],w=j[11],x=j[12],y=j[13],z=j[14],aa=j[15],ba=k[0],ca=k[1],da=k[2],ea=k[3],fa=k[4],ga=k[5],ha=k[6],ia=k[7],ja=k[8],ka=k[9],la=k[10],ma=k[11],na=k[12],oa=k[13],pa=k[14],qa=k[15];return (Math.abs(l-ba)<=h.EPSILON*Math.max(1,Math.abs(l),Math.abs(ba))&&Math.abs(m-ca)<=h.EPSILON*Math.max(1,Math.abs(m),Math.abs(ca))&&Math.abs(n-da)<=h.EPSILON*Math.max(1,Math.abs(n),Math.abs(da))&&Math.abs(o-ea)<=h.EPSILON*Math.max(1,Math.abs(o),Math.abs(ea))&&Math.abs(p-fa)<=h.EPSILON*Math.max(1,Math.abs(p),Math.abs(fa))&&Math.abs(q-ga)<=h.EPSILON*Math.max(1,Math.abs(q),Math.abs(ga))&&Math.abs(r-ha)<=h.EPSILON*Math.max(1,Math.abs(r),Math.abs(ha))&&Math.abs(s-ia)<=h.EPSILON*Math.max(1,Math.abs(s),Math.abs(ia))&&Math.abs(t-ja)<=h.EPSILON*Math.max(1,Math.abs(t),Math.abs(ja))&&Math.abs(u-ka)<=h.EPSILON*Math.max(1,Math.abs(u),Math.abs(ka))&&Math.abs(v-la)<=h.EPSILON*Math.max(1,Math.abs(v),Math.abs(la))&&Math.abs(w-ma)<=h.EPSILON*Math.max(1,Math.abs(w),Math.abs(ma))&&Math.abs(x-na)<=h.EPSILON*Math.max(1,Math.abs(x),Math.abs(na))&&Math.abs(y-oa)<=h.EPSILON*Math.max(1,Math.abs(y),Math.abs(oa))&&Math.abs(z-pa)<=h.EPSILON*Math.max(1,Math.abs(z),Math.abs(pa))&&Math.abs(aa-qa)<=h.EPSILON*Math.max(1,Math.abs(aa),Math.abs(qa)));};f.exports=i;}),null);
__d("gl-matrix-vec3",["gl-matrix-common"],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();var h=c("gl-matrix-common"),i={};i.create=function(){var j=new h.ARRAY_TYPE(3);j[0]=0;j[1]=0;j[2]=0;return j;};i.clone=function(j){var k=new h.ARRAY_TYPE(3);k[0]=j[0];k[1]=j[1];k[2]=j[2];return k;};i.fromValues=function(j,k,l){var m=new h.ARRAY_TYPE(3);m[0]=j;m[1]=k;m[2]=l;return m;};i.copy=function(j,k){j[0]=k[0];j[1]=k[1];j[2]=k[2];return j;};i.set=function(j,k,l,m){j[0]=k;j[1]=l;j[2]=m;return j;};i.add=function(j,k,l){j[0]=k[0]+l[0];j[1]=k[1]+l[1];j[2]=k[2]+l[2];return j;};i.subtract=function(j,k,l){j[0]=k[0]-l[0];j[1]=k[1]-l[1];j[2]=k[2]-l[2];return j;};i.sub=i.subtract;i.multiply=function(j,k,l){j[0]=k[0]*l[0];j[1]=k[1]*l[1];j[2]=k[2]*l[2];return j;};i.mul=i.multiply;i.divide=function(j,k,l){j[0]=k[0]/l[0];j[1]=k[1]/l[1];j[2]=k[2]/l[2];return j;};i.div=i.divide;i.ceil=function(j,k){j[0]=Math.ceil(k[0]);j[1]=Math.ceil(k[1]);j[2]=Math.ceil(k[2]);return j;};i.floor=function(j,k){j[0]=Math.floor(k[0]);j[1]=Math.floor(k[1]);j[2]=Math.floor(k[2]);return j;};i.min=function(j,k,l){j[0]=Math.min(k[0],l[0]);j[1]=Math.min(k[1],l[1]);j[2]=Math.min(k[2],l[2]);return j;};i.max=function(j,k,l){j[0]=Math.max(k[0],l[0]);j[1]=Math.max(k[1],l[1]);j[2]=Math.max(k[2],l[2]);return j;};i.round=function(j,k){j[0]=Math.round(k[0]);j[1]=Math.round(k[1]);j[2]=Math.round(k[2]);return j;};i.scale=function(j,k,l){j[0]=k[0]*l;j[1]=k[1]*l;j[2]=k[2]*l;return j;};i.scaleAndAdd=function(j,k,l,m){j[0]=k[0]+(l[0]*m);j[1]=k[1]+(l[1]*m);j[2]=k[2]+(l[2]*m);return j;};i.distance=function(j,k){var l=k[0]-j[0],m=k[1]-j[1],n=k[2]-j[2];return Math.sqrt(l*l+m*m+n*n);};i.dist=i.distance;i.squaredDistance=function(j,k){var l=k[0]-j[0],m=k[1]-j[1],n=k[2]-j[2];return l*l+m*m+n*n;};i.sqrDist=i.squaredDistance;i.length=function(j){var k=j[0],l=j[1],m=j[2];return Math.sqrt(k*k+l*l+m*m);};i.len=i.length;i.squaredLength=function(j){var k=j[0],l=j[1],m=j[2];return k*k+l*l+m*m;};i.sqrLen=i.squaredLength;i.negate=function(j,k){j[0]=-k[0];j[1]=-k[1];j[2]=-k[2];return j;};i.inverse=function(j,k){j[0]=1/k[0];j[1]=1/k[1];j[2]=1/k[2];return j;};i.normalize=function(j,k){var l=k[0],m=k[1],n=k[2],o=l*l+m*m+n*n;if(o>0){o=1/Math.sqrt(o);j[0]=k[0]*o;j[1]=k[1]*o;j[2]=k[2]*o;}return j;};i.dot=function(j,k){return j[0]*k[0]+j[1]*k[1]+j[2]*k[2];};i.cross=function(j,k,l){var m=k[0],n=k[1],o=k[2],p=l[0],q=l[1],r=l[2];j[0]=n*r-o*q;j[1]=o*p-m*r;j[2]=m*q-n*p;return j;};i.lerp=function(j,k,l,m){var n=k[0],o=k[1],p=k[2];j[0]=n+m*(l[0]-n);j[1]=o+m*(l[1]-o);j[2]=p+m*(l[2]-p);return j;};i.hermite=function(j,k,l,m,n,o){var p=o*o,q=p*(2*o-3)+1,r=p*(o-2)+o,s=p*(o-1),t=p*(3-2*o);j[0]=k[0]*q+l[0]*r+m[0]*s+n[0]*t;j[1]=k[1]*q+l[1]*r+m[1]*s+n[1]*t;j[2]=k[2]*q+l[2]*r+m[2]*s+n[2]*t;return j;};i.bezier=function(j,k,l,m,n,o){var p=1-o,q=p*p,r=o*o,s=q*p,t=3*o*q,u=3*r*p,v=r*o;j[0]=k[0]*s+l[0]*t+m[0]*u+n[0]*v;j[1]=k[1]*s+l[1]*t+m[1]*u+n[1]*v;j[2]=k[2]*s+l[2]*t+m[2]*u+n[2]*v;return j;};i.random=function(j,k){k=k||1;var l=h.RANDOM()*2*Math.PI,m=(h.RANDOM()*2)-1,n=Math.sqrt(1-m*m)*k;j[0]=Math.cos(l)*n;j[1]=Math.sin(l)*n;j[2]=m*k;return j;};i.transformMat4=function(j,k,l){var m=k[0],n=k[1],o=k[2],p=l[3]*m+l[7]*n+l[11]*o+l[15];p=p||1;j[0]=(l[0]*m+l[4]*n+l[8]*o+l[12])/p;j[1]=(l[1]*m+l[5]*n+l[9]*o+l[13])/p;j[2]=(l[2]*m+l[6]*n+l[10]*o+l[14])/p;return j;};i.transformMat3=function(j,k,l){var m=k[0],n=k[1],o=k[2];j[0]=m*l[0]+n*l[3]+o*l[6];j[1]=m*l[1]+n*l[4]+o*l[7];j[2]=m*l[2]+n*l[5]+o*l[8];return j;};i.transformQuat=function(j,k,l){var m=k[0],n=k[1],o=k[2],p=l[0],q=l[1],r=l[2],s=l[3],t=s*m+q*o-r*n,u=s*n+r*m-p*o,v=s*o+p*n-q*m,w=-p*m-q*n-r*o;j[0]=t*s+w*-p+u*-r-v*-q;j[1]=u*s+w*-q+v*-p-t*-r;j[2]=v*s+w*-r+t*-q-u*-p;return j;};i.rotateX=function(j,k,l,m){var n=[],o=[];n[0]=k[0]-l[0];n[1]=k[1]-l[1];n[2]=k[2]-l[2];o[0]=n[0];o[1]=n[1]*Math.cos(m)-n[2]*Math.sin(m);o[2]=n[1]*Math.sin(m)+n[2]*Math.cos(m);j[0]=o[0]+l[0];j[1]=o[1]+l[1];j[2]=o[2]+l[2];return j;};i.rotateY=function(j,k,l,m){var n=[],o=[];n[0]=k[0]-l[0];n[1]=k[1]-l[1];n[2]=k[2]-l[2];o[0]=n[2]*Math.sin(m)+n[0]*Math.cos(m);o[1]=n[1];o[2]=n[2]*Math.cos(m)-n[0]*Math.sin(m);j[0]=o[0]+l[0];j[1]=o[1]+l[1];j[2]=o[2]+l[2];return j;};i.rotateZ=function(j,k,l,m){var n=[],o=[];n[0]=k[0]-l[0];n[1]=k[1]-l[1];n[2]=k[2]-l[2];o[0]=n[0]*Math.cos(m)-n[1]*Math.sin(m);o[1]=n[0]*Math.sin(m)+n[1]*Math.cos(m);o[2]=n[2];j[0]=o[0]+l[0];j[1]=o[1]+l[1];j[2]=o[2]+l[2];return j;};i.forEach=(function(){var j=i.create();return function(k,l,m,n,o,p){var q,r;if(!l)l=3;if(!m)m=0;if(n){r=Math.min((n*l)+m,k.length);}else r=k.length;for(q=m;q<r;q+=l){j[0]=k[q];j[1]=k[q+1];j[2]=k[q+2];o(j,j,p);k[q]=j[0];k[q+1]=j[1];k[q+2]=j[2];}return k;};})();i.angle=function(j,k){var l=i.fromValues(j[0],j[1],j[2]),m=i.fromValues(k[0],k[1],k[2]);i.normalize(l,l);i.normalize(m,m);var n=i.dot(l,m);if(n>1){return 0;}else return Math.acos(n);};i.str=function(j){return 'vec3('+j[0]+', '+j[1]+', '+j[2]+')';};i.exactEquals=function(j,k){return j[0]===k[0]&&j[1]===k[1]&&j[2]===k[2];};i.equals=function(j,k){var l=j[0],m=j[1],n=j[2],o=k[0],p=k[1],q=k[2];return (Math.abs(l-o)<=h.EPSILON*Math.max(1,Math.abs(l),Math.abs(o))&&Math.abs(m-p)<=h.EPSILON*Math.max(1,Math.abs(m),Math.abs(p))&&Math.abs(n-q)<=h.EPSILON*Math.max(1,Math.abs(n),Math.abs(q)));};f.exports=i;}),null);
__d("GLMatrix",["gl-matrix-common","gl-matrix-mat4","gl-matrix-vec3"],(function a(b,c,d,e,f,g){c.__markCompiled&&c.__markCompiled();g.glMatrix=c("gl-matrix-common");g.mat4=c("gl-matrix-mat4");g.vec3=c("gl-matrix-vec3");}),null);
__d('getErrorNameFromWebGLErrorCode',[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={'0':'NO_ERROR','1280':'INVALID_ENUM','1281':'INVALID_VALUE','1282':'INVALID_OPERATION','1285':'OUT_OF_MEMORY','1286':'INVALID_FRAMEBUFFER_OPERATION','37442':'CONTEXT_LOST_WEBGL'};function i(j){if(!(j in h))return 'UNKNOWN_ERROR';return h[j];}f.exports=i;}),null);
__d('SphericalRenderer',['DOM','EventEmitter','EventListener','VideoProjection','GLMatrix','getErrorNameFromWebGLErrorCode'],(function a(b,c,d,e,f,g){var h,i;if(c.__markCompiled)c.__markCompiled();var j=c('GLMatrix').glMatrix,k=c('GLMatrix').mat4,l=c('GLMatrix').vec3,m=window.devicePixelRatio||1;h=babelHelpers.inherits(n,c('EventEmitter'));i=h&&h.prototype;function n(o,p,q){'use strict';i.constructor.call(this);this.$SphericalRenderer2=q;this.$SphericalRenderer21=q.fieldOfView;this.$SphericalRenderer16=true;this.$SphericalRenderer15=o;this.$SphericalRenderer1=p;this.$SphericalRenderer9=k.create();this.$SphericalRenderer10=k.create();this.$SphericalRenderer3=false;this.$SphericalRenderer18=[];this.$SphericalRenderer20=null;this.$SphericalRenderer19=null;this.$SphericalRenderer17=q.projectionType===c('VideoProjection').UNPADDED_CUBESTRIP;this.$SphericalRenderer7=q.projectionType===c('VideoProjection').ROTATED_CUBEMAP;this.$SphericalRenderer11=null;this.$SphericalRenderer12=null;this.$SphericalRenderer8=null;this.$SphericalRenderer4=this.$SphericalRenderer22.bind(this);this.$SphericalRenderer5=this.$SphericalRenderer23.bind(this);this.$SphericalRenderer1.addEventListener('webglcontextlost',this.$SphericalRenderer4);this.$SphericalRenderer1.addEventListener('webglcontextrestored',this.$SphericalRenderer5);this.$SphericalRenderer24();}n.prototype.destroy=function(){'use strict';this.removeAllListeners();this.$SphericalRenderer1.removeEventListener('webglcontextlost',this.$SphericalRenderer4);this.$SphericalRenderer1.removeEventListener('webglcontextrestored',this.$SphericalRenderer5);};n.prototype.reconfigure=function(o,p){'use strict';this.$SphericalRenderer21=p.fieldOfView;this.$SphericalRenderer15=o;this.$SphericalRenderer2=p;this.$SphericalRenderer17=p.projectionType===c('VideoProjection').UNPADDED_CUBESTRIP;this.$SphericalRenderer7=p.projectionType===c('VideoProjection').ROTATED_CUBEMAP;this.$SphericalRenderer24();};n.prototype.hasRenderingContext=function(){'use strict';return !this.$SphericalRenderer3;};n.prototype.$SphericalRenderer22=function(o){'use strict';o.preventDefault();this.emit('renderingContextLost');this.$SphericalRenderer3=true;};n.prototype.$SphericalRenderer23=function(o){'use strict';this.$SphericalRenderer3=false;this.$SphericalRenderer24();this.emit('renderingContextRestore');};n.prototype.setAutoUpdateTexture=function(o){'use strict';this.$SphericalRenderer16=o;};n.prototype.updateFieldOfView=function(o){'use strict';this.$SphericalRenderer21=o;this.$SphericalRenderer25();};n.prototype.updateViewportDimensions=function(o,p){'use strict';this.$SphericalRenderer1.width=o*m;this.$SphericalRenderer1.height=p*m;this.$SphericalRenderer25();};n.prototype.$SphericalRenderer25=function(){'use strict';k.perspective(this.$SphericalRenderer9,j.toRadian(this.$SphericalRenderer21),this.$SphericalRenderer1.width/this.$SphericalRenderer1.height,.1,100);this.$SphericalRenderer6.viewport(0,0,this.$SphericalRenderer6.drawingBufferWidth,this.$SphericalRenderer6.drawingBufferHeight);};n.prototype.$SphericalRenderer24=function(){'use strict';this.$SphericalRenderer26();this.updateViewportDimensions(this.$SphericalRenderer1.clientWidth,this.$SphericalRenderer1.clientHeight);if(!this.$SphericalRenderer27())throw new Error('Failed to intialize shaders: '+c('getErrorNameFromWebGLErrorCode')(this.$SphericalRenderer6.getError()));this.$SphericalRenderer28();this.$SphericalRenderer6.clearColor(0,0,0,1);this.$SphericalRenderer15.setAttribute('crossorigin','anonymous');if(this.$SphericalRenderer2.projectionType===c('VideoProjection').ROTATED_CUBEMAP)this.$SphericalRenderer29();};n.prototype.getScreenshotDataURL=function(o,p,q,r){'use strict';if(!this.$SphericalRenderer6||this.$SphericalRenderer3)return '';this.render(o,p);return this.$SphericalRenderer1.toDataURL(q,r);};n.prototype.$SphericalRenderer26=function(){'use strict';if(this.$SphericalRenderer6&&!this.$SphericalRenderer3)return;if(!b.WebGLRenderingContext)throw new Error('WebGLRenderingContext not available.');var o=['webgl','experimental-webgl','webkit-3d','moz-webgl'],p=null,q=null,r=c('EventListener').listen(this.$SphericalRenderer1,'webglcontextcreationerror',function(u){return q=u.statusMessage;});for(var s=0;s<o.length;s++){try{p=this.$SphericalRenderer1.getContext(o[s]);}catch(t){}if(p)break;}r.remove();if(!p){if(!q)q='Unknown error.';throw new Error('Failed to acquire 3D rendering context: '+q);}this.$SphericalRenderer6=p;this.$SphericalRenderer3=false;};n.prototype.$SphericalRenderer27=function(){'use strict';var o=this.$SphericalRenderer30();if(!o)return false;var p=this.$SphericalRenderer31();if(!p)return false;this.$SphericalRenderer14=this.$SphericalRenderer6.createProgram();this.$SphericalRenderer6.attachShader(this.$SphericalRenderer14,o);this.$SphericalRenderer6.attachShader(this.$SphericalRenderer14,p);this.$SphericalRenderer6.linkProgram(this.$SphericalRenderer14);if(!this.$SphericalRenderer6.getProgramParameter(this.$SphericalRenderer14,this.$SphericalRenderer6.LINK_STATUS))return false;this.$SphericalRenderer6.useProgram(this.$SphericalRenderer14);this.$SphericalRenderer14.vertexPositionAttribute=this.$SphericalRenderer6.getAttribLocation(this.$SphericalRenderer14,'aVertexPosition');this.$SphericalRenderer6.enableVertexAttribArray(this.$SphericalRenderer14.vertexPositionAttribute);this.$SphericalRenderer14.pMatrixUniform=this.$SphericalRenderer6.getUniformLocation(this.$SphericalRenderer14,'uPMatrix');this.$SphericalRenderer14.mvMatrixUniform=this.$SphericalRenderer6.getUniformLocation(this.$SphericalRenderer14,'uMVMatrix');this.$SphericalRenderer14.samplerUniform=this.$SphericalRenderer6.getUniformLocation(this.$SphericalRenderer14,'uSampler');if(!this.$SphericalRenderer17){this.$SphericalRenderer14.textureCoordAttribute=this.$SphericalRenderer6.getAttribLocation(this.$SphericalRenderer14,'aTextureCoord');this.$SphericalRenderer6.enableVertexAttribArray(this.$SphericalRenderer14.textureCoordAttribute);}return true;};n.prototype.$SphericalRenderer28=function(){'use strict';this.$SphericalRenderer13=this.$SphericalRenderer6.createTexture();this.$SphericalRenderer13.image=this.$SphericalRenderer15;var o=this.$SphericalRenderer17?this.$SphericalRenderer6.TEXTURE_CUBE_MAP:this.$SphericalRenderer6.TEXTURE_2D;this.$SphericalRenderer6.bindTexture(o,this.$SphericalRenderer13);this.$SphericalRenderer6.texParameteri(o,this.$SphericalRenderer6.TEXTURE_MAG_FILTER,this.$SphericalRenderer6.LINEAR);this.$SphericalRenderer6.texParameteri(o,this.$SphericalRenderer6.TEXTURE_MIN_FILTER,this.$SphericalRenderer6.LINEAR);this.$SphericalRenderer6.texParameteri(o,this.$SphericalRenderer6.TEXTURE_WRAP_S,this.$SphericalRenderer6.CLAMP_TO_EDGE);this.$SphericalRenderer6.texParameteri(o,this.$SphericalRenderer6.TEXTURE_WRAP_T,this.$SphericalRenderer6.CLAMP_TO_EDGE);this.$SphericalRenderer6.bindTexture(o,null);};n.prototype.$SphericalRenderer32=function(o){'use strict';var p=30,q=30,r=2,s=[],t=[],u,v;for(u=0;u<=p;u++){var w=(u/p-.5)*Math.PI,x=Math.sin(w),y=Math.cos(w);for(v=0;v<=q;v++){var z=(v/q-.5)*2*Math.PI,aa=Math.sin(z),ba=Math.cos(z),ca=ba*y,da=x,ea=aa*y,fa=v/q,ga=u/p;t.push(fa);t.push(ga);s.push(r*ca);s.push(r*da);s.push(r*ea);}}var ha=[];for(u=0;u<p;u++)for(v=0;v<q;v++){var ia=u*(q+1)+v,ja=ia+q+1;ha.push(ia);ha.push(ja);ha.push(ia+1);ha.push(ja);ha.push(ja+1);ha.push(ia+1);}this.$SphericalRenderer18[o]=this.$SphericalRenderer6.createBuffer();this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ARRAY_BUFFER,this.$SphericalRenderer18[o]);this.$SphericalRenderer6.bufferData(this.$SphericalRenderer6.ARRAY_BUFFER,new Float32Array(t),this.$SphericalRenderer6.STATIC_DRAW);this.$SphericalRenderer18[o].itemSize=2;this.$SphericalRenderer18[o].numItems=t.length/2;this.$SphericalRenderer20=this.$SphericalRenderer6.createBuffer();this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ARRAY_BUFFER,this.$SphericalRenderer20);this.$SphericalRenderer6.bufferData(this.$SphericalRenderer6.ARRAY_BUFFER,new Float32Array(s),this.$SphericalRenderer6.STATIC_DRAW);if(this.$SphericalRenderer20){this.$SphericalRenderer20.itemSize=3;this.$SphericalRenderer20.numItems=s.length/3;}this.$SphericalRenderer19=this.$SphericalRenderer6.createBuffer();this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ELEMENT_ARRAY_BUFFER,this.$SphericalRenderer19);this.$SphericalRenderer6.bufferData(this.$SphericalRenderer6.ELEMENT_ARRAY_BUFFER,new Uint16Array(ha),this.$SphericalRenderer6.STATIC_DRAW);if(this.$SphericalRenderer19){this.$SphericalRenderer19.itemSize=1;this.$SphericalRenderer19.numItems=ha.length;}};n.prototype.$SphericalRenderer33=function(o,p,q){'use strict';var r=[5,1,3,7,0,4,6,2,6,7,3,2,0,1,5,4,4,5,7,6,1,0,2,3],s=[];for(var t=0;t<r.length;t++){var u=r[t]>>2&1,v=r[t]>>1&1,w=r[t]>>0&1;s.push(u*2-1);s.push(v*2-1);s.push(w*2-1);}this.$SphericalRenderer20=this.$SphericalRenderer6.createBuffer();this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ARRAY_BUFFER,this.$SphericalRenderer20);this.$SphericalRenderer6.bufferData(this.$SphericalRenderer6.ARRAY_BUFFER,new Float32Array(s),this.$SphericalRenderer6.STATIC_DRAW);if(this.$SphericalRenderer20){this.$SphericalRenderer20.itemSize=3;this.$SphericalRenderer20.numItems=s.length/3;}if(!this.$SphericalRenderer17){var x,y,z,aa,ba,ca=[];if(this.$SphericalRenderer7){var da=this.$SphericalRenderer13.image.videoWidth/2;p=da/(Math.floor(da/32)*32);z=(p-1)/2;x=3;y=2;aa=1/y;ba=1/x;ca.push((0+z)*aa);ca.push((1-z)*ba);ca.push((0+z)*aa);ca.push((0+z)*ba);ca.push((1-z)*aa);ca.push((0+z)*ba);ca.push((1-z)*aa);ca.push((1-z)*ba);ca.push((0+z)*aa);ca.push((3-z)*ba);ca.push((0+z)*aa);ca.push((2+z)*ba);ca.push((1-z)*aa);ca.push((2+z)*ba);ca.push((1-z)*aa);ca.push((3-z)*ba);ca.push((2-z)*aa);ca.push((3-z)*ba);ca.push((1+z)*aa);ca.push((3-z)*ba);ca.push((1+z)*aa);ca.push((2+z)*ba);ca.push((2-z)*aa);ca.push((2+z)*ba);ca.push((2-z)*aa);ca.push((1-z)*ba);ca.push((1+z)*aa);ca.push((1-z)*ba);ca.push((1+z)*aa);ca.push((0+z)*ba);ca.push((2-z)*aa);ca.push((0+z)*ba);ca.push((0+z)*aa);ca.push((2-z)*ba);ca.push((0+z)*aa);ca.push((1+z)*ba);ca.push((1-z)*aa);ca.push((1+z)*ba);ca.push((1-z)*aa);ca.push((2-z)*ba);ca.push((1+z)*aa);ca.push((1+z)*ba);ca.push((2-z)*aa);ca.push((1+z)*ba);ca.push((2-z)*aa);ca.push((2-z)*ba);ca.push((1+z)*aa);ca.push((2-z)*ba);}else{z=(p-1)/2;x=2;y=3;aa=1/y;ba=1/x;for(var ea=0;ea<x;++ea)for(var fa=0;fa<y;++fa){var ga=x-1-ea,ha=fa;ca.push((ha+z)*aa);ca.push((ga+z)*ba);ca.push((ha+1-z)*aa);ca.push((ga+z)*ba);ca.push((ha+1-z)*aa);ca.push((ga+1-z)*ba);ca.push((ha+z)*aa);ca.push((ga+1-z)*ba);}}this.$SphericalRenderer18[q]=this.$SphericalRenderer6.createBuffer();this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ARRAY_BUFFER,this.$SphericalRenderer18[q]);this.$SphericalRenderer6.bufferData(this.$SphericalRenderer6.ARRAY_BUFFER,new Float32Array(ca),this.$SphericalRenderer6.STATIC_DRAW);this.$SphericalRenderer18[q].itemSize=2;this.$SphericalRenderer18[q].numItems=ca.length/2;}var ia=[];for(var ja=0;ja<r.length;ja+=4){ia.push(ja);ia.push(ja+2);ia.push(ja+1);ia.push(ja);ia.push(ja+3);ia.push(ja+2);}this.$SphericalRenderer19=this.$SphericalRenderer6.createBuffer();this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ELEMENT_ARRAY_BUFFER,this.$SphericalRenderer19);this.$SphericalRenderer6.bufferData(this.$SphericalRenderer6.ELEMENT_ARRAY_BUFFER,new Uint16Array(ia),this.$SphericalRenderer6.STATIC_DRAW);if(this.$SphericalRenderer19){this.$SphericalRenderer19.itemSize=1;this.$SphericalRenderer19.numItems=ia.length;}};n.prototype.$SphericalRenderer29=function(){'use strict';this.$SphericalRenderer11=l.fromValues(1,1,-1);this.$SphericalRenderer12=l.fromValues(-1,1,0);var o=k.create();k.rotate(o,o,j.toRadian(15),this.$SphericalRenderer12);l.transformMat4(this.$SphericalRenderer11,this.$SphericalRenderer11,o);this.$SphericalRenderer8=k.create();k.lookAt(this.$SphericalRenderer8,l.fromValues(0,0,0),l.fromValues(1,1,1),this.$SphericalRenderer12);};n.prototype.$SphericalRenderer30=function(){'use strict';var o=this.$SphericalRenderer6.createShader(this.$SphericalRenderer6.VERTEX_SHADER),p='\n attribute vec3 aVertexPosition;\n\n uniform mat4 uMVMatrix;\n uniform mat4 uPMatrix;\n\n varying highp vec3 vVertexDirectionVector;\n\n void main(void) {\n gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n vVertexDirectionVector = aVertexPosition;\n }\n ',q='\n attribute vec3 aVertexPosition;\n attribute vec2 aTextureCoord;\n\n uniform mat4 uMVMatrix;\n uniform mat4 uPMatrix;\n\n varying highp vec2 vTextureCoord;\n\n void main(void) {\n gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n vTextureCoord = aTextureCoord;\n }\n ',r=this.$SphericalRenderer17?p:q;this.$SphericalRenderer6.shaderSource(o,r);this.$SphericalRenderer6.compileShader(o);if(!this.$SphericalRenderer6.getShaderParameter(o,this.$SphericalRenderer6.COMPILE_STATUS))return null;return o;};n.prototype.$SphericalRenderer31=function(){'use strict';var o=this.$SphericalRenderer6.createShader(this.$SphericalRenderer6.FRAGMENT_SHADER),p='\n varying highp vec3 vVertexDirectionVector;\n uniform samplerCube uSampler;\n\n void main(void) {\n gl_FragColor = textureCube(uSampler, vVertexDirectionVector);\n }\n ',q='\n varying highp vec2 vTextureCoord;\n\n uniform sampler2D uSampler;\n\n void main(void) {\n gl_FragColor = texture2D(\n uSampler,\n vec2(vTextureCoord.s, vTextureCoord.t)\n );\n }\n ',r=this.$SphericalRenderer17?p:q;this.$SphericalRenderer6.shaderSource(o,r);this.$SphericalRenderer6.compileShader(o);if(!this.$SphericalRenderer6.getShaderParameter(o,this.$SphericalRenderer6.COMPILE_STATUS))return null;return o;};n.prototype.$SphericalRenderer34=function(){'use strict';if(this.$SphericalRenderer17){this.$SphericalRenderer35();}else{this.$SphericalRenderer6.bindTexture(this.$SphericalRenderer6.TEXTURE_2D,this.$SphericalRenderer13);this.$SphericalRenderer6.pixelStorei(this.$SphericalRenderer6.UNPACK_FLIP_Y_WEBGL,true);try{this.$SphericalRenderer6.texImage2D(this.$SphericalRenderer6.TEXTURE_2D,0,this.$SphericalRenderer6.RGBA,this.$SphericalRenderer6.RGBA,this.$SphericalRenderer6.UNSIGNED_BYTE,this.$SphericalRenderer13.image);}catch(o){this.emit('renderingError',o);}this.$SphericalRenderer6.bindTexture(this.$SphericalRenderer6.TEXTURE_2D,null);}};n.prototype.renderWithRotationMatrix=function(o){'use strict';if(this.$SphericalRenderer3)return;if(this.$SphericalRenderer16)this.$SphericalRenderer34();this.$SphericalRenderer10=o;this.$SphericalRenderer36();};n.prototype.render=function(o,p){'use strict';if(this.$SphericalRenderer3)return;if(this.$SphericalRenderer16)this.$SphericalRenderer34();if(this.$SphericalRenderer7){k.copy(this.$SphericalRenderer10,this.$SphericalRenderer8);k.rotate(this.$SphericalRenderer10,this.$SphericalRenderer10,j.toRadian(p),this.$SphericalRenderer11);k.rotate(this.$SphericalRenderer10,this.$SphericalRenderer10,j.toRadian(o-80),this.$SphericalRenderer12);}else{k.identity(this.$SphericalRenderer10);k.rotateX(this.$SphericalRenderer10,this.$SphericalRenderer10,-j.toRadian(p));k.rotateY(this.$SphericalRenderer10,this.$SphericalRenderer10,j.toRadian(o));}this.$SphericalRenderer36();};n.prototype.$SphericalRenderer36=function(){'use strict';this.$SphericalRenderer6.clear(this.$SphericalRenderer6.COLOR_BUFFER_BIT|this.$SphericalRenderer6.DEPTH_BUFFER_BIT);this.$SphericalRenderer6.activeTexture(this.$SphericalRenderer6.TEXTURE0);if(this.$SphericalRenderer17){this.$SphericalRenderer6.bindTexture(this.$SphericalRenderer6.TEXTURE_CUBE_MAP,this.$SphericalRenderer13);if(this.$SphericalRenderer20===null)this.$SphericalRenderer33(this.$SphericalRenderer2.projectionType,this.$SphericalRenderer2.expansionCoef||0,0);}else{this.$SphericalRenderer6.bindTexture(this.$SphericalRenderer6.TEXTURE_2D,this.$SphericalRenderer13);var o=this.$SphericalRenderer13.image.videoWidth;if(this.$SphericalRenderer2.projectionType===c('VideoProjection').CUBEMAP||this.$SphericalRenderer2.projectionType===c('VideoProjection').ROTATED_CUBEMAP){if(!(o in this.$SphericalRenderer18))this.$SphericalRenderer33(this.$SphericalRenderer2.projectionType,this.$SphericalRenderer2.expansionCoef||0,o);}else if(!(o in this.$SphericalRenderer18))this.$SphericalRenderer32(o);this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ARRAY_BUFFER,this.$SphericalRenderer18[o]);this.$SphericalRenderer6.vertexAttribPointer(this.$SphericalRenderer14.textureCoordAttribute,this.$SphericalRenderer18[o].itemSize,this.$SphericalRenderer6.FLOAT,false,0,0);}this.$SphericalRenderer6.uniform1i(this.$SphericalRenderer14.samplerUniform,0);this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ARRAY_BUFFER,this.$SphericalRenderer20);if(this.$SphericalRenderer20)this.$SphericalRenderer6.vertexAttribPointer(this.$SphericalRenderer14.vertexPositionAttribute,this.$SphericalRenderer20.itemSize,this.$SphericalRenderer6.FLOAT,false,0,0);this.$SphericalRenderer6.bindBuffer(this.$SphericalRenderer6.ELEMENT_ARRAY_BUFFER,this.$SphericalRenderer19);this.$SphericalRenderer6.uniformMatrix4fv(this.$SphericalRenderer14.pMatrixUniform,false,this.$SphericalRenderer9);this.$SphericalRenderer6.uniformMatrix4fv(this.$SphericalRenderer14.mvMatrixUniform,false,this.$SphericalRenderer10);if(this.$SphericalRenderer19)this.$SphericalRenderer6.drawElements(this.$SphericalRenderer6.TRIANGLES,this.$SphericalRenderer19.numItems,this.$SphericalRenderer6.UNSIGNED_SHORT,0);this.$SphericalRenderer6.bindTexture(this.$SphericalRenderer6.TEXTURE_2D,null);};n.prototype.$SphericalRenderer37=function(){'use strict';var o=this.$SphericalRenderer6.getParameter(this.$SphericalRenderer6.MAX_CUBE_MAP_TEXTURE_SIZE),p=this.$SphericalRenderer13.image.width;return Math.min(o,p);};n.prototype.$SphericalRenderer35=function(){'use strict';var o=this.$SphericalRenderer37(),p=this.$SphericalRenderer13.image.width,q=c('DOM').create('canvas',{width:o,height:o}),r=q.getContext('2d');this.$SphericalRenderer6.pixelStorei(this.$SphericalRenderer6.UNPACK_FLIP_Y_WEBGL,false);this.$SphericalRenderer6.bindTexture(this.$SphericalRenderer6.TEXTURE_CUBE_MAP,this.$SphericalRenderer13);for(var s=0;s<6;s++){r.drawImage(this.$SphericalRenderer13.image,0,s*p,p,p,0,0,o,o);var t=new Uint8Array(r.getImageData(0,0,o,o).data);this.$SphericalRenderer6.texImage2D(this.$SphericalRenderer6.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,this.$SphericalRenderer6.RGBA,o,o,0,this.$SphericalRenderer6.RGBA,this.$SphericalRenderer6.UNSIGNED_BYTE,t);}this.$SphericalRenderer6.bindTexture(this.$SphericalRenderer6.TEXTURE_CUBE_MAP,null);};f.exports=n;}),null);
__d("degToRad",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(i){return i*Math.PI/180;}f.exports=h;}),null);
__d("radToDeg",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(i){return i*180/Math.PI;}f.exports=h;}),null);
__d('SphericalViewportControl',['cx','CSS','DOMQuery','Event','EventEmitter','Keys','SubscriptionsHandler','VelocityTracker','debounce','getElementRect','performanceNow','requestAnimationFrame','throttle','degToRad','radToDeg'],(function a(b,c,d,e,f,g,h){var i,j;if(c.__markCompiled)c.__markCompiled();var k=c('DOMQuery').scry(window.document.body,'#globalContainer')[0]||window.document.body,l=20,m=110,n=.01,o=1000,p=['W','A','S','D'].reduce(function(s,t){s[t]=t.charCodeAt(0);return s;},{}),q={Up:"__tu",Down:"__tz",Left:"_2a6u",Right:"_2a6v",UpLeft:"__t-",UpRight:"__u0",DownLeft:"__u1",DownRight:"__u3"};i=babelHelpers.inherits(r,c('EventEmitter'));j=i&&i.prototype;function r(s,t){var u=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];'use strict';j.constructor.call(this);this.$SphericalViewportControl2=new (c('VelocityTracker'))(300);this.$SphericalViewportControl3=new (c('VelocityTracker'))(300);this.$SphericalViewportControl5=new (c('SubscriptionsHandler'))();this.$SphericalViewportControl22=s;this.$SphericalViewportControl40(t);this.$SphericalViewportControl13={x:0,y:0};this.$SphericalViewportControl9={left:0,right:0,up:0,down:0};this.$SphericalViewportControl15={x:0,y:0};this.$SphericalViewportControl16={x:0,y:0};this.$SphericalViewportControl17=new (c('VelocityTracker'))();this.$SphericalViewportControl21=new (c('SubscriptionsHandler'))();this.$SphericalViewportControl24=false;this.$SphericalViewportControl14=false;this.$SphericalViewportControl27=u.enableGyro||false;this.$SphericalViewportControl28=u.slipFactor||0;this.$SphericalViewportControl31=u.springFactor||0;this.$SphericalViewportControl32=u.maxSpringDegrees||15;this.$SphericalViewportControl33=u.maxStretchXDegrees||20;this.$SphericalViewportControl34=u.maxStretchYDegrees||20;this.$SphericalViewportControl36=u.rubberBandConstant||0;this.$SphericalViewportControl35=u.enableRubberBanding||false;this.$SphericalViewportControl38=false;this.$SphericalViewportControl39=0;this.$SphericalViewportControl37=c('debounce')(function(){return this.emit('zoomStart');}.bind(this),o);this.$SphericalViewportControl21.addSubscriptions(c('Event').listen(s,'mousedown',function(v){return this.$SphericalViewportControl41(v);}.bind(this)),c('Event').listen(s,'mouseenter',function(v){return this.$SphericalViewportControl42(v);}.bind(this)),c('Event').listen(s,'mouseleave',function(v){return this.$SphericalViewportControl43(v);}.bind(this)),c('Event').listen(s,'click',function(v){return this.$SphericalViewportControl44(v);}.bind(this)),c('Event').listen(s,'wheel',function(v){return this.$SphericalViewportControl45(v);}.bind(this)),c('Event').listen(s,'keydown',function(v){return this.$SphericalViewportControl46(v);}.bind(this)),c('Event').listen(s,'keyup',function(v){return this.$SphericalViewportControl47(v);}.bind(this)),c('Event').listen(s,'blur',function(v){return this.$SphericalViewportControl48(v);}.bind(this)),c('Event').listen(s,'touchstart',function(v){return this.$SphericalViewportControl49(v);}.bind(this)),c('Event').listen(s,'touchmove',function(v){return this.$SphericalViewportControl50(v);}.bind(this)),c('Event').listen(s,'touchend',function(v){return this.$SphericalViewportControl51(v);}.bind(this)),c('Event').listen(s,'touchcancel',function(v){return this.$SphericalViewportControl51(v);}.bind(this)));if(this.$SphericalViewportControl27)this.$SphericalViewportControl21.addSubscriptions(c('Event').listen(s,'mousemove',function(v){return this.$SphericalViewportControl52(v);}.bind(this)));}r.prototype.destroy=function(){'use strict';this.removeAllListeners();this.getSubscriptions().remove();};r.prototype.$SphericalViewportControl40=function(s){'use strict';if(this.$SphericalViewportControl22.clientHeight&&this.$SphericalViewportControl22.clientWidth){this.$SphericalViewportControl1=this.$SphericalViewportControl22.clientWidth/this.$SphericalViewportControl22.clientHeight;}else this.$SphericalViewportControl1=1;this.$SphericalViewportControl4=s.fieldOfView;this.$SphericalViewportControl30=Boolean(s.enableZoom);this.$SphericalViewportControl20=(s.panningVelocityFactor||0)/15*80||80;this.$SphericalViewportControl8=(s.keyboardVelocityFactor||0)*1000||80;if(s.partialLimits){this.$SphericalViewportControl25={left:s.partialLimits.partialLeftDegrees,right:s.partialLimits.partialRightDegrees,up:s.partialLimits.partialTopDegrees,down:s.partialLimits.partialBottomDegrees};this.$SphericalViewportControl26=true;}else{this.$SphericalViewportControl26=false;this.$SphericalViewportControl25={up:null,down:null,left:null,right:null};}this.$SphericalViewportControl19={x:s.initialHeading,y:s.initialPitch};if((this.$SphericalViewportControl25.up||this.$SphericalViewportControl25.up===0)&&(this.$SphericalViewportControl25.down||this.$SphericalViewportControl25.down===0)){var t=this.$SphericalViewportControl25.up+this.$SphericalViewportControl25.down;if(this.$SphericalViewportControl4>t){this.$SphericalViewportControl4=t;this.$SphericalViewportControl19.y=(this.$SphericalViewportControl25.up-this.$SphericalViewportControl25.down)/2;}}this.$SphericalViewportControl18={x:this.$SphericalViewportControl19.x,y:this.$SphericalViewportControl19.y};};r.prototype.reconfigure=function(s){'use strict';this.$SphericalViewportControl40(s);};r.prototype.setEnableGyro=function(s){'use strict';this.$SphericalViewportControl27=s;};r.prototype.$SphericalViewportControl41=function(s){'use strict';if(this.$SphericalViewportControl12)this.$SphericalViewportControl53();this.$SphericalViewportControl11=true;this.$SphericalViewportControl54(s);};r.prototype.$SphericalViewportControl49=function(s){'use strict';if(this.$SphericalViewportControl11)this.$SphericalViewportControl53();if(this.$SphericalViewportControl12){this.$SphericalViewportControl55(s);this.$SphericalViewportControl12=false;this.$SphericalViewportControl53();}else this.$SphericalViewportControl12=true;this.$SphericalViewportControl54(s);};r.prototype.$SphericalViewportControl55=function(s){'use strict';if(s.touches.length===2&&this.$SphericalViewportControl30){this.$SphericalViewportControl38=true;this.$SphericalViewportControl39=this.$SphericalViewportControl56(s);}};r.prototype.$SphericalViewportControl50=function(s){'use strict';if(this.$SphericalViewportControl38){this.$SphericalViewportControl57(s);if(this.$SphericalViewportControl30)c('Event').kill(s);}};r.prototype.$SphericalViewportControl57=function(s){'use strict';var t=this.$SphericalViewportControl56(s),u=this.$SphericalViewportControl4*(this.$SphericalViewportControl39/t),v=u-this.$SphericalViewportControl4;this.$SphericalViewportControl58(v);this.$SphericalViewportControl39=t;};r.prototype.$SphericalViewportControl56=function(s){'use strict';var t=s.touches[0].pageX-s.touches[1].pageX,u=s.touches[0].pageY-s.touches[1].pageY;return Math.sqrt(Math.pow(t,2)+Math.pow(u,2));};r.prototype.$SphericalViewportControl51=function(s){'use strict';if(this.$SphericalViewportControl38){this.$SphericalViewportControl38=false;}else if(this.$SphericalViewportControl12)this.$SphericalViewportControl43(s);};r.prototype.$SphericalViewportControl54=function(s){'use strict';this.$SphericalViewportControl59();this.$SphericalViewportControl60(s);this.$SphericalViewportControl61(s);this.$SphericalViewportControl62();s.preventDefault();};r.prototype.$SphericalViewportControl43=function(s){'use strict';if(this.$SphericalViewportControl12||this.$SphericalViewportControl11){var t=this.$SphericalViewportControl63();this.$SphericalViewportControl3=new (c('VelocityTracker'))(300,t);}if(this.$SphericalViewportControl29){this.$SphericalViewportControl64();this.$SphericalViewportControl29=false;}this.$SphericalViewportControl53();};r.prototype.$SphericalViewportControl65=function(s){'use strict';if(this.$SphericalViewportControl12||this.$SphericalViewportControl11)this.$SphericalViewportControl53();};r.prototype.$SphericalViewportControl66=function(s){'use strict';this.$SphericalViewportControl61(s);this.$SphericalViewportControl6=true;this.emit('updateViewportMove');};r.prototype.$SphericalViewportControl52=function(s){'use strict';if(this.$SphericalViewportControl29){this.$SphericalViewportControl67(s);this.emit('updateViewportMove');}};r.prototype.$SphericalViewportControl59=function(){'use strict';this.$SphericalViewportControl29=false;this.$SphericalViewportControl27=false;};r.prototype.$SphericalViewportControl68=function(s){'use strict';this.$SphericalViewportControl61(s);this.$SphericalViewportControl53();this.$SphericalViewportControl64();s.preventDefault();};r.prototype.$SphericalViewportControl53=function(s){'use strict';c('CSS').removeClass(k,"_2a6t");c('CSS').removeClass(this.$SphericalViewportControl22,"_2a6t");c('CSS').removeClass(k,"_4ox5");c('CSS').removeClass(this.$SphericalViewportControl22,"_4ox5");this.$SphericalViewportControl12=false;this.$SphericalViewportControl11=false;this.$SphericalViewportControl5.release();if(this.$SphericalViewportControl23){c('CSS').removeClass(k,this.$SphericalViewportControl23);this.$SphericalViewportControl23='';}};r.prototype.$SphericalViewportControl69=function(s){'use strict';if(this.$SphericalViewportControl12&&s.changedTouches){return s.changedTouches[0];}else if(this.$SphericalViewportControl11){return s;}else if(this.$SphericalViewportControl29)return s;return null;};r.prototype.$SphericalViewportControl70=function(s){'use strict';var t=this.$SphericalViewportControl69(s);if(!t)return this.$SphericalViewportControl15;return {x:t.screenX,y:t.screenY};};r.prototype.$SphericalViewportControl71=function(s){'use strict';var t=this.$SphericalViewportControl69(s);if(!t)return this.$SphericalViewportControl16;return {x:t.clientX,y:t.clientY};};r.prototype.$SphericalViewportControl60=function(s){'use strict';this.$SphericalViewportControl15=this.$SphericalViewportControl70(s);this.$SphericalViewportControl13={x:0,y:0};this.$SphericalViewportControl17=new (c('VelocityTracker'))();this.$SphericalViewportControl3=new (c('VelocityTracker'))(300);c('CSS').addClass(k,"_2a6t");c('CSS').addClass(this.$SphericalViewportControl22,"_2a6t");c('CSS').addClass(k,"_4ox5");c('CSS').addClass(this.$SphericalViewportControl22,"_4ox5");this.$SphericalViewportControl5.engage();var t=b.document.body;if(this.$SphericalViewportControl12){this.$SphericalViewportControl5.addSubscriptions(c('Event').listen(t,'touchmove',function(u){return this.$SphericalViewportControl66(u);}.bind(this)),c('Event').listen(t,'touchend',function(u){return this.$SphericalViewportControl68(u);}.bind(this)),c('Event').listen(t,'touchcancel',function(u){return this.$SphericalViewportControl65(u);}.bind(this)));}else this.$SphericalViewportControl5.addSubscriptions(c('Event').listen(t,'mousemove',function(u){return this.$SphericalViewportControl66(u);}.bind(this)),c('Event').listen(t,'mouseup',function(u){return this.$SphericalViewportControl68(u);}.bind(this)),c('Event').listen(t,'mouseleave',function(u){return this.$SphericalViewportControl65(u);}.bind(this)));};r.prototype.$SphericalViewportControl67=function(s){'use strict';this.$SphericalViewportControl72(s,this.$SphericalViewportControl28);};r.prototype.$SphericalViewportControl61=function(s){'use strict';this.$SphericalViewportControl72(s,1);};r.prototype.$SphericalViewportControl72=function(s,t){'use strict';var u=this.$SphericalViewportControl70(s),v=this.$SphericalViewportControl14?{x:0,y:0}:this.$SphericalViewportControl13;this.$SphericalViewportControl13={x:t*(u.x-this.$SphericalViewportControl15.x)+v.x,y:t*(u.y-this.$SphericalViewportControl15.y)+v.y};this.$SphericalViewportControl14=false;this.$SphericalViewportControl15=u;this.$SphericalViewportControl17.update(u.x,u.y);this.$SphericalViewportControl16=this.$SphericalViewportControl71(s);};r.prototype.$SphericalViewportControl63=function(){'use strict';var s=this.$SphericalViewportControl73(),t=-this.$SphericalViewportControl17.getVelocityX()*s,u=this.$SphericalViewportControl17.getVelocityY()*s,v=this.$SphericalViewportControl29?this.$SphericalViewportControl28:1;if(this.$SphericalViewportControl74())t=-t;return {x:t*v,y:u*v};};r.prototype.$SphericalViewportControl75=function(s,t){'use strict';return c('radToDeg')(Math.atan(s/t));};r.prototype.$SphericalViewportControl76=function(s,t,u){'use strict';return {x:this.$SphericalViewportControl75(s.x-this.$SphericalViewportControl22.clientWidth/2,u),y:-this.$SphericalViewportControl75(s.y-this.$SphericalViewportControl22.clientHeight/2,t)};};r.prototype.$SphericalViewportControl77=function(s,t){'use strict';var u={x:s.x-t.x,y:s.y-t.y},v=this.$SphericalViewportControl22.clientHeight/(2*Math.tan(c('degToRad')(this.getVerticalFieldOfView()/2))),w=v*Math.cos(c('degToRad')(this.$SphericalViewportControl18.y)),x=w-(this.$SphericalViewportControl22.clientHeight/2-s.y)*Math.sin(c('degToRad')(this.$SphericalViewportControl18.y));if(this.$SphericalViewportControl18.y==-90&&t.y<0||this.$SphericalViewportControl18.y==90&&t.y>0){var y=this.$SphericalViewportControl75(u.y-this.$SphericalViewportControl22.clientHeight/2,u.x-this.$SphericalViewportControl22.clientWidth/2),z=this.$SphericalViewportControl75(s.y-this.$SphericalViewportControl22.clientHeight/2,s.x-this.$SphericalViewportControl22.clientWidth/2),aa=z-y;if(aa>90){aa=180-aa;}else if(aa<-90)aa=180+aa;return {x:aa*Math.sign(this.$SphericalViewportControl18.y),y:0};}else{var ba=this.$SphericalViewportControl76(u,v,x),ca=this.$SphericalViewportControl76(s,v,x);return {x:ba.x-ca.x,y:ba.y-ca.y};}};r.prototype.$SphericalViewportControl74=function(){'use strict';var s=this.$SphericalViewportControl16.y-c('getElementRect')(this.$SphericalViewportControl22).top,t=this.$SphericalViewportControl22.clientHeight/(2*Math.tan(c('degToRad')(this.getVerticalFieldOfView()/2))),u=-t/Math.tan(c('degToRad')(this.$SphericalViewportControl18.y))+this.$SphericalViewportControl22.clientHeight/2,v=s>u&&this.$SphericalViewportControl18.y<0||s<u&&this.$SphericalViewportControl18.y>0;return v;};r.prototype.$SphericalViewportControl78=function(){'use strict';var s=0,t=0,u={x:0,y:0};if(!this.$SphericalViewportControl14){this.$SphericalViewportControl14=true;var v=c('getElementRect')(this.$SphericalViewportControl22),w=this.$SphericalViewportControl16.x<v.left,x=this.$SphericalViewportControl16.x>v.right,y=this.$SphericalViewportControl16.y<v.top,z=this.$SphericalViewportControl16.y>v.bottom;this.$SphericalViewportControl79(w,x,y,z);var aa={x:this.$SphericalViewportControl16.x-v.left,y:this.$SphericalViewportControl16.y-v.top};if(!w&&!x){u.x=this.$SphericalViewportControl77(aa,this.$SphericalViewportControl13).x;this.$SphericalViewportControl13.x=0;}else{var ba=this.$SphericalViewportControl74();if(w&&!ba||x&&ba){s+=this.$SphericalViewportControl20;}else s-=this.$SphericalViewportControl20;}if(!y&&!z){u.y=this.$SphericalViewportControl77(aa,this.$SphericalViewportControl13).y;this.$SphericalViewportControl13.y=0;}else{if(y)t-=this.$SphericalViewportControl20;if(z)t+=this.$SphericalViewportControl20;}}this.$SphericalViewportControl3.updateVelocity(s,t);return this.$SphericalViewportControl80(u);};r.prototype.$SphericalViewportControl80=function(s){'use strict';if(!this.$SphericalViewportControl35)return s;if(!this.$SphericalViewportControl26)return s;var t=this.$SphericalViewportControl18,u=t.x,v=t.y,w=s.x,x=s.y,y=u+w,z=v+x,aa=this.$SphericalViewportControl25,ba=aa.left,ca=aa.right,da=aa.up,ea=aa.down,fa=this.getVerticalFieldOfView(),ga=this.getHorizontalFieldOfView(),ha=ba!=null?y>360-ba+ga/2:true,ia=ca!=null?y<ca-ga/2:true,ja=da!=null?z<da-fa/2:true,ka=ea!=null?z>-ea+fa/2:true;if(!ha&&!ia)w*=this.$SphericalViewportControl36;if(!ja||!ka)x*=this.$SphericalViewportControl36;return {x:w,y:x};};r.prototype.$SphericalViewportControl42=function(s){'use strict';this.emit('mouseEnter');if(this.$SphericalViewportControl11){this.$SphericalViewportControl3=new (c('VelocityTracker'))(300);}else if(this.$SphericalViewportControl27&&this.$SphericalViewportControl28){this.$SphericalViewportControl3=new (c('VelocityTracker'))(300);this.$SphericalViewportControl29=true;this.$SphericalViewportControl15=this.$SphericalViewportControl70(s);this.$SphericalViewportControl13={x:0,y:0};this.$SphericalViewportControl62();}};r.prototype.$SphericalViewportControl44=function(s){'use strict';this.$SphericalViewportControl22.focus();if(!this.$SphericalViewportControl6)this.emit('DOM/click',s);this.$SphericalViewportControl6=false;return false;};r.prototype.$SphericalViewportControl45=function(s){'use strict';if(this.$SphericalViewportControl24)s.preventDefault();c('throttle')(this.$SphericalViewportControl81,100,this)(s);if(this.$SphericalViewportControl30)c('Event').kill(s);};r.prototype.$SphericalViewportControl81=function(s){'use strict';this.emit('wheelScroll',s);if(!this.$SphericalViewportControl30)return;var t=(s.deltaX||0)+(s.deltaY||0)+(s.deltaZ||0),u=t/120*45/10;this.$SphericalViewportControl58(u);};r.prototype.$SphericalViewportControl58=function(s){'use strict';var t=this.setFieldOfView(this.$SphericalViewportControl4+s);if(t)this.$SphericalViewportControl37();};r.prototype.$SphericalViewportControl46=function(s){'use strict';var t=this.$SphericalViewportControl82(s);if(t){this.$SphericalViewportControl9[t]=1;if(!this.$SphericalViewportControl10){this.$SphericalViewportControl10=true;this.$SphericalViewportControl59();this.$SphericalViewportControl62();this.emit('updateViewportMove');}return false;}return true;};r.prototype.$SphericalViewportControl47=function(s){'use strict';var t=this.$SphericalViewportControl82(s);if(t){this.$SphericalViewportControl9[t]=0;var u=false;for(var v in this.$SphericalViewportControl9)if(this.$SphericalViewportControl9.hasOwnProperty(v)&&this.$SphericalViewportControl9[v]>0){u=true;break;}this.$SphericalViewportControl10=u;return false;}return true;};r.prototype.$SphericalViewportControl64=function(){'use strict';var s=this.$SphericalViewportControl63();this.$SphericalViewportControl3=new (c('VelocityTracker'))(300,s);};r.prototype.$SphericalViewportControl62=function(){var s,t=this;'use strict';if(!this.$SphericalViewportControl7)(function(){t.$SphericalViewportControl7=true;t.$SphericalViewportControl2.updateVelocity(0,0);t.emit('updateViewportBegin');var u=t.once('updateViewportMove',function(){return this.emit('updateViewportMoveStart',this.$SphericalViewportControl29);}.bind(t));t.once('updateViewportEnd',function(){return u.remove();});c('requestAnimationFrame')(function(){return this.$SphericalViewportControl83(c('performanceNow')());}.bind(t));})();};r.prototype.$SphericalViewportControl83=function(s){'use strict';var t=c('performanceNow')(),u=t-s;this.$SphericalViewportControl84();var v=this.$SphericalViewportControl78(),w=false;if(this.$SphericalViewportControl26&&this.$SphericalViewportControl35&&this.$SphericalViewportControl31&&!this.$SphericalViewportControl11&&!this.$SphericalViewportControl12){var x=this.$SphericalViewportControl85()*u/1000;v.x+=x;var y=this.$SphericalViewportControl86()*u/1000;v.y+=y;if(x||y)w=true;}v.x+=this.$SphericalViewportControl2.getVelocityX()*u/1000;v.y+=this.$SphericalViewportControl2.getVelocityY()*u/1000;v.x+=this.$SphericalViewportControl3.getVelocityX()*u/1000;v.y+=this.$SphericalViewportControl3.getVelocityY()*u/1000;this.$SphericalViewportControl87(v.x,v.y);var z=this.$SphericalViewportControl2.getSpeed()>0||this.$SphericalViewportControl3.getSpeed()>0;if(this.$SphericalViewportControl11||this.$SphericalViewportControl10||this.$SphericalViewportControl12||this.$SphericalViewportControl38||this.$SphericalViewportControl29||z||w){c('requestAnimationFrame')(function(){return this.$SphericalViewportControl83(t);}.bind(this));}else{this.$SphericalViewportControl7=false;this.emit('updateViewportEnd',this.$SphericalViewportControl18.x,this.$SphericalViewportControl18.y);}};r.prototype.$SphericalViewportControl85=function(){'use strict';var s=180,t=0,u=this.$SphericalViewportControl25,v=u.left,w=u.right,x=this.getHorizontalFieldOfView();if(v!=null&&w!=null)s=(w-v)/2+180;if(v!=null&&this.$SphericalViewportControl18.x>=s){var y=360-v+x/2-this.$SphericalViewportControl18.x;if(y>0)t=Math.min(y,this.$SphericalViewportControl32)*this.$SphericalViewportControl31;}if(w!=null&&this.$SphericalViewportControl18.x<=s){var z=w-x/2-this.$SphericalViewportControl18.x;if(z<0)t=Math.max(z,-this.$SphericalViewportControl32)*this.$SphericalViewportControl31;}return Math.abs(t)<n?0:t;};r.prototype.$SphericalViewportControl86=function(){'use strict';var s=0,t=this.$SphericalViewportControl25,u=t.up,v=t.down,w=this.getVerticalFieldOfView();if(u!=null){var x=u-w/2-this.$SphericalViewportControl18.y;if(x<0)s=Math.max(x,-this.$SphericalViewportControl32)*this.$SphericalViewportControl31;}if(v!=null){var y=-v+w/2-this.$SphericalViewportControl18.y;if(y>0)s=Math.min(y,this.$SphericalViewportControl32)*this.$SphericalViewportControl31;}return Math.abs(s)<n?0:s;};r.prototype.$SphericalViewportControl79=function(s,t,u,v){'use strict';var w='';if(s||t||u||v){var x=s?'Left':t?'Right':'',y=u?'Up':v?'Down':'';w=q[y+x];}if(this.$SphericalViewportControl23!=w){if(this.$SphericalViewportControl23){c('CSS').removeClass(k,this.$SphericalViewportControl23);this.$SphericalViewportControl23='';}if(w){this.$SphericalViewportControl23=w;c('CSS').addClass(k,w);}}};r.prototype.getSubscriptions=function(){'use strict';return {remove:function(){this.$SphericalViewportControl21.release();this.$SphericalViewportControl5.release();}.bind(this)};};r.prototype.$SphericalViewportControl48=function(s){'use strict';for(var t in this.$SphericalViewportControl9)this.$SphericalViewportControl9[t]=0;this.$SphericalViewportControl10=false;};r.prototype.getOrientation=function(){'use strict';return this.$SphericalViewportControl18;};r.prototype.$SphericalViewportControl88=function(s,t){'use strict';var u=(s+360)%360,v=Math.max(-90,Math.min(90,t));if(!this.$SphericalViewportControl26)return {x:u,y:v};var w=this.$SphericalViewportControl25,x=w.left,y=w.right,z=w.up,aa=w.down,ba=this.getVerticalFieldOfView(),ca=this.getHorizontalFieldOfView(),da=0,ea=0;if(this.$SphericalViewportControl35){da=this.$SphericalViewportControl33;ea=this.$SphericalViewportControl34;}if(x!=null)u=u<=180?u:Math.max(u,360-x+ca/2-da);if(y!=null)u=u>=180?u:Math.min(u,y-ca/2+da);if(z!=null)v=Math.min(v,z-ba/2+ea);if(aa!=null)v=Math.max(v,-aa+ba/2-ea);return {x:u,y:v};};r.prototype.setSphericalOrientation=function(s,t){'use strict';var u=this.$SphericalViewportControl88(s,t),v=u.x,w=u.y,x=v!==this.$SphericalViewportControl18.x||w!==this.$SphericalViewportControl18.y;if(x){this.$SphericalViewportControl18={x:v,y:w};this.emit('viewportChange',v,w,this.$SphericalViewportControl4);}};r.prototype.setRelativeSphericalOrientation=function(s,t){'use strict';this.setSphericalOrientation(s+this.$SphericalViewportControl19.x,t+this.$SphericalViewportControl19.y);};r.prototype.$SphericalViewportControl87=function(s,t){'use strict';this.setSphericalOrientation(this.$SphericalViewportControl18.x+s,this.$SphericalViewportControl18.y+t);};r.prototype.setFieldOfView=function(s){'use strict';var t=this.$SphericalViewportControl4,u=m,v=this.$SphericalViewportControl25.up||this.$SphericalViewportControl25.up===0,w=this.$SphericalViewportControl25.up||0,x=this.$SphericalViewportControl25.down||this.$SphericalViewportControl25.down===0,y=this.$SphericalViewportControl25.down||0,z=this.$SphericalViewportControl25.left||this.$SphericalViewportControl25.right,aa=this.$SphericalViewportControl25.left||0,ba=this.$SphericalViewportControl25.right||0;if(v&&x)u=Math.min(u,(v?w:180)+(x?y:180));var ca=Math.min(u,Math.max(l,s)),da=ca*this.getAspectRatio(),ea=false,fa=this.$SphericalViewportControl18.x,ga=this.$SphericalViewportControl18.y;if(x&&ca/2-ga>y){ga=ca/2-y;ea=true;}if(v&&ga+ca/2>w){ga=w-ca/2;ea=true;}if(z){var ha=((ba-aa)/2+180)%360;if(fa>ha&&da/2+360-fa>aa){fa=360+da/2-aa;ea=true;}if(fa<ha&&fa+da/2>ba){fa=ba-da/2;ea=true;}}if(ea)this.$SphericalViewportControl18={x:fa,y:ga};if(t!==ca||ea){this.$SphericalViewportControl4=ca;this.emit('viewportChange',this.$SphericalViewportControl18.x,this.$SphericalViewportControl18.y,ca);return true;}return false;};r.prototype.getVerticalFieldOfView=function(){'use strict';return this.$SphericalViewportControl4;};r.prototype.getAspectRatio=function(){'use strict';if(this.$SphericalViewportControl22&&this.$SphericalViewportControl22.clientWidth&&this.$SphericalViewportControl22.clientHeight)return this.$SphericalViewportControl22.clientWidth/this.$SphericalViewportControl22.clientHeight;return this.$SphericalViewportControl1;};r.prototype.getHorizontalFieldOfView=function(){'use strict';return this.$SphericalViewportControl4*this.getAspectRatio();};r.prototype.setPreventScrollDefaultAction=function(s){'use strict';this.$SphericalViewportControl24=s;};r.prototype.updateViewport=function(s,t,u){'use strict';this.$SphericalViewportControl18={x:s,y:t};this.$SphericalViewportControl4=u;};r.prototype.isUpdating=function(){'use strict';return this.$SphericalViewportControl7;};r.prototype.$SphericalViewportControl84=function(){'use strict';var s=this.$SphericalViewportControl8*(this.$SphericalViewportControl9.right-this.$SphericalViewportControl9.left),t=this.$SphericalViewportControl8*(this.$SphericalViewportControl9.up-this.$SphericalViewportControl9.down);this.$SphericalViewportControl2.updateVelocity(s,t);};r.prototype.$SphericalViewportControl82=function(s){'use strict';var t=c('Event').getKeyCode(s),u=null;switch(t){case c('Keys').LEFT:case p.A:u='left';break;case c('Keys').UP:case p.W:u='up';break;case c('Keys').RIGHT:case p.D:u='right';break;case c('Keys').DOWN:case p.S:u='down';break;}return u;};r.prototype.$SphericalViewportControl73=function(){'use strict';return this.$SphericalViewportControl4/this.$SphericalViewportControl22.clientHeight;};f.exports=r;}),null);
__d('SphericalImageRenderer',['cx','CSS','DOM','EventEmitter','SphericalViewportControl','SphericalRenderer','Vector','SphericalPhotoConfig','SphericalPhotoViewerLoggerUtil','SphericalMediaConstants'],(function a(b,c,d,e,f,g,h){var i,j;if(c.__markCompiled)c.__markCompiled();var k=c('SphericalPhotoViewerLoggerUtil').logDragStart,l=c('SphericalPhotoViewerLoggerUtil').logMouseOverStart,m=c('SphericalPhotoViewerLoggerUtil').logWWWGyroStart,n=c('SphericalPhotoViewerLoggerUtil').logZoomStart,o=c('SphericalPhotoViewerLoggerUtil').logSignificantMovement,p=c('SphericalMediaConstants').LOGGER_SIGNIFICANT_MOVEMENT_DEGREE,q=c('SphericalMediaConstants').GYRO_SLIP_FACTOR,r=c('SphericalMediaConstants').RB_FRICTION,s=c('SphericalMediaConstants').RB_SPRING_FACTOR,t=c('SphericalMediaConstants').RB_MAX_SPRING_DEGREE,u=c('SphericalMediaConstants').RB_MAX_STRETCH_X_DEGREE,v=c('SphericalMediaConstants').RB_MAX_STRETCH_Y_DEGREE,w=window.devicePixelRatio||1;i=babelHelpers.inherits(x,c('EventEmitter'));j=i&&i.prototype;function x(y,z,aa,ba,ca){'use strict';j.constructor.call(this);this.$SphericalImageRenderer4=y;this.$SphericalImageRenderer1=ca;this.$SphericalImageRenderer6=z;this.$SphericalImageRenderer7={pitch:z.initialPitch,yaw:z.initialHeading};this.$SphericalImageRenderer5=c('DOM').create('canvas',{width:aa*w,height:ba*w,className:"_2a6s",tabIndex:0});var da=new (c('SphericalRenderer'))(y,this.$SphericalImageRenderer5,z);da.addListener('renderingError',this.$SphericalImageRenderer8.bind(this));var ea={enableGyro:c('SphericalPhotoConfig').www_spherical_photo_slip_panning,slipFactor:q,springFactor:s,maxSpringDegrees:t,maxStretchXDegrees:u,maxStretchYDegrees:v,rubberBandConstant:r,enableRubberBanding:c('SphericalPhotoConfig').www_spherical_photo_rubberbanding},fa=new (c('SphericalViewportControl'))(this.$SphericalImageRenderer5,z,ea);fa.addListener('viewportChange',function(ga,ha,ia){return this.emit('viewportChange',ga,ha,ia);}.bind(this));fa.addListener('viewportChange',function(ga,ha,ia){return this.$SphericalImageRenderer9(ga,ha,ia);}.bind(this));fa.addListener('updateViewportBegin',function(){return this.emit('updateViewportBegin');}.bind(this));fa.addListener('updateViewportEnd',function(ga,ha){this.$SphericalImageRenderer10(ga,ha);this.emit('updateViewportEnd');}.bind(this));fa.addListener('DOM/click',function(ga){return this.emit('DOM/click',ga);}.bind(this));fa.addListener('updateViewportMoveStart',function(ga){return ga?m({photoID:this.$SphericalImageRenderer1}):k({photoID:this.$SphericalImageRenderer1});}.bind(this));fa.addListener('mouseEnter',function(){return l({photoID:this.$SphericalImageRenderer1});}.bind(this));fa.addListener('zoomStart',function(){return n({photoID:this.$SphericalImageRenderer1});}.bind(this));c('CSS').hide(y);this.$SphericalImageRenderer2=fa;this.$SphericalImageRenderer3=da;da.updateViewportDimensions(aa,ba);if(this.$SphericalImageRenderer4.complete){setTimeout(function(){return this.$SphericalImageRenderer11();}.bind(this),0);}else this.$SphericalImageRenderer4.onload=function(){return this.$SphericalImageRenderer11();}.bind(this);}x.prototype.attachTo=function(y){'use strict';this.detach();y.appendChild(this.$SphericalImageRenderer5);};x.prototype.detach=function(){'use strict';if(this.$SphericalImageRenderer5.parentElement)this.$SphericalImageRenderer5.parentElement.removeChild(this.$SphericalImageRenderer5);c('CSS').hide(this.$SphericalImageRenderer5);};x.prototype.reconfigure=function(y,z,aa,ba,ca){'use strict';this.$SphericalImageRenderer4=y;this.$SphericalImageRenderer1=ca;this.$SphericalImageRenderer6=z;this.$SphericalImageRenderer3.setAutoUpdateTexture(true);this.$SphericalImageRenderer3.reconfigure(y,z);this.$SphericalImageRenderer3.updateViewportDimensions(aa,ba);this.$SphericalImageRenderer2.reconfigure(z);if(c('SphericalPhotoConfig').www_spherical_photo_slip_panning)this.$SphericalImageRenderer2.setEnableGyro(true);if(this.$SphericalImageRenderer4.complete){setTimeout(function(){return this.$SphericalImageRenderer11();}.bind(this),0);}else this.$SphericalImageRenderer4.onload=function(){return this.$SphericalImageRenderer11();}.bind(this);};x.prototype.isHealthy=function(){'use strict';return this.$SphericalImageRenderer3.hasRenderingContext();};x.prototype.getDimensions=function(){'use strict';return new (c('Vector'))(this.$SphericalImageRenderer5.width/w,this.$SphericalImageRenderer5.height/w);};x.prototype.setDimensions=function(y){'use strict';this.$SphericalImageRenderer3.updateViewportDimensions(y.x,y.y);var z=this.$SphericalImageRenderer2.getOrientation();this.$SphericalImageRenderer12(z.x,z.y);};x.prototype.getSphericalConfig=function(){'use strict';return this.$SphericalImageRenderer6;};x.prototype.$SphericalImageRenderer10=function(y,z){'use strict';var aa=y-this.$SphericalImageRenderer7.yaw,ba=z-this.$SphericalImageRenderer7.pitch,ca=Math.sqrt(Math.pow(aa,2)+Math.pow(ba,2));if(p<ca)o({photoID:this.$SphericalImageRenderer1});this.$SphericalImageRenderer7={yaw:y,pitch:z};};x.prototype.$SphericalImageRenderer11=function(){'use strict';this.emit('imageLoaded');var y=this.$SphericalImageRenderer2.getOrientation();this.$SphericalImageRenderer12(y.x,y.y);this.$SphericalImageRenderer3.setAutoUpdateTexture(false);c('CSS').show(this.$SphericalImageRenderer5);};x.prototype.$SphericalImageRenderer9=function(y,z,aa){'use strict';if(aa!==this.$SphericalImageRenderer13)this.$SphericalImageRenderer3.updateFieldOfView(aa);this.$SphericalImageRenderer12(y,z);};x.prototype.$SphericalImageRenderer8=function(y){'use strict';this.emit('error',{error:'SPHERICAL_IMAGE_RENDER_ERROR',message:y.message});};x.prototype.$SphericalImageRenderer12=function(y,z){'use strict';this.$SphericalImageRenderer3.render(y,z);};x.prototype.setFieldOfView=function(y){'use strict';this.$SphericalImageRenderer3.updateFieldOfView(y);this.$SphericalImageRenderer2.setFieldOfView(y);};x.prototype.setSphericalOrientation=function(y,z){'use strict';this.$SphericalImageRenderer2.setSphericalOrientation(y,z);};x.prototype.getSnapshot=function(y,z,aa){'use strict';this.$SphericalImageRenderer12(y,z);return this.$SphericalImageRenderer5?this.$SphericalImageRenderer5.toDataURL(aa):null;};f.exports=x;}),null);
__d('SphericalImageRendererPool',['SphericalImageRenderer'],(function a(b,c,d,e,f,g){'use strict';if(c.__markCompiled)c.__markCompiled();function h(){this.$SphericalImageRendererPool1=[];}h.prototype.get=function(i,j,k,l,m,n){if(!this.$SphericalImageRendererPool1.length){return new (c('SphericalImageRenderer'))(i,j,k,l,m);}else{var o=this.$SphericalImageRendererPool1.pop();o.reconfigure(i,j,k,l,m);return o;}};h.prototype['return']=function(i){if(!i.isHealthy())return;i.detach();i.removeAllListeners();this.$SphericalImageRendererPool1.push(i);};f.exports=new h();}),null);
__d('SphericalImageViewer',['DOM','CSS','EventEmitter','Bootloader','SphericalImageRendererPool','Vector','VisibilityObserver'],(function a(b,c,d,e,f,g){var h,i;if(c.__markCompiled)c.__markCompiled();h=babelHelpers.inherits(j,c('EventEmitter'));i=h&&h.prototype;function j(k,l,m,n,o,p,q,r){'use strict';i.constructor.call(this);this.$SphericalImageViewer1=k;this.$SphericalImageViewer8=p;this.$SphericalImageViewer9=q;this.$SphericalImageViewer10=n;this.$SphericalImageViewer7=p/q;this.$SphericalImageViewer5=m;this.$SphericalImageViewer2=o;this.$SphericalImageViewer3=l;this.$SphericalImageViewer4=null;this.$SphericalImageViewer6=o.fieldOfView;this.$SphericalImageViewer12=r;this.imageLoaded=false;this.$SphericalImageViewer11=c('Vector').from(o.initialHeading,o.initialPitch);c('VisibilityObserver').instance.addListener(this.$SphericalImageViewer1,c('VisibilityObserver').VISIBILITY_CHANGE.visiblestart,function(){return this.$SphericalImageViewer13();}.bind(this));c('VisibilityObserver').instance.addListener(this.$SphericalImageViewer1,c('VisibilityObserver').VISIBILITY_CHANGE.visibleend,function(){return this.$SphericalImageViewer14();}.bind(this));if(c('VisibilityObserver').instance.getCurrentState(this.$SphericalImageViewer1)===c('VisibilityObserver').VISIBILITY.visible)setTimeout(function(){return this.$SphericalImageViewer13();}.bind(this),0);}j.prototype.getFBID=function(){'use strict';return this.$SphericalImageViewer12;};j.prototype.reconfigure=function(k){'use strict';this.$SphericalImageViewer2=k;if(this.$SphericalImageViewer4)this.$SphericalImageViewer4.reconfigure(this.$SphericalImageViewer3,this.$SphericalImageViewer2,this.$SphericalImageViewer8,this.$SphericalImageViewer9,this.$SphericalImageViewer12);};j.prototype.destroy=function(){'use strict';this.$SphericalImageViewer1=c('DOM').create('div');this.$SphericalImageViewer5=c('DOM').create('div');this.$SphericalImageViewer3=c('DOM').create('div');if(this.$SphericalImageViewer4){c('SphericalImageRendererPool')['return'](this.$SphericalImageViewer4);this.$SphericalImageViewer4=null;}};j.prototype.suspend=function(){'use strict';this.$SphericalImageViewer14();};j.prototype.resume=function(){'use strict';this.$SphericalImageViewer13();};j.prototype.$SphericalImageViewer13=function(){'use strict';if(this.$SphericalImageViewer4!==null)return;var k=c('SphericalImageRendererPool').get(this.$SphericalImageViewer3,this.$SphericalImageViewer2,this.$SphericalImageViewer8,this.$SphericalImageViewer9,this.$SphericalImageViewer12);this.$SphericalImageViewer4=k;['viewportChange','updateViewportBegin','updateViewportEnd','imageLoaded','DOM/click','error'].forEach(function(l){return (k.addListener(l,this.emit.bind(this,l)));}.bind(this));k.addListener('imageLoaded',function(){this.imageLoaded=true;c('CSS').hide(this.$SphericalImageViewer5);}.bind(this));k.addListener('viewportChange',function(l,m,n){this.$SphericalImageViewer11.x=l;this.$SphericalImageViewer11.y=m;this.$SphericalImageViewer6=n;}.bind(this));k.addListener('DOM/click',function(l){return this.$SphericalImageViewer15(l);}.bind(this));k.attachTo(this.$SphericalImageViewer1);};j.prototype.$SphericalImageViewer14=function(){'use strict';c('CSS').show(this.$SphericalImageViewer5);if(this.$SphericalImageViewer4){c('SphericalImageRendererPool')['return'](this.$SphericalImageViewer4);this.$SphericalImageViewer4=null;}};j.prototype.$SphericalImageViewer15=function(k){'use strict';this.emit('DOM/click',k);if(k.button==0)this.$SphericalImageViewer16();};j.prototype.$SphericalImageViewer16=function(){'use strict';if(this.$SphericalImageViewer10)c('Bootloader').loadModules(["PhotoSnowlift"],function(k){return k.bootstrap(this.$SphericalImageViewer10);}.bind(this),'SphericalImageViewer');};j.prototype.getOrientation=function(){'use strict';return this.$SphericalImageViewer11;};j.prototype.getDimensions=function(){'use strict';return {x:this.$SphericalImageViewer8,y:this.$SphericalImageViewer9};};j.prototype.setDimensions=function(k){'use strict';if(this.$SphericalImageViewer4)this.$SphericalImageViewer4.setDimensions(k);this.$SphericalImageViewer8=k.x;this.$SphericalImageViewer9=k.y;this.$SphericalImageViewer7=k.x/k.y;};j.prototype.getInitialViewElement=function(){'use strict';return this.$SphericalImageViewer5;};j.prototype.getRootNode=function(){'use strict';return this.$SphericalImageViewer1;};j.prototype.getAspectRatio=function(){'use strict';return this.$SphericalImageViewer7;};j.prototype.getVerticalFieldOfView=function(){'use strict';return this.$SphericalImageViewer6;};j.prototype.getHorizontalFieldOfView=function(){'use strict';return this.$SphericalImageViewer6*this.getAspectRatio();};j.prototype.setSphericalOrientation=function(k,l){'use strict';if(this.$SphericalImageViewer4)this.$SphericalImageViewer4.setSphericalOrientation(k,l);this.$SphericalImageViewer11.x=k;this.$SphericalImageViewer11.y=l;};j.prototype.setFieldOfView=function(k){'use strict';if(this.$SphericalImageViewer4)this.$SphericalImageViewer4.setFieldOfView(k);this.$SphericalImageViewer6=k;};j.prototype.getSnapshot=function(k){'use strict';return this.$SphericalImageViewer4?this.$SphericalImageViewer4.getSnapshot(this.$SphericalImageViewer11.x,this.$SphericalImageViewer11.y,k):null;};f.exports=j;}),null);
__d('SphericalPhotoCastingComponent',['regeneratorRuntime','SubscriptionsHandler','CastingExperienceManager','SphericalImageViewer'],(function a(b,c,d,e,f,g){var h,i;if(c.__markCompiled)c.__markCompiled();h=babelHelpers.inherits(j,c('SphericalImageViewer'));i=h&&h.prototype;function j(k,l,m,n,o,p,q,r,s,t){'use strict';i.constructor.call(this,k,l,m,n,o,p.WWW,q.WWW,r);this.$SphericalPhotoCastingComponent1='360Photo';this.$SphericalPhotoCastingComponent2=c('CastingExperienceManager').getInstance();this.$SphericalPhotoCastingComponent3=false;this.$SphericalPhotoCastingComponent4=false;this.$SphericalPhotoCastingComponent6=r;this.$SphericalPhotoCastingComponent7=this.$SphericalPhotoCastingComponent2.hasFoundReceiver();this.$SphericalPhotoCastingComponent5={photo_uri:t,cubemap_uri:s,permalink_uri:n,sphericalConfig:o,width:p.TV,height:q.TV,fbid:r};this.$SphericalPhotoCastingComponent8=new (c('SubscriptionsHandler'))();this.$SphericalPhotoCastingComponent8.addSubscriptions(this.$SphericalPhotoCastingComponent2.addListener(c('CastingExperienceManager').RECEIVER_STATUS_CHANGED,function(u){return (this.$SphericalPhotoCastingComponent10(u));}.bind(this)),this.$SphericalPhotoCastingComponent2.addListener(c('CastingExperienceManager').RECEIVER_DISCONNECTED,function(){return this.$SphericalPhotoCastingComponent11();}.bind(this)),this.$SphericalPhotoCastingComponent2.addListener(c('CastingExperienceManager').SESSION_DISCONNECTED,function(){return this.$SphericalPhotoCastingComponent11();}.bind(this)),this.$SphericalPhotoCastingComponent2.addListener(c('CastingExperienceManager').EXPERIENCE_ENDED,function(){return this.$SphericalPhotoCastingComponent11();}.bind(this)),this.$SphericalPhotoCastingComponent2.addListener(c('CastingExperienceManager').SESSION_MESSAGE,function(u){return this.$SphericalPhotoCastingComponent12(u);}.bind(this)),this.$SphericalPhotoCastingComponent2.addListener(c('CastingExperienceManager').ERROR,function(u){return this.$SphericalPhotoCastingComponent13(u);}.bind(this)),this.$SphericalPhotoCastingComponent2.addListener(c('CastingExperienceManager').STOP_VIEW,function(){return this.$SphericalPhotoCastingComponent14();}.bind(this)),this.addListener('photoCasting/startCasting',function(u){return this.$SphericalPhotoCastingComponent15(u);}.bind(this)),this.addListener('photoCasting/stopCasting',function(u){return this.$SphericalPhotoCastingComponent15(u);}.bind(this)),this.addListener('viewportChange',function(u,v,w){if(this.$SphericalPhotoCastingComponent3){var x={x:u,y:v};this.$SphericalPhotoCastingComponent2.sendCommand('image_orientation_changed',x);}}.bind(this)),this.addListener('updateViewportEnd',function(){if(this.$SphericalPhotoCastingComponent3)this.$SphericalPhotoCastingComponent2.sendCommand('image_orientation_change_stopped');}.bind(this)),this.addListener('photoCasting/buttonLoaded',function(){return (this.emit('photoCasting/receiverStateChange',this.$SphericalPhotoCastingComponent7));}.bind(this)));}j.prototype.destroy=function(){'use strict';this.$SphericalPhotoCastingComponent8.release();};j.prototype.$SphericalPhotoCastingComponent15=function k(l){return c('regeneratorRuntime').async(function m(n){while(1)switch(n.prev=n.next){case 0:'use strict';if(!l){n.next=13;break;}this.$SphericalPhotoCastingComponent3=true;n.prev=3;n.next=6;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent16());case 6:n.next=11;break;case 8:n.prev=8;n.t0=n['catch'](3);this.$SphericalPhotoCastingComponent3=false;case 11:n.next=15;break;case 13:n.next=15;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent17());case 15:case 'end':return n.stop();}},null,this,[[3,8]]);};j.prototype.$SphericalPhotoCastingComponent16=function k(){var l,m,n,o,p;return c('regeneratorRuntime').async(function q(r){while(1)switch(r.prev=r.next){case 0:'use strict';if(this.$SphericalPhotoCastingComponent2.isCasting(this.$SphericalPhotoCastingComponent1)){r.next=4;break;}r.next=4;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent2.startCasting(this.$SphericalPhotoCastingComponent1));case 4:r.next=6;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent18());case 6:l=r.sent;m=!!l.photo_id;n=this.$SphericalPhotoCastingComponent6&&l.photo_id===this.$SphericalPhotoCastingComponent6;if(!(m&&!n)){r.next=15;break;}r.next=12;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent2.sendCommand('stop_showing_photo',this.$SphericalPhotoCastingComponent5));case 12:o=r.sent;this.$SphericalPhotoCastingComponent6=o.reference_id;this.$SphericalPhotoCastingComponent4=true;case 15:if(this.$SphericalPhotoCastingComponent4){r.next=21;break;}r.next=18;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent2.sendCommand('show_photo',this.$SphericalPhotoCastingComponent5));case 18:p=r.sent;this.$SphericalPhotoCastingComponent6=p.reference_id;this.$SphericalPhotoCastingComponent4=true;case 21:case 'end':return r.stop();}},null,this);};j.prototype.$SphericalPhotoCastingComponent17=function k(){return c('regeneratorRuntime').async(function l(m){while(1)switch(m.prev=m.next){case 0:'use strict';if(!this.$SphericalPhotoCastingComponent3){m.next=5;break;}m.next=4;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent2.sendCommand('stop_casting'));case 4:this.$SphericalPhotoCastingComponent3=false;case 5:this.$SphericalPhotoCastingComponent19();case 6:case 'end':return m.stop();}},null,this);};j.prototype.$SphericalPhotoCastingComponent19=function(){'use strict';if(this.$SphericalPhotoCastingComponent4)this.$SphericalPhotoCastingComponent4=false;if(this.$SphericalPhotoCastingComponent3)this.$SphericalPhotoCastingComponent3=false;};j.prototype.$SphericalPhotoCastingComponent12=function(k){'use strict';if(this.$SphericalPhotoCastingComponent3)if(k.type==='status_update')this.$SphericalPhotoCastingComponent20(k.data);};j.prototype.$SphericalPhotoCastingComponent20=function(k){'use strict';if(this.$SphericalPhotoCastingComponent6&&this.$SphericalPhotoCastingComponent6!==k.reference_id){this.$SphericalPhotoCastingComponent19();return;}var l=k.state==='play';if(l!==this.$SphericalPhotoCastingComponent4)this.$SphericalPhotoCastingComponent4=l;};j.prototype.$SphericalPhotoCastingComponent10=function(k){'use strict';this.$SphericalPhotoCastingComponent7=k;this.emit('photoCasting/receiverStateChange',k);};j.prototype.$SphericalPhotoCastingComponent11=function(){'use strict';this.$SphericalPhotoCastingComponent19();};j.prototype.$SphericalPhotoCastingComponent14=function(){'use strict';if(this.$SphericalPhotoCastingComponent4){this.emit('photoCasting/castingStateChange',this.getFBID());this.$SphericalPhotoCastingComponent19();}};j.prototype.$SphericalPhotoCastingComponent18=function k(){var l;return c('regeneratorRuntime').async(function m(n){while(1)switch(n.prev=n.next){case 0:'use strict';n.next=3;return c('regeneratorRuntime').awrap(this.$SphericalPhotoCastingComponent2.getExperienceState());case 3:l=n.sent;return n.abrupt('return',l.experience_specific_state);case 5:case 'end':return n.stop();}},null,this);};j.prototype.$SphericalPhotoCastingComponent13=function(k){'use strict';this.$SphericalPhotoCastingComponent9=k;};f.exports=j;}),null);
__d('PhotoSnowliftViewable',['cx','CSS','DOM','EncryptedImg','Event','EventEmitter','ImageUtils','PhotoSnowliftViewableSphericalPhoto','SphericalPhotoConfig','Vector'],(function a(b,c,d,e,f,g,h){var i,j,k,l,m,n;if(c.__markCompiled)c.__markCompiled();var o=2000,p=60,q=0,r=0;function s(z,aa){var ba;if(z.src&&z.complete){setTimeout(aa,0);}else (function(){var ca=c('Event').listen(z,'load',function(){ca.remove();aa();});})();}function t(z,aa){if(c('EncryptedImg').isEncrypted(aa)){c('EncryptedImg').insertIntoDOM(aa,z);}else z.src=aa;}i=babelHelpers.inherits(u,c('EventEmitter'));j=i&&i.prototype;function u(){var z=arguments.length<=0||arguments[0]===undefined?o:arguments[0],aa=arguments.length<=1||arguments[1]===undefined?1:arguments[1];'use strict';j.constructor.call(this);this.$PhotoSnowliftViewable5=c('DOM').create('div',{className:"_2-sx"});this.$PhotoSnowliftViewable4=z;this.$PhotoSnowliftViewable3=aa;this.$PhotoSnowliftViewable1=null;this.$PhotoSnowliftViewable2=0;this.$PhotoSnowliftViewable6();setTimeout(function(){return this.whenReady(function(){return this.$PhotoSnowliftViewable7();}.bind(this));}.bind(this),0);}u.prototype.$PhotoSnowliftViewable6=function(){'use strict';this.$PhotoSnowliftViewable1=setTimeout(function(){return this.$PhotoSnowliftViewable8();}.bind(this),this.$PhotoSnowliftViewable4);};u.prototype.$PhotoSnowliftViewable8=function(){'use strict';if(this.isReady())return;if(this.$PhotoSnowliftViewable2<this.$PhotoSnowliftViewable3){this.reload();this.$PhotoSnowliftViewable2++;this.$PhotoSnowliftViewable6();}else this.emit('loadingfailed');};u.prototype.reload=function(){'use strict';};u.prototype.$PhotoSnowliftViewable7=function(){'use strict';if(this.$PhotoSnowliftViewable1!==null){clearTimeout(this.$PhotoSnowliftViewable1);this.$PhotoSnowliftViewable1=null;}};u.prototype.getElement=function(){'use strict';return this.$PhotoSnowliftViewable5;};u.prototype.show=function(){'use strict';c('CSS').show(this.getElement());};u.prototype.hide=function(){'use strict';c('CSS').hide(this.getElement());};u.prototype.suspend=function(){'use strict';};u.prototype.resume=function(){'use strict';};u.prototype.onToggleIntoFullScreen=function(){'use strict';};u.prototype.onToggleOutOfFullScreen=function(){'use strict';};u.prototype.onEnterFullScreen=function(){'use strict';};u.prototype.onExitFullScreen=function(){'use strict';};u.prototype.getNaturalDimensions=function(){'use strict';return this.getDimensions();};u.prototype.getDimensions=function(){'use strict';return c('Vector').getElementDimensions(this.getElement());};u.prototype.setDimensions=function(z){'use strict';var aa=this.getElement();aa.style.width=z.x+'px';aa.style.height=z.y+'px';};u.prototype.isReady=function(){'use strict';throw new Error('Viewable has no concept of readiness - should be calling a subclass');};u.prototype.whenReady=function(z){'use strict';if(this.isReady()){setTimeout(z,0);}else this.once('ready',z);};k=babelHelpers.inherits(v,u);l=k&&k.prototype;function v(z,aa){var ba=arguments.length<=2||arguments[2]===undefined?false:arguments[2],ca=arguments[3];'use strict';l.constructor.call(this);this.$PhotoSnowliftViewablePhoto1=ca;this.$PhotoSnowliftViewablePhoto6=z;this.$PhotoSnowliftViewablePhoto5=aa;this.$PhotoSnowliftViewablePhoto2=ba;this.addListener('imageloaded',function(da){return this.$PhotoSnowliftViewablePhoto7(da);}.bind(this));this.$PhotoSnowliftViewablePhoto8();}v.prototype.$PhotoSnowliftViewablePhoto8=function(){'use strict';if(this.$PhotoSnowliftViewablePhoto3&&this.$PhotoSnowliftViewablePhoto3.parentElement)this.$PhotoSnowliftViewablePhoto3.parentElement.removeChild(this.$PhotoSnowliftViewablePhoto3);var z=c('DOM').create('img',{className:'spotlight',alt:''});this.$PhotoSnowliftViewablePhoto3=z;this.$PhotoSnowliftViewablePhoto3.setAttribute('aria-describedby','fbPhotosSnowliftCaption');this.$PhotoSnowliftViewablePhoto3.setAttribute('aria-busy','true');this.getElement().appendChild(this.$PhotoSnowliftViewablePhoto3);this.$PhotoSnowliftViewablePhoto9(this.$PhotoSnowliftViewablePhoto10());s(this.$PhotoSnowliftViewablePhoto3,function(){return this.emit('imageloaded',z);}.bind(this));this.whenReady(function(){return this.$PhotoSnowliftViewablePhoto11();}.bind(this));};v.prototype.$PhotoSnowliftViewablePhoto9=function(z){'use strict';this.$PhotoSnowliftViewablePhoto4=z;t(this.$PhotoSnowliftViewablePhoto3,this.$PhotoSnowliftViewablePhoto4);};v.prototype.$PhotoSnowliftViewablePhoto7=function(z){'use strict';if(this.$PhotoSnowliftViewablePhoto3!==z)return;this.emit('ready');};v.prototype.reload=function(){'use strict';this.$PhotoSnowliftViewablePhoto8();};v.prototype.$PhotoSnowliftViewablePhoto10=function(){'use strict';if(this.$PhotoSnowliftViewablePhoto2)return this.$PhotoSnowliftViewablePhoto6;return this.$PhotoSnowliftViewablePhoto5||this.$PhotoSnowliftViewablePhoto6;};v.prototype.$PhotoSnowliftViewablePhoto11=function(){'use strict';this.$PhotoSnowliftViewablePhoto3.setAttribute('aria-busy','false');};v.prototype.isReady=function(){'use strict';return this.$PhotoSnowliftViewablePhoto3.src&&c('ImageUtils').hasLoaded(this.$PhotoSnowliftViewablePhoto3);};v.prototype.getNaturalDimensions=function(){'use strict';if(this.$PhotoSnowliftViewablePhoto1)return this.$PhotoSnowliftViewablePhoto1;if(this.$PhotoSnowliftViewablePhoto3&&this.$PhotoSnowliftViewablePhoto3.naturalWidth&&this.$PhotoSnowliftViewablePhoto3.naturalHeight)return c('Vector').from(this.$PhotoSnowliftViewablePhoto3.naturalWidth,this.$PhotoSnowliftViewablePhoto3.naturalHeight);return l.getNaturalDimensions.call(this);};v.prototype.$PhotoSnowliftViewablePhoto12=function(){'use strict';return this.$PhotoSnowliftViewablePhoto4===this.$PhotoSnowliftViewablePhoto6;};v.prototype.onToggleIntoFullScreen=function(){'use strict';if(!this.$PhotoSnowliftViewablePhoto12())if(this.$PhotoSnowliftViewablePhoto4!==this.$PhotoSnowliftViewablePhoto6)t(new Image(),this.$PhotoSnowliftViewablePhoto6);};v.prototype.onEnterFullScreen=function(){'use strict';if(!this.$PhotoSnowliftViewablePhoto12())this.$PhotoSnowliftViewablePhoto9(this.$PhotoSnowliftViewablePhoto6);};m=babelHelpers.inherits(w,u);n=m&&m.prototype;function w(z){'use strict';n.constructor.call(this);this.$PhotoSnowliftViewableImageWrapper1=z;this.getElement().appendChild(z);if(this.$PhotoSnowliftViewableImageWrapper1.complete){this.$PhotoSnowliftViewableImageWrapper2();}else c('Event').listen(this.$PhotoSnowliftViewableImageWrapper1,'load',function(){return this.$PhotoSnowliftViewableImageWrapper2();}.bind(this));}w.prototype.$PhotoSnowliftViewableImageWrapper2=function(){'use strict';(function(){return this.emit('ready');}).bind(this);};w.prototype.isReady=function(){'use strict';return c('ImageUtils').hasLoaded(this.$PhotoSnowliftViewableImageWrapper1);};w.prototype.getNaturalDimensions=function(){'use strict';if(this.$PhotoSnowliftViewableImageWrapper1&&this.$PhotoSnowliftViewableImageWrapper1.naturalWidth&&this.$PhotoSnowliftViewableImageWrapper1.naturalHeight)return c('Vector').from(this.$PhotoSnowliftViewableImageWrapper1.naturalWidth,this.$PhotoSnowliftViewableImageWrapper1.naturalHeight);return n.getNaturalDimensions.call(this);};function x(z){var aa=arguments.length<=1||arguments[1]===undefined?false:arguments[1];if(c('SphericalPhotoConfig').spherical_photo_render_www&&z.spherical){return new (c('PhotoSnowliftViewableSphericalPhoto'))(z.url,z.smallurl,z.spherical.cubestripuri,z.spherical.initialviewverticalfov||p,z.spherical.initialpitch||q,z.spherical.initialheading||r,aa,z.dimensions,z.spherical.partialLimits,String(z.info.fbid));}else return new v(z.url,z.smallurl,aa,z.dimensions);}function y(z){var aa=z.parentElement,ba=new w(z);if(aa)aa.appendChild(ba.getElement());return ba;}f.exports.Viewable=u;f.exports.Photo=v;f.exports.SphericalPhoto=c('PhotoSnowliftViewableSphericalPhoto');f.exports.fromStreamData=x;f.exports.fromImageElement=y;}),null);
__d('SphericalCastingButton',['cx','XUIOverlayButton.react','Image.react','React','Event','ReactDOM','SphericalImageViewer'],(function a(b,c,d,e,f,g,h){if(c.__markCompiled)c.__markCompiled();function i(j,k,l){'use strict';this.onClick=function(m){c('Event').kill(m);if(!this.$SphericalCastingButton3){this.$SphericalCastingButton3=true;this.$SphericalCastingButton1.emit('photoCasting/startCasting',this.$SphericalCastingButton3);}else{this.$SphericalCastingButton3=false;this.$SphericalCastingButton1.emit('photoCasting/stopCasting',this.$SphericalCastingButton3);}this.render();}.bind(this);this.isNotCasting=function(m){if(m===this.$SphericalCastingButton1.getFBID()){this.$SphericalCastingButton3=false;this.render();}}.bind(this);this.render=function(){var m=this.$SphericalCastingButton3?'/images/video/player/embedded_controls/icons/cast-connected.png':'/images/video/player/embedded_controls/icons/cast.png',n=c('React').createElement(c('Image.react'),{src:m}),o=this.$SphericalCastingButton4?"_3wh8":"_56-d";c('ReactDOM').render(c('React').createElement('div',{className:o},c('React').createElement(c('XUIOverlayButton.react'),{image:n})),this.$SphericalCastingButton2);}.bind(this);this.$SphericalCastingButton1=j;this.$SphericalCastingButton2=k;this.$SphericalCastingButton3=false;this.$SphericalCastingButton4=l;this.$SphericalCastingButton1.addListener('photoCasting/receiverStateChange',function(m){return this.$SphericalCastingButton5(m);}.bind(this));this.$SphericalCastingButton1.addListener('photoCasting/castingStateChange',function(m){return this.isNotCasting(m);}.bind(this));c('Event').listen(this.$SphericalCastingButton2,'click',function(m){return this.onClick(m);}.bind(this));this.$SphericalCastingButton1.emit('photoCasting/buttonLoaded');}i.prototype.$SphericalCastingButton5=function(j){'use strict';if(this.$SphericalCastingButton3&&!j)this.$SphericalCastingButton3=false;if(j){this.render();}else c('ReactDOM').unmountComponentAtNode(this.$SphericalCastingButton2);};f.exports=i;}),null);
__d("d3/behavior/behavior",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={};f.exports=h;}),null);
__d("d3/core/dispatch",["d3/core/map"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/map")._Map,i=function l(){var m=new j(),n=-1,o=arguments.length;while(++n<o)m[arguments[n]]=k(m);return m;};function j(){}j.prototype.on=function(l,m){var n=l.indexOf("."),o="";if(n>0){o=l.substring(n+1);l=l.substring(0,n);}return arguments.length<2?this[l].on(o):this[l].on(o,m);};function k(l){var m=[],n=new h();function event(){var o=m,p=-1,q=o.length,r;while(++p<q)if(r=o[p].on)r.apply(this,arguments);return l;}event.on=function(o,p){var q=n.get(o),r;if(arguments.length<2)return q&&q.on;if(q){q.on=null;m=m.slice(0,r=m.indexOf(q)).concat(m.slice(r+1));n.remove(o);}if(p)m.push(n.set(o,{on:p}));return l;};return event;}i._dispatch=j;i._event=k;f.exports=i;}),null);
__d("d3/core/event",["d3/core/dispatch","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/dispatch")._dispatch,i=c("d3/core/dispatch")._event;c("d3/core/core").event=null;function j(){c("d3/core/core").event.stopPropagation();c("d3/core/core").event.preventDefault();}function k(){var m=c("d3/core/core").event,n;while(n=m.sourceEvent)m=n;return m;}function l(m){var n=new h(),o=0,p=arguments.length;while(++o<p)n[arguments[o]]=i(n);n.of=function(q,r){return function(s){try{var t=s.sourceEvent=c("d3/core/core").event;s.target=m;c("d3/core/core").event=s;n[s.type].apply(q,r);}finally{c("d3/core/core").event=t;}};};return n;}g._eventCancel=j;g._eventSource=k;g._eventDispatch=l;}),null);
__d("d3/core/array",["d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._document,i=k;function j(n){var o=-1,p=n.length,q=[];while(++o<p)q.push(n[o]);return q;}function k(n){return Array.prototype.slice.call(n);}try{i(h.documentElement.childNodes)[0].nodeType;}catch(l){i=j;}var m=[].__proto__?function(n,o){n.__proto__=o;}:function(n,o){for(var p in o)n[p]=o[p];};g._array=i;g._arraySubclass=m;}),null);
__d("d3/core/selection-root",["d3/core/core","d3/core/array","d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._document,i=c("d3\/core\/array")._array,j=c("d3\/core\/selection")._selection([[h]]);j[0].parentNode=c("d3\/core\/selection")._selectRoot;var k=function l(m){return typeof m==="string"?j.select(m):c("d3\/core\/selection")._selection([[m]]);};k.all=function(l){return typeof l==="string"?j.selectAll(l):c("d3\/core\/selection")._selection([i(l)]);};k._selectionRoot=j;f.exports=k;}),null);
__d("d3/core/selection",["d3/core/array","d3/core/core","d3/core/selection-root"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/array")._arraySubclass,i=c("d3\/core\/core")._document;function j(r){h(r,p);return r;}var k=function r(s,t){return t.querySelector(s);},l=function r(s,t){return t.querySelectorAll(s);},m=i.documentElement,n=m.matchesSelector||m.webkitMatchesSelector||m.mozMatchesSelector||m.msMatchesSelector||m.oMatchesSelector,o=function r(s,t){return n.call(s,t);};if(typeof Sizzle==="function"){k=function r(s,t){return Sizzle(s,t)[0]||null;};l=function r(s,t){return Sizzle.uniqueSort(Sizzle(s,t));};o=Sizzle.matchesSelector;}var p=[],q=function r(){return c("d3\/core\/selection-root")._selectionRoot;};q.prototype=p;q._selectionPrototype=p;q._select=k;q._selectAll=l;q._selectRoot=m;q._selectMatches=o;q._selection=j;f.exports=q;}),null);
__d("d3/core/mouse",["d3/core/core","d3/core/event","d3/core/selection-root"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/event")._eventSource,i=c("d3/core/core")._window,j=c("d3/core/core")._document,k=function n(o){return m(o,h());},l=/WebKit/.test(i.navigator.userAgent)?-1:0;function m(n,o){var p=n.ownerSVGElement||n;if(p.createSVGPoint){var q=p.createSVGPoint();if(l<0&&(i.scrollX||i.scrollY)){p=c("d3/core/selection-root")(j.body).append("svg").style("position","absolute").style("top",0).style("left",0);var r=p[0][0].getScreenCTM();l=!(r.f||r.e);p.remove();}if(l){q.x=o.pageX;q.y=o.pageY;}else{q.x=o.clientX;q.y=o.clientY;}q=q.matrixTransform(n.getScreenCTM().inverse());return [q.x,q.y];}var s=n.getBoundingClientRect();return [o.clientX-s.left-n.clientLeft,o.clientY-s.top-n.clientTop];}k._mousePoint=m;f.exports=k;}),null);
__d("d3/core/touches",["d3/core/event","d3/core/array","d3/core/mouse"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/event")._eventSource,i=c("d3\/core\/array")._array,j=c("d3\/core\/mouse")._mousePoint,k=function l(m,n){if(arguments.length<2)n=h().touches;return n?i(n).map(function(o){var p=j(m,o);p.identifier=o.identifier;return p;}):[];};f.exports=k;}),null);
__d("d3/behavior/drag",["d3/core/event","d3/core/core","d3/core/selection-root","d3/core/touches","d3/core/mouse","d3/core/rebind"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/event")._eventDispatch,i=c("d3/core/core")._window,j=c("d3/core/event")._eventCancel,k=function l(){var event=h(n,"drag","dragstart","dragend"),m=null;function n(){this.on("mousedown.drag",o).on("touchstart.drag",o);}function o(){var p=this,q=event.of(p,arguments),r=c("d3/core/core").event.target,s=c("d3/core/core").event.touches?c("d3/core/core").event.changedTouches[0].identifier:null,t,u=x(),v=0,w=c("d3/core/selection-root")(i).on(s!=null?"touchmove.drag-"+s:"mousemove.drag",y).on(s!=null?"touchend.drag-"+s:"mouseup.drag",z,true);if(m){t=m.apply(p,arguments);t=[t.x-u[0],t.y-u[1]];}else t=[0,0];if(s==null)j();q({type:"dragstart"});function x(){var ba=p.parentNode;return s!=null?c("d3/core/touches")(ba).filter(function(ca){return ca.identifier===s;})[0]:c("d3/core/mouse")(ba);}function y(){if(!p.parentNode)return z();var ba=x(),ca=ba[0]-u[0],da=ba[1]-u[1];v|=ca|da;u=ba;j();q({type:"drag",x:ba[0]+t[0],y:ba[1]+t[1],dx:ca,dy:da});}function z(){q({type:"dragend"});if(v){j();if(c("d3/core/core").event.target===r)w.on("click.drag",aa,true);}w.on(s!=null?"touchmove.drag-"+s:"mousemove.drag",null).on(s!=null?"touchend.drag-"+s:"mouseup.drag",null);}function aa(){j();w.on("click.drag",null);}}n.origin=function(p){if(!arguments.length)return m;m=p;return n;};return c("d3/core/rebind")(n,event,"on");};f.exports=k;}),null);
__d("d3/behavior/zoom",["d3/core/event","d3/core/core","d3/core/selection-root","d3/core/mouse","d3/core/touches","d3/core/rebind"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/event")._eventDispatch,i=c("d3/core/core")._window,j=c("d3/core/event")._eventCancel,k=function o(){var p=[0,0],q,r=1,s,t=l,event=h(z,"zoom"),u,v,w,x,y;function z(){this.on("mousedown.zoom",ga).on("mousemove.zoom",ia).on(n+".zoom",ha).on("dblclick.zoom",ja).on("touchstart.zoom",ka).on("touchmove.zoom",la).on("touchend.zoom",ka);}z.translate=function(ma){if(!arguments.length)return p;p=ma.map(Number);ea();return z;};z.scale=function(ma){if(!arguments.length)return r;r=+ma;ea();return z;};z.scaleExtent=function(ma){if(!arguments.length)return t;t=ma==null?l:ma.map(Number);return z;};z.x=function(ma){if(!arguments.length)return v;v=ma;u=ma.copy();p=[0,0];r=1;return z;};z.y=function(ma){if(!arguments.length)return x;x=ma;w=ma.copy();p=[0,0];r=1;return z;};function aa(ma){return [(ma[0]-p[0])/r,(ma[1]-p[1])/r];}function ba(ma){return [ma[0]*r+p[0],ma[1]*r+p[1]];}function ca(ma){r=Math.max(t[0],Math.min(t[1],ma));}function da(ma,na){na=ba(na);p[0]+=ma[0]-na[0];p[1]+=ma[1]-na[1];}function ea(){if(v)v.domain(u.range().map(function(ma){return (ma-p[0])/r;}).map(u.invert));if(x)x.domain(w.range().map(function(ma){return (ma-p[1])/r;}).map(w.invert));}function fa(event){ea();c("d3/core/core").event.preventDefault();event({type:"zoom",scale:r,translate:p});}function ga(){var ma=this,na=event.of(ma,arguments),oa=c("d3/core/core").event.target,pa=0,qa=c("d3/core/selection-root")(i).on("mousemove.zoom",sa).on("mouseup.zoom",ta),ra=aa(c("d3/core/mouse")(ma));i.focus();j();function sa(){pa=1;da(c("d3/core/mouse")(ma),ra);fa(na);}function ta(){if(pa)j();qa.on("mousemove.zoom",null).on("mouseup.zoom",null);if(pa&&c("d3/core/core").event.target===oa)qa.on("click.zoom",ua,true);}function ua(){j();qa.on("click.zoom",null);}}function ha(){if(!q)q=aa(c("d3/core/mouse")(this));ca(Math.pow(2,m()*.002)*r);da(c("d3/core/mouse")(this),q);fa(event.of(this,arguments));}function ia(){q=null;}function ja(){var ma=c("d3/core/mouse")(this),na=aa(ma),oa=Math.log(r)/Math.LN2;ca(Math.pow(2,c("d3/core/core").event.shiftKey?Math.ceil(oa)-1:Math.floor(oa)+1));da(ma,na);fa(event.of(this,arguments));}function ka(){var ma=c("d3/core/touches")(this),na=Date.now();s=r;q={};ma.forEach(function(qa){q[qa.identifier]=aa(qa);});j();if(ma.length===1){if(na-y<500){var oa=ma[0],pa=aa(ma[0]);ca(r*2);da(oa,pa);fa(event.of(this,arguments));}y=na;}}function la(){var ma=c("d3/core/touches")(this),na=ma[0],oa=q[na.identifier];if(pa=ma[1]){var pa,qa=q[pa.identifier];na=[(na[0]+pa[0])/2,(na[1]+pa[1])/2];oa=[(oa[0]+qa[0])/2,(oa[1]+qa[1])/2];ca(c("d3/core/core").event.scale*s);}da(na,oa);y=null;fa(event.of(this,arguments));}return c("d3/core/rebind")(z,event,"on");},l=[0,Infinity],m,n="onwheel" in document?(m=function o(){return -c("d3/core/core").event.deltaY*(c("d3/core/core").event.deltaMode?120:1);},"wheel"):"onmousewheel" in document?(m=function o(){return c("d3/core/core").event.wheelDelta;},"mousewheel"):(m=function o(){return -c("d3/core/core").event.detail;},"MozMousePixelScroll");f.exports=k;}),null);
__d("d3/d3.behavior",["d3/behavior/behavior","d3/behavior/drag","d3/behavior/zoom"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/behavior/behavior").drag=c("d3\/behavior\/drag");c("d3/behavior/behavior").zoom=c("d3\/behavior\/zoom");f.exports=c("d3/behavior/behavior");}),null);
__d("d3/compat/date",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();if(!Date.now)Date.now=function(){return +new Date();};}),null);
__d("d3/compat/style",["d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._document,i=c("d3/core/core")._window;try{h.createElement("div").style.setProperty("opacity",0,"");}catch(j){var k=i.CSSStyleDeclaration.prototype,l=k.setProperty;k.setProperty=function(m,n,o){l.call(this,m,n+"",o);};}}),null);
__d("d3/core/ascending",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j,k){return j<k?-1:j>k?1:j>=k?0:NaN;};f.exports=h;}),null);
__d("d3/core/descending",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j,k){return k<j?-1:k>j?1:k>=j?0:NaN;};f.exports=h;}),null);
__d("d3/core/ease",["d3/core/identity","d3/core/core","d3/core/map"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/identity")._identity,i=c("d3\/core\/core")._u03c0,j=function aa(){return h;},k=c("d3/core/map")({linear:j,poly:t,quad:function aa(){return q;},cubic:function aa(){return r;},sin:function aa(){return u;},exp:function aa(){return v;},circle:function aa(){return w;},elastic:x,back:y,bounce:function aa(){return z;}}),l=c("d3/core/map")({"in":h,out:o,"in-out":p,"out-in":function aa(ba){return p(o(ba));}}),m=function aa(ba){var ca=ba.indexOf("-"),da=ca>=0?ba.substring(0,ca):ba,ea=ca>=0?ba.substring(ca+1):"in";da=k.get(da)||j;ea=l.get(ea)||h;return n(ea(da.apply(null,Array.prototype.slice.call(arguments,1))));};function n(aa){return function(ba){return ba<=0?0:ba>=1?1:aa(ba);};}function o(aa){return function(ba){return 1-aa(1-ba);};}function p(aa){return function(ba){return .5*(ba<.5?aa(2*ba):2-aa(2-2*ba));};}function q(aa){return aa*aa;}function r(aa){return aa*aa*aa;}function s(aa){if(aa<=0)return 0;if(aa>=1)return 1;var ba=aa*aa,ca=ba*aa;return 4*(aa<.5?ca:3*(aa-ba)+ca-.75);}function t(aa){return function(ba){return Math.pow(ba,aa);};}function u(aa){return 1-Math.cos(aa*i/2);}function v(aa){return Math.pow(2,10*(aa-1));}function w(aa){return 1-Math.sqrt(1-aa*aa);}function x(aa,ba){var ca;if(arguments.length<2)ba=.45;if(arguments.length){ca=ba/(2*i)*Math.asin(1/aa);}else aa=1,ca=ba/4;return function(da){return 1+aa*Math.pow(2,10*-da)*Math.sin((da-ca)*2*i/ba);};}function y(aa){if(!aa)aa=1.70158;return function(ba){return ba*ba*((aa+1)*ba-aa);};}function z(aa){return aa<1/2.75?7.5625*aa*aa:aa<2/2.75?7.5625*(aa-=1.5/2.75)*aa+.75:aa<2.5/2.75?7.5625*(aa-=2.25/2.75)*aa+.9375:7.5625*(aa-=2.625/2.75)*aa+.984375;}m._cubicInOut=s;f.exports=m;}),null);
__d("d3/core/entries",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j){var k=[];for(var l in j)k.push({key:l,value:j[l]});return k;};f.exports=h;}),null);
__d("d3/core/extent",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j,k){var l=-1,m=j.length,n,o,p;if(arguments.length===1){while(++l<m&&((n=p=j[l])==null||n!=n))n=p=undefined;while(++l<m)if((o=j[l])!=null){if(n>o)n=o;if(p<o)p=o;}}else{while(++l<m&&((n=p=k.call(j,j[l],l))==null||n!=n))n=undefined;while(++l<m)if((o=k.call(j,j[l],l))!=null){if(n>o)n=o;if(p<o)p=o;}}return [n,p];};f.exports=h;}),null);
__d("d3/core/functor",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(j){return typeof j==="function"?j:function(){return j;};}var i=h;i._functor=h;f.exports=i;}),null);
__d("d3/core/xhr",["d3/core/core","d3/core/identity","d3/core/array","d3/core/dispatch","d3/core/rebind"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/identity")._identity,i=c("d3/core/core")._window,j=c("d3\/core\/array")._array,k=function m(n,o,p){var q={},r=c("d3/core/dispatch")("progress","load","error"),s={},t=h,u=new (i.XDomainRequest&&/^(http(s)?:)?\/\//.test(n)?XDomainRequest:XMLHttpRequest)();"onload" in u?u.onload=u.onerror=v:u.onreadystatechange=function(){u.readyState>3&&v();};function v(){var w=u.status;!w&&u.responseText||w>=200&&w<300||w===304?r.load.call(q,t.call(q,u)):r.error.call(q,u);}u.onprogress=function(event){var w=c("d3/core/core").event;c("d3/core/core").event=event;try{r.progress.call(q,u);}finally{c("d3/core/core").event=w;}};q.header=function(w,x){w=(w+"").toLowerCase();if(arguments.length<2)return s[w];if(x==null){delete s[w];}else s[w]=x+"";return q;};q.mimeType=function(w){if(!arguments.length)return o;o=w==null?null:w+"";return q;};q.response=function(w){t=w;return q;};["get","post"].forEach(function(w){q[w]=function(){return q.send.apply(q,[w].concat(j(arguments)));};});q.send=function(w,x,y){if(arguments.length===2&&typeof x==="function")y=x,x=null;u.open(w,n,true);if(o!=null&&!("accept" in s))s.accept=o+",*/*";if(u.setRequestHeader)for(var z in s)u.setRequestHeader(z,s[z]);if(o!=null&&u.overrideMimeType)u.overrideMimeType(o);if(y!=null)q.on("error",y).on("load",function(aa){y(null,aa);});u.send(x==null?null:x);return q;};q.abort=function(){u.abort();return q;};c("d3/core/rebind")(q,r,"on");if(arguments.length===2&&typeof o==="function")p=o,o=null;return p==null?q:q.get(l(p));};function l(m){return m.length===1?function(n,o){m(n==null?o:null);}:m;}f.exports=k;}),null);
__d("d3/core/html",["d3/core/core","d3/core/xhr"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._document,i=function k(l,m){return c("d3/core/xhr")(l,"text/html",m).response(j);};function j(k){var l=h.createRange();l.selectNode(h.body);return l.createContextualFragment(k.responseText);}f.exports=i;}),null);
__d("d3/core/json",["d3/core/xhr"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(k,l){return c("d3/core/xhr")(k,"application/json",l).response(i);};function i(j){return JSON.parse(j.responseText);}f.exports=h;}),null);
__d("d3/core/keys",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j){var k=[];for(var l in j)k.push(l);return k;};f.exports=h;}),null);
__d("d3/core/number",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(i){return i!=null&&!isNaN(i);}g._number=h;}),null);
__d("d3/core/mean",["d3/core/number"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/number")._number,i=function j(k,l){var m=k.length,n,o=0,p=-1,q=0;if(arguments.length===1){while(++p<m)if(h(n=k[p]))o+=(n-o)/++q;}else while(++p<m)if(h(n=l.call(k,k[p],p)))o+=(n-o)/++q;return q?o:undefined;};f.exports=i;}),null);
__d("d3/core/quantile",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j,k){var l=(j.length-1)*k+1,m=Math.floor(l),n=+j[m-1],o=l-m;return o?n+o*(j[m]-n):n;};f.exports=h;}),null);
__d("d3/core/median",["d3/core/number","d3/core/quantile","d3/core/ascending"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/number")._number,i=function j(k,l){if(arguments.length>1)k=k.map(l);k=k.filter(h);return k.length?c("d3/core/quantile")(k.sort(c("d3/core/ascending")),.5):undefined;};f.exports=i;}),null);
__d("d3/core/merge",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j){return Array.prototype.concat.apply([],j);};f.exports=h;}),null);
__d("d3/core/nest",["d3/core/map"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/map")._Map,i=function j(){var k={},l=[],m=[],n,o;function p(r,s){if(s>=l.length)return o?o.call(k,r):n?r.sort(n):r;var t=-1,u=r.length,v=l[s++],w,x,y=new h(),z,aa={};while(++t<u)if(z=y.get(w=v(x=r[t]))){z.push(x);}else y.set(w,[x]);y.forEach(function(ba,ca){aa[ba]=p(ca,s);});return aa;}function q(r,s){if(s>=l.length)return r;var t=[],u=m[s++],v;for(v in r)t.push({key:v,values:q(r[v],s)});if(u)t.sort(function(w,x){return u(w.key,x.key);});return t;}k.map=function(r){return p(r,0);};k.entries=function(r){return q(p(r,0),0);};k.key=function(r){l.push(r);return k;};k.sortKeys=function(r){m[l.length-1]=r;return k;};k.sortValues=function(r){n=r;return k;};k.rollup=function(r){o=r;return k;};return k;};f.exports=i;}),null);
__d("d3/core/permute",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j,k){var l=[],m=-1,n=k.length;while(++m<n)l[m]=j[k[m]];return l;};f.exports=h;}),null);
__d("d3/core/random",["d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={normal:function i(j,k){var l=arguments.length;if(l<2)k=1;if(l<1)j=0;return function(){var m,n,o;do{m=Math.random()*2-1;n=Math.random()*2-1;o=m*m+n*n;}while(!o||o>1);return j+k*m*Math.sqrt(-2*Math.log(o)/o);};},logNormal:function i(){var j=h.normal.apply(c("d3/core/core"),arguments);return function(){return Math.exp(j());};},irwinHall:function i(j){return function(){for(var k=0,l=0;l<j;l++)k+=Math.random();return k/j;};}};f.exports=h;}),null);
__d("d3/core/selection-append",["d3/core/selection","d3/core/core","d3/core/ns"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype,i=c("d3\/core\/core")._document;h.append=function(j){j=c("d3/core/ns").qualify(j);function k(){return this.appendChild(i.createElementNS(this.namespaceURI,j));}function l(){return this.appendChild(i.createElementNS(j.space,j.local));}return this.select(j.local?l:k);};}),null);
__d("d3/core/selection-attr",["d3/core/selection","d3/core/ns"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.attr=function(j,k){if(arguments.length<2){if(typeof j==="string"){var l=this.node();j=c("d3/core/ns").qualify(j);return j.local?l.getAttributeNS(j.space,j.local):l.getAttribute(j);}for(k in j)this.each(i(k,j[k]));return this;}return this.each(i(j,k));};function i(j,k){j=c("d3/core/ns").qualify(j);function l(){this.removeAttribute(j);}function m(){this.removeAttributeNS(j.space,j.local);}function n(){this.setAttribute(j,k);}function o(){this.setAttributeNS(j.space,j.local,k);}function p(){var r=k.apply(this,arguments);if(r==null){this.removeAttribute(j);}else this.setAttribute(j,r);}function q(){var r=k.apply(this,arguments);if(r==null){this.removeAttributeNS(j.space,j.local);}else this.setAttributeNS(j.space,j.local,r);}return k==null?j.local?m:l:typeof k==="function"?j.local?q:p:j.local?o:n;}}),null);
__d("d3/core/selection-call",["d3/core/selection","d3/core/array"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype,i=c("d3\/core\/array")._array;h.call=function(j){var k=i(arguments);j.apply(k[0]=this,k);return this;};}),null);
__d("d3/core/collapse",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(i){return i.trim().replace(/\s+/g," ");}g._collapse=h;}),null);
__d("d3/core/selection-classed",["d3/core/selection","d3/core/collapse","d3/core/requote"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype,i=c("d3\/core\/collapse")._collapse;h.classed=function(m,n){if(arguments.length<2){if(typeof m==="string"){var o=this.node(),p=(m=m.trim().split(/^|\s+/g)).length,q=-1;if(n=o.classList){while(++q<p)if(!n.contains(m[q]))return false;}else{n=o.className;if(n.baseVal!=null)n=n.baseVal;while(++q<p)if(!j(m[q]).test(n))return false;}return true;}for(n in m)this.each(k(n,m[n]));return this;}return this.each(k(m,n));};function j(m){return new RegExp("(?:^|\\s+)"+c("d3/core/requote")(m)+"(?:\\s+|$)","g");}function k(m,n){m=m.trim().split(/\s+/).map(l);var o=m.length;function p(){var r=-1;while(++r<o)m[r](this,n);}function q(){var r=-1,s=n.apply(this,arguments);while(++r<o)m[r](this,s);}return typeof n==="function"?q:p;}function l(m){var n=j(m);return function(o,p){if(q=o.classList)return p?q.add(m):q.remove(m);var q=o.className,r=q.baseVal!=null,s=r?q.baseVal:q;if(p){n.lastIndex=0;if(!n.test(s)){s=i(s+" "+m);if(r){q.baseVal=s;}else o.className=s;}}else if(s){s=i(s.replace(n," "));if(r){q.baseVal=s;}else o.className=s;}};}}),null);
__d("d3/core/selection-enter",["d3/core/array","d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/array")._arraySubclass,i=c("d3\/core\/selection")._selectionPrototype;function j(m){h(m,k);return m;}var k=[],l=j;l.prototype=k;k.append=i.append;k.insert=i.insert;k.empty=i.empty;k.node=i.node;l._enterPrototype=k;l._enter=j;f.exports=l;}),null);
__d("d3/core/selection-data",["d3/core/selection","d3/core/map","d3/core/selection-enter"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/selection")._selectionPrototype,i=c("d3\/core\/map")._Map,j=c("d3/core/selection")._selection;h.data=function(l,m){var n=-1,o=this.length,p,q;if(!arguments.length){l=new Array(o=(p=this[0]).length);while(++n<o)if(q=p[n])l[n]=q.__data__;return l;}function r(v,w){var x,y=v.length,z=w.length,aa=Math.min(y,z),ba=new Array(z),ca=new Array(z),da=new Array(y),ea,fa;if(m){var ga=new i(),ha=new i(),ia=[],ja;for(x=-1;++x<y;){ja=m.call(ea=v[x],ea.__data__,x);if(ga.has(ja)){da[x]=ea;}else ga.set(ja,ea);ia.push(ja);}for(x=-1;++x<z;){ja=m.call(w,fa=w[x],x);if(ea=ga.get(ja)){ba[x]=ea;ea.__data__=fa;}else if(!ha.has(ja))ca[x]=k(fa);ha.set(ja,fa);ga.remove(ja);}for(x=-1;++x<y;)if(ga.has(ia[x]))da[x]=v[x];}else{for(x=-1;++x<aa;){ea=v[x];fa=w[x];if(ea){ea.__data__=fa;ba[x]=ea;}else ca[x]=k(fa);}for(;x<z;++x)ca[x]=k(w[x]);for(;x<y;++x)da[x]=v[x];}ca.update=ba;ca.parentNode=ba.parentNode=da.parentNode=v.parentNode;s.push(ca);t.push(ba);u.push(da);}var s=c("d3\/core\/selection-enter")._enter([]),t=j([]),u=j([]);if(typeof l==="function"){while(++n<o)r(p=this[n],l.call(p,p.parentNode.__data__,n));}else while(++n<o)r(p=this[n],l);t.enter=function(){return s;};t.exit=function(){return u;};return t;};function k(l){return {__data__:l};}}),null);
__d("d3/core/selection-datum",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.datum=function(i){return arguments.length?this.property("__data__",i):this.property("__data__");};}),null);
__d("d3/core/selection-empty",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.empty=function(){return !this.node();};}),null);
__d("d3/core/selection-enter-select",["d3/core/selection","d3/core/selection-enter"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selection;c("d3\/core\/selection-enter")._enterPrototype.select=function(i){var j=[],k,l,m,n,o;for(var p=-1,q=this.length;++p<q;){m=(n=this[p]).update;j.push(k=[]);k.parentNode=n.parentNode;for(var r=-1,s=n.length;++r<s;)if(o=n[r]){k.push(m[r]=l=i.call(n.parentNode,o.__data__,r));l.__data__=o.__data__;}else k.push(null);}return h(j);};}),null);
__d("d3/core/selection-html",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.html=function(i){return arguments.length?this.each(typeof i==="function"?function(){var j=i.apply(this,arguments);this.innerHTML=j==null?"":j;}:i==null?function(){this.innerHTML="";}:function(){this.innerHTML=i;}):this.node().innerHTML;};}),null);
__d("d3/core/selection-insert",["d3/core/selection","d3/core/core","d3/core/ns"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/selection")._selectionPrototype,i=c("d3\/core\/core")._document,j=c("d3/core/selection")._select;h.insert=function(k,l){k=c("d3/core/ns").qualify(k);function m(){return this.insertBefore(i.createElementNS(this.namespaceURI,k),j(l,this));}function n(){return this.insertBefore(i.createElementNS(k.space,k.local),j(l,this));}return this.select(k.local?n:m);};}),null);
__d("d3/core/selection-node",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.node=function(){for(var i=0,j=this.length;i<j;i++)for(var k=this[i],l=0,m=k.length;l<m;l++){var n=k[l];if(n)return n;}return null;};}),null);
__d("d3/core/selection-on",["d3/core/selection","d3/core/array","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype,i=c("d3\/core\/array")._array;h.on=function(k,l,m){var n=arguments.length;if(n<3){if(typeof k!=="string"){if(n<2)l=false;for(m in k)this.each(j(m,k[m],l));return this;}if(n<2)return (n=this.node()["__on"+k])&&n._;m=false;}return this.each(j(k,l,m));};function j(k,l,m){var n="__on"+k,o=k.indexOf(".");if(o>0)k=k.substring(0,o);function p(){var r=this[n];if(r){this.removeEventListener(k,r,r.$);delete this[n];}}function q(){var r=this,s=i(arguments);p.call(this);this.addEventListener(k,this[n]=t,t.$=m);t._=l;function t(u){var v=c("d3/core/core").event;c("d3/core/core").event=u;s[0]=r.__data__;try{l.apply(r,s);}finally{c("d3/core/core").event=v;}}}return l?q:p;}}),null);
__d("d3/core/selection-order",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.order=function(){for(var i=-1,j=this.length;++i<j;)for(var k=this[i],l=k.length-1,m=k[l],n;--l>=0;)if(n=k[l]){if(m&&m!==n.nextSibling)m.parentNode.insertBefore(n,m);m=n;}return this;};}),null);
__d("d3/core/selection-property",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.property=function(j,k){if(arguments.length<2){if(typeof j==="string")return this.node()[j];for(k in j)this.each(i(k,j[k]));return this;}return this.each(i(j,k));};function i(j,k){function l(){delete this[j];}function m(){this[j]=k;}function n(){var o=k.apply(this,arguments);if(o==null){delete this[j];}else this[j]=o;}return k==null?l:typeof k==="function"?n:m;}}),null);
__d("d3/core/selection-remove",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.remove=function(){return this.each(function(){var i=this.parentNode;if(i)i.removeChild(this);});};}),null);
__d("d3/core/selection-sort",["d3/core/selection","d3/core/ascending"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.sort=function(j){j=i.apply(this,arguments);for(var k=-1,l=this.length;++k<l;)this[k].sort(j);return this.order();};function i(j){if(!arguments.length)j=c("d3/core/ascending");return function(k,l){return !k-!l||j(k.__data__,l.__data__);};}}),null);
__d("d3/core/selection-style",["d3/core/selection","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype,i=c("d3\/core\/core")._window;h.style=function(k,l,m){var n=arguments.length;if(n<3){if(typeof k!=="string"){if(n<2)l="";for(m in k)this.each(j(m,k[m],l));return this;}if(n<2)return i.getComputedStyle(this.node(),null).getPropertyValue(k);m="";}return this.each(j(k,l,m));};function j(k,l,m){function n(){this.style.removeProperty(k);}function o(){this.style.setProperty(k,l,m);}function p(){var q=l.apply(this,arguments);if(q==null){this.style.removeProperty(k);}else this.style.setProperty(k,q,m);}return l==null?n:typeof l==="function"?p:o;}}),null);
__d("d3/core/selection-text",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.text=function(i){return arguments.length?this.each(typeof i==="function"?function(){var j=i.apply(this,arguments);this.textContent=j==null?"":j;}:i==null?function(){this.textContent="";}:function(){this.textContent=i;}):this.node().textContent;};}),null);
__d("d3/core/timer",["d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._window,i=0,j={},k=null,l,m,n=function r(s,t,u){if(arguments.length<3){if(arguments.length<2){t=0;}else if(!isFinite(t))return;u=Date.now();}var v=j[s.id];if(v&&v.callback===s){v.then=u;v.delay=t;}else j[s.id=++i]=k={callback:s,then:u,delay:t,next:k};if(!l){m=clearTimeout(m);l=1;q(o);}};function o(){var r,s=Date.now(),t=k;while(t){r=s-t.then;if(r>=t.delay)t.flush=t.callback(r);t=t.next;}var u=p()-s;if(u>24){if(isFinite(u)){clearTimeout(m);m=setTimeout(o,u);}l=0;}else{l=1;q(o);}}n.flush=function(){var r,s=Date.now(),t=k;while(t){r=s-t.then;if(!t.delay)t.flush=t.callback(r);t=t.next;}p();};function p(){var r=null,s=k,t=Infinity;while(s)if(s.flush){delete j[s.callback.id];s=r?r.next=s.next:k=s.next;}else{t=Math.min(t,s.then+s.delay);s=(r=s).next;}return t;}var q=h.requestAnimationFrame||h.webkitRequestAnimationFrame||h.mozRequestAnimationFrame||h.oRequestAnimationFrame||h.msRequestAnimationFrame||function(r){setTimeout(r,17);};f.exports=n;}),null);
__d("d3/core/transition",["d3/core/array","d3/core/ease","d3/core/selection","d3/core/selection-root","d3/core/map","d3/core/dispatch","d3/core/timer"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/array")._arraySubclass,i=c("d3\/core\/ease")._cubicInOut,j=c("d3\/core\/selection")._selectionPrototype,k=c("d3\/core\/selection-root")._selectionRoot,l=c("d3\/core\/map")._Map;function m(t,u){h(t,n);t.id=u;return t;}var n=[],o=0,p,q={ease:i,delay:0,duration:250};n.call=j.call;n.empty=j.empty;n.node=j.node;var r=function t(u){return arguments.length?t._transitionInheritId?u.transition():u:k.transition();};r.prototype=n;function s(t,u,v,w){var x=t.__transition__||(t.__transition__={active:0,count:0}),y=x[v];if(!y){var z=w.time;y=x[v]={tween:new l(),event:c("d3/core/dispatch")("start","end"),time:z,ease:w.ease,delay:w.delay,duration:w.duration};++x.count;c("d3/core/timer")(function(aa){var ba=t.__data__,ca=y.ease,event=y.event,da=y.delay,ea=y.duration,fa=[];return da<=aa?ga(aa):c("d3/core/timer")(ga,da,z),1;function ga(ja){if(x.active>v)return ia();x.active=v;event.start.call(t,ba,u);y.tween.forEach(function(ka,la){if(la=la.call(t,ba,u))fa.push(la);});if(!ha(ja))c("d3/core/timer")(ha,0,z);return 1;}function ha(ja){if(x.active!==v)return ia();var ka=(ja-da)/ea,la=ca(ka),ma=fa.length;while(ma>0)fa[--ma].call(t,la);if(ka>=1){ia();event.end.call(t,ba,u);return 1;}}function ia(){if(--x.count){delete x[v];}else delete t.__transition__;return 1;}},0,z);return y;}}r._transitionPrototype=n;r._transitionId=o;r._transitionInheritId=p;r._transitionInherit=q;r._transition=m;r._transitionNode=s;f.exports=r;}),null);
__d("d3/core/selection-transition",["d3/core/transition","d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype,i=c("d3/core/transition")._transitionNode,j=c("d3/core/transition")._transition;h.transition=function(){var k=c("d3/core/transition")._transitionInheritId||++c("d3/core/transition")._transitionId,l=[],m,n,o=Object.create(c("d3/core/transition")._transitionInherit);o.time=Date.now();for(var p=-1,q=this.length;++p<q;){l.push(m=[]);for(var r=this[p],s=-1,t=r.length;++s<t;){if(n=r[s])i(n,s,k,o);m.push(n);}}return j(l,k);};}),null);
__d("d3/core/shuffle",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j){var k=j.length,l,m;while(k){m=Math.random()*k--|0;l=j[k],j[k]=j[m],j[m]=l;}return j;};f.exports=h;}),null);
__d("d3/core/sum",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j,k){var l=0,m=j.length,n,o=-1;if(arguments.length===1){while(++o<m)if(!isNaN(n=+j[o]))l+=n;}else while(++o<m)if(!isNaN(n=+k.call(j,j[o],o)))l+=n;return l;};f.exports=h;}),null);
__d("d3/core/text",["d3/core/xhr","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(){return c("d3/core/xhr").apply(c("d3/core/core"),arguments).response(i);};function i(j){return j.responseText;}f.exports=h;}),null);
__d("d3/core/selection-each",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/selection")._selectionPrototype;h.each=function(j){return i(this,function(k,l,m){j.call(k,k.__data__,l,m);});};function i(j,k){for(var l=0,m=j.length;l<m;l++)for(var n=j[l],o=0,p=n.length,q;o<p;o++)if(q=n[o])k(q,o,l);return j;}g._each=i;}),null);
__d("d3/core/transition-tween",["d3/core/transition","d3/core/selection-each"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype,i=c("d3\/core\/selection-each")._each;h.tween=function(k,l){var m=this.id;if(arguments.length<2)return this.node().__transition__[m].tween.get(k);return i(this,l==null?function(n){n.__transition__[m].tween.remove(k);}:function(n){n.__transition__[m].tween.set(k,l);});};function j(k,l,m,n){var o=k.id;return i(k,typeof m==="function"?function(p,q,r){p.__transition__[o].tween.set(l,n(m.call(p,p.__data__,q,r)));}:(m=n(m),function(p){p.__transition__[o].tween.set(l,m);}));}g._tween=j;}),null);
__d("d3/core/transition-attr",["d3/core/transition","d3/core/interpolate","d3/core/ns","d3/core/transition-tween"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype,i=c("d3\/core\/interpolate")._interpolateByName;h.attr=function(j,k){if(arguments.length<2){for(k in j)this.attr(k,j[k]);return this;}var l=i(j),m=c("d3/core/ns").qualify(j);function n(){this.removeAttribute(m);}function o(){this.removeAttributeNS(m.space,m.local);}return c("d3\/core\/transition-tween")._tween(this,"attr."+j,k,function(p){function q(){var s=this.getAttribute(m),t;return s!==p&&(t=l(s,p),function(u){this.setAttribute(m,t(u));});}function r(){var s=this.getAttributeNS(m.space,m.local),t;return s!==p&&(t=l(s,p),function(u){this.setAttributeNS(m.space,m.local,t(u));});}return p==null?m.local?o:n:(p+="",m.local?r:q);});};h.attrTween=function(j,k){var l=c("d3/core/ns").qualify(j);function m(o,p){var q=k.call(this,o,p,this.getAttribute(l));return q&&function(r){this.setAttribute(l,q(r));};}function n(o,p){var q=k.call(this,o,p,this.getAttributeNS(l.space,l.local));return q&&function(r){this.setAttributeNS(l.space,l.local,q(r));};}return this.tween("attr."+j,l.local?n:m);};}),null);
__d("d3/core/transition-delay",["d3/core/transition","d3/core/selection-each"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype,i=c("d3\/core\/selection-each")._each;h.delay=function(j){var k=this.id;return i(this,typeof j==="function"?function(l,m,n){l.__transition__[k].delay=j.call(l,l.__data__,m,n)|0;}:(j|=0,function(l){l.__transition__[k].delay=j;}));};}),null);
__d("d3/core/transition-duration",["d3/core/transition","d3/core/selection-each"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype,i=c("d3\/core\/selection-each")._each;h.duration=function(j){var k=this.id;return i(this,typeof j==="function"?function(l,m,n){l.__transition__[k].duration=Math.max(1,j.call(l,l.__data__,m,n)|0);}:(j=Math.max(1,j|0),function(l){l.__transition__[k].duration=j;}));};}),null);
__d("d3/core/transition-each",["d3/core/transition","d3/core/selection-each"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/transition")._transitionPrototype,i=c("d3\/core\/selection-each")._each;h.each=function(j,k){var l=this.id;if(arguments.length<2){var m=c("d3/core/transition")._transitionInherit,n=c("d3/core/transition")._transitionInheritId;c("d3/core/transition")._transitionInheritId=l;i(this,function(o,p,q){c("d3/core/transition")._transitionInherit=o.__transition__[l];j.call(o,o.__data__,p,q);});c("d3/core/transition")._transitionInherit=m;c("d3/core/transition")._transitionInheritId=n;}else i(this,function(o){o.__transition__[l].event.on(j,k);});return this;};}),null);
__d("d3/core/transition-ease",["d3/core/transition","d3/core/selection-each","d3/core/ease","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype,i=c("d3\/core\/selection-each")._each;h.ease=function(j){var k=this.id;if(arguments.length<1)return this.node().__transition__[k].ease;if(typeof j!=="function")j=c("d3/core/ease").apply(c("d3/core/core"),arguments);return i(this,function(l){l.__transition__[k].ease=j;});};}),null);
__d("d3/core/selection-filter",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/selection")._selectionPrototype,i=c("d3/core/selection")._selection,j=c("d3/core/selection")._selectMatches;h.filter=function(l){var m=[],n,o,p;if(typeof l!=="function")l=k(l);for(var q=0,r=this.length;q<r;q++){m.push(n=[]);n.parentNode=(o=this[q]).parentNode;for(var s=0,t=o.length;s<t;s++)if((p=o[s])&&l.call(p,p.__data__,s))n.push(p);}return i(m);};function k(l){return function(){return j(this,l);};}g._filter=k;}),null);
__d("d3/core/transition-filter",["d3/core/transition","d3/core/selection-filter"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/transition")._transitionPrototype,i=c("d3\/core\/selection-filter")._filter,j=c("d3/core/transition")._transition;h.filter=function(k){var l=[],m,n,o;if(typeof k!=="function")k=i(k);for(var p=0,q=this.length;p<q;p++){l.push(m=[]);for(var n=this[p],r=0,s=n.length;r<s;r++)if((o=n[r])&&k.call(o,o.__data__,r))m.push(o);}return j(l,this.id,this.time).ease(this.ease());};}),null);
__d("d3/core/transition-remove",["d3/core/transition"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype;h.remove=function(){return this.each("end.transition",function(){var i;if(!this.__transition__&&(i=this.parentNode))i.removeChild(this);});};}),null);
__d("d3/core/selection-select",["d3/core/selection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/selection")._selectionPrototype,i=c("d3/core/selection")._selection,j=c("d3/core/selection")._select;h.select=function(l){var m=[],n,o,p,q;if(typeof l!=="function")l=k(l);for(var r=-1,s=this.length;++r<s;){m.push(n=[]);n.parentNode=(p=this[r]).parentNode;for(var t=-1,u=p.length;++t<u;)if(q=p[t]){n.push(o=l.call(q,q.__data__,t));if(o&&"__data__" in q)o.__data__=q.__data__;}else n.push(null);}return i(m);};function k(l){return function(){return j(l,this);};}g._selector=k;}),null);
__d("d3/core/transition-select",["d3/core/transition","d3/core/selection-select"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/transition")._transitionPrototype,i=c("d3\/core\/selection-select")._selector,j=c("d3/core/transition")._transitionNode,k=c("d3/core/transition")._transition;h.select=function(l){var m=this.id,n=[],o,p,q;if(typeof l!=="function")l=i(l);for(var r=-1,s=this.length;++r<s;){n.push(o=[]);for(var t=this[r],u=-1,v=t.length;++u<v;)if((q=t[u])&&(p=l.call(q,q.__data__,u))){if("__data__" in q)p.__data__=q.__data__;j(p,u,m,q.__transition__[m]);o.push(p);}else o.push(null);}return k(n,m);};}),null);
__d("d3/core/selection-selectAll",["d3/core/selection","d3/core/array"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/selection")._selectionPrototype,i=c("d3\/core\/array")._array,j=c("d3/core/selection")._selection,k=c("d3/core/selection")._selectAll;h.selectAll=function(m){var n=[],o,p;if(typeof m!=="function")m=l(m);for(var q=-1,r=this.length;++q<r;)for(var s=this[q],t=-1,u=s.length;++t<u;)if(p=s[t]){n.push(o=i(m.call(p,p.__data__,t)));o.parentNode=p;}return j(n);};function l(m){return function(){return k(m,this);};}g._selectorAll=l;}),null);
__d("d3/core/transition-selectAll",["d3/core/transition","d3/core/selection-selectAll"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/transition")._transitionPrototype,i=c("d3\/core\/selection-selectAll")._selectorAll,j=c("d3/core/transition")._transitionNode,k=c("d3/core/transition")._transition;h.selectAll=function(l){var m=this.id,n=[],o,p,q,r,s;if(typeof l!=="function")l=i(l);for(var t=-1,u=this.length;++t<u;)for(var v=this[t],w=-1,x=v.length;++w<x;)if(q=v[w]){s=q.__transition__[m];p=l.call(q,q.__data__,w);n.push(o=[]);for(var y=-1,z=p.length;++y<z;){j(r=p[y],y,m,s);o.push(r);}}return k(n,m);};}),null);
__d("d3/core/transition-style",["d3/core/transition","d3/core/interpolate","d3/core/core","d3/core/transition-tween"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype,i=c("d3\/core\/interpolate")._interpolateByName,j=c("d3\/core\/core")._window;h.style=function(k,l,m){var n=arguments.length;if(n<3){if(typeof k!=="string"){if(n<2)l="";for(m in k)this.style(m,k[m],l);return this;}m="";}var o=i(k);function p(){this.style.removeProperty(k);}return c("d3\/core\/transition-tween")._tween(this,"style."+k,l,function(q){function r(){var s=j.getComputedStyle(this,null).getPropertyValue(k),t;return s!==q&&(t=o(s,q),function(u){this.style.setProperty(k,t(u),m);});}return q==null?p:(q+="",r);});};h.styleTween=function(k,l,m){if(arguments.length<3)m="";return this.tween("style."+k,function(n,o){var p=l.call(this,n,o,j.getComputedStyle(this,null).getPropertyValue(k));return p&&function(q){this.style.setProperty(k,p(q),m);};});};}),null);
__d("d3/core/transition-text",["d3/core/transition","d3/core/transition-tween"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/transition")._transitionPrototype;h.text=function(j){return c("d3\/core\/transition-tween")._tween(this,"text",j,i);};function i(j){if(j==null)j="";return function(){this.textContent=j;};}}),null);
__d("d3/core/transition-transition",["d3/core/transition"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/transition")._transitionPrototype,i=c("d3/core/transition")._transitionNode,j=c("d3/core/transition")._transition;h.transition=function(){var k=this.id,l=++c("d3/core/transition")._transitionId,m=[],n,o,p,q;for(var r=0,s=this.length;r<s;r++){m.push(n=[]);for(var o=this[r],t=0,u=o.length;t<u;t++){if(p=o[t]){q=Object.create(p.__transition__[k]);q.delay+=q.duration;i(p,t,l,q);}n.push(p);}}return j(m,l);};}),null);
__d("d3/core/zip",["d3/core/min"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(){if(!(o=arguments.length))return [];for(var k=-1,l=c("d3/core/min")(arguments,i),m=new Array(l);++k<l;)for(var n=-1,o,p=m[k]=new Array(o);++n<o;)p[n]=arguments[n][k];return m;};function i(j){return j.length;}f.exports=h;}),null);
__d("d3/core/transpose",["d3/core/zip","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j){return c("d3/core/zip").apply(c("d3/core/core"),j);};f.exports=h;}),null);
__d("d3/core/values",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(j){var k=[];for(var l in j)if(j.hasOwnProperty(l))k.push(j[l]);return k;};f.exports=h;}),null);
__d("d3/core/xml",["d3/core/xhr","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(){return c("d3/core/xhr").apply(c("d3/core/core"),arguments).response(i);};function i(j){return j.responseXML;}f.exports=h;}),null);
__d("d3/d3.core",["d3/compat/date","d3/compat/style","d3/core/selection-attr","d3/core/selection-classed","d3/core/selection-style","d3/core/selection-property","d3/core/selection-text","d3/core/selection-html","d3/core/selection-append","d3/core/selection-insert","d3/core/selection-remove","d3/core/selection-data","d3/core/selection-datum","d3/core/selection-order","d3/core/selection-sort","d3/core/selection-on","d3/core/selection-call","d3/core/selection-empty","d3/core/selection-node","d3/core/selection-transition","d3/core/selection-enter-select","d3/core/transition-select","d3/core/transition-selectAll","d3/core/transition-filter","d3/core/transition-attr","d3/core/transition-style","d3/core/transition-text","d3/core/transition-remove","d3/core/transition-ease","d3/core/transition-delay","d3/core/transition-duration","d3/core/transition-each","d3/core/transition-transition","d3/core/core","d3/core/map","d3/core/functor","d3/core/rebind","d3/core/ascending","d3/core/descending","d3/core/mean","d3/core/median","d3/core/min","d3/core/max","d3/core/extent","d3/core/random","d3/core/sum","d3/core/quantile","d3/core/shuffle","d3/core/transpose","d3/core/zip","d3/core/bisect","d3/core/nest","d3/core/keys","d3/core/values","d3/core/entries","d3/core/permute","d3/core/merge","d3/core/range","d3/core/requote","d3/core/round","d3/core/xhr","d3/core/text","d3/core/json","d3/core/html","d3/core/xml","d3/core/ns","d3/core/dispatch","d3/core/format","d3/core/formatPrefix","d3/core/ease","d3/core/transform","d3/core/interpolate","d3/core/rgb","d3/core/hsl","d3/core/hcl","d3/core/lab","d3/core/selection","d3/core/selection-root","d3/core/selection-enter","d3/core/transition","d3/core/timer","d3/core/mouse","d3/core/touches"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3\/compat\/date");c("d3\/compat\/style");c("d3\/core\/selection-attr");c("d3\/core\/selection-classed");c("d3\/core\/selection-style");c("d3\/core\/selection-property");c("d3\/core\/selection-text");c("d3\/core\/selection-html");c("d3\/core\/selection-append");c("d3\/core\/selection-insert");c("d3\/core\/selection-remove");c("d3\/core\/selection-data");c("d3\/core\/selection-datum");c("d3\/core\/selection-order");c("d3\/core\/selection-sort");c("d3\/core\/selection-on");c("d3\/core\/selection-call");c("d3\/core\/selection-empty");c("d3\/core\/selection-node");c("d3\/core\/selection-transition");c("d3\/core\/selection-enter-select");c("d3\/core\/transition-select");c("d3\/core\/transition-selectAll");c("d3\/core\/transition-filter");c("d3\/core\/transition-attr");c("d3\/core\/transition-style");c("d3\/core\/transition-text");c("d3\/core\/transition-remove");c("d3\/core\/transition-ease");c("d3\/core\/transition-delay");c("d3\/core\/transition-duration");c("d3\/core\/transition-each");c("d3\/core\/transition-transition");c("d3/core/core").map=c("d3\/core\/map");c("d3/core/core").functor=c("d3\/core\/functor");c("d3/core/core").rebind=c("d3\/core\/rebind");c("d3/core/core").ascending=c("d3\/core\/ascending");c("d3/core/core").descending=c("d3\/core\/descending");c("d3/core/core").mean=c("d3\/core\/mean");c("d3/core/core").median=c("d3\/core\/median");c("d3/core/core").min=c("d3\/core\/min");c("d3/core/core").max=c("d3\/core\/max");c("d3/core/core").extent=c("d3\/core\/extent");c("d3/core/core").random=c("d3\/core\/random");c("d3/core/core").sum=c("d3\/core\/sum");c("d3/core/core").quantile=c("d3\/core\/quantile");c("d3/core/core").shuffle=c("d3\/core\/shuffle");c("d3/core/core").transpose=c("d3\/core\/transpose");c("d3/core/core").zip=c("d3\/core\/zip");c("d3/core/core").bisect=c("d3\/core\/bisect");c("d3/core/core").bisector=c("d3\/core\/bisect").or;c("d3/core/core").bisectLeft=c("d3\/core\/bisect").left;c("d3/core/core").bisectRight=c("d3\/core\/bisect").right;c("d3/core/core").nest=c("d3\/core\/nest");c("d3/core/core").keys=c("d3\/core\/keys");c("d3/core/core").values=c("d3\/core\/values");c("d3/core/core").entries=c("d3\/core\/entries");c("d3/core/core").permute=c("d3\/core\/permute");c("d3/core/core").merge=c("d3\/core\/merge");c("d3/core/core").range=c("d3\/core\/range");c("d3/core/core").requote=c("d3\/core\/requote");c("d3/core/core").round=c("d3\/core\/round");c("d3/core/core").xhr=c("d3\/core\/xhr");c("d3/core/core").text=c("d3\/core\/text");c("d3/core/core").json=c("d3\/core\/json");c("d3/core/core").html=c("d3\/core\/html");c("d3/core/core").xml=c("d3\/core\/xml");c("d3/core/core").ns=c("d3\/core\/ns");c("d3/core/core").dispatch=c("d3\/core\/dispatch");c("d3/core/core").format=c("d3\/core\/format");c("d3/core/core").formatPrefix=c("d3\/core\/formatPrefix");c("d3/core/core").ease=c("d3\/core\/ease");c("d3/core/core").transform=c("d3\/core\/transform");c("d3/core/core").interpolate=c("d3\/core\/interpolate");c("d3/core/core").interpolators=c("d3\/core\/interpolate").interpolators;c("d3/core/core").interpolateRgb=c("d3\/core\/interpolate").rgb;c("d3/core/core").interpolateLab=c("d3\/core\/interpolate").lab;c("d3/core/core").interpolateHcl=c("d3\/core\/interpolate").hcl;c("d3/core/core").interpolateHsl=c("d3\/core\/interpolate").hsl;c("d3/core/core").interpolateRound=c("d3\/core\/interpolate").round;c("d3/core/core").interpolateArray=c("d3\/core\/interpolate").array;c("d3/core/core").interpolateString=c("d3\/core\/interpolate").string;c("d3/core/core").interpolateNumber=c("d3\/core\/interpolate").number;c("d3/core/core").interpolateObject=c("d3\/core\/interpolate").object;c("d3/core/core").interpolateTransform=c("d3\/core\/interpolate").transform;c("d3/core/core").rgb=c("d3\/core\/rgb");c("d3/core/core").hsl=c("d3\/core\/hsl");c("d3/core/core").hcl=c("d3\/core\/hcl");c("d3/core/core").lab=c("d3\/core\/lab");c("d3/core/core").selection=c("d3\/core\/selection");c("d3/core/core").select=c("d3\/core\/selection-root");c("d3/core/core").selectAll=c("d3\/core\/selection-root").all;c("d3/core/core").selection.enter=c("d3\/core\/selection-enter");c("d3/core/core").transition=c("d3\/core\/transition");c("d3/core/core").timer=c("d3\/core\/timer");c("d3/core/core").mouse=c("d3\/core\/mouse");c("d3/core/core").touches=c("d3\/core\/touches");f.exports=c("d3/core/core");}),null);
__d("d3/dsv/dsv",["d3/core/xhr"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(i,j){var k=new RegExp("[\""+i+"\n]"),l=i.charCodeAt(0);function m(q,r){return c("d3/core/xhr")(q,j,r).response(n);}function n(q){return m.parse(q.responseText);}m.parse=function(q){var r;return m.parseRows(q,function(s){if(r)return r(s);r=new Function("d","return {"+s.map(function(t,u){return JSON.stringify(t)+": d["+u+"]";}).join(",")+"}");});};m.parseRows=function(q,r){var s={},t={},u=[],v=q.length,w=0,x=0,y,z;function aa(){if(w>=v)return t;if(z)return z=false,s;var ca=w;if(q.charCodeAt(ca)===34){var da=ca;while(da++<v)if(q.charCodeAt(da)===34){if(q.charCodeAt(da+1)!==34)break;++da;}w=da+2;var ea=q.charCodeAt(da+1);if(ea===13){z=true;if(q.charCodeAt(da+2)===10)++w;}else if(ea===10)z=true;return q.substring(ca+1,da).replace(/""/g,"\"");}while(w<v){var ea=q.charCodeAt(w++),fa=1;if(ea===10){z=true;}else if(ea===13){z=true;if(q.charCodeAt(w)===10)++w,++fa;}else if(ea!==l)continue;return q.substring(ca,w-fa);}return q.substring(ca);}while((y=aa())!==t){var ba=[];while(y!==s&&y!==t){ba.push(y);y=aa();}if(r&&!(ba=r(ba,x++)))continue;u.push(ba);}return u;};m.format=function(q){return q.map(o).join("\n");};function o(q){return q.map(p).join(i);}function p(q){return k.test(q)?"\""+q.replace(/\"/g,"\"\"")+"\"":q;}return m;}g._dsv=h;}),null);
__d("d3/dsv/csv",["d3/dsv/dsv"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/dsv\/dsv")._dsv,i=h(",","text/csv");f.exports=i;}),null);
__d("d3/dsv/tsv",["d3/dsv/dsv"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/dsv\/dsv")._dsv,i=h("\t","text/tab-separated-values");f.exports=i;}),null);
__d("d3/d3.dsv",["d3/core/core","d3/dsv/csv","d3/dsv/tsv"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/core/core").csv=c("d3\/dsv\/csv");c("d3/core/core").tsv=c("d3\/dsv\/tsv");f.exports=c("d3/core/core");}),null);
__d("d3/geo/cartesian",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(n){var o=n[0],p=n[1],q=Math.cos(p);return [q*Math.cos(o),q*Math.sin(o),Math.sin(p)];}function i(n,o){return n[0]*o[0]+n[1]*o[1]+n[2]*o[2];}function j(n,o){return [n[1]*o[2]-n[2]*o[1],n[2]*o[0]-n[0]*o[2],n[0]*o[1]-n[1]*o[0]];}function k(n,o){n[0]+=o[0];n[1]+=o[1];n[2]+=o[2];}function l(n,o){return [n[0]*o,n[1]*o,n[2]*o];}function m(n){var o=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=o;n[1]/=o;n[2]/=o;}g._cartesian=h;g._cartesianDot=i;g._cartesianCross=j;g._cartesianAdd=k;g._cartesianScale=l;g._cartesianNormalize=m;}),null);
__d("d3/geo/spherical",["d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03b5;function i(k){return [Math.atan2(k[1],k[0]),Math.asin(Math.max(-1,Math.min(1,k[2])))];}function j(k,l){return Math.abs(k[0]-l[0])<h&&Math.abs(k[1]-l[1])<h;}g._spherical=i;g._sphericalEqual=j;}),null);
__d("d3/geo/circle",["d3/core/core","d3/geo/cartesian","d3/geo/spherical","d3/geo/rotation"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._radians,i=c("d3/core/core")._degrees,j=c("d3/core/core")._u03c0,k=c("d3\/geo\/spherical")._spherical,l=c("d3/geo/cartesian")._cartesian,m=c("d3/geo/cartesian")._cartesianNormalize,n=c("d3/core/core")._u03b5,o=function r(){var s=[0,0],t,u=6,v;function w(){var x=typeof s==="function"?s.apply(this,arguments):s,y=c("d3\/geo\/rotation")._rotation(-x[0]*h,-x[1]*h,0).invert,z=[];v(null,null,1,{point:function aa(ba,ca){z.push(ba=y(ba,ca));ba[0]*=i,ba[1]*=i;}});return {type:"Polygon",coordinates:[z]};}w.origin=function(x){if(!arguments.length)return s;s=x;return w;};w.angle=function(x){if(!arguments.length)return t;v=p((t=+x)*h,u*h);return w;};w.precision=function(x){if(!arguments.length)return u;v=p(t*h,(u=+x)*h);return w;};return w.angle(90);};function p(r,s){var t=Math.cos(r),u=Math.sin(r);return function(v,w,x,y){if(v!=null){v=q(t,v);w=q(t,w);if(x>0?v<w:v>w)v+=x*2*j;}else{v=r+x*2*j;w=r;}var z;for(var aa=x*s,ba=v;x>0?ba>w:ba<w;ba-=aa)y.point((z=k([t,-u*Math.cos(ba),-u*Math.sin(ba)]))[0],z[1]);};}function q(r,s){var t=l(s);t[0]-=r;m(t);var u=Math.acos(Math.max(-1,Math.min(1,-t[1])));return ((-t[2]<0?-u:u)+2*Math.PI-n)%(2*Math.PI);}o._circleInterpolate=p;f.exports=o;}),null);
__d("d3/core/noop",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(){}g._noop=h;}),null);
__d("d3/geo/clip",["d3/core/core","d3/core/noop","d3/core/merge"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._u03b5,i=c("d3/core/core")._u03c0,j=c("d3\/core\/noop")._noop;function k(r,s,t){return function(u){var v=s(u),w={point:x,lineStart:z,lineEnd:aa,polygonStart:function la(){w.point=ia;w.lineStart=ja;w.lineEnd=ka;ea=false;da=ca=0;ba=[];u.polygonStart();},polygonEnd:function la(){w.point=x;w.lineStart=z;w.lineEnd=aa;ba=c("d3/core/merge")(ba);if(ba.length){l(ba,t,u);}else if(ca<-h||ea&&da<-h){u.lineStart();t(null,null,1,u);u.lineEnd();}u.polygonEnd();ba=null;},sphere:function la(){u.polygonStart();u.lineStart();t(null,null,1,u);u.lineEnd();u.polygonEnd();}};function x(la,ma){if(r(la,ma))u.point(la,ma);}function y(la,ma){v.point(la,ma);}function z(){w.point=y;v.lineStart();}function aa(){w.point=x;v.lineEnd();}var ba,ca,da,ea,fa=p(),ga=s(fa),ha;function ia(la,ma){ga.point(la,ma);ha.push([la,ma]);}function ja(){ga.lineStart();ha=[];}function ka(){ia(ha[0][0],ha[0][1]);ga.lineEnd();var la=ga.clean(),ma=fa.buffer(),na,oa=ma.length;if(!oa){ea=true;da+=q(ha,-1);ha=null;return;}ha=null;if(la&1){na=ma[0];ca+=q(na,1);var oa=na.length-1,pa=-1,qa;u.lineStart();while(++pa<oa)u.point((qa=na[pa])[0],qa[1]);u.lineEnd();return;}if(oa>1&&la&2)ma.push(ma.pop().concat(ma.shift()));ba.push(ma.filter(o));}return w;};}function l(r,s,t){var u=[],v=[];r.forEach(function(ba){var ca=ba.length;if(ca<=1)return;var da=ba[0],ea=ba[ca-1],fa={point:da,points:ba,other:null,visited:false,entry:true,subject:true},ga={point:da,points:[da],other:fa,visited:false,entry:false,subject:false};fa.other=ga;u.push(fa);v.push(ga);fa={point:ea,points:[ea],other:null,visited:false,entry:false,subject:true};ga={point:ea,points:[ea],other:fa,visited:false,entry:true,subject:false};fa.other=ga;u.push(fa);v.push(ga);});v.sort(n);m(u);m(v);if(!u.length)return;var w=u[0],x,y,z;while(1){x=w;while(x.visited)if((x=x.next)===w)return;y=x.points;t.lineStart();do{x.visited=x.other.visited=true;if(x.entry){if(x.subject){for(var aa=0;aa<y.length;aa++)t.point((z=y[aa])[0],z[1]);}else s(x.point,x.next.point,1,t);x=x.next;}else{if(x.subject){y=x.prev.points;for(var aa=y.length;--aa>=0;)t.point((z=y[aa])[0],z[1]);}else s(x.point,x.prev.point,-1,t);x=x.prev;}x=x.other;y=x.points;}while(!x.visited);t.lineEnd();}}function m(r){if(!(s=r.length))return;var s,t=0,u=r[0],v;while(++t<s){u.next=v=r[t];v.prev=u;u=v;}u.next=v=r[0];v.prev=u;}function n(r,s){return ((r=r.point)[0]<0?r[1]-i/2-h:i/2-r[1])-((s=s.point)[0]<0?s[1]-i/2-h:i/2-s[1]);}function o(r){return r.length>1;}function p(){var r=[],s;return {lineStart:function t(){r.push(s=[]);},point:function t(u,v){s.push([u,v]);},lineEnd:j,buffer:function t(){var t=r;r=[];s=null;return t;}};}function q(r,s){if(!(t=r.length))return 0;var t,u=0,v=0,w=r[0],x=w[0],y=w[1],z=Math.cos(y),aa=Math.atan2(s*Math.sin(x)*z,Math.sin(y)),ba=1-s*Math.cos(x)*z,ca=aa,da,ea;while(++u<t){w=r[u];z=Math.cos(y=w[1]);da=Math.atan2(s*Math.sin(x=w[0])*z,Math.sin(y));ea=1-s*Math.cos(x)*z;if(Math.abs(ba-2)<h&&Math.abs(ea-2)<h)continue;if(!(Math.abs(ea)<h||Math.abs(ba)<h))if(Math.abs(Math.abs(da-aa)-i)<h){if(ea+ba>2)v+=4*(da-aa);}else if(Math.abs(ba-2)<h){v+=4*(da-ca);}else v+=((3*i+da-aa)%(2*i)-i)*(ba+ea);ca=aa,aa=da,ba=ea;}return v;}g._clip=k;}),null);
__d("d3/geo/clip-circle",["d3/core/core","d3/geo/spherical","d3/geo/cartesian","d3/geo/clip","d3/geo/circle"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._radians,i=c("d3\/geo\/clip")._clip,j=c("d3/geo/spherical")._sphericalEqual,k=c("d3/core/core")._u03b5,l=c("d3/geo/cartesian")._cartesian,m=c("d3/geo/cartesian")._cartesianCross,n=c("d3/geo/cartesian")._cartesianDot,o=c("d3/geo/cartesian")._cartesianScale,p=c("d3/geo/cartesian")._cartesianAdd,q=c("d3/geo/spherical")._spherical;function r(s){var t=s*h,u=Math.cos(t),v=c("d3\/geo\/circle")._circleInterpolate(t,6*h);return i(w,x,v);function w(z,aa){return Math.cos(z)*Math.cos(aa)>u;}function x(z){var aa,ba,ca,da;return {lineStart:function ea(){ca=ba=false;da=1;},point:function ea(fa,ga){var ha=[fa,ga],ia,ja=w(fa,ga);if(!aa&&(ca=ba=ja))z.lineStart();if(ja!==ba){ia=y(aa,ha);if(j(aa,ia)||j(ha,ia)){ha[0]+=k;ha[1]+=k;ja=w(ha[0],ha[1]);}}if(ja!==ba){da=0;if(ba=ja){z.lineStart();ia=y(ha,aa);z.point(ia[0],ia[1]);}else{ia=y(aa,ha);z.point(ia[0],ia[1]);z.lineEnd();}aa=ia;}if(ja&&(!aa||!j(aa,ha)))z.point(ha[0],ha[1]);aa=ha;},lineEnd:function ea(){if(ba)z.lineEnd();aa=null;},clean:function ea(){return da|(ca&&ba)<<1;}};}function y(z,aa){var ba=l(z,0),ca=l(aa,0),da=[1,0,0],ea=m(ba,ca),fa=n(ea,ea),ga=ea[0],ha=fa-ga*ga;if(!ha)return z;var ia=u*fa/ha,ja=-u*ga/ha,ka=m(da,ea),la=o(da,ia),ma=o(ea,ja);p(la,ma);var na=ka,oa=n(la,na),pa=n(na,na),qa=Math.sqrt(oa*oa-pa*(n(la,la)-1)),ra=o(na,(-oa-qa)/pa);p(ra,la);return q(ra);}}g._clipCircle=r;}),null);
__d("d3/geo/equirectangular",["d3/core/core","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03c0,i;function j(k,l){return [k,l];}(i=function k(){return c("d3\/geo\/projection")._projection(j).scale(250/h);}).raw=j.invert=j;i._equirectangular=j;f.exports=i;}),null);
__d("d3/core/true",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(){return true;}g._true=h;}),null);
__d("d3/geo/clip-antimeridian",["d3/core/core","d3/geo/clip","d3/core/true"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/clip")._clip,i=c("d3\/core\/true")._true,j=c("d3/core/core")._u03c0,k=c("d3/core/core")._u03b5,l=h(i,m,o);function m(p){var q=NaN,r=NaN,s=NaN,t;return {lineStart:function u(){p.lineStart();t=1;},point:function u(v,w){var x=v>0?j:-j,y=Math.abs(v-q);if(Math.abs(y-j)<k){p.point(q,r=(r+w)/2>0?j/2:-j/2);p.point(s,r);p.lineEnd();p.lineStart();p.point(x,r);p.point(v,r);t=0;}else if(s!==x&&y>=j){if(Math.abs(q-s)<k)q-=s*k;if(Math.abs(v-x)<k)v-=x*k;r=n(q,r,v,w);p.point(s,r);p.lineEnd();p.lineStart();p.point(x,r);t=0;}p.point(q=v,r=w);s=x;},lineEnd:function u(){p.lineEnd();q=r=NaN;},clean:function u(){return 2-t;}};}function n(p,q,r,s){var t,u,v=Math.sin(p-r);return Math.abs(v)>k?Math.atan((Math.sin(q)*(u=Math.cos(s))*Math.sin(r)-Math.sin(s)*(t=Math.cos(q))*Math.sin(p))/(t*u*v)):(q+s)/2;}function o(p,q,r,s){var t;if(p==null){t=r*j/2;s.point(-j,t);s.point(0,t);s.point(j,t);s.point(j,0);s.point(j,-t);s.point(0,-t);s.point(-j,-t);s.point(-j,0);s.point(-j,t);}else if(Math.abs(p[0]-q[0])>k){var u=(p[0]<q[0]?1:-1)*j;t=r*u/2;s.point(-u,t);s.point(0,t);s.point(u,t);}else s.point(q[0],q[1]);}g._clipAntimeridian=l;}),null);
__d("d3/geo/compose",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(i,j){function k(l,m){return l=i(l,m),j(l[0],l[1]);}if(i.invert&&j.invert)k.invert=function(l,m){return l=j.invert(l,m),l&&i.invert(l[0],l[1]);};return k;}g._compose=h;}),null);
__d("d3/geo/resample",["d3/geo/cartesian","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/cartesian")._cartesian,i=c("d3\/core\/core")._u03b5;function j(k){var l=.5,m=16;function n(p){var q,r,s,t,u,v,w={point:x,lineStart:y,lineEnd:aa,polygonStart:function ca(){p.polygonStart();w.lineStart=ba;},polygonEnd:function ca(){p.polygonEnd();w.lineStart=y;}};function x(ca,da){ca=k(ca,da);p.point(ca[0],ca[1]);}function y(){r=NaN;w.point=z;p.lineStart();}function z(ca,da){var ea=h([ca,da]),fa=k(ca,da);o(r,s,q,t,u,v,r=fa[0],s=fa[1],q=ca,t=ea[0],u=ea[1],v=ea[2],m,p);p.point(r,s);}function aa(){w.point=x;p.lineEnd();}function ba(){var ca,da,ea,fa,ga,ha,ia;y();w.point=function(ja,ka){z(ca=ja,da=ka),ea=r,fa=s,ga=t,ha=u,ia=v;w.point=z;};w.lineEnd=function(){o(r,s,q,t,u,v,ea,fa,ca,ga,ha,ia,m,p);w.lineEnd=aa;aa();};}return w;}function o(p,q,r,s,t,u,v,w,x,y,z,aa,ba,ca){var da=v-p,ea=w-q,fa=da*da+ea*ea;if(fa>4*l&&ba--){var ga=s+y,ha=t+z,ia=u+aa,ja=Math.sqrt(ga*ga+ha*ha+ia*ia),ka=Math.asin(ia/=ja),la=Math.abs(Math.abs(ia)-1)<i?(r+x)/2:Math.atan2(ha,ga),ma=k(la,ka),na=ma[0],oa=ma[1],pa=na-p,qa=oa-q,ra=ea*pa-da*qa;if(ra*ra/fa>l||Math.abs((da*pa+ea*qa)/fa-.5)>.3){o(p,q,r,s,t,u,na,oa,la,ga/=ja,ha/=ja,ia,ba,ca);ca.point(na,oa);o(na,oa,la,ga,ha,ia,v,w,x,y,z,aa,ba,ca);}}}n.precision=function(p){if(!arguments.length)return Math.sqrt(l);m=(l=p*p)>0&&16;return n;};return n;}g._resample=j;}),null);
__d("d3/geo/projection",["d3/core/core","d3/geo/resample","d3/geo/clip-antimeridian","d3/geo/compose","d3/core/rebind","d3/geo/clip-circle","d3/geo/rotation"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/resample")._resample,i=c("d3\/geo\/clip-antimeridian")._clipAntimeridian,j=c("d3/core/core")._radians,k=c("d3/core/core")._degrees,l=c("d3\/geo\/compose")._compose,m=c("d3/core/core")._u03c0,n=o;n.mutator=p;function o(r){return p(function(){return r;})();}function p(r){var s,t,u,v=h(function(la,ma){la=s(la,ma);return [la[0]*w+ea,fa-la[1]*w];}),w=150,x=480,y=250,z=0,aa=0,ba=0,ca=0,da=0,ea,fa,ga=i,ha=null;function ia(la){la=u(la[0]*j,la[1]*j);return [la[0]*w+ea,fa-la[1]*w];}function ja(la){la=u.invert((la[0]-ea)/w,(fa-la[1])/w);return la&&[la[0]*k,la[1]*k];}ia.stream=function(la){return q(t,ga(v(la)));};ia.clipAngle=function(la){if(!arguments.length)return ha;ga=la==null?(ha=la,i):c("d3\/geo\/clip-circle")._clipCircle(ha=+la);return ia;};ia.scale=function(la){if(!arguments.length)return w;w=+la;return ka();};ia.translate=function(la){if(!arguments.length)return [x,y];x=+la[0];y=+la[1];return ka();};ia.center=function(la){if(!arguments.length)return [z*k,aa*k];z=la[0]%360*j;aa=la[1]%360*j;return ka();};ia.rotate=function(la){if(!arguments.length)return [ba*k,ca*k,da*k];ba=la[0]%360*j;ca=la[1]%360*j;da=la.length>2?la[2]%360*j:0;return ka();};c("d3/core/rebind")(ia,v,"precision");function ka(){u=l(t=c("d3\/geo\/rotation")._rotation(ba,ca,da),s);var la=s(z,aa);ea=x-la[0]*w;fa=y+la[1]*w;return ia;}return function(){s=r.apply(this,arguments);ia.invert=s.invert&&ja;return ka();};}function q(r,s){return {point:function t(u,v){v=r(u*j,v*j),u=v[0];s.point(u>m?u-2*m:u<-m?u+2*m:u,v[1]);},sphere:function t(){s.sphere();},lineStart:function t(){s.lineStart();},lineEnd:function t(){s.lineEnd();},polygonStart:function t(){s.polygonStart();},polygonEnd:function t(){s.polygonEnd();}};}n._projection=o;n._projectionMutator=p;f.exports=n;}),null);
__d("d3/geo/rotation",["d3/geo/compose","d3/core/core","d3/geo/equirectangular"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/compose")._compose,i=c("d3\/core\/core")._u03c0;function j(n,o,p){return n?o||p?h(l(n),m(o,p)):l(n):o||p?m(o,p):c("d3\/geo\/equirectangular")._equirectangular;}function k(n){return function(o,p){return o+=n,[o>i?o-2*i:o<-i?o+2*i:o,p];};}function l(n){var o=k(n);o.invert=k(-n);return o;}function m(n,o){var p=Math.cos(n),q=Math.sin(n),r=Math.cos(o),s=Math.sin(o);function t(u,v){var w=Math.cos(v),x=Math.cos(u)*w,y=Math.sin(u)*w,z=Math.sin(v),aa=z*p+x*q;return [Math.atan2(y*r-aa*s,x*p-z*q),Math.asin(Math.max(-1,Math.min(1,aa*r+y*s)))];}t.invert=function(u,v){var w=Math.cos(v),x=Math.cos(u)*w,y=Math.sin(u)*w,z=Math.sin(v),aa=z*r-y*s;return [Math.atan2(y*r+z*s,x*p+aa*q),Math.asin(Math.max(-1,Math.min(1,aa*p-x*q)))];};return t;}g._rotation=j;}),null);
__d("d3/geo/albers",["d3/core/core","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._radians,i=c("d3\/geo\/projection")._projectionMutator,j=c("d3/core/core")._degrees,k;function l(m,n){var o=Math.sin(m),p=(o+Math.sin(n))/2,q=1+o*(2*p-o),r=Math.sqrt(q)/p;function s(t,u){var v=Math.sqrt(q-2*p*Math.sin(u))/p;return [v*Math.sin(t*=p),r-v*Math.cos(t)];}s.invert=function(t,u){var v=r-u;return [Math.atan2(t,v)/p,Math.asin((q-(t*t+v*v)*p*p)/(2*p))];};return s;}(k=function m(){var n=29.5*h,o=45.5*h,p=i(l),q=p(n,o);q.parallels=function(r){if(!arguments.length)return [n*j,o*j];return p(n=r[0]*h,o=r[1]*h);};return q.rotate([98,0]).center([0,38]).scale(1000);}).raw=l;f.exports=k;}),null);
__d("d3/geo/albers-usa",["d3/geo/albers"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(){var j=c("d3/geo/albers")(),k=c("d3/geo/albers")().rotate([160,0]).center([0,60]).parallels([55,65]),l=c("d3/geo/albers")().rotate([160,0]).center([0,20]).parallels([8,18]),m=c("d3/geo/albers")().rotate([60,0]).center([0,10]).parallels([8,18]);function n(p){return o(p)(p);}function o(p){var q=p[0],r=p[1];return r>50?k:q<-140?l:r<21?m:j;}n.scale=function(p){if(!arguments.length)return j.scale();j.scale(p);k.scale(p*.6);l.scale(p);m.scale(p*1.5);return n.translate(j.translate());};n.translate=function(p){if(!arguments.length)return j.translate();var q=j.scale(),r=p[0],s=p[1];j.translate(p);k.translate([r-.4*q,s+.17*q]);l.translate([r-.19*q,s+.2*q]);m.translate([r+.58*q,s+.43*q]);return n;};return n.scale(j.scale());};f.exports=h;}),null);
__d("d3/geo/stream",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function n(o,p){if(j.hasOwnProperty(o.type)){j[o.type](o,p);}else i(o,p);};function i(n,o){if(k.hasOwnProperty(n.type))k[n.type](n,o);}var j={Feature:function n(o,p){i(o.geometry,p);},FeatureCollection:function n(o,p){var q=o.features,r=-1,s=q.length;while(++r<s)i(q[r].geometry,p);}},k={Sphere:function n(o,p){p.sphere();},Point:function n(o,p){var q=o.coordinates;p.point(q[0],q[1]);},MultiPoint:function n(o,p){var q=o.coordinates,r=-1,s=q.length,t;while(++r<s)t=q[r],p.point(t[0],t[1]);},LineString:function n(o,p){l(o.coordinates,p,0);},MultiLineString:function n(o,p){var q=o.coordinates,r=-1,s=q.length;while(++r<s)l(q[r],p,0);},Polygon:function n(o,p){m(o.coordinates,p);},MultiPolygon:function n(o,p){var q=o.coordinates,r=-1,s=q.length;while(++r<s)m(q[r],p);},GeometryCollection:function n(o,p){var q=o.geometries,r=-1,s=q.length;while(++r<s)i(q[r],p);}};function l(n,o,p){var q=-1,r=n.length-p,s;o.lineStart();while(++q<r)s=n[q],o.point(s[0],s[1]);o.lineEnd();}function m(n,o){var p=-1,q=n.length;o.polygonStart();while(++p<q)l(n[p],o,1);o.polygonEnd();}f.exports=h;}),null);
__d("d3/geo/area",["d3/core/core","d3/core/noop","d3/geo/stream"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._u03c0,i=c("d3\/core\/noop")._noop,j=c("d3/core/core")._radians,k=function q(r){l=0;c("d3/geo/stream")(r,o);return l;},l,m,n,o={sphere:function q(){l+=4*h;},point:i,lineStart:i,lineEnd:i,polygonStart:function q(){m=1,n=0;o.lineStart=p;},polygonEnd:function q(){var r=2*Math.atan2(n,m);l+=r<0?4*h+r:r;o.lineStart=o.lineEnd=o.point=i;}};function p(){var q,r,s,t,u;o.point=function(w,x){o.point=v;s=(q=w)*j,t=Math.cos(x=(r=x)*j/2+h/4),u=Math.sin(x);};function v(w,x){w*=j;x=x*j/2+h/4;var y=w-s,z=Math.cos(x),aa=Math.sin(x),ba=u*aa,ca=m,da=n,ea=t*z+ba*Math.cos(y),fa=ba*Math.sin(y);m=ca*ea-da*fa;n=da*ea+ca*fa;s=w,t=z,u=aa;}o.lineEnd=function(){v(q,r);};}f.exports=k;}),null);
__d("d3/geo/azimuthal",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(i,j){function k(l,m){var n=Math.cos(l),o=Math.cos(m),p=i(n*o);return [p*o*Math.sin(l),p*Math.sin(m)];}k.invert=function(l,m){var n=Math.sqrt(l*l+m*m),o=j(n),p=Math.sin(o),q=Math.cos(o);return [Math.atan2(l*p,n*q),Math.asin(n&&m*p/n)];};return k;}g._azimuthal=h;}),null);
__d("d3/geo/azimuthal-equal-area",["d3/geo/azimuthal","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/azimuthal")._azimuthal,i=c("d3\/geo\/projection")._projection,j,k=h(function(l){return Math.sqrt(2/(1+l));},function(l){return 2*Math.asin(l/2);});(j=function l(){return i(k);}).raw=k;f.exports=j;}),null);
__d("d3/geo/azimuthal-equidistant",["d3/geo/azimuthal","d3/core/identity","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/azimuthal")._azimuthal,i=c("d3\/core\/identity")._identity,j=c("d3\/geo\/projection")._projection,k,l=h(function(m){var n=Math.acos(m);return n&&n/Math.sin(n);},i);(k=function m(){return j(l);}).raw=l;f.exports=k;}),null);
__d("d3/geo/bounds",["d3/core/identity","d3/core/noop","d3/geo/stream"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/identity")._identity,i=c("d3\/core\/noop")._noop,j=k(h);function k(l){var m,n,o,p,q={point:r,lineStart:i,lineEnd:i,polygonStart:function t(){q.lineEnd=s;},polygonEnd:function t(){q.point=r;}};function r(t,u){if(t<m)m=t;if(t>o)o=t;if(u<n)n=u;if(u>p)p=u;}function s(){q.point=q.lineEnd=i;}return function(t){p=o=-(m=n=Infinity);c("d3/geo/stream")(t,l(q));return [[m,n],[o,p]];};}j._bounds=k;f.exports=j;}),null);
__d("d3/geo/centroid",["d3/core/core","d3/geo/stream"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._u03b5,i=c("d3/core/core")._degrees,j=c("d3/core/core")._radians,k=function v(w){v._centroidDimension=m=v._centroidX=v._centroidY=v._centroidZ=0;c("d3/geo/stream")(w,q);var x;if(m&&Math.abs(x=Math.sqrt(v._centroidX*v._centroidX+v._centroidY*v._centroidY+v._centroidZ*v._centroidZ))>h)return [Math.atan2(v._centroidY,v._centroidX)*i,Math.asin(Math.max(-1,Math.min(1,v._centroidZ/x)))*i];},l,m,n,o,p,q={sphere:function v(){if(k._centroidDimension<2){k._centroidDimension=2;m=k._centroidX=k._centroidY=k._centroidZ=0;}},point:r,lineStart:t,lineEnd:u,polygonStart:function v(){if(k._centroidDimension<2){k._centroidDimension=2;m=k._centroidX=k._centroidY=k._centroidZ=0;}q.lineStart=s;},polygonEnd:function v(){q.lineStart=t;}};function r(v,w){if(k._centroidDimension)return;++m;v*=j;var x=Math.cos(w*=j);k._centroidX+=(x*Math.cos(v)-k._centroidX)/m;k._centroidY+=(x*Math.sin(v)-k._centroidY)/m;k._centroidZ+=(Math.sin(w)-k._centroidZ)/m;}function s(){var v,w;k._centroidDimension=1;t();k._centroidDimension=2;var x=q.point;q.point=function(y,z){x(v=y,w=z);};q.lineEnd=function(){q.point(v,w);u();q.lineEnd=u;};}function t(){var v,w,x;if(k._centroidDimension>1)return;if(k._centroidDimension<1){k._centroidDimension=1;m=k._centroidX=k._centroidY=k._centroidZ=0;}q.point=function(z,aa){z*=j;var ba=Math.cos(aa*=j);v=ba*Math.cos(z);w=ba*Math.sin(z);x=Math.sin(aa);q.point=y;};function y(z,aa){z*=j;var ba=Math.cos(aa*=j),ca=ba*Math.cos(z),da=ba*Math.sin(z),ea=Math.sin(aa),fa=Math.atan2(Math.sqrt((fa=w*ea-x*da)*fa+(fa=x*ca-v*ea)*fa+(fa=v*da-w*ca)*fa),v*ca+w*da+x*ea);m+=fa;k._centroidX+=fa*(v+(v=ca));k._centroidY+=fa*(w+(w=da));k._centroidZ+=fa*(x+(x=ea));}}function u(){q.point=r;}k._centroidDimension=l;k._centroidX=n;k._centroidY=o;k._centroidZ=p;f.exports=k;}),null);
__d("d3/geo/geo",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={};f.exports=h;}),null);
__d("d3/geo/gnomonic",["d3/geo/azimuthal","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/azimuthal")._azimuthal,i=c("d3\/geo\/projection")._projection,j,k=h(function(l){return 1/l;},Math.atan);(j=function l(){return i(k);}).raw=k;f.exports=j;}),null);
__d("d3/geo/graticule",["d3/core/core","d3/core/range"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03b5,i=function l(){var m,n,o,p,q=22.5,r=q,s,t,u=2.5;function v(){return {type:"MultiLineString",coordinates:w()};}function w(){return c("d3/core/range")(Math.ceil(n/q)*q,m,q).map(s).concat(c("d3/core/range")(Math.ceil(p/r)*r,o,r).map(t));}v.lines=function(){return w().map(function(x){return {type:"LineString",coordinates:x};});};v.outline=function(){return {type:"Polygon",coordinates:[s(n).concat(t(o).slice(1),s(m).reverse().slice(1),t(p).reverse().slice(1))]};};v.extent=function(x){if(!arguments.length)return [[n,p],[m,o]];n=+x[0][0],m=+x[1][0];p=+x[0][1],o=+x[1][1];if(n>m)x=n,n=m,m=x;if(p>o)x=p,p=o,o=x;return v.precision(u);};v.step=function(x){if(!arguments.length)return [q,r];q=+x[0],r=+x[1];return v;};v.precision=function(z){if(!arguments.length)return u;u=+z;s=j(p,o,u);t=k(n,m,u);return v;};return v.extent([[-180+h,-90+h],[180-h,90-h]]);};function j(l,m,n){var o=c("d3/core/range")(l,m-h,n).concat(m);return function(p){return o.map(function(q){return [p,q];});};}function k(l,m,n){var o=c("d3/core/range")(l,m-h,n).concat(m);return function(p){return o.map(function(q){return [q,p];});};}f.exports=i;}),null);
__d("d3/geo/interpolate",["d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._radians,i=function k(l,m){return j(l[0]*h,l[1]*h,m[0]*h,m[1]*h);};function j(k,l,m,n){var o=Math.cos(l),p=Math.sin(l),q=Math.cos(n),r=Math.sin(n),s=o*Math.cos(k),t=o*Math.sin(k),u=q*Math.cos(m),v=q*Math.sin(m),w=Math.acos(Math.max(-1,Math.min(1,p*r+o*q*Math.cos(m-k)))),x=1/Math.sin(w);function y(z){var aa=Math.sin(z*=w)*x,ba=Math.sin(w-z)*x,ca=ba*s+aa*u,da=ba*t+aa*v,ea=ba*p+aa*r;return [Math.atan2(da,ca)/h,Math.atan2(ea,Math.sqrt(ca*ca+da*da))/h];}y.distance=w;return y;}f.exports=i;}),null);
__d("d3/geo/greatArc",["d3/core/core","d3/geo/interpolate"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._source,i=c("d3/core/core")._target,j=c("d3/core/core")._radians,k=function l(){var m=h,n,o=i,p,q=6*j,r;function s(){var t=n||m.apply(this,arguments),u=p||o.apply(this,arguments),v=r||c("d3/geo/interpolate")(t,u),w=0,x=q/v.distance,y=[t];while((w+=x)<1)y.push(v(w));y.push(u);return {type:"LineString",coordinates:y};}s.distance=function(){return (r||c("d3/geo/interpolate")(n||m.apply(this,arguments),p||o.apply(this,arguments))).distance;};s.source=function(t){if(!arguments.length)return m;m=t,n=typeof t==="function"?null:t;r=n&&p?c("d3/geo/interpolate")(n,p):null;return s;};s.target=function(t){if(!arguments.length)return o;o=t,p=typeof t==="function"?null:t;r=n&&p?c("d3/geo/interpolate")(n,p):null;return s;};s.precision=function(t){if(!arguments.length)return q/j;q=t*j;return s;};return s;};f.exports=k;}),null);
__d("d3/geo/mercator",["d3/core/core","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03c0,i=c("d3\/geo\/projection")._projection,j;function k(l,m){return [l/(2*h),Math.max(-.5,Math.min(+.5,Math.log(Math.tan(h/4+m/2))/(2*h)))];}k.invert=function(l,m){return [2*h*l,2*Math.atan(Math.exp(2*h*m))-h/2];};(j=function l(){return i(k).scale(500);}).raw=k;f.exports=j;}),null);
__d("d3/geo/orthographic",["d3/geo/azimuthal","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/azimuthal")._azimuthal,i=c("d3\/geo\/projection")._projection,j,k=h(function(){return 1;},Math.asin);(j=function l(){return i(k);}).raw=k;f.exports=j;}),null);
__d("d3/geo/path-buffer",["d3/geo/path"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();function h(){var i=c("d3\/geo\/path")._pathCircle(4.5),j=[],k={point:l,lineStart:function q(){k.point=m;},lineEnd:o,polygonStart:function q(){k.lineEnd=p;},polygonEnd:function q(){k.lineEnd=o;k.point=l;},pointRadius:function q(r){i=c("d3\/geo\/path")._pathCircle(r);return k;},result:function q(){if(j.length){var q=j.join("");j=[];return q;}}};function l(q,r){j.push("M",q,",",r,i);}function m(q,r){j.push("M",q,",",r);k.point=n;}function n(q,r){j.push("L",q,",",r);}function o(){k.point=l;}function p(){j.push("Z");}return k;}g._pathBuffer=h;}),null);
__d("d3/geo/path-area",["d3/core/noop"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/noop")._noop,i,j,k={point:h,lineStart:h,lineEnd:h,polygonStart:function m(){j=0;k.lineStart=l;},polygonEnd:function m(){k.lineStart=k.lineEnd=k.point=h;g._pathAreaSum+=Math.abs(j/2);}};function l(){var m,n,o,p;k.point=function(r,s){k.point=q;m=o=r,n=p=s;};function q(r,s){j+=p*r-o*s;o=r,p=s;}k.lineEnd=function(){q(m,n);};}g._pathAreaSum=i;g._pathArea=k;}),null);
__d("d3/geo/path-centroid",["d3/geo/centroid"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={point:i,lineStart:j,lineEnd:k,polygonStart:function m(){h.lineStart=l;},polygonEnd:function m(){h.point=i;h.lineStart=j;h.lineEnd=k;}};function i(m,n){if(c("d3/geo/centroid")._centroidDimension)return;c("d3/geo/centroid")._centroidX+=m;c("d3/geo/centroid")._centroidY+=n;++c("d3/geo/centroid")._centroidZ;}function j(){var m,n;if(c("d3/geo/centroid")._centroidDimension!==1)if(c("d3/geo/centroid")._centroidDimension<1){c("d3/geo/centroid")._centroidDimension=1;c("d3/geo/centroid")._centroidX=c("d3/geo/centroid")._centroidY=c("d3/geo/centroid")._centroidZ=0;}else return;h.point=function(p,q){h.point=o;m=p,n=q;};function o(p,q){var r=p-m,s=q-n,t=Math.sqrt(r*r+s*s);c("d3/geo/centroid")._centroidX+=t*(m+p)/2;c("d3/geo/centroid")._centroidY+=t*(n+q)/2;c("d3/geo/centroid")._centroidZ+=t;m=p,n=q;}}function k(){h.point=i;}function l(){var m,n,o,p;if(c("d3/geo/centroid")._centroidDimension<2){c("d3/geo/centroid")._centroidDimension=2;c("d3/geo/centroid")._centroidX=c("d3/geo/centroid")._centroidY=c("d3/geo/centroid")._centroidZ=0;}h.point=function(r,s){h.point=q;m=o=r,n=p=s;};function q(r,s){var t=p*r-o*s;c("d3/geo/centroid")._centroidX+=t*(o+r);c("d3/geo/centroid")._centroidY+=t*(p+s);c("d3/geo/centroid")._centroidZ+=t*3;o=r,p=s;}h.lineEnd=function(){q(m,n);};}g._pathCentroid=h;}),null);
__d("d3/geo/path-context",["d3/core/noop","d3/core/core"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/noop")._noop,i=c("d3\/core\/core")._u03c0;function j(k){var l=4.5,m={point:n,lineStart:function s(){m.point=o;},lineEnd:q,polygonStart:function s(){m.lineEnd=r;},polygonEnd:function s(){m.lineEnd=q;m.point=n;},pointRadius:function s(t){l=t;return m;},result:h};function n(s,t){k.moveTo(s,t);k.arc(s,t,l,0,2*i);}function o(s,t){k.moveTo(s,t);m.point=p;}function p(s,t){k.lineTo(s,t);}function q(){m.point=n;}function r(){k.closePath();}return m;}g._pathContext=j;}),null);
__d("d3/geo/path",["d3/geo/path-area","d3/geo/centroid","d3/core/core","d3/geo/path-centroid","d3/geo/bounds","d3/core/identity","d3/geo/path-context","d3/geo/resample","d3/geo/stream","d3/geo/albers-usa","d3/geo/path-buffer"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/geo/path-area")._pathArea,i=c("d3\/geo\/path-centroid")._pathCentroid,j=c("d3\/geo\/bounds")._bounds,k=c("d3\/core\/identity")._identity,l=c("d3\/geo\/path-context")._pathContext,m=c("d3\/geo\/resample")._resample,n=c("d3/core/core")._degrees,o=c("d3/core/core")._radians,p=function s(){var t=4.5,u,v,w,x;function y(z){if(z)c("d3/geo/stream")(z,w(x.pointRadius(typeof t==="function"?+t.apply(this,arguments):t)));return x.result();}y.area=function(z){c("d3/geo/path-area")._pathAreaSum=0;c("d3/geo/stream")(z,w(h));return c("d3/geo/path-area")._pathAreaSum;};y.centroid=function(z){c("d3/geo/centroid")._centroidDimension=c("d3/geo/centroid")._centroidX=c("d3/geo/centroid")._centroidY=c("d3/geo/centroid")._centroidZ=0;c("d3/geo/stream")(z,w(i));return c("d3/geo/centroid")._centroidZ?[c("d3/geo/centroid")._centroidX/c("d3/geo/centroid")._centroidZ,c("d3/geo/centroid")._centroidY/c("d3/geo/centroid")._centroidZ]:undefined;};y.bounds=function(z){return j(w)(z);};y.projection=function(z){if(!arguments.length)return u;w=(u=z)?z.stream||r(z):k;return y;};y.context=function(z){if(!arguments.length)return v;x=(v=z)==null?new (c("d3\/geo\/path-buffer")._pathBuffer)():new l(z);return y;};y.pointRadius=function(z){if(!arguments.length)return t;t=typeof z==="function"?z:+z;return y;};return y.projection(c("d3/geo/albers-usa")()).context(null);};function q(s){return "m0,"+s+"a"+s+","+s+" 0 1,1 0,"+ -2*s+"a"+s+","+s+" 0 1,1 0,"+ +2*s+"z";}function r(s){var t=m(function(u,v){return s([u*n,v*n]);});return function(u){u=t(u);return {point:function v(w,x){u.point(w*o,x*o);},sphere:function v(){u.sphere();},lineStart:function v(){u.lineStart();},lineEnd:function v(){u.lineEnd();},polygonStart:function v(){u.polygonStart();},polygonEnd:function v(){u.polygonEnd();}};};}p._pathCircle=q;f.exports=p;}),null);
__d("d3/geo/stereographic",["d3/geo/azimuthal","d3/geo/projection"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geo\/azimuthal")._azimuthal,i=c("d3\/geo\/projection")._projection,j,k=h(function(l){return 1/(1+l);},function(l){return 2*Math.atan(l);});(j=function l(){return i(k);}).raw=k;f.exports=j;}),null);
__d("d3/d3.geo",["d3/geo/geo","d3/geo/stream","d3/geo/albers-usa","d3/geo/albers","d3/geo/azimuthal-equal-area","d3/geo/azimuthal-equidistant","d3/geo/bounds","d3/geo/centroid","d3/geo/circle","d3/geo/equirectangular","d3/geo/gnomonic","d3/geo/graticule","d3/geo/interpolate","d3/geo/greatArc","d3/geo/mercator","d3/geo/orthographic","d3/geo/path","d3/geo/area","d3/geo/projection","d3/geo/stereographic"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/geo/geo").stream=c("d3\/geo\/stream");c("d3/geo/geo").albersUsa=c("d3\/geo\/albers-usa");c("d3/geo/geo").albers=c("d3\/geo\/albers");c("d3/geo/geo").azimuthalEqualArea=c("d3\/geo\/azimuthal-equal-area");c("d3/geo/geo").azimuthalEquidistant=c("d3\/geo\/azimuthal-equidistant");c("d3/geo/geo").bounds=c("d3\/geo\/bounds");c("d3/geo/geo").centroid=c("d3\/geo\/centroid");c("d3/geo/geo").circle=c("d3\/geo\/circle");c("d3/geo/geo").equirectangular=c("d3\/geo\/equirectangular");c("d3/geo/geo").gnomonic=c("d3\/geo\/gnomonic");c("d3/geo/geo").graticule=c("d3\/geo\/graticule");c("d3/geo/geo").interpolate=c("d3\/geo\/interpolate");c("d3/geo/geo").greatArc=c("d3\/geo\/greatArc");c("d3/geo/geo").mercator=c("d3\/geo\/mercator");c("d3/geo/geo").orthographic=c("d3\/geo\/orthographic");c("d3/geo/geo").path=c("d3\/geo\/path");c("d3/geo/geo").area=c("d3\/geo\/area");c("d3/geo/geo").projection=c("d3\/geo\/projection");c("d3/geo/geo").projectionMutator=c("d3\/geo\/projection").mutator;c("d3/geo/geo").stereographic=c("d3\/geo\/stereographic");f.exports=c("d3/geo/geo");}),null);
__d("d3/geom/voronoi",["d3/core/core","d3/core/range"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03b5,i=function l(m){var n=m.map(function(){return [];}),o=1e+06;k(m,function(p){var q,r,s,t,u,v;if(p.a===1&&p.b>=0){q=p.ep.r;r=p.ep.l;}else{q=p.ep.l;r=p.ep.r;}if(p.a===1){u=q?q.y:-o;s=p.c-p.b*u;v=r?r.y:o;t=p.c-p.b*v;}else{s=q?q.x:-o;u=p.c-p.a*s;t=r?r.x:o;v=p.c-p.a*t;}var w=[s,u],x=[t,v];n[p.region.l.index].push(w,x);n[p.region.r.index].push(w,x);});n=n.map(function(p,q){var r=m[q][0],s=m[q][1],t=p.map(function(v){return Math.atan2(v[0]-r,v[1]-s);}),u=c("d3/core/range")(p.length).sort(function(v,w){return t[v]-t[w];});return u.filter(function(v,w){return !w||t[v]-t[u[w-1]]>h;}).map(function(v){return p[v];});});n.forEach(function(p,q){var r=p.length;if(!r)return p.push([-o,-o],[-o,o],[o,o],[o,-o]);if(r>2)return;var s=m[q],t=p[0],u=p[1],v=s[0],w=s[1],x=t[0],y=t[1],z=u[0],aa=u[1],ba=Math.abs(z-x),ca=aa-y;if(Math.abs(ca)<h){var da=w<y?-o:o;p.push([-o,da],[o,da]);}else if(ba<h){var ea=v<x?-o:o;p.push([ea,-o],[ea,o]);}else{var da=(z-x)*(y-w)<(x-v)*(aa-y)?o:-o,fa=Math.abs(ca)-ba;if(Math.abs(fa)<h){p.push([ca<0?da:-da,da]);}else{if(fa>0)da*=-1;p.push([-o,da],[o,da]);}}});return n;},j={l:"r",r:"l"};function k(l,m){var n={list:l.map(function(fa,ga){return {index:ga,x:fa[0],y:fa[1]};}).sort(function(fa,ga){return fa.y<ga.y?-1:fa.y>ga.y?1:fa.x<ga.x?-1:fa.x>ga.x?1:0;}),bottomSite:null},o={list:[],leftEnd:null,rightEnd:null,init:function fa(){o.leftEnd=o.createHalfEdge(null,"l");o.rightEnd=o.createHalfEdge(null,"l");o.leftEnd.r=o.rightEnd;o.rightEnd.l=o.leftEnd;o.list.unshift(o.leftEnd,o.rightEnd);},createHalfEdge:function fa(ga,ha){return {edge:ga,side:ha,vertex:null,l:null,r:null};},insert:function fa(ga,ha){ha.l=ga;ha.r=ga.r;ga.r.l=ha;ga.r=ha;},leftBound:function fa(ga){var ha=o.leftEnd;do{ha=ha.r;}while(ha!=o.rightEnd&&p.rightOf(ha,ga));ha=ha.l;return ha;},del:function fa(ga){ga.l.r=ga.r;ga.r.l=ga.l;ga.edge=null;},right:function fa(ga){return ga.r;},left:function fa(ga){return ga.l;},leftRegion:function fa(ga){return ga.edge==null?n.bottomSite:ga.edge.region[ga.side];},rightRegion:function fa(ga){return ga.edge==null?n.bottomSite:ga.edge.region[j[ga.side]];}},p={bisect:function fa(ga,ha){var ia={region:{l:ga,r:ha},ep:{l:null,r:null}},ja=ha.x-ga.x,ka=ha.y-ga.y,la=ja>0?ja:-ja,ma=ka>0?ka:-ka;ia.c=ga.x*ja+ga.y*ka+(ja*ja+ka*ka)*.5;if(la>ma){ia.a=1;ia.b=ka/ja;ia.c/=ja;}else{ia.b=1;ia.a=ja/ka;ia.c/=ka;}return ia;},intersect:function fa(ga,ha){var ia=ga.edge,ja=ha.edge;if(!ia||!ja||ia.region.r==ja.region.r)return null;var ka=ia.a*ja.b-ia.b*ja.a;if(Math.abs(ka)<1e-10)return null;var la=(ia.c*ja.b-ja.c*ia.b)/ka,ma=(ja.c*ia.a-ia.c*ja.a)/ka,na=ia.region.r,oa=ja.region.r,pa,qa;if(na.y<oa.y||na.y==oa.y&&na.x<oa.x){pa=ga;qa=ia;}else{pa=ha;qa=ja;}var ra=la>=qa.region.r.x;if(ra&&pa.side==="l"||!ra&&pa.side==="r")return null;return {x:la,y:ma};},rightOf:function fa(ga,ha){var ia=ga.edge,ja=ia.region.r,ka=ha.x>ja.x;if(ka&&ga.side==="l")return 1;if(!ka&&ga.side==="r")return 0;if(ia.a===1){var la=ha.y-ja.y,ma=ha.x-ja.x,na=0,oa=0;if(!ka&&ia.b<0||ka&&ia.b>=0){oa=na=la>=ia.b*ma;}else{oa=ha.x+ha.y*ia.b>ia.c;if(ia.b<0)oa=!oa;if(!oa)na=1;}if(!na){var pa=ja.x-ia.region.l.x;oa=ia.b*(ma*ma-la*la)<pa*la*(1+2*ma/pa+ia.b*ia.b);if(ia.b<0)oa=!oa;}}else{var qa=ia.c-ia.a*ha.x,ra=ha.y-qa,sa=ha.x-ja.x,ta=qa-ja.y;oa=ra*ra>sa*sa+ta*ta;}return ga.side==="l"?oa:!oa;},endPoint:function fa(ga,ha,ia){ga.ep[ha]=ia;if(!ga.ep[j[ha]])return;m(ga);},distance:function fa(ga,ha){var ia=ga.x-ha.x,ja=ga.y-ha.y;return Math.sqrt(ia*ia+ja*ja);}},q={list:[],insert:function fa(ga,ha,ia){ga.vertex=ha;ga.ystar=ha.y+ia;for(var ja=0,ka=q.list,la=ka.length;ja<la;ja++){var ma=ka[ja];if(ga.ystar>ma.ystar||ga.ystar==ma.ystar&&ha.x>ma.vertex.x){continue;}else break;}ka.splice(ja,0,ga);},del:function fa(ga){for(var ha=0,ia=q.list,ja=ia.length;ha<ja&&ia[ha]!=ga;++ha);ia.splice(ha,1);},empty:function fa(){return q.list.length===0;},nextEvent:function fa(ga){for(var ha=0,ia=q.list,ja=ia.length;ha<ja;++ha)if(ia[ha]==ga)return ia[ha+1];return null;},min:function fa(){var ga=q.list[0];return {x:ga.vertex.x,y:ga.ystar};},extractMin:function fa(){return q.list.shift();}};o.init();n.bottomSite=n.list.shift();var r=n.list.shift(),s,t,u,v,w,x,y,z,aa,ba,ca,da,ea;while(true){if(!q.empty())s=q.min();if(r&&(q.empty()||r.y<s.y||r.y==s.y&&r.x<s.x)){t=o.leftBound(r);u=o.right(t);y=o.rightRegion(t);da=p.bisect(y,r);x=o.createHalfEdge(da,"l");o.insert(t,x);ba=p.intersect(t,x);if(ba){q.del(t);q.insert(t,ba,p.distance(ba,r));}t=x;x=o.createHalfEdge(da,"r");o.insert(t,x);ba=p.intersect(x,u);if(ba)q.insert(x,ba,p.distance(ba,r));r=n.list.shift();}else if(!q.empty()){t=q.extractMin();v=o.left(t);u=o.right(t);w=o.right(u);y=o.leftRegion(t);z=o.rightRegion(u);ca=t.vertex;p.endPoint(t.edge,t.side,ca);p.endPoint(u.edge,u.side,ca);o.del(t);q.del(u);o.del(u);ea="l";if(y.y>z.y){aa=y;y=z;z=aa;ea="r";}da=p.bisect(y,z);x=o.createHalfEdge(da,ea);o.insert(v,x);p.endPoint(da,j[ea],ca);ba=p.intersect(v,x);if(ba){q.del(v);q.insert(v,ba,p.distance(ba,y));}ba=p.intersect(x,w);if(ba)q.insert(x,ba,p.distance(ba,y));}else break;}for(t=o.right(o.leftEnd);t!=o.rightEnd;t=o.right(t))m(t.edge);}i._tessellate=k;f.exports=i;}),null);
__d("d3/geom/delaunay",["d3/geom/voronoi"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/geom\/voronoi")._tessellate,i=function j(k){var l=k.map(function(){return [];}),m=[];h(k,function(n){l[n.region.l.index].push(k[n.region.r.index]);});l.forEach(function(n,o){var p=k[o],q=p[0],r=p[1];n.forEach(function(u){u.angle=Math.atan2(u[0]-q,u[1]-r);});n.sort(function(u,v){return u.angle-v.angle;});for(var s=0,t=n.length-1;s<t;s++)m.push([p,n[s],n[s+1]]);});return m;};f.exports=i;}),null);
__d("d3/geom/geom",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={};f.exports=h;}),null);
__d("d3/geom/hull",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(k){if(k.length<3)return [];var l=k.length,m=l-1,n=[],o=[],p,q,r=0,s,t,u,v,w,x,y,z;for(p=1;p<l;++p)if(k[p][1]<k[r][1]){r=p;}else if(k[p][1]==k[r][1])r=k[p][0]<k[r][0]?p:r;for(p=0;p<l;++p){if(p===r)continue;t=k[p][1]-k[r][1];s=k[p][0]-k[r][0];n.push({angle:Math.atan2(t,s),index:p});}n.sort(function(ba,ca){return ba.angle-ca.angle;});y=n[0].angle;x=n[0].index;w=0;for(p=1;p<m;++p){q=n[p].index;if(y==n[p].angle){s=k[x][0]-k[r][0];t=k[x][1]-k[r][1];u=k[q][0]-k[r][0];v=k[q][1]-k[r][1];if(s*s+t*t>=u*u+v*v){n[p].index=-1;}else{n[w].index=-1;y=n[p].angle;w=p;x=q;}}else{y=n[p].angle;w=p;x=q;}}o.push(r);for(p=0,q=0;p<2;++q)if(n[q].index!==-1){o.push(n[q].index);p++;}z=o.length;for(;q<m;++q){if(n[q].index===-1)continue;while(!i(o[z-2],o[z-1],n[q].index,k))--z;o[z++]=n[q].index;}var aa=[];for(p=0;p<z;++p)aa.push(k[o[p]]);return aa;};function i(j,k,l,m){var n,o,p,q,r,s,t;n=m[j];o=n[0];p=n[1];n=m[k];q=n[0];r=n[1];n=m[l];s=n[0];t=n[1];return (t-p)*(q-o)-(r-p)*(s-o)>0;}f.exports=h;}),null);
__d("d3/geom/polygon",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function k(l){l.area=function(){var m=0,n=l.length,o=l[n-1][1]*l[0][0]-l[n-1][0]*l[0][1];while(++m<n)o+=l[m-1][1]*l[m][0]-l[m-1][0]*l[m][1];return o*.5;};l.centroid=function(m){var n=-1,o=l.length,p=0,q=0,r,s=l[o-1],t;if(!arguments.length)m=-1/(6*l.area());while(++n<o){r=s;s=l[n];t=r[0]*s[1]-s[0]*r[1];p+=(r[0]+s[0])*t;q+=(r[1]+s[1])*t;}return [p*m,q*m];};l.clip=function(m){var n,o=-1,p=l.length,q,r,s=l[p-1],t,u,v;while(++o<p){n=m.slice();m.length=0;t=l[o];u=n[(r=n.length)-1];q=-1;while(++q<r){v=n[q];if(i(v,s,t)){if(!i(u,s,t))m.push(j(u,v,s,t));m.push(v);}else if(i(u,s,t))m.push(j(u,v,s,t));u=v;}s=t;}return m;};return l;};function i(k,l,m){return (m[0]-l[0])*(k[1]-l[1])<(m[1]-l[1])*(k[0]-l[0]);}function j(k,l,m,n){var o=k[0],p=m[0],q=l[0]-o,r=n[0]-p,s=k[1],t=m[1],u=l[1]-s,v=n[1]-t,w=(r*(s-t)-v*(o-p))/(v*q-r*u);return [o+w*q,s+w*u];}f.exports=h;}),null);
__d("d3/geom/quadtree",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function k(l,m,n,o,p){var q,r=-1,s=l.length;if(arguments.length<5)if(arguments.length===3){p=n;o=m;n=m=0;}else{m=n=Infinity;o=p=-Infinity;while(++r<s){q=l[r];if(q.x<m)m=q.x;if(q.y<n)n=q.y;if(q.x>o)o=q.x;if(q.y>p)p=q.y;}}var t=o-m,u=p-n;if(t>u){p=n+t;}else o=m+u;function v(y,z,aa,ba,ca,da){if(isNaN(z.x)||isNaN(z.y))return;if(y.leaf){var ea=y.point;if(ea){if(Math.abs(ea.x-z.x)+Math.abs(ea.y-z.y)<.01){w(y,z,aa,ba,ca,da);}else{y.point=null;w(y,ea,aa,ba,ca,da);w(y,z,aa,ba,ca,da);}}else y.point=z;}else w(y,z,aa,ba,ca,da);}function w(y,z,aa,ba,ca,da){var ea=(aa+ca)*.5,fa=(ba+da)*.5,ga=z.x>=ea,ha=z.y>=fa,ia=(ha<<1)+ga;y.leaf=false;y=y.nodes[ia]||(y.nodes[ia]=i());if(ga){aa=ea;}else ca=ea;if(ha){ba=fa;}else da=fa;v(y,z,aa,ba,ca,da);}var x=i();x.add=function(y){v(x,y,m,n,o,p);};x.visit=function(y){j(y,x,m,n,o,p);};l.forEach(x.add);return x;};function i(){return {leaf:true,nodes:[],point:null};}function j(k,l,m,n,o,p){if(!k(l,m,n,o,p)){var q=(m+o)*.5,r=(n+p)*.5,s=l.nodes;if(s[0])j(k,s[0],m,n,q,r);if(s[1])j(k,s[1],q,n,o,r);if(s[2])j(k,s[2],m,r,q,p);if(s[3])j(k,s[3],q,r,o,p);}}f.exports=h;}),null);
__d("d3/d3.geom",["d3/geom/geom","d3/geom/hull","d3/geom/polygon","d3/geom/voronoi","d3/geom/delaunay","d3/geom/quadtree"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/geom/geom").hull=c("d3\/geom\/hull");c("d3/geom/geom").polygon=c("d3\/geom\/polygon");c("d3/geom/geom").voronoi=c("d3\/geom\/voronoi");c("d3/geom/geom").delaunay=c("d3\/geom\/delaunay");c("d3/geom/geom").quadtree=c("d3\/geom\/quadtree");f.exports=c("d3/geom/geom");}),null);
__d("d3/layout/bundle",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function l(){return function(m){var n=[],o=-1,p=m.length;while(++o<p)n.push(i(m[o]));return n;};};function i(l){var m=l.source,n=l.target,o=k(m,n),p=[m];while(m!==o){m=m.parent;p.push(m);}var q=p.length;while(n!==o){p.splice(q,0,n);n=n.parent;}return p;}function j(l){var m=[],n=l.parent;while(n!=null){m.push(l);l=n;n=n.parent;}m.push(l);return m;}function k(l,m){if(l===m)return l;var n=j(l),o=j(m),p=n.pop(),q=o.pop(),r=null;while(p===q){r=p;p=n.pop();q=o.pop();}return r;}f.exports=h;}),null);
__d("d3/layout/chord",["d3/core/core","d3/core/range"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03c0,i=function j(){var k={},l,m,n,o,p=0,q,r,s;function t(){var v={},w=[],x=c("d3/core/range")(o),y=[],z,aa,ba,ca,da;l=[];m=[];z=0,ca=-1;while(++ca<o){aa=0,da=-1;while(++da<o)aa+=n[ca][da];w.push(aa);y.push(c("d3/core/range")(o));z+=aa;}if(q)x.sort(function(la,ma){return q(w[la],w[ma]);});if(r)y.forEach(function(la,ma){la.sort(function(na,oa){return r(n[ma][na],n[ma][oa]);});});z=(2*h-p*o)/z;aa=0,ca=-1;while(++ca<o){ba=aa,da=-1;while(++da<o){var ea=x[ca],fa=y[ea][da],ga=n[ea][fa],ha=aa,ia=aa+=ga*z;v[ea+"-"+fa]={index:ea,subindex:fa,startAngle:ha,endAngle:ia,value:ga};}m[ea]={index:ea,startAngle:ba,endAngle:aa,value:(aa-ba)/z};aa+=p;}ca=-1;while(++ca<o){da=ca-1;while(++da<o){var ja=v[ca+"-"+da],ka=v[da+"-"+ca];if(ja.value||ka.value)l.push(ja.value<ka.value?{source:ka,target:ja}:{source:ja,target:ka});}}if(s)u();}function u(){l.sort(function(v,w){return s((v.source.value+v.target.value)/2,(w.source.value+w.target.value)/2);});}k.matrix=function(v){if(!arguments.length)return n;o=(n=v)&&n.length;l=m=null;return k;};k.padding=function(v){if(!arguments.length)return p;p=v;l=m=null;return k;};k.sortGroups=function(v){if(!arguments.length)return q;q=v;l=m=null;return k;};k.sortSubgroups=function(v){if(!arguments.length)return r;r=v;l=null;return k;};k.sortChords=function(v){if(!arguments.length)return s;s=v;if(l)u();return k;};k.chords=function(){if(!l)t();return l;};k.groups=function(){if(!m)t();return m;};return k;};f.exports=i;}),null);
__d("d3/layout/hierarchy",["d3/core/rebind","d3/core/merge"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function n(){var o=l,p=j,q=k;function r(u,v,w){var x=p.call(t,u,v);u.depth=v;w.push(u);if(x&&(z=x.length)){var y=-1,z,aa=u.children=[],ba=0,ca=v+1,da;while(++y<z){da=r(x[y],ca,w);da.parent=u;aa.push(da);ba+=da.value;}if(o)aa.sort(o);if(q)u.value=ba;}else if(q)u.value=+q.call(t,u,v)||0;return u;}function s(u,v){var w=u.children,x=0;if(w&&(z=w.length)){var y=-1,z,aa=v+1;while(++y<z)x+=s(w[y],aa);}else if(q)x=+q.call(t,u,v)||0;if(q)u.value=x;return x;}function t(u){var v=[];r(u,0,v);return v;}t.sort=function(u){if(!arguments.length)return o;o=u;return t;};t.children=function(u){if(!arguments.length)return p;p=u;return t;};t.value=function(u){if(!arguments.length)return q;q=u;return t;};t.revalue=function(u){s(u,0);return u;};return t;};function i(n,o){c("d3/core/rebind")(n,o,"sort","children","value");n.nodes=n;n.links=m;return n;}function j(n){return n.children;}function k(n){return n.value;}function l(n,o){return o.value-n.value;}function m(n){return c("d3/core/merge")(n.map(function(o){return (o.children||[]).map(function(p){return {source:o,target:p};});}));}h._hierarchyRebind=i;f.exports=h;}),null);
__d("d3/layout/tree",["d3/layout/hierarchy"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/layout/hierarchy")._hierarchyRebind,i=function u(){var v=c("d3/layout/hierarchy")().sort(null).value(null),w=j,x=[1,1];function y(z,aa){var ba=v.call(this,z,aa),ca=ba[0];function da(ma,na){var oa=ma.children,pa=ma._tree;if(oa&&(qa=oa.length)){var qa,ra=oa[0],sa,ta=ra,ua,va=-1;while(++va<qa){ua=oa[va];da(ua,sa);ta=fa(ua,sa,ta);sa=ua;}r(ma);var wa=.5*(ra._tree.prelim+ua._tree.prelim);if(na){pa.prelim=na._tree.prelim+w(ma,na);pa.mod=pa.prelim-wa;}else pa.prelim=wa;}else if(na)pa.prelim=na._tree.prelim+w(ma,na);}function ea(ma,na){ma.x=ma._tree.prelim+na;var oa=ma.children;if(oa&&(qa=oa.length)){var pa=-1,qa;na+=ma._tree.mod;while(++pa<qa)ea(oa[pa],na);}}function fa(ma,na,oa){if(na){var pa=ma,qa=ma,ra=na,sa=ma.parent.children[0],ta=pa._tree.mod,ua=qa._tree.mod,va=ra._tree.mod,wa=sa._tree.mod,xa;while(ra=l(ra),pa=k(pa),ra&&pa){sa=k(sa);qa=l(qa);qa._tree.ancestor=ma;xa=ra._tree.prelim+va-pa._tree.prelim-ta+w(ra,pa);if(xa>0){s(t(ra,ma,oa),ma,xa);ta+=xa;ua+=xa;}va+=ra._tree.mod;ta+=pa._tree.mod;wa+=sa._tree.mod;ua+=qa._tree.mod;}if(ra&&!l(qa)){qa._tree.thread=ra;qa._tree.mod+=va-ua;}if(pa&&!k(sa)){sa._tree.thread=pa;sa._tree.mod+=ta-wa;oa=ma;}}return oa;}q(ca,function(ma,na){ma._tree={ancestor:ma,prelim:0,mod:0,change:0,shift:0,number:na?na._tree.number+1:0};});da(ca);ea(ca,-ca._tree.prelim);var ga=m(ca,o),ha=m(ca,n),ia=m(ca,p),ja=ga.x-w(ga,ha)/2,ka=ha.x+w(ha,ga)/2,la=ia.depth||1;q(ca,function(ma){ma.x=(ma.x-ja)/(ka-ja)*x[0];ma.y=ma.depth/la*x[1];delete ma._tree;});return ba;}y.separation=function(z){if(!arguments.length)return w;w=z;return y;};y.size=function(z){if(!arguments.length)return x;x=z;return y;};return h(y,v);};function j(u,v){return u.parent==v.parent?1:2;}function k(u){var v=u.children;return v&&v.length?v[0]:u._tree.thread;}function l(u){var v=u.children,w;return v&&(w=v.length)?v[w-1]:u._tree.thread;}function m(u,v){var w=u.children;if(w&&(y=w.length)){var x,y,z=-1;while(++z<y)if(v(x=m(w[z],v),u)>0)u=x;}return u;}function n(u,v){return u.x-v.x;}function o(u,v){return v.x-u.x;}function p(u,v){return u.depth-v.depth;}function q(u,v){function w(x,y){var z=x.children;if(z&&(da=z.length)){var aa,ba=null,ca=-1,da;while(++ca<da){aa=z[ca];w(aa,ba);ba=aa;}}v(x,y);}w(u,null);}function r(u){var v=0,w=0,x=u.children,y=x.length,z;while(--y>=0){z=x[y]._tree;z.prelim+=v;z.mod+=v;v+=z.shift+(w+=z.change);}}function s(u,v,w){u=u._tree;v=v._tree;var x=w/(v.number-u.number);u.change+=x;v.change-=x;v.shift+=w;v.prelim+=w;v.mod+=w;}function t(u,v,w){return u._tree.ancestor.parent==v.parent?u._tree.ancestor:w;}i._treeSeparation=j;i._treeVisitAfter=q;f.exports=i;}),null);
__d("d3/layout/cluster",["d3/layout/tree","d3/layout/hierarchy","d3/core/max"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/layout/tree")._treeSeparation,i=c("d3/layout/tree")._treeVisitAfter,j=c("d3/layout/hierarchy")._hierarchyRebind,k=function p(){var q=c("d3/layout/hierarchy")().sort(null).value(null),r=h,s=[1,1];function t(u,v){var w=q.call(this,u,v),x=w[0],y,z=0;i(x,function(ea){var fa=ea.children;if(fa&&fa.length){ea.x=m(fa);ea.y=l(fa);}else{ea.x=y?z+=r(ea,y):0;ea.y=0;y=ea;}});var aa=n(x),ba=o(x),ca=aa.x-r(aa,ba)/2,da=ba.x+r(ba,aa)/2;i(x,function(ea){ea.x=(ea.x-ca)/(da-ca)*s[0];ea.y=(1-(x.y?ea.y/x.y:1))*s[1];});return w;}t.separation=function(u){if(!arguments.length)return r;r=u;return t;};t.size=function(u){if(!arguments.length)return s;s=u;return t;};return j(t,q);};function l(p){return 1+c("d3/core/max")(p,function(q){return q.y;});}function m(p){return p.reduce(function(q,r){return q+r.x;},0)/p.length;}function n(p){var q=p.children;return q&&q.length?n(q[0]):p;}function o(p){var q=p.children,r;return q&&(r=q.length)?o(q[r-1]):p;}f.exports=k;}),null);
__d("d3/layout/force",["d3/core/identity","d3/core/dispatch","d3/geom/quadtree","d3/core/timer","d3/behavior/drag","d3/core/core","d3/core/rebind"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/identity")._identity,i=function q(){var r={},event=c("d3/core/dispatch")("start","tick","end"),s=[1,1],t,u,v=.9,w=o,x=p,y=-30,z=.1,aa=.8,ba=[],ca=[],da,ea,fa;function ga(ia){return function(ja,ka,la,ma){if(ja.point!==ia){var na=ja.cx-ia.x,oa=ja.cy-ia.y,pa=1/Math.sqrt(na*na+oa*oa);if((ma-ka)*pa<aa){var qa=ja.charge*pa*pa;ia.px-=na*qa;ia.py-=oa*qa;return true;}if(ja.point&&isFinite(pa)){var qa=ja.pointCharge*pa*pa;ia.px-=na*qa;ia.py-=oa*qa;}}return !ja.charge;};}r.tick=function(){if((u*=.99)<.005){event.end({type:"end",alpha:u=0});return true;}var ia=ba.length,ja=ca.length,ka,la,ma,na,oa,pa,qa,ra,sa;for(la=0;la<ja;++la){ma=ca[la];na=ma.source;oa=ma.target;ra=oa.x-na.x;sa=oa.y-na.y;if(pa=ra*ra+sa*sa){pa=u*ea[la]*((pa=Math.sqrt(pa))-da[la])/pa;ra*=pa;sa*=pa;oa.x-=ra*(qa=na.weight/(oa.weight+na.weight));oa.y-=sa*qa;na.x+=ra*(qa=1-qa);na.y+=sa*qa;}}if(qa=u*z){ra=s[0]/2;sa=s[1]/2;la=-1;if(qa)while(++la<ia){ma=ba[la];ma.x+=(ra-ma.x)*qa;ma.y+=(sa-ma.y)*qa;}}if(y){n(ka=c("d3/geom/quadtree")(ba),u,fa);la=-1;while(++la<ia)if(!(ma=ba[la]).fixed)ka.visit(ga(ma));}la=-1;while(++la<ia){ma=ba[la];if(ma.fixed){ma.x=ma.px;ma.y=ma.py;}else{ma.x-=(ma.px-(ma.px=ma.x))*v;ma.y-=(ma.py-(ma.py=ma.y))*v;}}event.tick({type:"tick",alpha:u});};r.nodes=function(ia){if(!arguments.length)return ba;ba=ia;return r;};r.links=function(ia){if(!arguments.length)return ca;ca=ia;return r;};r.size=function(ia){if(!arguments.length)return s;s=ia;return r;};r.linkDistance=function(ia){if(!arguments.length)return w;w=typeof ia==="function"?ia:+ia;return r;};r.distance=r.linkDistance;r.linkStrength=function(ia){if(!arguments.length)return x;x=typeof ia==="function"?ia:+ia;return r;};r.friction=function(ia){if(!arguments.length)return v;v=+ia;return r;};r.charge=function(ia){if(!arguments.length)return y;y=typeof ia==="function"?ia:+ia;return r;};r.gravity=function(ia){if(!arguments.length)return z;z=+ia;return r;};r.theta=function(ia){if(!arguments.length)return aa;aa=+ia;return r;};r.alpha=function(ia){if(!arguments.length)return u;ia=+ia;if(u){if(ia>0){u=ia;}else u=0;}else if(ia>0){event.start({type:"start",alpha:u=ia});c("d3/core/timer")(r.tick);}return r;};r.start=function(){var ia,ja,ka=ba.length,la=ca.length,ma=s[0],na=s[1],oa,pa;for(ia=0;ia<ka;++ia){(pa=ba[ia]).index=ia;pa.weight=0;}for(ia=0;ia<la;++ia){pa=ca[ia];if(typeof pa.source=="number")pa.source=ba[pa.source];if(typeof pa.target=="number")pa.target=ba[pa.target];++pa.source.weight;++pa.target.weight;}for(ia=0;ia<ka;++ia){pa=ba[ia];if(isNaN(pa.x))pa.x=qa("x",ma);if(isNaN(pa.y))pa.y=qa("y",na);if(isNaN(pa.px))pa.px=pa.x;if(isNaN(pa.py))pa.py=pa.y;}da=[];if(typeof w==="function"){for(ia=0;ia<la;++ia)da[ia]=+w.call(this,ca[ia],ia);}else for(ia=0;ia<la;++ia)da[ia]=w;ea=[];if(typeof x==="function"){for(ia=0;ia<la;++ia)ea[ia]=+x.call(this,ca[ia],ia);}else for(ia=0;ia<la;++ia)ea[ia]=x;fa=[];if(typeof y==="function"){for(ia=0;ia<ka;++ia)fa[ia]=+y.call(this,ba[ia],ia);}else for(ia=0;ia<ka;++ia)fa[ia]=y;function qa(sa,ta){var ua=ra(ia),va=-1,wa=ua.length,xa;while(++va<wa)if(!isNaN(xa=ua[va][sa]))return xa;return Math.random()*ta;}function ra(){if(!oa){oa=[];for(ja=0;ja<ka;++ja)oa[ja]=[];for(ja=0;ja<la;++ja){var sa=ca[ja];oa[sa.source.index].push(sa.target);oa[sa.target.index].push(sa.source);}}return oa[ia];}return r.resume();};r.resume=function(){return r.alpha(.1);};r.stop=function(){return r.alpha(0);};r.drag=function(){if(!t)t=c("d3/behavior/drag")().origin(h).on("dragstart.force",j).on("drag.force",ha).on("dragend.force",k);if(!arguments.length)return t;this.on("mouseover.force",l).on("mouseout.force",m).call(t);};function ha(ia){ia.px=c("d3/core/core").event.x,ia.py=c("d3/core/core").event.y;r.resume();}return c("d3/core/rebind")(r,event,"on");};function j(q){q.fixed|=2;}function k(q){q.fixed&=~6;}function l(q){q.fixed|=4;q.px=q.x,q.py=q.y;}function m(q){q.fixed&=~4;}function n(q,r,s){var t=0,u=0;q.charge=0;if(!q.leaf){var v=q.nodes,w=v.length,x=-1,y;while(++x<w){y=v[x];if(y==null)continue;n(y,r,s);q.charge+=y.charge;t+=y.charge*y.cx;u+=y.charge*y.cy;}}if(q.point){if(!q.leaf){q.point.x+=Math.random()-.5;q.point.y+=Math.random()-.5;}var z=r*s[q.point.index];q.charge+=q.pointCharge=z;t+=z*q.point.x;u+=z*q.point.y;}q.cx=t/q.charge;q.cy=u/q.charge;}var o=20,p=1;f.exports=i;}),null);
__d("d3/layout/histogram",["d3/core/functor","d3/core/bisect","d3/core/min","d3/core/max"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/functor")._functor,i=function m(){var n=true,o=Number,p=l,q=j;function r(s,t){var u=[],v=s.map(o,this),w=p.call(this,v,t),x=q.call(this,w,v,t),y,t=-1,z=v.length,aa=x.length-1,ba=n?1:1/z,ca;while(++t<aa){y=u[t]=[];y.dx=x[t+1]-(y.x=x[t]);y.y=0;}if(aa>0){t=-1;while(++t<z){ca=v[t];if(ca>=w[0]&&ca<=w[1]){y=u[c("d3/core/bisect")(x,ca,1,aa)-1];y.y+=ba;y.push(s[t]);}}}return u;}r.value=function(s){if(!arguments.length)return o;o=s;return r;};r.range=function(s){if(!arguments.length)return p;p=h(s);return r;};r.bins=function(s){if(!arguments.length)return q;q=typeof s==="number"?function(t){return k(t,s);}:h(s);return r;};r.frequency=function(s){if(!arguments.length)return n;n=!!s;return r;};return r;};function j(m,n){return k(m,Math.ceil(Math.log(n.length)/Math.LN2+1));}function k(m,n){var o=-1,p=+m[0],q=(m[1]-p)/n,r=[];while(++o<=n)r[o]=q*o+p;return r;}function l(m){return [c("d3/core/min")(m),c("d3/core/max")(m)];}f.exports=i;}),null);
__d("d3/layout/layout",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={};f.exports=h;}),null);
__d("d3/layout/pack",["d3/layout/hierarchy","d3/layout/tree"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/layout\/tree")._treeVisitAfter,i=c("d3/layout/hierarchy")._hierarchyRebind,j=function t(){var u=c("d3/layout/hierarchy")().sort(k),v=0,w=[1,1];function x(y,z){var aa=u.call(this,y,z),ba=aa[0];ba.x=0;ba.y=0;h(ba,function(ga){ga.r=Math.sqrt(ga.value);});h(ba,o);var ca=w[0],da=w[1],ea=Math.max(2*ba.r/ca,2*ba.r/da);if(v>0){var fa=v*ea/2;h(ba,function(ga){ga.r+=fa;});h(ba,o);h(ba,function(ga){ga.r-=fa;});ea=Math.max(2*ba.r/ca,2*ba.r/da);}r(ba,ca/2,da/2,1/ea);return aa;}x.size=function(y){if(!arguments.length)return w;w=y;return x;};x.padding=function(y){if(!arguments.length)return v;v=+y;return x;};return i(x,u);};function k(t,u){return t.value-u.value;}function l(t,u){var v=t._pack_next;t._pack_next=u;u._pack_prev=t;u._pack_next=v;v._pack_prev=u;}function m(t,u){t._pack_next=u;u._pack_prev=t;}function n(t,u){var v=u.x-t.x,w=u.y-t.y,x=t.r+u.r;return x*x-v*v-w*w>.001;}function o(t){if(!(u=t.children)||!(fa=u.length))return;var u,v=Infinity,w=-Infinity,x=Infinity,y=-Infinity,z,aa,ba,ca,da,ea,fa;function ga(na){v=Math.min(na.x-na.r,v);w=Math.max(na.x+na.r,w);x=Math.min(na.y-na.r,x);y=Math.max(na.y+na.r,y);}u.forEach(p);z=u[0];z.x=-z.r;z.y=0;ga(z);if(fa>1){aa=u[1];aa.x=aa.r;aa.y=0;ga(aa);if(fa>2){ba=u[2];s(z,aa,ba);ga(ba);l(z,ba);z._pack_prev=ba;l(ba,aa);aa=z._pack_next;for(ca=3;ca<fa;ca++){s(z,aa,ba=u[ca]);var ha=0,ia=1,ja=1;for(da=aa._pack_next;da!==aa;da=da._pack_next,ia++)if(n(da,ba)){ha=1;break;}if(ha==1)for(ea=z._pack_prev;ea!==da._pack_prev;ea=ea._pack_prev,ja++)if(n(ea,ba))break;if(ha){if(ia<ja||ia==ja&&aa.r<z.r){m(z,aa=da);}else m(z=ea,aa);ca--;}else{l(z,ba);aa=ba;ga(ba);}}}}var ka=(v+w)/2,la=(x+y)/2,ma=0;for(ca=0;ca<fa;ca++){ba=u[ca];ba.x-=ka;ba.y-=la;ma=Math.max(ma,ba.r+Math.sqrt(ba.x*ba.x+ba.y*ba.y));}t.r=ma;u.forEach(q);}function p(t){t._pack_next=t._pack_prev=t;}function q(t){delete t._pack_next;delete t._pack_prev;}function r(t,u,v,w){var x=t.children;t.x=u+=w*t.x;t.y=v+=w*t.y;t.r*=w;if(x){var y=-1,z=x.length;while(++y<z)r(x[y],u,v,w);}}function s(t,u,v){var w=t.r+v.r,x=u.x-t.x,y=u.y-t.y;if(w&&(x||y)){var z=u.r+v.r,aa=x*x+y*y;z*=z;w*=w;var ba=.5+(w-z)/(2*aa),ca=Math.sqrt(Math.max(0,2*z*(w+aa)-(w-=aa)*w-z*z))/(2*aa);v.x=t.x+ba*x+ca*y;v.y=t.y+ba*y-ca*x;}else{v.x=t.x+w;v.y=t.y;}}f.exports=j;}),null);
__d("d3/layout/partition",["d3/layout/hierarchy"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/layout/hierarchy")._hierarchyRebind,i=function j(){var k=c("d3/layout/hierarchy")(),l=[1,1];function m(p,q,r,s){var t=p.children;p.x=q;p.y=p.depth*s;p.dx=r;p.dy=s;if(t&&(v=t.length)){var u=-1,v,w,x;r=p.value?r/p.value:0;while(++u<v){m(w=t[u],q,x=w.value*r,s);q+=x;}}}function n(p){var q=p.children,r=0;if(q&&(t=q.length)){var s=-1,t;while(++s<t)r=Math.max(r,n(q[s]));}return 1+r;}function o(p,q){var r=k.call(this,p,q);m(r[0],0,l[0],l[1]/n(r[0]));return r;}o.size=function(p){if(!arguments.length)return l;l=p;return o;};return h(o,k);};f.exports=i;}),null);
__d("d3/layout/pie",["d3/core/core","d3/core/sum","d3/core/range"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03c0,i=function k(){var l=Number,m=j,n=0,o=2*h;function p(q){var r=q.map(function(w,x){return +l.call(p,w,x);}),s=+(typeof n==="function"?n.apply(this,arguments):n),t=((typeof o==="function"?o.apply(this,arguments):o)-n)/c("d3/core/sum")(r),u=c("d3/core/range")(q.length);if(m!=null)u.sort(m===j?function(w,x){return r[x]-r[w];}:function(w,x){return m(q[w],q[x]);});var v=[];u.forEach(function(w){var x;v[w]={data:q[w],value:x=r[w],startAngle:s,endAngle:s+=x*t};});return v;}p.value=function(q){if(!arguments.length)return l;l=q;return p;};p.sort=function(q){if(!arguments.length)return m;m=q;return p;};p.startAngle=function(q){if(!arguments.length)return n;n=q;return p;};p.endAngle=function(q){if(!arguments.length)return o;o=q;return p;};return p;},j={};f.exports=i;}),null);
__d("d3/layout/stack",["d3/core/identity","d3/core/permute","d3/core/map","d3/core/range"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/identity")._identity,i=function t(){var u=h,v=o,w=p,x=l,y=j,z=k;function aa(ba,ca){var da=ba.map(function(ma,na){return u.call(aa,ma,na);}),ea=da.map(function(ma){return ma.map(function(na,oa){return [y.call(aa,na,oa),z.call(aa,na,oa)];});}),fa=v.call(aa,ea,ca);da=c("d3/core/permute")(da,fa);ea=c("d3/core/permute")(ea,fa);var ga=w.call(aa,ea,ca),ha=da.length,ia=da[0].length,ja,ka,la;for(ka=0;ka<ia;++ka){x.call(aa,da[0][ka],la=ga[ka],ea[0][ka][1]);for(ja=1;ja<ha;++ja)x.call(aa,da[ja][ka],la+=ea[ja-1][ka][1],ea[ja][ka][1]);}return ba;}aa.values=function(ba){if(!arguments.length)return u;u=ba;return aa;};aa.order=function(ba){if(!arguments.length)return v;v=typeof ba==="function"?ba:m.get(ba)||o;return aa;};aa.offset=function(ba){if(!arguments.length)return w;w=typeof ba==="function"?ba:n.get(ba)||p;return aa;};aa.x=function(ba){if(!arguments.length)return y;y=ba;return aa;};aa.y=function(ba){if(!arguments.length)return z;z=ba;return aa;};aa.out=function(ba){if(!arguments.length)return x;x=ba;return aa;};return aa;};function j(t){return t.x;}function k(t){return t.y;}function l(t,u,v){t.y0=u;t.y=v;}var m=c("d3/core/map")({"inside-out":function t(u){var v=u.length,w,x,y=u.map(q),z=u.map(r),aa=c("d3/core/range")(v).sort(function(fa,ga){return y[fa]-y[ga];}),ba=0,ca=0,da=[],ea=[];for(w=0;w<v;++w){x=aa[w];if(ba<ca){ba+=z[x];da.push(x);}else{ca+=z[x];ea.push(x);}}return ea.reverse().concat(da);},reverse:function t(u){return c("d3/core/range")(u.length).reverse();},"default":o}),n=c("d3/core/map")({silhouette:function t(u){var v=u.length,w=u[0].length,x=[],y=0,z,aa,ba,ca=[];for(aa=0;aa<w;++aa){for(z=0,ba=0;z<v;z++)ba+=u[z][aa][1];if(ba>y)y=ba;x.push(ba);}for(aa=0;aa<w;++aa)ca[aa]=(y-x[aa])/2;return ca;},wiggle:function t(u){var v=u.length,w=u[0],x=w.length,y,z,aa,ba,ca,da,ea,fa,ga,ha=[];ha[0]=fa=ga=0;for(z=1;z<x;++z){for(y=0,ba=0;y<v;++y)ba+=u[y][z][1];for(y=0,ca=0,ea=w[z][0]-w[z-1][0];y<v;++y){for(aa=0,da=(u[y][z][1]-u[y][z-1][1])/(2*ea);aa<y;++aa)da+=(u[aa][z][1]-u[aa][z-1][1])/ea;ca+=da*u[y][z][1];}ha[z]=fa-=ba?ca/ba*ea:0;if(fa<ga)ga=fa;}for(z=0;z<x;++z)ha[z]-=ga;return ha;},expand:function t(u){var v=u.length,w=u[0].length,x=1/v,y,z,aa,ba=[];for(z=0;z<w;++z){for(y=0,aa=0;y<v;y++)aa+=u[y][z][1];if(aa){for(y=0;y<v;y++)u[y][z][1]/=aa;}else for(y=0;y<v;y++)u[y][z][1]=x;}for(z=0;z<w;++z)ba[z]=0;return ba;},zero:p});function o(t){return c("d3/core/range")(t.length);}function p(t){var u=-1,v=t[0].length,w=[];while(++u<v)w[u]=0;return w;}function q(t){var u=1,v=0,w=t[0][1],x,y=t.length;for(;u<y;++u)if((x=t[u][1])>w){v=u;w=x;}return v;}function r(t){return t.reduce(s,0);}function s(t,u){return t+u[1];}f.exports=i;}),null);
__d("d3/layout/treemap",["d3/layout/hierarchy"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/layout/hierarchy")._hierarchyRebind,i=function l(){var m=c("d3/layout/hierarchy")(),n=Math.round,o=[1,1],p=null,q=j,r=false,s,t="squarify",u=.5*(1+Math.sqrt(5));function v(ba,ca){var da=-1,ea=ba.length,fa,ga;while(++da<ea){ga=(fa=ba[da]).value*(ca<0?0:ca);fa.area=isNaN(ga)||ga<=0?0:ga;}}function w(ba){var ca=ba.children;if(ca&&ca.length){var da=q(ba),ea=[],fa=ca.slice(),ga,ha=Infinity,ia,ja=t==="slice"?da.dx:t==="dice"?da.dy:t==="slice-dice"?ba.depth&1?da.dy:da.dx:Math.min(da.dx,da.dy),ka;v(fa,da.dx*da.dy/ba.value);ea.area=0;while((ka=fa.length)>0){ea.push(ga=fa[ka-1]);ea.area+=ga.area;if(t!=="squarify"||(ia=y(ea,ja))<=ha){fa.pop();ha=ia;}else{ea.area-=ea.pop().area;z(ea,ja,da,false);ja=Math.min(da.dx,da.dy);ea.length=ea.area=0;ha=Infinity;}}if(ea.length){z(ea,ja,da,true);ea.length=ea.area=0;}ca.forEach(w);}}function x(ba){var ca=ba.children;if(ca&&ca.length){var da=q(ba),ea=ca.slice(),fa,ga=[];v(ea,da.dx*da.dy/ba.value);ga.area=0;while(fa=ea.pop()){ga.push(fa);ga.area+=fa.area;if(fa.z!=null){z(ga,fa.z?da.dx:da.dy,da,!ea.length);ga.length=ga.area=0;}}ca.forEach(x);}}function y(ba,ca){var da=ba.area,ea,fa=0,ga=Infinity,ha=-1,ia=ba.length;while(++ha<ia){if(!(ea=ba[ha].area))continue;if(ea<ga)ga=ea;if(ea>fa)fa=ea;}da*=da;ca*=ca;return da?Math.max(ca*fa*u/da,da/(ca*ga*u)):Infinity;}function z(ba,ca,da,ea){var fa=-1,ga=ba.length,ha=da.x,ia=da.y,ja=ca?n(ba.area/ca):0,ka;if(ca==da.dx){if(ea||ja>da.dy)ja=da.dy;while(++fa<ga){ka=ba[fa];ka.x=ha;ka.y=ia;ka.dy=ja;ha+=ka.dx=Math.min(da.x+da.dx-ha,ja?n(ka.area/ja):0);}ka.z=true;ka.dx+=da.x+da.dx-ha;da.y+=ja;da.dy-=ja;}else{if(ea||ja>da.dx)ja=da.dx;while(++fa<ga){ka=ba[fa];ka.x=ha;ka.y=ia;ka.dx=ja;ia+=ka.dy=Math.min(da.y+da.dy-ia,ja?n(ka.area/ja):0);}ka.z=false;ka.dy+=da.y+da.dy-ia;da.x+=ja;da.dx-=ja;}}function aa(ba){var ca=s||m(ba),da=ca[0];da.x=0;da.y=0;da.dx=o[0];da.dy=o[1];if(s)m.revalue(da);v([da],da.dx*da.dy/da.value);(s?x:w)(da);if(r)s=ca;return ca;}aa.size=function(ba){if(!arguments.length)return o;o=ba;return aa;};aa.padding=function(ba){if(!arguments.length)return p;function ca(fa){var ga=ba.call(aa,fa,fa.depth);return ga==null?j(fa):k(fa,typeof ga==="number"?[ga,ga,ga,ga]:ga);}function da(fa){return k(fa,ba);}var ea;q=(p=ba)==null?j:(ea=typeof ba)==="function"?ca:ea==="number"?(ba=[ba,ba,ba,ba],da):da;return aa;};aa.round=function(ba){if(!arguments.length)return n!=Number;n=ba?Math.round:Number;return aa;};aa.sticky=function(ba){if(!arguments.length)return r;r=ba;s=null;return aa;};aa.ratio=function(ba){if(!arguments.length)return u;u=ba;return aa;};aa.mode=function(ba){if(!arguments.length)return t;t=ba+"";return aa;};return h(aa,m);};function j(l){return {x:l.x,y:l.y,dx:l.dx,dy:l.dy};}function k(l,m){var n=l.x+m[3],o=l.y+m[0],p=l.dx-m[1]-m[3],q=l.dy-m[0]-m[2];if(p<0){n+=p/2;p=0;}if(q<0){o+=q/2;q=0;}return {x:n,y:o,dx:p,dy:q};}f.exports=i;}),null);
__d("d3/d3.layout",["d3/layout/layout","d3/layout/bundle","d3/layout/chord","d3/layout/force","d3/layout/partition","d3/layout/pie","d3/layout/stack","d3/layout/histogram","d3/layout/hierarchy","d3/layout/pack","d3/layout/cluster","d3/layout/tree","d3/layout/treemap"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/layout/layout").bundle=c("d3\/layout\/bundle");c("d3/layout/layout").chord=c("d3\/layout\/chord");c("d3/layout/layout").force=c("d3\/layout\/force");c("d3/layout/layout").partition=c("d3\/layout\/partition");c("d3/layout/layout").pie=c("d3\/layout\/pie");c("d3/layout/layout").stack=c("d3\/layout\/stack");c("d3/layout/layout").histogram=c("d3\/layout\/histogram");c("d3/layout/layout").hierarchy=c("d3\/layout\/hierarchy");c("d3/layout/layout").pack=c("d3\/layout\/pack");c("d3/layout/layout").cluster=c("d3\/layout\/cluster");c("d3/layout/layout").tree=c("d3\/layout\/tree");c("d3/layout/layout").treemap=c("d3\/layout\/treemap");f.exports=c("d3/layout/layout");}),null);
__d("d3/scale/category",["d3/scale/ordinal"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function m(){return c("d3/scale/ordinal")().range(i);};h.category20=function(){return c("d3/scale/ordinal")().range(j);};h.category20b=function(){return c("d3/scale/ordinal")().range(k);};h.category20c=function(){return c("d3/scale/ordinal")().range(l);};var i=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],j=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],k=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],l=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];f.exports=h;}),null);
__d("d3/scale/identity",["d3/scale/linear"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/scale/linear")._linearTicks,i=c("d3/scale/linear")._linearTickFormat,j=function l(){return k([0,1]);};function k(l){function m(n){return +n;}m.invert=m;m.domain=m.range=function(n){if(!arguments.length)return l;l=n.map(m);return m;};m.ticks=function(n){return h(l,n);};m.tickFormat=function(n){return i(l,n);};m.copy=function(){return k(l);};return m;}f.exports=j;}),null);
__d("d3/scale/log",["d3/scale/nice","d3/scale/linear","d3/scale/scale","d3/core/format"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/scale/nice")._nice,i=c("d3/scale/nice")._niceDefault,j=c("d3\/scale\/scale")._scaleExtent,k=c("d3/scale/linear")._linearRebind,l=function q(){return m(c("d3/scale/linear")(),o);};function m(q,r){var s=r.pow;function t(u){return q(r(u));}t.invert=function(u){return s(q.invert(u));};t.domain=function(u){if(!arguments.length)return q.domain().map(s);r=u[0]<0?p:o;s=r.pow;q.domain(u.map(r));return t;};t.nice=function(){q.domain(h(q.domain(),i));return t;};t.ticks=function(){var u=j(q.domain()),v=[];if(u.every(isFinite)){var w=Math.floor(u[0]),x=Math.ceil(u[1]),y=s(u[0]),z=s(u[1]);if(r===p){v.push(s(w));for(;w++<x;)for(var aa=9;aa>0;aa--)v.push(s(w)*aa);}else{for(;w<x;w++)for(var aa=1;aa<10;aa++)v.push(s(w)*aa);v.push(s(w));}for(w=0;v[w]<y;w++);for(x=v.length;v[x-1]>z;x--);v=v.slice(w,x);}return v;};t.tickFormat=function(u,v){if(arguments.length<2)v=n;if(!arguments.length)return v;var w=Math.max(.1,u/t.ticks().length),x=r===p?(y=-1e-12,Math.floor):(y=1e-12,Math.ceil),y;return function(z){return z/s(x(r(z)+y))<=w?v(z):"";};};t.copy=function(){return m(q.copy(),r);};return k(t,q);}var n=c("d3/core/format")(".0e");function o(q){return Math.log(q<0?0:q)/Math.LN10;}function p(q){return -Math.log(q>0?0:-q)/Math.LN10;}o.pow=function(q){return Math.pow(10,q);};p.pow=function(q){return -Math.pow(10,-q);};f.exports=l;}),null);
__d("d3/scale/pow",["d3/scale/linear","d3/scale/nice"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/scale/linear")._linearTicks,i=c("d3/scale/linear")._linearTickFormat,j=c("d3\/scale\/nice")._nice,k=c("d3/scale/linear")._linearNice,l=c("d3/scale/linear")._linearRebind,m=function p(){return n(c("d3/scale/linear")(),1);};function n(p,q){var r=o(q),s=o(1/q);function t(u){return p(r(u));}t.invert=function(u){return s(p.invert(u));};t.domain=function(u){if(!arguments.length)return p.domain().map(s);p.domain(u.map(r));return t;};t.ticks=function(u){return h(t.domain(),u);};t.tickFormat=function(u){return i(t.domain(),u);};t.nice=function(){return t.domain(j(t.domain(),k));};t.exponent=function(u){if(!arguments.length)return q;var v=t.domain();r=o(q=u);s=o(1/q);return t.domain(v);};t.copy=function(){return n(p.copy(),q);};return l(t,p);}function o(p){return function(q){return q<0?-Math.pow(-q,p):Math.pow(q,p);};}f.exports=m;}),null);
__d("d3/scale/quantile",["d3/core/quantile","d3/core/bisect","d3/core/ascending"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(){return i([],[]);};function i(j,k){var l;function m(){var o=0,p=k.length;l=[];while(++o<p)l[o-1]=c("d3/core/quantile")(j,o/p);return n;}function n(o){if(isNaN(o=+o))return NaN;return k[c("d3/core/bisect")(l,o)];}n.domain=function(o){if(!arguments.length)return j;j=o.filter(function(p){return !isNaN(p);}).sort(c("d3/core/ascending"));return m();};n.range=function(o){if(!arguments.length)return k;k=o;return m();};n.quantiles=function(){return l;};n.copy=function(){return i(j,k);};return m();}f.exports=h;}),null);
__d("d3/scale/quantize",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(){return i(0,1,[0,1]);};function i(j,k,l){var m,n;function o(q){return l[Math.max(0,Math.min(n,Math.floor(m*(q-j))))];}function p(){m=l.length/(k-j);n=l.length-1;return o;}o.domain=function(q){if(!arguments.length)return [j,k];j=+q[0];k=+q[q.length-1];return p();};o.range=function(q){if(!arguments.length)return l;l=q;return p();};o.copy=function(){return i(j,k,l);};return p();}f.exports=h;}),null);
__d("d3/scale/sqrt",["d3/scale/pow"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function i(){return c("d3/scale/pow")().exponent(.5);};f.exports=h;}),null);
__d("d3/scale/threshold",["d3/core/bisect"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=function j(){return i([.5],[0,1]);};function i(j,k){function l(m){return k[c("d3/core/bisect")(j,m)];}l.domain=function(m){if(!arguments.length)return j;j=m;return l;};l.range=function(m){if(!arguments.length)return k;k=m;return l;};l.copy=function(){return i(j,k);};return l;}f.exports=h;}),null);
__d("d3/d3.scale",["d3/scale/scale","d3/scale/linear","d3/scale/log","d3/scale/pow","d3/scale/sqrt","d3/scale/ordinal","d3/scale/category","d3/scale/quantile","d3/scale/quantize","d3/scale/threshold","d3/scale/identity"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/scale/scale").linear=c("d3\/scale\/linear");c("d3/scale/scale").log=c("d3\/scale\/log");c("d3/scale/scale").pow=c("d3\/scale\/pow");c("d3/scale/scale").sqrt=c("d3\/scale\/sqrt");c("d3/scale/scale").ordinal=c("d3\/scale\/ordinal");c("d3/scale/scale").category10=c("d3\/scale\/category");c("d3/scale/scale").category20=c("d3\/scale\/category").category20;c("d3/scale/scale").category20b=c("d3\/scale\/category").category20b;c("d3/scale/scale").category20c=c("d3\/scale\/category").category20c;c("d3/scale/scale").quantile=c("d3\/scale\/quantile");c("d3/scale/scale").quantize=c("d3\/scale\/quantize");c("d3/scale/scale").threshold=c("d3\/scale\/threshold");c("d3/scale/scale").identity=c("d3\/scale\/identity");f.exports=c("d3/scale/scale");}),null);
__d("d3/svg/arc",["d3/core/core","d3/core/functor"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/core")._u03c0,i=c("d3\/core\/functor")._functor,j=function q(){var r=m,s=n,t=o,u=p;function v(){var w=r.apply(this,arguments),x=s.apply(this,arguments),y=t.apply(this,arguments)+k,z=u.apply(this,arguments)+k,aa=(z<y&&(aa=y,y=z,z=aa),z-y),ba=aa<h?"0":"1",ca=Math.cos(y),da=Math.sin(y),ea=Math.cos(z),fa=Math.sin(z);return aa>=l?w?"M0,"+x+"A"+x+","+x+" 0 1,1 0,"+ -x+"A"+x+","+x+" 0 1,1 0,"+x+"M0,"+w+"A"+w+","+w+" 0 1,0 0,"+ -w+"A"+w+","+w+" 0 1,0 0,"+w+"Z":"M0,"+x+"A"+x+","+x+" 0 1,1 0,"+ -x+"A"+x+","+x+" 0 1,1 0,"+x+"Z":w?"M"+x*ca+","+x*da+"A"+x+","+x+" 0 "+ba+",1 "+x*ea+","+x*fa+"L"+w*ea+","+w*fa+"A"+w+","+w+" 0 "+ba+",0 "+w*ca+","+w*da+"Z":"M"+x*ca+","+x*da+"A"+x+","+x+" 0 "+ba+",1 "+x*ea+","+x*fa+"L0,0"+"Z";}v.innerRadius=function(w){if(!arguments.length)return r;r=i(w);return v;};v.outerRadius=function(w){if(!arguments.length)return s;s=i(w);return v;};v.startAngle=function(w){if(!arguments.length)return t;t=i(w);return v;};v.endAngle=function(w){if(!arguments.length)return u;u=i(w);return v;};v.centroid=function(){var w=(r.apply(this,arguments)+s.apply(this,arguments))/2,x=(t.apply(this,arguments)+u.apply(this,arguments))/2+k;return [Math.cos(x)*w,Math.sin(x)*w];};return v;},k=-h/2,l=2*h-1e-06;function m(q){return q.innerRadius;}function n(q){return q.outerRadius;}function o(q){return q.startAngle;}function p(q){return q.endAngle;}j._arcOffset=k;j._arcStartAngle=o;j._arcEndAngle=p;f.exports=j;}),null);
__d("d3/svg/line",["d3/core/true","d3/core/functor","d3/core/identity","d3/core/map"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/true")._true,i=c("d3\/core\/functor")._functor,j=c("d3\/core\/identity")._identity;function k(la){var ma=m,na=n,oa=h,pa=p,qa=pa.key,ra=.7;function sa(ta){var ua=[],va=[],wa=-1,xa=ta.length,ya,za=i(ma),ab=i(na);function bb(){ua.push("M",pa(la(va),ra));}while(++wa<xa)if(oa.call(this,ya=ta[wa],wa)){va.push([+za.call(this,ya,wa),+ab.call(this,ya,wa)]);}else if(va.length){bb();va=[];}if(va.length)bb();return ua.length?ua.join(""):null;}sa.x=function(ta){if(!arguments.length)return ma;ma=ta;return sa;};sa.y=function(ta){if(!arguments.length)return na;na=ta;return sa;};sa.defined=function(ta){if(!arguments.length)return oa;oa=ta;return sa;};sa.interpolate=function(ta){if(!arguments.length)return qa;if(typeof ta==="function"){qa=pa=ta;}else qa=(pa=o.get(ta)||p).key;return sa;};sa.tension=function(ta){if(!arguments.length)return ra;ra=ta;return sa;};return sa;}var l=function la(){return k(j);};function m(la){return la[0];}function n(la){return la[1];}var o=c("d3/core/map")({linear:p,"linear-closed":q,"step-before":r,"step-after":s,basis:y,"basis-open":z,"basis-closed":aa,bundle:ba,cardinal:v,"cardinal-open":t,"cardinal-closed":u,monotone:ka});o.forEach(function(la,ma){ma.key=la;ma.closed=/-closed$/.test(la);});function p(la){return la.join("L");}function q(la){return p(la)+"Z";}function r(la){var ma=0,na=la.length,oa=la[0],pa=[oa[0],",",oa[1]];while(++ma<na)pa.push("V",(oa=la[ma])[1],"H",oa[0]);return pa.join("");}function s(la){var ma=0,na=la.length,oa=la[0],pa=[oa[0],",",oa[1]];while(++ma<na)pa.push("H",(oa=la[ma])[0],"V",oa[1]);return pa.join("");}function t(la,ma){return la.length<4?p(la):la[1]+w(la.slice(1,la.length-1),x(la,ma));}function u(la,ma){return la.length<3?p(la):la[0]+w((la.push(la[0]),la),x([la[la.length-2]].concat(la,[la[1]]),ma));}function v(la,ma){return la.length<3?p(la):la[0]+w(la,x(la,ma));}function w(la,ma){if(ma.length<1||la.length!=ma.length&&la.length!=ma.length+2)return p(la);var na=la.length!=ma.length,oa="",pa=la[0],qa=la[1],ra=ma[0],sa=ra,ta=1;if(na){oa+="Q"+(qa[0]-ra[0]*2/3)+","+(qa[1]-ra[1]*2/3)+","+qa[0]+","+qa[1];pa=la[1];ta=2;}if(ma.length>1){sa=ma[1];qa=la[ta];ta++;oa+="C"+(pa[0]+ra[0])+","+(pa[1]+ra[1])+","+(qa[0]-sa[0])+","+(qa[1]-sa[1])+","+qa[0]+","+qa[1];for(var ua=2;ua<ma.length;ua++,ta++){qa=la[ta];sa=ma[ua];oa+="S"+(qa[0]-sa[0])+","+(qa[1]-sa[1])+","+qa[0]+","+qa[1];}}if(na){var va=la[ta];oa+="Q"+(qa[0]+sa[0]*2/3)+","+(qa[1]+sa[1]*2/3)+","+va[0]+","+va[1];}return oa;}function x(la,ma){var na=[],oa=(1-ma)/2,pa,qa=la[0],ra=la[1],sa=1,ta=la.length;while(++sa<ta){pa=qa;qa=ra;ra=la[sa];na.push([oa*(ra[0]-pa[0]),oa*(ra[1]-pa[1])]);}return na;}function y(la){if(la.length<3)return p(la);var ma=1,na=la.length,oa=la[0],pa=oa[0],qa=oa[1],ra=[pa,pa,pa,(oa=la[1])[0]],sa=[qa,qa,qa,oa[1]],ta=[pa,",",qa];ga(ta,ra,sa);while(++ma<na){oa=la[ma];ra.shift();ra.push(oa[0]);sa.shift();sa.push(oa[1]);ga(ta,ra,sa);}ma=-1;while(++ma<2){ra.shift();ra.push(oa[0]);sa.shift();sa.push(oa[1]);ga(ta,ra,sa);}return ta.join("");}function z(la){if(la.length<4)return p(la);var ma=[],na=-1,oa=la.length,pa,qa=[0],ra=[0];while(++na<3){pa=la[na];qa.push(pa[0]);ra.push(pa[1]);}ma.push(ca(fa,qa)+","+ca(fa,ra));--na;while(++na<oa){pa=la[na];qa.shift();qa.push(pa[0]);ra.shift();ra.push(pa[1]);ga(ma,qa,ra);}return ma.join("");}function aa(la){var ma,na=-1,oa=la.length,pa=oa+4,qa,ra=[],sa=[];while(++na<4){qa=la[na%oa];ra.push(qa[0]);sa.push(qa[1]);}ma=[ca(fa,ra),",",ca(fa,sa)];--na;while(++na<pa){qa=la[na%oa];ra.shift();ra.push(qa[0]);sa.shift();sa.push(qa[1]);ga(ma,ra,sa);}return ma.join("");}function ba(la,ma){var na=la.length-1;if(na){var oa=la[0][0],pa=la[0][1],qa=la[na][0]-oa,ra=la[na][1]-pa,sa=-1,ta,ua;while(++sa<=na){ta=la[sa];ua=sa/na;ta[0]=ma*ta[0]+(1-ma)*(oa+ua*qa);ta[1]=ma*ta[1]+(1-ma)*(pa+ua*ra);}}return y(la);}function ca(la,ma){return la[0]*ma[0]+la[1]*ma[1]+la[2]*ma[2]+la[3]*ma[3];}var da=[0,2/3,1/3,0],ea=[0,1/3,2/3,0],fa=[0,1/6,2/3,1/6];function ga(la,ma,na){la.push("C",ca(da,ma),",",ca(da,na),",",ca(ea,ma),",",ca(ea,na),",",ca(fa,ma),",",ca(fa,na));}function ha(la,ma){return (ma[1]-la[1])/(ma[0]-la[0]);}function ia(la){var ma=0,na=la.length-1,oa=[],pa=la[0],qa=la[1],ra=oa[0]=ha(pa,qa);while(++ma<na)oa[ma]=(ra+(ra=ha(pa=qa,qa=la[ma+1])))/2;oa[ma]=ra;return oa;}function ja(la){var ma=[],na,oa,pa,qa,ra=ia(la),sa=-1,ta=la.length-1;while(++sa<ta){na=ha(la[sa],la[sa+1]);if(Math.abs(na)<1e-06){ra[sa]=ra[sa+1]=0;}else{oa=ra[sa]/na;pa=ra[sa+1]/na;qa=oa*oa+pa*pa;if(qa>9){qa=na*3/Math.sqrt(qa);ra[sa]=qa*oa;ra[sa+1]=qa*pa;}}}sa=-1;while(++sa<=ta){qa=(la[Math.min(ta,sa+1)][0]-la[Math.max(0,sa-1)][0])/(6*(1+ra[sa]*ra[sa]));ma.push([qa||0,ra[sa]*qa||0]);}return ma;}function ka(la){return la.length<3?p(la):la[0]+w(la,ja(la));}l._lineInterpolators=o;l._line=k;l._lineX=m;l._lineY=n;l._lineLinear=p;l._lineStepBefore=r;l._lineStepAfter=s;f.exports=l;}),null);
__d("d3/svg/area",["d3/svg/line","d3/core/true","d3/core/functor","d3/core/identity"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/svg/line")._lineX,i=c("d3/svg/line")._lineY,j=c("d3\/core\/true")._true,k=c("d3/svg/line")._lineLinear,l=c("d3\/core\/functor")._functor,m=c("d3/svg/line")._lineInterpolators,n=c("d3/svg/line")._lineStepBefore,o=c("d3/svg/line")._lineStepAfter,p=c("d3\/core\/identity")._identity;function q(s){var t=h,u=h,v=0,w=i,x=j,y=k,z=y.key,aa=y,ba="L",ca=.7;function da(ea){var fa=[],ga=[],ha=[],ia=-1,ja=ea.length,ka,la=l(t),ma=l(v),na=t===u?function(){return pa;}:l(u),oa=v===w?function(){return qa;}:l(w),pa,qa;function ra(){fa.push("M",y(s(ha),ca),ba,aa(s(ga.reverse()),ca),"Z");}while(++ia<ja)if(x.call(this,ka=ea[ia],ia)){ga.push([pa=+la.call(this,ka,ia),qa=+ma.call(this,ka,ia)]);ha.push([+na.call(this,ka,ia),+oa.call(this,ka,ia)]);}else if(ga.length){ra();ga=[];ha=[];}if(ga.length)ra();return fa.length?fa.join(""):null;}da.x=function(ea){if(!arguments.length)return u;t=u=ea;return da;};da.x0=function(ea){if(!arguments.length)return t;t=ea;return da;};da.x1=function(ea){if(!arguments.length)return u;u=ea;return da;};da.y=function(ea){if(!arguments.length)return w;v=w=ea;return da;};da.y0=function(ea){if(!arguments.length)return v;v=ea;return da;};da.y1=function(ea){if(!arguments.length)return w;w=ea;return da;};da.defined=function(ea){if(!arguments.length)return x;x=ea;return da;};da.interpolate=function(ea){if(!arguments.length)return z;if(typeof ea==="function"){z=y=ea;}else z=(y=m.get(ea)||k).key;aa=y.reverse||y;ba=y.closed?"M":"L";return da;};da.tension=function(ea){if(!arguments.length)return ca;ca=ea;return da;};return da;}n.reverse=o;o.reverse=n;var r=function s(){return q(p);};r._area=q;f.exports=r;}),null);
__d("d3/svg/line-radial",["d3/svg/line","d3/svg/arc"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/svg\/line")._line,i=c("d3\/svg\/arc")._arcOffset,j=function l(){var m=h(k);m.radius=m.x,delete m.x;m.angle=m.y,delete m.y;return m;};function k(l){var m,n=-1,o=l.length,p,q;while(++n<o){m=l[n];p=m[0];q=m[1]+i;m[0]=p*Math.cos(q);m[1]=p*Math.sin(q);}return l;}j._lineRadial=k;f.exports=j;}),null);
__d("d3/svg/area-radial",["d3/svg/area","d3/svg/line-radial"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/svg\/area")._area,i=c("d3\/svg\/line-radial")._lineRadial,j=function k(){var l=h(i);l.radius=l.x,delete l.x;l.innerRadius=l.x0,delete l.x0;l.outerRadius=l.x1,delete l.x1;l.angle=l.y,delete l.y;l.startAngle=l.y0,delete l.y0;l.endAngle=l.y1,delete l.y1;return l;};f.exports=j;}),null);
__d("d3/svg/axis",["d3/scale/scale","d3/scale/linear","d3/core/selection-root","d3/core/transition"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/scale/scale")._scaleRange,i=c("d3/scale/scale")._scaleExtent,j=function p(){var q=c("d3/scale/linear")(),r=k,s=6,t=6,u=6,v=3,w=[10],x=null,y,z=0;function aa(ba){ba.each(function(){var ca=c("d3/core/selection-root")(this),da=x==null?q.ticks?q.ticks.apply(q,w):q.domain():x,ea=y==null?q.tickFormat?q.tickFormat.apply(q,w):String:y,fa=o(q,da,z),ga=ca.selectAll(".tick.minor").data(fa,String),ha=ga.enter().insert("line",".tick").attr("class","tick minor").style("opacity",1e-06),ia=c("d3/core/transition")(ga.exit()).style("opacity",1e-06).remove(),ja=c("d3/core/transition")(ga).style("opacity",1),ka=ca.selectAll(".tick.major").data(da,String),la=ka.enter().insert("g","path").attr("class","tick major").style("opacity",1e-06),ma=c("d3/core/transition")(ka.exit()).style("opacity",1e-06).remove(),na=c("d3/core/transition")(ka).style("opacity",1),oa,pa=h(q),qa=ca.selectAll(".domain").data([0]),ra=(qa.enter().append("path").attr("class","domain"),c("d3/core/transition")(qa)),sa=q.copy(),ta=this.__chart__||sa;this.__chart__=sa;la.append("line");la.append("text");var ua=la.select("line"),va=na.select("line"),wa=ka.select("text").text(ea),xa=la.select("text"),ya=na.select("text");switch(r){case "bottom":oa=m;ha.attr("y2",t);ja.attr("x2",0).attr("y2",t);ua.attr("y2",s);xa.attr("y",Math.max(s,0)+v);va.attr("x2",0).attr("y2",s);ya.attr("x",0).attr("y",Math.max(s,0)+v);wa.attr("dy",".71em").style("text-anchor","middle");ra.attr("d","M"+pa[0]+","+u+"V0H"+pa[1]+"V"+u);break;case "top":oa=m;ha.attr("y2",-t);ja.attr("x2",0).attr("y2",-t);ua.attr("y2",-s);xa.attr("y",-(Math.max(s,0)+v));va.attr("x2",0).attr("y2",-s);ya.attr("x",0).attr("y",-(Math.max(s,0)+v));wa.attr("dy","0em").style("text-anchor","middle");ra.attr("d","M"+pa[0]+","+ -u+"V0H"+pa[1]+"V"+ -u);break;case "left":oa=n;ha.attr("x2",-t);ja.attr("x2",-t).attr("y2",0);ua.attr("x2",-s);xa.attr("x",-(Math.max(s,0)+v));va.attr("x2",-s).attr("y2",0);ya.attr("x",-(Math.max(s,0)+v)).attr("y",0);wa.attr("dy",".32em").style("text-anchor","end");ra.attr("d","M"+ -u+","+pa[0]+"H0V"+pa[1]+"H"+ -u);break;case "right":oa=n;ha.attr("x2",t);ja.attr("x2",t).attr("y2",0);ua.attr("x2",s);xa.attr("x",Math.max(s,0)+v);va.attr("x2",s).attr("y2",0);ya.attr("x",Math.max(s,0)+v).attr("y",0);wa.attr("dy",".32em").style("text-anchor","start");ra.attr("d","M"+u+","+pa[0]+"H0V"+pa[1]+"H"+u);break;}if(q.ticks){la.call(oa,ta);na.call(oa,sa);ma.call(oa,sa);ha.call(oa,ta);ja.call(oa,sa);ia.call(oa,sa);}else{var za=sa.rangeBand()/2,ab=function bb(cb){return sa(cb)+za;};la.call(oa,ab);na.call(oa,ab);}});}aa.scale=function(ba){if(!arguments.length)return q;q=ba;return aa;};aa.orient=function(ba){if(!arguments.length)return r;r=ba in l?ba+"":k;return aa;};aa.ticks=function(){if(!arguments.length)return w;w=arguments;return aa;};aa.tickValues=function(ba){if(!arguments.length)return x;x=ba;return aa;};aa.tickFormat=function(ba){if(!arguments.length)return y;y=ba;return aa;};aa.tickSize=function(ba,ca){if(!arguments.length)return s;var da=arguments.length-1;s=+ba;t=da>1?+ca:s;u=da>0?+arguments[da]:s;return aa;};aa.tickPadding=function(ba){if(!arguments.length)return v;v=+ba;return aa;};aa.tickSubdivide=function(ba){if(!arguments.length)return z;z=+ba;return aa;};return aa;},k="bottom",l={top:1,right:1,bottom:1,left:1};function m(p,q){p.attr("transform",function(r){return "translate("+q(r)+",0)";});}function n(p,q){p.attr("transform",function(r){return "translate(0,"+q(r)+")";});}function o(p,q,r){t=[];if(r&&q.length>1){var s=i(p.domain()),t,u=-1,v=q.length,w=(q[1]-q[0])/++r,x,y;while(++u<v)for(x=r;--x>0;)if((y=+q[u]-x*w)>=s[0])t.push(y);for(--u,x=0;++x<r&&(y=+q[u]+x*w)<s[1];)t.push(y);}return t;}f.exports=j;}),null);
__d("d3/svg/brush",["d3/core/event","d3/core/core","d3/scale/scale","d3/core/selection-root","d3/core/touches","d3/core/mouse","d3/core/rebind"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/event")._eventDispatch,i=c("d3\/scale\/scale")._scaleRange,j=c("d3/core/core")._window,k=c("d3/core/event")._eventCancel,l=function o(){var event=h(u,"brushstart","brush","brushend"),p=null,q=null,r=n[0],s=[[0,0],[0,0]],t;function u(z){z.each(function(){var aa=c("d3/core/selection-root")(this),ba=aa.selectAll(".background").data([0]),ca=aa.selectAll(".extent").data([0]),da=aa.selectAll(".resize").data(r,String),ea;aa.style("pointer-events","all").on("mousedown.brush",y).on("touchstart.brush",y);ba.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");ca.enter().append("rect").attr("class","extent").style("cursor","move");da.enter().append("g").attr("class",function(fa){return "resize "+fa;}).style("cursor",function(fa){return m[fa];}).append("rect").attr("x",function(fa){return /[ew]$/.test(fa)?-3:null;}).attr("y",function(fa){return /^[ns]/.test(fa)?-3:null;}).attr("width",6).attr("height",6).style("visibility","hidden");da.style("display",u.empty()?"none":null);da.exit().remove();if(p){ea=i(p);ba.attr("x",ea[0]).attr("width",ea[1]-ea[0]);w(aa);}if(q){ea=i(q);ba.attr("y",ea[0]).attr("height",ea[1]-ea[0]);x(aa);}v(aa);});}function v(z){z.selectAll(".resize").attr("transform",function(aa){return "translate("+s[+/e$/.test(aa)][0]+","+s[+/^s/.test(aa)][1]+")";});}function w(z){z.select(".extent").attr("x",s[0][0]);z.selectAll(".extent,.n>rect,.s>rect").attr("width",s[1][0]-s[0][0]);}function x(z){z.select(".extent").attr("y",s[0][1]);z.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1][1]-s[0][1]);}function y(){var z=this,aa=c("d3/core/selection-root")(c("d3/core/core").event.target),ba=event.of(z,arguments),ca=c("d3/core/selection-root")(z),da=aa.datum(),ea=!/^(n|s)$/.test(da)&&p,fa=!/^(e|w)$/.test(da)&&q,ga=aa.classed("extent"),ha,ia=na(),ja,ka=c("d3/core/selection-root")(j).on("mousemove.brush",qa).on("mouseup.brush",sa).on("touchmove.brush",qa).on("touchend.brush",sa).on("keydown.brush",oa).on("keyup.brush",pa);if(ga){ia[0]=s[0][0]-ia[0];ia[1]=s[0][1]-ia[1];}else if(da){var la=+/w$/.test(da),ma=+/^n/.test(da);ja=[s[1-la][0]-ia[0],s[1-ma][1]-ia[1]];ia[0]=s[la][0];ia[1]=s[ma][1];}else if(c("d3/core/core").event.altKey)ha=ia.slice();ca.style("pointer-events","none").selectAll(".resize").style("display",null);c("d3/core/selection-root")("body").style("cursor",aa.style("cursor"));ba({type:"brushstart"});qa();k();function na(){var ta=c("d3/core/core").event.changedTouches;return ta?c("d3/core/touches")(z,ta)[0]:c("d3/core/mouse")(z);}function oa(){if(c("d3/core/core").event.keyCode==32){if(!ga){ha=null;ia[0]-=s[1][0];ia[1]-=s[1][1];ga=2;}k();}}function pa(){if(c("d3/core/core").event.keyCode==32&&ga==2){ia[0]+=s[1][0];ia[1]+=s[1][1];ga=0;k();}}function qa(){var ta=na(),ua=false;if(ja){ta[0]+=ja[0];ta[1]+=ja[1];}if(!ga)if(c("d3/core/core").event.altKey){if(!ha)ha=[(s[0][0]+s[1][0])/2,(s[0][1]+s[1][1])/2];ia[0]=s[+(ta[0]<ha[0])][0];ia[1]=s[+(ta[1]<ha[1])][1];}else ha=null;if(ea&&ra(ta,p,0)){w(ca);ua=true;}if(fa&&ra(ta,q,1)){x(ca);ua=true;}if(ua){v(ca);ba({type:"brush",mode:ga?"move":"resize"});}}function ra(ta,ua,va){var wa=i(ua),xa=wa[0],ya=wa[1],za=ia[va],ab=s[1][va]-s[0][va],bb,cb;if(ga){xa-=za;ya-=ab+za;}bb=Math.max(xa,Math.min(ya,ta[va]));if(ga){cb=(bb+=za)+ab;}else{if(ha)za=Math.max(xa,Math.min(ya,2*ha[va]-bb));if(za<bb){cb=bb;bb=za;}else cb=za;}if(s[0][va]!==bb||s[1][va]!==cb){t=null;s[0][va]=bb;s[1][va]=cb;return true;}}function sa(){qa();ca.style("pointer-events","all").selectAll(".resize").style("display",u.empty()?"none":null);c("d3/core/selection-root")("body").style("cursor",null);ka.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null);ba({type:"brushend"});k();}}u.x=function(z){if(!arguments.length)return p;p=z;r=n[!p<<1|!q];return u;};u.y=function(z){if(!arguments.length)return q;q=z;r=n[!p<<1|!q];return u;};u.extent=function(z){var aa,ba,ca,da,ea;if(!arguments.length){z=t||s;if(p){aa=z[0][0],ba=z[1][0];if(!t){aa=s[0][0],ba=s[1][0];if(p.invert)aa=p.invert(aa),ba=p.invert(ba);if(ba<aa)ea=aa,aa=ba,ba=ea;}}if(q){ca=z[0][1],da=z[1][1];if(!t){ca=s[0][1],da=s[1][1];if(q.invert)ca=q.invert(ca),da=q.invert(da);if(da<ca)ea=ca,ca=da,da=ea;}}return p&&q?[[aa,ca],[ba,da]]:p?[aa,ba]:q&&[ca,da];}t=[[0,0],[0,0]];if(p){aa=z[0],ba=z[1];if(q)aa=aa[0],ba=ba[0];t[0][0]=aa,t[1][0]=ba;if(p.invert)aa=p(aa),ba=p(ba);if(ba<aa)ea=aa,aa=ba,ba=ea;s[0][0]=aa|0,s[1][0]=ba|0;}if(q){ca=z[0],da=z[1];if(p)ca=ca[1],da=da[1];t[0][1]=ca,t[1][1]=da;if(q.invert)ca=q(ca),da=q(da);if(da<ca)ea=ca,ca=da,da=ea;s[0][1]=ca|0,s[1][1]=da|0;}return u;};u.clear=function(){t=null;s[0][0]=s[0][1]=s[1][0]=s[1][1]=0;return u;};u.empty=function(){return p&&s[0][0]===s[1][0]||q&&s[0][1]===s[1][1];};return c("d3/core/rebind")(u,event,"on");},m={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},n=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]];f.exports=l;}),null);
__d("d3/svg/chord",["d3/core/core","d3/svg/arc","d3/core/functor"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._source,i=c("d3/core/core")._target,j=c("d3/svg/arc")._arcStartAngle,k=c("d3/svg/arc")._arcEndAngle,l=c("d3/svg/arc")._arcOffset,m=c("d3/core/core")._u03c0,n=c("d3\/core\/functor")._functor,o=function q(){var r=h,s=i,t=p,u=j,v=k;function w(ba,ca){var da=x(this,r,ba,ca),ea=x(this,s,ba,ca);return "M"+da.p0+z(da.r,da.p1,da.a1-da.a0)+(y(da,ea)?aa(da.r,da.p1,da.r,da.p0):aa(da.r,da.p1,ea.r,ea.p0)+z(ea.r,ea.p1,ea.a1-ea.a0)+aa(ea.r,ea.p1,da.r,da.p0))+"Z";}function x(ba,ca,da,ea){var fa=ca.call(ba,da,ea),ga=t.call(ba,fa,ea),ha=u.call(ba,fa,ea)+l,ia=v.call(ba,fa,ea)+l;return {r:ga,a0:ha,a1:ia,p0:[ga*Math.cos(ha),ga*Math.sin(ha)],p1:[ga*Math.cos(ia),ga*Math.sin(ia)]};}function y(ba,ca){return ba.a0==ca.a0&&ba.a1==ca.a1;}function z(ba,ca,da){return "A"+ba+","+ba+" 0 "+ +(da>m)+",1 "+ca;}function aa(ba,ca,da,ea){return "Q 0,0 "+ea;}w.radius=function(ba){if(!arguments.length)return t;t=n(ba);return w;};w.source=function(ba){if(!arguments.length)return r;r=n(ba);return w;};w.target=function(ba){if(!arguments.length)return s;s=n(ba);return w;};w.startAngle=function(ba){if(!arguments.length)return u;u=n(ba);return w;};w.endAngle=function(ba){if(!arguments.length)return v;v=n(ba);return w;};return w;};function p(q){return q.radius;}f.exports=o;}),null);
__d("d3/svg/diagonal",["d3/core/core","d3/core/functor"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/core/core")._source,i=c("d3/core/core")._target,j=c("d3\/core\/functor")._functor,k=function m(){var n=h,o=i,p=l;function q(r,s){var t=n.call(this,r,s),u=o.call(this,r,s),v=(t.y+u.y)/2,w=[t,{x:t.x,y:v},{x:u.x,y:v},u];w=w.map(p);return "M"+w[0]+"C"+w[1]+" "+w[2]+" "+w[3];}q.source=function(r){if(!arguments.length)return n;n=j(r);return q;};q.target=function(r){if(!arguments.length)return o;o=j(r);return q;};q.projection=function(r){if(!arguments.length)return p;p=r;return q;};return q;};function l(m){return [m.x,m.y];}k._diagonalProjection=l;f.exports=k;}),null);
__d("d3/svg/diagonal-radial",["d3/svg/diagonal","d3/svg/arc"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/svg/diagonal")._diagonalProjection,i=c("d3\/svg\/arc")._arcOffset,j=function l(){var m=c("d3/svg/diagonal")(),n=h,o=m.projection;m.projection=function(p){return arguments.length?o(k(n=p)):n;};return m;};function k(l){return function(){var m=l.apply(this,arguments),n=m[0],o=m[1]+i;return [n*Math.cos(o),n*Math.sin(o)];};}f.exports=j;}),null);
__d("d3/svg/svg",[],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h={};f.exports=h;}),null);
__d("d3/svg/symbol",["d3/core/core","d3/core/functor","d3/core/map"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/core\/functor")._functor,i=c("d3/core/core")._u03c0,j=c("d3/core/core")._radians,k=function r(){var s=m,t=l;function u(v,w){return (o.get(s.call(this,v,w))||n)(t.call(this,v,w));}u.type=function(v){if(!arguments.length)return s;s=h(v);return u;};u.size=function(v){if(!arguments.length)return t;t=h(v);return u;};return u;};function l(){return 64;}function m(){return "circle";}function n(r){var s=Math.sqrt(r/i);return "M0,"+s+"A"+s+","+s+" 0 1,1 0,"+ -s+"A"+s+","+s+" 0 1,1 0,"+s+"Z";}var o=c("d3/core/map")({circle:n,cross:function r(s){var t=Math.sqrt(s/5)/2;return "M"+ -3*t+","+ -t+"H"+ -t+"V"+ -3*t+"H"+t+"V"+ -t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+ -t+"V"+t+"H"+ -3*t+"Z";},diamond:function r(s){var t=Math.sqrt(s/(2*q)),u=t*q;return "M0,"+ -t+"L"+u+",0"+" 0,"+t+" "+ -u+",0"+"Z";},square:function r(s){var t=Math.sqrt(s)/2;return "M"+ -t+","+ -t+"L"+t+","+ -t+" "+t+","+t+" "+ -t+","+t+"Z";},"triangle-down":function r(s){var t=Math.sqrt(s/p),u=t*p/2;return "M0,"+u+"L"+t+","+ -u+" "+ -t+","+ -u+"Z";},"triangle-up":function r(s){var t=Math.sqrt(s/p),u=t*p/2;return "M0,"+ -u+"L"+t+","+u+" "+ -t+","+u+"Z";}});k.types=o.keys();var p=Math.sqrt(3),q=Math.tan(30*j);f.exports=k;}),null);
__d("d3/d3.svg",["d3/svg/svg","d3/svg/arc","d3/svg/line","d3/svg/line-radial","d3/svg/area","d3/svg/area-radial","d3/svg/chord","d3/svg/diagonal","d3/svg/diagonal-radial","d3/svg/symbol","d3/svg/axis","d3/svg/brush"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/svg/svg").arc=c("d3\/svg\/arc");c("d3/svg/svg").line=c("d3\/svg\/line");c("d3/svg/svg").line.radial=c("d3\/svg\/line-radial");c("d3/svg/svg").area=c("d3\/svg\/area");c("d3/svg/svg").area.radial=c("d3\/svg\/area-radial");c("d3/svg/svg").chord=c("d3\/svg\/chord");c("d3/svg/svg").diagonal=c("d3\/svg\/diagonal");c("d3/svg/svg").diagonal.radial=c("d3\/svg\/diagonal-radial");c("d3/svg/svg").symbol=c("d3\/svg\/symbol");c("d3/svg/svg").symbolTypes=c("d3\/svg\/symbol").types;c("d3/svg/svg").axis=c("d3\/svg\/axis");c("d3/svg/svg").brush=c("d3\/svg\/brush");f.exports=c("d3/svg/svg");}),null);
__d("d3/time/format-iso",["d3/time/format-utc"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/time\/format-utc")("%Y-%m-%dT%H:%M:%S.%LZ"),i=Date.prototype.toISOString?j:h;function j(k){return k.toISOString();}j.parse=function(k){var l=new Date(k);return isNaN(l)?null:l;};j.toString=h.toString;f.exports=i;}),null);
__d("d3/time/week",["d3/time/time","d3/time/interval","d3/time/day","d3/time/year"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/time/time")._daySymbols,i=c("d3\/time\/interval")._interval;h.forEach(function(k,l){k=k.toLowerCase();l=7-l;var m=c("d3/time/time")[k]=i(function(n){(n=c("d3/time/day")(n)).setDate(n.getDate()-(n.getDay()+l)%7);return n;},function(n,o){n.setDate(n.getDate()+Math.floor(o)*7);},function(n){var o=c("d3/time/year")(n).getDay();return Math.floor((c("d3/time/day").ofYear(n)+(o+l)%7)/7)-(o!==l);});c("d3/time/time")[k+"s"]=m.range;c("d3/time/time")[k+"s"].utc=m.utc.range;c("d3/time/time")[k+"OfYear"]=function(n){var o=c("d3/time/year")(n).getDay();return Math.floor((c("d3/time/day").ofYear(n)+(o+l)%7)/7);};});var j=c("d3/time/time").sunday;j.s=c("d3/time/time").sunday.range;j.s.utc=c("d3/time/time").sunday.utc.range;j.ofYear=c("d3/time/time").sundayOfYear;f.exports=j;}),null);
__d("d3/time/scale",["d3/scale/nice","d3/core/true","d3/core/bisect","d3/core/rebind","d3/time/second","d3/time/minute","d3/time/hour","d3/time/day","d3/time/week","d3/time/month","d3/time/year","d3/time/format","d3/scale/linear"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3\/scale\/nice")._nice,i=c("d3\/core\/true")._true;function j(v,w,x){function y(z){return v(z);}y.invert=function(z){return l(v.invert(z));};y.domain=function(z){if(!arguments.length)return v.domain().map(l);v.domain(z);return y;};y.nice=function(z){return y.domain(h(y.domain(),function(){return z;}));};y.ticks=function(z,aa){var ba=k(y.domain());if(typeof z!=="function"){var ca=ba[1]-ba[0],da=ca/z,ea=c("d3/core/bisect")(p,da);if(ea==p.length)return w.year(ba,z);if(!ea)return v.ticks(z).map(l);if(Math.log(da/p[ea-1])<Math.log(p[ea]/da))--ea;z=w[ea];aa=z[1];z=z[0].range;}return z(ba[0],new Date(+ba[1]+1),aa);};y.tickFormat=function(){return x;};y.copy=function(){return j(v.copy(),w,x);};return c("d3/core/rebind")(y,v,"range","rangeRound","interpolate","clamp");}function k(v){var w=v[0],x=v[v.length-1];return w<x?[w,x]:[x,w];}function l(v){return new Date(v);}function m(v){return function(w){var x=v.length-1,y=v[x];while(!y[1](w))y=v[--x];return y[0](w);};}function n(v){var w=new Date(v,0,1);w.setFullYear(v);return w;}function o(v){var w=v.getFullYear(),x=n(w),y=n(w+1);return w+(v-x)/(y-x);}var p=[1000,5000,15000,30000,60000,300000,900000,1800000,3600000,10800000,21600000,43200000,86400000,172800000,604800000,2.592e+09,7.776e+09,3.1536e+10],q=[[c("d3/time/second"),1],[c("d3/time/second"),5],[c("d3/time/second"),15],[c("d3/time/second"),30],[c("d3/time/minute"),1],[c("d3/time/minute"),5],[c("d3/time/minute"),15],[c("d3/time/minute"),30],[c("d3/time/hour"),1],[c("d3/time/hour"),3],[c("d3/time/hour"),6],[c("d3/time/hour"),12],[c("d3/time/day"),1],[c("d3/time/day"),2],[c("d3/time/week"),1],[c("d3/time/month"),1],[c("d3/time/month"),3],[c("d3/time/year"),1]],r=[[c("d3/time/format")("%Y"),i],[c("d3/time/format")("%B"),function(v){return v.getMonth();}],[c("d3/time/format")("%b %d"),function(v){return v.getDate()!=1;}],[c("d3/time/format")("%a %d"),function(v){return v.getDay()&&v.getDate()!=1;}],[c("d3/time/format")("%I %p"),function(v){return v.getHours();}],[c("d3/time/format")("%I:%M"),function(v){return v.getMinutes();}],[c("d3/time/format")(":%S"),function(v){return v.getSeconds();}],[c("d3/time/format")(".%L"),function(v){return v.getMilliseconds();}]],s=c("d3/scale/linear")(),t=m(r);q.year=function(v,w){return s.domain(v.map(o)).ticks(w).map(n);};var u=function v(){return j(c("d3/scale/linear")(),q,t);};u._scaleLocalMethods=q;u._scaleLinear=s;u._scale=j;u._scaleFormat=m;f.exports=u;}),null);
__d("d3/time/scale-utc",["d3/time/scale","d3/core/true","d3/time/format-utc","d3/scale/linear"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c("d3/time/scale")._scaleLocalMethods,i=c("d3\/core\/true")._true,j=c("d3/time/scale")._scaleFormat,k=c("d3/time/scale")._scaleLinear,l=c("d3/time/scale")._scale,m=h.map(function(s){return [s[0].utc,s[1]];}),n=[[c("d3/time/format-utc")("%Y"),i],[c("d3/time/format-utc")("%B"),function(s){return s.getUTCMonth();}],[c("d3/time/format-utc")("%b %d"),function(s){return s.getUTCDate()!=1;}],[c("d3/time/format-utc")("%a %d"),function(s){return s.getUTCDay()&&s.getUTCDate()!=1;}],[c("d3/time/format-utc")("%I %p"),function(s){return s.getUTCHours();}],[c("d3/time/format-utc")("%I:%M"),function(s){return s.getUTCMinutes();}],[c("d3/time/format-utc")(":%S"),function(s){return s.getUTCSeconds();}],[c("d3/time/format-utc")(".%L"),function(s){return s.getUTCMilliseconds();}]],o=j(n);function p(s){var t=new Date(Date.UTC(s,0,1));t.setUTCFullYear(s);return t;}function q(s){var t=s.getUTCFullYear(),u=p(t),v=p(t+1);return t+(s-u)/(v-u);}m.year=function(s,t){return k.domain(s.map(q)).ticks(t).map(p);};var r=function s(){return l(c("d3/scale/linear")(),m,o);};f.exports=r;}),null);
__d("d3/d3.time",["d3/time/time","d3/time/format","d3/time/format-utc","d3/time/format-iso","d3/time/second","d3/time/minute","d3/time/hour","d3/time/day","d3/time/week","d3/time/month","d3/time/year","d3/time/scale","d3/time/scale-utc"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/time/time").format=c("d3\/time\/format");c("d3/time/time").format.utc=c("d3\/time\/format-utc");c("d3/time/time").format.iso=c("d3\/time\/format-iso");c("d3/time/time").second=c("d3\/time\/second");c("d3/time/time").seconds=c("d3\/time\/second").s;c("d3/time/time").minute=c("d3\/time\/minute");c("d3/time/time").minutes=c("d3\/time\/minute").s;c("d3/time/time").hour=c("d3\/time\/hour");c("d3/time/time").hours=c("d3\/time\/hour").s;c("d3/time/time").day=c("d3\/time\/day");c("d3/time/time").days=c("d3\/time\/day").s;c("d3/time/time").dayOfYear=c("d3\/time\/day").ofYear;c("d3/time/time").week=c("d3\/time\/week");c("d3/time/time").weeks=c("d3\/time\/week").s;c("d3/time/time").weekOfYear=c("d3\/time\/week").ofYear;c("d3/time/time").month=c("d3\/time\/month");c("d3/time/time").months=c("d3\/time\/month").s;c("d3/time/time").year=c("d3\/time\/year");c("d3/time/time").years=c("d3\/time\/year").s;c("d3/time/time").scale=c("d3\/time\/scale");c("d3/time/time").scale.utc=c("d3\/time\/scale-utc");f.exports=c("d3/time/time");}),null);
__d("d3/d3",["d3/d3.core","d3/d3.scale","d3/d3.svg","d3/d3.behavior","d3/d3.layout","d3/d3.geo","d3/d3.dsv","d3/d3.time","d3/d3.geom"],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();c("d3/d3.core").scale=c("d3\/d3.scale");c("d3/d3.core").svg=c("d3\/d3.svg");c("d3/d3.core").behavior=c("d3\/d3.behavior");c("d3/d3.core").layout=c("d3\/d3.layout");c("d3/d3.core").geo=c("d3\/d3.geo");c("d3/d3.core").dsv=c("d3\/d3.dsv");c("d3/d3.core").time=c("d3\/d3.time");c("d3/d3.core").geom=c("d3\/d3.geom");f.exports=c("d3/d3.core");}),null);
__d('SphericalHeadingIndicator.react',['cx','d3/d3','degToRad','React','EventSubscription','shallowCompare'],(function a(b,c,d,e,f,g,h){if(c.__markCompiled)c.__markCompiled();var i=c('React').PropTypes,j=c('React').createClass({displayName:'SphericalHeadingIndicator',_currentHeading:0,_currentFOV:0,_activeCount:0,_listeners:[],propTypes:{heading:i.number.isRequired,horizontalFieldOfView:i.number.isRequired,click:i.func,imageViewer:i.object.isRequired,recenterControl:i.object.isRequired,absoluteHeading:i.bool,auto:i.bool,fullscreen:i.bool},getInitialState:function k(){return {active:false};},shouldComponentUpdate:function k(l,m){return c('shallowCompare')(this,l,m);},drawArc:function k(l,m){this._currentHeading=l;this._currentFOV=m;var n=c('degToRad')(m),o=c('degToRad')(l-(this.props.absoluteHeading?0:this.props.heading)),p=this.props.auto?o+n/2:o-n/2,q=this.props.auto?o-n/2+2*Math.PI:o+n/2,r=c('d3/d3').svg.arc().innerRadius(this.props.fullscreen?5:3.5).outerRadius(this.props.fullscreen?13:9).startAngle(p).endAngle(q);c('d3/d3').select(this.refs.arc).attr('d',r);},setActive:function k(l){this._activeCount+=l?1:-1;if(l||this._activeCount===0)this.setState({active:l});},componentDidUpdate:function k(l,m){var n=l.heading!==this.props.heading?this.props.heading:this._currentHeading,o=l.horizontalFieldOfView!==this.props.horizontalFieldOfView?this.props.horizontalFieldOfView:this._currentFOV;this.drawArc(n,o);},componentDidMount:function k(){this.drawArc(this.props.heading,this.props.horizontalFieldOfView);this._listeners.push(this.props.imageViewer.addListener('updateViewportBegin',function(){return this.setActive(true);}.bind(this)));this._listeners.push(this.props.imageViewer.addListener('updateViewportEnd',function(){return setTimeout(function(){return this.setActive(false);}.bind(this),1000);}.bind(this)));this._listeners.push(this.props.imageViewer.addListener('viewportChange',function(l,m,n){this._currentFOV=n;this.drawArc(l,this._currentFOV);}.bind(this)));this._listeners.push(this.props.recenterControl.addListener('animationStart',function(){return this.setActive(true);}.bind(this)));this._listeners.push(this.props.recenterControl.addListener('animationEnd',function(){return setTimeout(function(){return this.setActive(false);}.bind(this),1000);}.bind(this)));},componentWillUnmount:function k(){this._removeListeners();},_removeListeners:function k(){this._listeners.forEach(function(l){return l.remove();});this._listeners=[];},render:function k(){var l=this.props.fullscreen?50:35,m=l/2,n=this.props.fullscreen?'22.75,7 27.25,7 25,2.5':'15,5 20,5 17.5,2',o='translate('+m+','+m+')',p=c('React').createElement('circle',{className:"_4zph",cx:m,cy:m,r:this.props.fullscreen?17.25:12,style:{strokeWidth:this.props.fullscreen?1.5:1}}),q=this.props.auto?null:c('React').createElement('circle',{cx:m,cy:m,r:this.props.fullscreen?3:2}),r=this.props.auto?c('React').createElement('circle',{className:"_5qyh",cx:m,cy:m,r:this.props.fullscreen?14.75:10.25,style:{strokeWidth:this.props.fullscreen?3.75:2.75}}):null,s=this.props.auto?c('React').createElement('circle',{className:"_5qyh",cx:m,cy:m,r:this.props.fullscreen?4:2.75,style:{strokeWidth:this.props.fullscreen?2.25:1.75}}):null,t=this.props.auto?c('React').createElement('div',{className:"_5qyr",style:{top:this.props.fullscreen?'54.5px':'38px'}},'AUTO'):null;return (c('React').createElement('div',{className:"_5qys"+(this.state.active?' '+"_4zpe":''),style:{width:l+'px',height:l+'px'}},c('React').createElement('svg',{onClick:this.props.click,className:"_5qyy",width:l,height:l},c('React').createElement('g',{className:"_4zpd"+(this.state.active?' '+"_4zpe":'')},c('React').createElement('circle',{cx:m,cy:m,r:m}),c('React').createElement('g',{className:"_4zpf"+(this.state.active?' '+"_4zpe":'')},c('React').createElement('circle',{className:"_4zpg",cx:m,cy:m,r:m}),p,r,s,q,c('React').createElement('polygon',{points:n}),c('React').createElement('g',{transform:o},c('React').createElement('path',{ref:'arc'}))))),t));}});f.exports=j;}),null);
__d('easeInOutInterpolate',['invariant'],(function a(b,c,d,e,f,g,h){if(c.__markCompiled)c.__markCompiled();var i=function j(k){!(k>=0&&k<=1)?h(0):void 0;return Math.cos((k+1)*Math.PI)/2+.5;};f.exports=i;}),null);
__d('SphericalRecenterControl',['easeInOutInterpolate','requestAnimationFrame','SphericalImageViewer','EventEmitter'],(function a(b,c,d,e,f,g){var h,i;if(c.__markCompiled)c.__markCompiled();var j=1000;h=babelHelpers.inherits(k,c('EventEmitter'));i=h&&h.prototype;function k(l,m,n){'use strict';i.constructor.call(this);this.$SphericalRecenterControl3=l;this.$SphericalRecenterControl2=n;this.$SphericalRecenterControl1=false;this.$SphericalRecenterControl7=this.$SphericalRecenterControl9.bind(this);this.$SphericalRecenterControl6={x:m.x,y:m.y};this.$SphericalRecenterControl5=this.$SphericalRecenterControl6;l.addListener('updateViewportBegin',function(){return this.$SphericalRecenterControl10();}.bind(this));l.addListener('viewportChange',function(o,p){return this.$SphericalRecenterControl5={x:o,y:p};}.bind(this));}k.prototype.recenter=function(){'use strict';if(this.$SphericalRecenterControl1||this.$SphericalRecenterControl2)return;this.$SphericalRecenterControl1=true;this.$SphericalRecenterControl4=Date.now();var l=this.$SphericalRecenterControl5,m=this.$SphericalRecenterControl6.x-l.x;if(Math.abs(m)>180)m=m>0?m-360:m+360;this.$SphericalRecenterControl8={basePitch:l.y,deltaPitch:this.$SphericalRecenterControl6.y-l.y,baseYaw:l.x,deltaYaw:m};this.emit('animationStart');c('requestAnimationFrame')(this.$SphericalRecenterControl7);};k.prototype.$SphericalRecenterControl10=function(){'use strict';this.$SphericalRecenterControl1=false;};k.prototype.$SphericalRecenterControl9=function(){'use strict';if(!this.$SphericalRecenterControl1){this.emit('animationEnd');return;}var l=Date.now();if(l-this.$SphericalRecenterControl4>j){this.$SphericalRecenterControl1=false;this.emit('animationEnd');return;}c('requestAnimationFrame')(this.$SphericalRecenterControl7);var m=this.$SphericalRecenterControl8,n=c('easeInOutInterpolate')((l-this.$SphericalRecenterControl4)/j),o=m.deltaPitch*n+m.basePitch,p=m.deltaYaw*n+m.baseYaw;this.$SphericalRecenterControl3.setSphericalOrientation(p,o);};f.exports=k;}),null);
__d('SphericalImageHeadingIndicator',['cx','Event','DeferredComponent.react','React','ReactDOM','SphericalImageViewer','SphericalRecenterControl','cancelAnimationFrame','destroyOnUnload','requestAnimationFrame','SphericalPhotoViewerLoggerUtil'],(function a(b,c,d,e,f,g,h){if(c.__markCompiled)c.__markCompiled();var i=c('SphericalPhotoViewerLoggerUtil').logTapHeadingIndicator;function j(k,l,m,n,o){'use strict';this.$SphericalImageHeadingIndicator1=o;this.$SphericalImageHeadingIndicator2=k;this.$SphericalImageHeadingIndicator4=l;this.$SphericalImageHeadingIndicator8=m;this.$SphericalImageHeadingIndicator9=n;this.$SphericalImageHeadingIndicator5=null;this.$SphericalImageHeadingIndicator11=k.getOrientation();this.$SphericalImageHeadingIndicator12();c('destroyOnUnload')(function(){return this.$SphericalImageHeadingIndicator13();}.bind(this));}j.prototype.$SphericalImageHeadingIndicator13=function(){'use strict';if(this.$SphericalImageHeadingIndicator10){this.$SphericalImageHeadingIndicator10.remove();this.$SphericalImageHeadingIndicator10=null;}c('ReactDOM').unmountComponentAtNode(this.$SphericalImageHeadingIndicator4);};j.prototype.setFullscreen=function(k){'use strict';if(this.$SphericalImageHeadingIndicator9!=k)this.$SphericalImageHeadingIndicator14();this.$SphericalImageHeadingIndicator9=k;};j.prototype.$SphericalImageHeadingIndicator12=function(){'use strict';this.$SphericalImageHeadingIndicator3=new (c('SphericalRecenterControl'))(this.$SphericalImageHeadingIndicator2,this.$SphericalImageHeadingIndicator11,false);this.$SphericalImageHeadingIndicator14();this.$SphericalImageHeadingIndicator10=c('Event').listen(this.$SphericalImageHeadingIndicator4,'click',function(k){return this.$SphericalImageHeadingIndicator15(k);}.bind(this));};j.prototype.$SphericalImageHeadingIndicator15=function(k){'use strict';c('Event').kill(k);this.$SphericalImageHeadingIndicator3.recenter();i({photoID:this.$SphericalImageHeadingIndicator1});};j.prototype.$SphericalImageHeadingIndicator14=function(){'use strict';c('cancelAnimationFrame')(this.$SphericalImageHeadingIndicator5);this.$SphericalImageHeadingIndicator5=c('requestAnimationFrame')(function(){return this.$SphericalImageHeadingIndicator16();}.bind(this));};j.prototype.$SphericalImageHeadingIndicator16=function(){'use strict';c('ReactDOM').render(c('React').createElement('button',{className:"_q52"+(this.$SphericalImageHeadingIndicator8?' '+"_42a0":'')},c('React').createElement(c('DeferredComponent.react'),{deferredPlaceholder:c('React').createElement('span',null),deferredComponent:function k(l){return (e(['SphericalHeadingIndicator.react'],l));},heading:this.$SphericalImageHeadingIndicator11.x,horizontalFieldOfView:this.$SphericalImageHeadingIndicator2.getHorizontalFieldOfView(),imageViewer:this.$SphericalImageHeadingIndicator2,recenterControl:this.$SphericalImageHeadingIndicator3,fullscreen:this.$SphericalImageHeadingIndicator9})),this.$SphericalImageHeadingIndicator4);};f.exports=j;}),null);
__d('SphericalMediaUtils',['UserAgent'],(function a(b,c,d,e,f,g){if(c.__markCompiled)c.__markCompiled();var h=c('UserAgent').isBrowser('Chrome'),i=c('UserAgent').isBrowser('Safari'),j=c('UserAgent').isBrowser('Firefox');f.exports={getZoomLevel:function k(){var l=void 0;if(h||i){l=Math.round(window.outerWidth/window.innerWidth);}else if(j)l=Math.round(window.devicePixelRatio);return l||1;},getPixelRatio:function k(){return window.devicePixelRatio||1;},normalizeOrientation:function k(l){var m=l.pitch,n=l.yaw;return {pitch:m!==0?-m:0,yaw:n};}};}),null);
__d('PhotoSnowliftViewableSphericalPhoto',['cx','CSS','DOM','EncryptedImg','Event','FullScreen','ImageUtils','ResizeEventHandler','SphericalMediaUtils','SphericalCastingButton','SphericalImageHeadingIndicator','SphericalImageViewer','SphericalPhotoCastingComponent','SphericalPhotoConfig','Vector','VideoProjection','PhotoSnowliftViewable','getViewportDimensions','SphericalPhotoViewerLoggerUtil'],(function a(b,c,d,e,f,g,h){var i,j;if(c.__markCompiled)c.__markCompiled();var k=c('PhotoSnowliftViewable').Viewable,l=c('SphericalPhotoViewerLoggerUtil').logEnterSnowlift,m=c('SphericalPhotoViewerLoggerUtil').logExitSnowlift,n=c('SphericalPhotoViewerLoggerUtil').logEnterFullScreen,o=c('SphericalPhotoViewerLoggerUtil').logExitFullScreen,p=2000*16;function q(u,v){var w;if(u.src&&u.complete){setTimeout(v,0);}else (function(){var x=c('Event').listen(u,'load',function(){x.remove();v();});})();}function r(u,v){if(c('EncryptedImg').isEncrypted(v)){c('EncryptedImg').insertIntoDOM(v,u);}else u.src=v;}i=babelHelpers.inherits(s,k);j=i&&i.prototype;function s(u,v,w,x,y,z){var aa=arguments.length<=6||arguments[6]===undefined?false:arguments[6],ba=arguments[7],ca=arguments[8],da=arguments[9];'use strict';j.constructor.call(this,p);t.call(this);this.$PhotoSnowliftViewableSphericalPhoto3=ba;this.$PhotoSnowliftViewableSphericalPhoto13=u;this.$PhotoSnowliftViewableSphericalPhoto12=v;this.$PhotoSnowliftViewableSphericalPhoto7=aa;this.$PhotoSnowliftViewableSphericalPhoto2=w;this.$PhotoSnowliftViewableSphericalPhoto9=x;var ea=c('SphericalMediaUtils').normalizeOrientation({pitch:y,yaw:z}),fa=ea.pitch,ga=ea.yaw;this.$PhotoSnowliftViewableSphericalPhoto10=fa;this.$PhotoSnowliftViewableSphericalPhoto11=ga;this.$PhotoSnowliftViewableSphericalPhoto4=false;this.$PhotoSnowliftViewableSphericalPhoto15=ca;this.$PhotoSnowliftViewableSphericalPhoto16=da;this.addListener('cubestriploaded',function(ha){return this.$PhotoSnowliftViewableSphericalPhoto20(ha);}.bind(this));this.addListener('initialviewloaded',function(ha){return this.$PhotoSnowliftViewableSphericalPhoto21(ha);}.bind(this));this.addListener('ready',function(){return this.$PhotoSnowliftViewableSphericalPhoto22();}.bind(this));this.$PhotoSnowliftViewableSphericalPhoto23();}s.prototype.$PhotoSnowliftViewableSphericalPhoto23=function(){'use strict';var u=this.getElement();this.$PhotoSnowliftViewableSphericalPhoto1=c('DOM').create('img',{className:'hidden_elem'});this.$PhotoSnowliftViewableSphericalPhoto1.crossOrigin='anonymous';r(this.$PhotoSnowliftViewableSphericalPhoto1,this.$PhotoSnowliftViewableSphericalPhoto2);u.appendChild(this.$PhotoSnowliftViewableSphericalPhoto1);this.$PhotoSnowliftViewableSphericalPhoto8=c('DOM').create('img',{});r(this.$PhotoSnowliftViewableSphericalPhoto8,this.$PhotoSnowliftViewableSphericalPhoto24());u.appendChild(this.$PhotoSnowliftViewableSphericalPhoto8);var v=this.$PhotoSnowliftViewableSphericalPhoto8;q(this.$PhotoSnowliftViewableSphericalPhoto8,function(){return this.emit('initialviewloaded',v);}.bind(this));this.$PhotoSnowliftViewableSphericalPhoto5=c('DOM').create('div',{className:"_3lfe"});var w=new (c('ResizeEventHandler'))(this.setDimensionsToRoot);this.$PhotoSnowliftViewableSphericalPhoto17=c('Event').listen(window,'resize',w.handleEvent);u.appendChild(this.$PhotoSnowliftViewableSphericalPhoto5);this.$PhotoSnowliftViewableSphericalPhoto19=c('DOM').create('div',{});u.appendChild(this.$PhotoSnowliftViewableSphericalPhoto19);l({photoID:this.$PhotoSnowliftViewableSphericalPhoto16});};s.prototype.$PhotoSnowliftViewableSphericalPhoto21=function(u){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto8!==u)return;var v=this.$PhotoSnowliftViewableSphericalPhoto1;q(this.$PhotoSnowliftViewableSphericalPhoto1,function(){return this.emit('cubestriploaded',v);}.bind(this));};s.prototype.$PhotoSnowliftViewableSphericalPhoto20=function(u){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto1!==u)return;this.emit('ready');this.setDimensionsToRoot();};s.prototype.suspend=function(){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto14)this.$PhotoSnowliftViewableSphericalPhoto14.suspend();};s.prototype.resume=function(){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto14)this.$PhotoSnowliftViewableSphericalPhoto14.resume();};s.prototype.reload=function(){'use strict';this.$PhotoSnowliftViewableSphericalPhoto23();};s.prototype.hide=function(){'use strict';if(c('CSS').shown(this.getElement()))m({photoID:this.$PhotoSnowliftViewableSphericalPhoto16});j.hide.call(this);if(this.$PhotoSnowliftViewableSphericalPhoto17){this.$PhotoSnowliftViewableSphericalPhoto17.remove();this.$PhotoSnowliftViewableSphericalPhoto17=null;}};s.prototype.$PhotoSnowliftViewableSphericalPhoto25=function(u){'use strict';var v={projectionType:c('VideoProjection').UNPADDED_CUBESTRIP,fieldOfView:this.$PhotoSnowliftViewableSphericalPhoto9,initialHeading:this.$PhotoSnowliftViewableSphericalPhoto11,initialPitch:this.$PhotoSnowliftViewableSphericalPhoto10,enableZoom:true};if(!u&&this.$PhotoSnowliftViewableSphericalPhoto15)v.partialLimits=this.$PhotoSnowliftViewableSphericalPhoto15;return v;};s.prototype.$PhotoSnowliftViewableSphericalPhoto22=function(){'use strict';var u=this.$PhotoSnowliftViewableSphericalPhoto25(this.$PhotoSnowliftViewableSphericalPhoto4),v=this.getNaturalDimensions();if(c('SphericalPhotoConfig').connected_tv_cast_spherical_photo){var w=700,x={WWW:v.x,TV:w},y={WWW:v.y,TV:w};this.$PhotoSnowliftViewableSphericalPhoto14=new (c('SphericalPhotoCastingComponent'))(this.getElement(),this.$PhotoSnowliftViewableSphericalPhoto1,this.$PhotoSnowliftViewableSphericalPhoto8,null,u,x,y,this.$PhotoSnowliftViewableSphericalPhoto16,this.$PhotoSnowliftViewableSphericalPhoto2,this.$PhotoSnowliftViewableSphericalPhoto24());}else this.$PhotoSnowliftViewableSphericalPhoto14=new (c('SphericalImageViewer'))(this.getElement(),this.$PhotoSnowliftViewableSphericalPhoto1,this.$PhotoSnowliftViewableSphericalPhoto8,null,u,v.x,v.y,this.$PhotoSnowliftViewableSphericalPhoto16);this.$PhotoSnowliftViewableSphericalPhoto6=new (c('SphericalImageHeadingIndicator'))(this.$PhotoSnowliftViewableSphericalPhoto14,this.$PhotoSnowliftViewableSphericalPhoto5,false,c('FullScreen').isFullScreen(),this.$PhotoSnowliftViewableSphericalPhoto16);if(this.$PhotoSnowliftViewableSphericalPhoto14)this.$PhotoSnowliftViewableSphericalPhoto18=new (c('SphericalCastingButton'))(this.$PhotoSnowliftViewableSphericalPhoto14,this.$PhotoSnowliftViewableSphericalPhoto19,true);};s.prototype.$PhotoSnowliftViewableSphericalPhoto24=function(){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto7)return this.$PhotoSnowliftViewableSphericalPhoto13;return this.$PhotoSnowliftViewableSphericalPhoto12||this.$PhotoSnowliftViewableSphericalPhoto13;};s.prototype.getNaturalDimensions=function(){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto4){var u=c('getViewportDimensions')();return c('Vector').from(u.width,u.height);}if(this.$PhotoSnowliftViewableSphericalPhoto3)return this.$PhotoSnowliftViewableSphericalPhoto3;if(this.$PhotoSnowliftViewableSphericalPhoto8&&this.$PhotoSnowliftViewableSphericalPhoto8.naturalWidth&&this.$PhotoSnowliftViewableSphericalPhoto8.naturalHeight)return c('Vector').from(this.$PhotoSnowliftViewableSphericalPhoto8.naturalWidth,this.$PhotoSnowliftViewableSphericalPhoto8.naturalHeight);return j.getNaturalDimensions.call(this);};s.prototype.isReady=function(){'use strict';return (this.$PhotoSnowliftViewableSphericalPhoto8&&this.$PhotoSnowliftViewableSphericalPhoto8.src&&c('ImageUtils').hasLoaded(this.$PhotoSnowliftViewableSphericalPhoto8)||this.$PhotoSnowliftViewableSphericalPhoto1&&this.$PhotoSnowliftViewableSphericalPhoto1.src&&c('ImageUtils').hasLoaded(this.$PhotoSnowliftViewableSphericalPhoto1));};s.prototype.onToggleIntoFullScreen=function(){'use strict';};s.prototype.onEnterFullScreen=function(){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto4)return;var u=this.$PhotoSnowliftViewableSphericalPhoto14;this.$PhotoSnowliftViewableSphericalPhoto4=true;var v=c('getViewportDimensions')(),w=c('Vector').from(v.width,v.height);this.setDimensions(w);if(u){var x=this.$PhotoSnowliftViewableSphericalPhoto25(this.$PhotoSnowliftViewableSphericalPhoto4);u.reconfigure(x);u.setDimensions(w);}if(this.$PhotoSnowliftViewableSphericalPhoto6)this.$PhotoSnowliftViewableSphericalPhoto6.setFullscreen(true);n({photoID:this.$PhotoSnowliftViewableSphericalPhoto16});};s.prototype.onExitFullScreen=function(){'use strict';if(!this.$PhotoSnowliftViewableSphericalPhoto4)return;var u=this.$PhotoSnowliftViewableSphericalPhoto14;this.$PhotoSnowliftViewableSphericalPhoto4=false;var v=this.getNaturalDimensions();this.setDimensions(v);if(u){var w=this.$PhotoSnowliftViewableSphericalPhoto25(this.$PhotoSnowliftViewableSphericalPhoto4);u.reconfigure(w);u.setDimensions(v);}if(this.$PhotoSnowliftViewableSphericalPhoto6)this.$PhotoSnowliftViewableSphericalPhoto6.setFullscreen(false);o({photoID:this.$PhotoSnowliftViewableSphericalPhoto16});};s.prototype.getOrientation=function(){'use strict';if(this.$PhotoSnowliftViewableSphericalPhoto14){return this.$PhotoSnowliftViewableSphericalPhoto14.getOrientation();}else return null;};var t=function u(){this.setDimensionsToRoot=function(){var v=this.$PhotoSnowliftViewableSphericalPhoto5;if(!v)return;var w=c('Vector').from(v.offsetWidth,v.offsetHeight);this.setDimensions(w);var x=this.$PhotoSnowliftViewableSphericalPhoto14;if(x)x.setDimensions(w);}.bind(this);};f.exports=s;}),null);
|
// this helper can add/remove node classnames
// and provides saving classname while 2+ modals are opening and closing
// based on https://github.com/reactjs/react-modal/blob/master/src/helpers/classList.js
const classPoll = {};
const incrementReference = (poll, className) => {
if (!poll[className]) {
poll[className] = 0;
}
poll[className] += 1;
return className;
};
const decrementReference = (poll, className) => {
if (poll[className]) {
poll[className] -= 1;
}
return className;
};
const trackClass = (classListRef, poll, classes) => {
classes.forEach((className) => {
incrementReference(poll, className);
classListRef.add(className);
});
};
const untrackClass = (classListRef, poll, classes) => {
classes.forEach((className) => {
decrementReference(poll, className);
if (poll[className] === 0) {
classListRef.remove(className);
}
});
};
export const add = (element, classString) => trackClass(
element.classList,
classPoll,
classString.split(' '),
);
export const remove = (element, classString) => untrackClass(
element.classList,
classPoll,
classString.split(' '),
);
|
# -*- coding: utf-8 -*-
"""Warning : this file has been generated, you shouldn't edit it"""
from os import linesep
from pyleecan.Classes.check import check_init_dict, check_var, raise_
from pyleecan.Functions.save import save
from pyleecan.Classes.SlotWind import SlotWind
# Import all class method
# Try/catch to remove unnecessary dependencies in unused method
try:
from pyleecan.Methods.Slot.SlotW60._comp_point_coordinate import (
_comp_point_coordinate,
)
except ImportError as error:
_comp_point_coordinate = error
try:
from pyleecan.Methods.Slot.SlotW60.build_geometry import build_geometry
except ImportError as error:
build_geometry = error
try:
from pyleecan.Methods.Slot.SlotW60.build_geometry_wind import build_geometry_wind
except ImportError as error:
build_geometry_wind = error
try:
from pyleecan.Methods.Slot.SlotW60.check import check
except ImportError as error:
check = error
try:
from pyleecan.Methods.Slot.SlotW60.comp_angle_opening import comp_angle_opening
except ImportError as error:
comp_angle_opening = error
try:
from pyleecan.Methods.Slot.SlotW60.comp_height import comp_height
except ImportError as error:
comp_height = error
try:
from pyleecan.Methods.Slot.SlotW60.comp_height_wind import comp_height_wind
except ImportError as error:
comp_height_wind = error
try:
from pyleecan.Methods.Slot.SlotW60.comp_surface import comp_surface
except ImportError as error:
comp_surface = error
try:
from pyleecan.Methods.Slot.SlotW60.comp_surface_wind import comp_surface_wind
except ImportError as error:
comp_surface_wind = error
from pyleecan.Classes.check import InitUnKnowClassError
class SlotW60(SlotWind):
VERSION = 1
IS_SYMMETRICAL = 0
# Check ImportError to remove unnecessary dependencies in unused method
# cf Methods.Slot.SlotW60._comp_point_coordinate
if isinstance(_comp_point_coordinate, ImportError):
_comp_point_coordinate = property(
fget=lambda x: raise_(
ImportError(
"Can't use SlotW60 method _comp_point_coordinate: "
+ str(_comp_point_coordinate)
)
)
)
else:
_comp_point_coordinate = _comp_point_coordinate
# cf Methods.Slot.SlotW60.build_geometry
if isinstance(build_geometry, ImportError):
build_geometry = property(
fget=lambda x: raise_(
ImportError(
"Can't use SlotW60 method build_geometry: " + str(build_geometry)
)
)
)
else:
build_geometry = build_geometry
# cf Methods.Slot.SlotW60.build_geometry_wind
if isinstance(build_geometry_wind, ImportError):
build_geometry_wind = property(
fget=lambda x: raise_(
ImportError(
"Can't use SlotW60 method build_geometry_wind: "
+ str(build_geometry_wind)
)
)
)
else:
build_geometry_wind = build_geometry_wind
# cf Methods.Slot.SlotW60.check
if isinstance(check, ImportError):
check = property(
fget=lambda x: raise_(
ImportError("Can't use SlotW60 method check: " + str(check))
)
)
else:
check = check
# cf Methods.Slot.SlotW60.comp_angle_opening
if isinstance(comp_angle_opening, ImportError):
comp_angle_opening = property(
fget=lambda x: raise_(
ImportError(
"Can't use SlotW60 method comp_angle_opening: "
+ str(comp_angle_opening)
)
)
)
else:
comp_angle_opening = comp_angle_opening
# cf Methods.Slot.SlotW60.comp_height
if isinstance(comp_height, ImportError):
comp_height = property(
fget=lambda x: raise_(
ImportError("Can't use SlotW60 method comp_height: " + str(comp_height))
)
)
else:
comp_height = comp_height
# cf Methods.Slot.SlotW60.comp_height_wind
if isinstance(comp_height_wind, ImportError):
comp_height_wind = property(
fget=lambda x: raise_(
ImportError(
"Can't use SlotW60 method comp_height_wind: "
+ str(comp_height_wind)
)
)
)
else:
comp_height_wind = comp_height_wind
# cf Methods.Slot.SlotW60.comp_surface
if isinstance(comp_surface, ImportError):
comp_surface = property(
fget=lambda x: raise_(
ImportError(
"Can't use SlotW60 method comp_surface: " + str(comp_surface)
)
)
)
else:
comp_surface = comp_surface
# cf Methods.Slot.SlotW60.comp_surface_wind
if isinstance(comp_surface_wind, ImportError):
comp_surface_wind = property(
fget=lambda x: raise_(
ImportError(
"Can't use SlotW60 method comp_surface_wind: "
+ str(comp_surface_wind)
)
)
)
else:
comp_surface_wind = comp_surface_wind
# save method is available in all object
save = save
def __init__(
self,
W1=0.02,
W2=0.03,
H1=0.05,
H2=0.15,
R1=0.03,
H3=0,
H4=0,
W3=0,
Zs=36,
init_dict=None,
):
"""Constructor of the class. Can be use in two ways :
- __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
for Matrix, None will initialise the property with an empty Matrix
for pyleecan type, None will call the default constructor
- __init__ (init_dict = d) d must be a dictionnary wiht every properties as keys
ndarray or list can be given for Vector and Matrix
object or dict can be given for pyleecan Object"""
if init_dict is not None: # Initialisation by dict
check_init_dict(
init_dict, ["W1", "W2", "H1", "H2", "R1", "H3", "H4", "W3", "Zs"]
)
# Overwrite default value with init_dict content
if "W1" in list(init_dict.keys()):
W1 = init_dict["W1"]
if "W2" in list(init_dict.keys()):
W2 = init_dict["W2"]
if "H1" in list(init_dict.keys()):
H1 = init_dict["H1"]
if "H2" in list(init_dict.keys()):
H2 = init_dict["H2"]
if "R1" in list(init_dict.keys()):
R1 = init_dict["R1"]
if "H3" in list(init_dict.keys()):
H3 = init_dict["H3"]
if "H4" in list(init_dict.keys()):
H4 = init_dict["H4"]
if "W3" in list(init_dict.keys()):
W3 = init_dict["W3"]
if "Zs" in list(init_dict.keys()):
Zs = init_dict["Zs"]
# Initialisation by argument
self.W1 = W1
self.W2 = W2
self.H1 = H1
self.H2 = H2
self.R1 = R1
self.H3 = H3
self.H4 = H4
self.W3 = W3
# Call SlotWind init
super(SlotW60, self).__init__(Zs=Zs)
# The class is frozen (in SlotWind init), for now it's impossible to
# add new properties
def __str__(self):
"""Convert this objet in a readeable string (for print)"""
SlotW60_str = ""
# Get the properties inherited from SlotWind
SlotW60_str += super(SlotW60, self).__str__() + linesep
SlotW60_str += "W1 = " + str(self.W1) + linesep
SlotW60_str += "W2 = " + str(self.W2) + linesep
SlotW60_str += "H1 = " + str(self.H1) + linesep
SlotW60_str += "H2 = " + str(self.H2) + linesep
SlotW60_str += "R1 = " + str(self.R1) + linesep
SlotW60_str += "H3 = " + str(self.H3) + linesep
SlotW60_str += "H4 = " + str(self.H4) + linesep
SlotW60_str += "W3 = " + str(self.W3)
return SlotW60_str
def __eq__(self, other):
"""Compare two objects (skip parent)"""
if type(other) != type(self):
return False
# Check the properties inherited from SlotWind
if not super(SlotW60, self).__eq__(other):
return False
if other.W1 != self.W1:
return False
if other.W2 != self.W2:
return False
if other.H1 != self.H1:
return False
if other.H2 != self.H2:
return False
if other.R1 != self.R1:
return False
if other.H3 != self.H3:
return False
if other.H4 != self.H4:
return False
if other.W3 != self.W3:
return False
return True
def as_dict(self):
"""Convert this objet in a json seriable dict (can be use in __init__)
"""
# Get the properties inherited from SlotWind
SlotW60_dict = super(SlotW60, self).as_dict()
SlotW60_dict["W1"] = self.W1
SlotW60_dict["W2"] = self.W2
SlotW60_dict["H1"] = self.H1
SlotW60_dict["H2"] = self.H2
SlotW60_dict["R1"] = self.R1
SlotW60_dict["H3"] = self.H3
SlotW60_dict["H4"] = self.H4
SlotW60_dict["W3"] = self.W3
# The class name is added to the dict fordeserialisation purpose
# Overwrite the mother class name
SlotW60_dict["__class__"] = "SlotW60"
return SlotW60_dict
def _set_None(self):
"""Set all the properties to None (except pyleecan object)"""
self.W1 = None
self.W2 = None
self.H1 = None
self.H2 = None
self.R1 = None
self.H3 = None
self.H4 = None
self.W3 = None
# Set to None the properties inherited from SlotWind
super(SlotW60, self)._set_None()
def _get_W1(self):
"""getter of W1"""
return self._W1
def _set_W1(self, value):
"""setter of W1"""
check_var("W1", value, "float", Vmin=0)
self._W1 = value
# Pole top width
# Type : float, min = 0
W1 = property(fget=_get_W1, fset=_set_W1, doc=u"""Pole top width""")
def _get_W2(self):
"""getter of W2"""
return self._W2
def _set_W2(self, value):
"""setter of W2"""
check_var("W2", value, "float", Vmin=0)
self._W2 = value
# Pole bottom width
# Type : float, min = 0
W2 = property(fget=_get_W2, fset=_set_W2, doc=u"""Pole bottom width""")
def _get_H1(self):
"""getter of H1"""
return self._H1
def _set_H1(self, value):
"""setter of H1"""
check_var("H1", value, "float", Vmin=0)
self._H1 = value
# Pole top height
# Type : float, min = 0
H1 = property(fget=_get_H1, fset=_set_H1, doc=u"""Pole top height""")
def _get_H2(self):
"""getter of H2"""
return self._H2
def _set_H2(self, value):
"""setter of H2"""
check_var("H2", value, "float", Vmin=0)
self._H2 = value
# Pole bottom height
# Type : float, min = 0
H2 = property(fget=_get_H2, fset=_set_H2, doc=u"""Pole bottom height""")
def _get_R1(self):
"""getter of R1"""
return self._R1
def _set_R1(self, value):
"""setter of R1"""
check_var("R1", value, "float", Vmin=0)
self._R1 = value
# Pole top radius
# Type : float, min = 0
R1 = property(fget=_get_R1, fset=_set_R1, doc=u"""Pole top radius""")
def _get_H3(self):
"""getter of H3"""
return self._H3
def _set_H3(self, value):
"""setter of H3"""
check_var("H3", value, "float", Vmin=0)
self._H3 = value
# Top Distance Ploe-coil
# Type : float, min = 0
H3 = property(fget=_get_H3, fset=_set_H3, doc=u"""Top Distance Ploe-coil """)
def _get_H4(self):
"""getter of H4"""
return self._H4
def _set_H4(self, value):
"""setter of H4"""
check_var("H4", value, "float", Vmin=0)
self._H4 = value
# Bottom Distance Ploe-coil
# Type : float, min = 0
H4 = property(fget=_get_H4, fset=_set_H4, doc=u"""Bottom Distance Ploe-coil """)
def _get_W3(self):
"""getter of W3"""
return self._W3
def _set_W3(self, value):
"""setter of W3"""
check_var("W3", value, "float", Vmin=0)
self._W3 = value
# Edge Distance Ploe-coil
# Type : float, min = 0
W3 = property(fget=_get_W3, fset=_set_W3, doc=u"""Edge Distance Ploe-coil """)
|
$(function(){
var $btn=$('input'),
timer,
i = 6;
timer = setInterval(function(){
i--;
if(i === 0){
clearInterval(timer);
$btn.val('同意');
$btn.removeAttr('disabled');
}else{
$btn.val('同意('+i+'s)');
}
},1000);
$btn.click(function(){
alert('就知道你会同意的');
});
})
|
var originalWebsocket = require('faye-websocket');
var proxyquire = require('proxyquire');
// Firebase has strict requirements about the hostname format. So we provide a dummy
// hostname and then change the URL to localhost inside the faye-websocket's Client
// constructor.
var firebase = proxyquire('firebase', {
'faye-websocket': {
Client: (url) => {
url = url.replace(/dummy\d+\.firebaseio\.test/i, 'localhost');
return new originalWebsocket.Client(url);
},
'@global': true
}
});
var FirebaseServer = require('firebase-server');
var FirebaseReporting = require('../dist');
const mod = {
port: 45000,
sequentialConnectionId: 0,
firebase: firebase,
newFirebaseApp: () => {
var name = 'test-firebase-client-' + mod.sequentialConnectionId;
var url = 'ws://dummy' + (mod.sequentialConnectionId++) + '.firebaseio.test:' + mod.port;
var config = {
databaseURL: url
};
return mod.firebase.initializeApp(config, name);
},
newFirebaseClient: () => {
return mod.newFirebaseApp().database().ref();
},
newFirebaseServer: (data) => {
return new FirebaseServer(mod.port, 'localhost:' + mod.port, data);
},
FirebaseReporting: FirebaseReporting
}
module.exports = mod;
|
$("#selall").click(function () {
if (!$("#selall").is(":checked")){
$(".checkbox").prop('checked', false);
}
else{
$(".checkbox").prop("checked","checked");
}
});
|
import { shallowMount } from '@vue/test-utils';
import Component from '@/pages/index.vue';
describe('Страница index', () => {
test('Корректно отображается заголовок', () => {
const wrapper = shallowMount(Component);
expect(wrapper.find('h1').text()).toBe('Главная страница');
});
});
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Meneame scraper
Usage:
scrap.py [options]
Options:
-h, --help show this screen.
--version show version.
-o DIRECTORY output directory [default: meneame].
--start START specify start page [default: 0].
--timeout TIME specify timeout after each request [default: 0].
--range RANGE specify the range. valid options\
(24h | 48h | week | month | year | all) [default: 24h].
"""
import logging
import json
from scraper.scraper import ScraperFactory
from docopt import docopt
from time import sleep
import os
SCRAPER_TYPE = 'meneame'
SCRAPER_BASE_URL = 'http://www.meneame.net/'
SCRAPER_NEWS_URL = 'topstories.php'
SCRAPER_COMMENTS_URL = 'comments_rss2.php'
# define logging configuration
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s')
def download_news(output, start=0, time_range=1, pause=1):
"""
Download news from meneame, and store them in the\
specified output directory.
:param output: the output directory
:param start: the number of page where to \
start at.
:param time_range: the time range to scrap.
:param pause: the number of seconds to wait\
after each request.
"""
output_dir = os.path.join(output, 'raw')
if not os.path.exists(output_dir):
os.makedirs(output_dir)
current_page = start # page counter
more_news = True
meneame = ScraperFactory.factory(SCRAPER_TYPE, SCRAPER_BASE_URL,
SCRAPER_NEWS_URL,
SCRAPER_COMMENTS_URL)
while more_news:
stories = meneame.scrap_page(params={
'range': time_range,
'page': current_page})
logging.info('Page %s: [%s]',
current_page,
",".join([str(story.id) for story in stories]))
for story in stories:
filepath = os.path.join(output_dir, '%s.json' % story.id)
if not os.path.exists(filepath):
logging.debug('Downloading comments for %s', story.id)
story.comments, story.published = meneame.scrap_comments(
params={'id': story.id})
logging.debug('Writing %s ...', filepath)
filename = open(filepath, 'w')
json.dump(story.to_dict(), filename)
filename.close()
sleep(pause)
else:
logging.warning('File %s already exists...', story.id)
if not stories:
more_news = False
current_page += 1
if __name__ == '__main__':
ARGS = docopt(__doc__, version='Meneame Scraper 1.0')
# transform the time range to index
try:
TIMERANGE = ['24h', '48h',
'week', 'month', 'year',
'all'].index(ARGS['--range'])
except ValueError:
logging.error('Error reading time range, not valid. Using \
default value [24h].')
TIMERANGE = 0
download_news(output=ARGS['-o'],
start=int(ARGS['--start']),
time_range=TIMERANGE,
pause=int(ARGS['--timeout']))
|
GoogleElectionMap.shapeReady({name:"19_86",type:"state",state:"19_86",bounds:[],centroid:[],shapes:[
{points:[
{x:31.2460155449588,y: 30.0489645822852}
,
{x:31.2459525127125,y: 30.0480376169998}
,
{x:31.246562154679,y: 30.0480530114094}
,
{x:31.2465802196485,y: 30.0482130556618}
,
{x:31.2462791277066,y: 30.0482308292499}
,
{x:31.2462804906972,y: 30.0483906507587}
,
{x:31.2465521541996,y: 30.0483833784059}
,
{x:31.246836540934,y: 30.0483653796592}
,
{x:31.24700424158,y: 30.0483312967428}
,
{x:31.247176566203,y: 30.0482718536698}
,
{x:31.2474623593568,y: 30.0481739715163}
,
{x:31.247584692332,y: 30.0481065966982}
,
{x:31.2476082035855,y: 30.0480805393059}
,
{x:31.2477571646307,y: 30.047915448146}
,
{x:31.2478275478781,y: 30.0478374425669}
,
{x:31.2480364391709,y: 30.047836593641}
,
{x:31.2480916912017,y: 30.0477828524131}
,
{x:31.2479748544107,y: 30.0475379607928}
,
{x:31.2480717464914,y: 30.0474920374562}
,
{x:31.2485220173233,y: 30.0473055479865}
,
{x:31.2490653826206,y: 30.0470512912819}
,
{x:31.2495958288471,y: 30.0468186494385}
,
{x:31.2498399818552,y: 30.0467129427273}
,
{x:31.250425038336,y: 30.0464628675462}
,
{x:31.2504631423255,y: 30.0463524373999}
,
{x:31.250733154719,y: 30.0455698950403}
,
{x:31.2511695352631,y: 30.0444556505558}
,
{x:31.2512374354431,y: 30.0442378370383}
,
{x:31.2512394091545,y: 30.0442315096852}
,
{x:31.2512421083012,y: 30.0442228497546}
,
{x:31.2513915152511,y: 30.04374356888}
,
{x:31.251367432095,y: 30.0436363056481}
,
{x:31.2513094075615,y: 30.043377876608}
,
{x:31.251252408157,y: 30.0431745630207}
,
{x:31.2510968358704,y: 30.0427471274869}
,
{x:31.2509808419534,y: 30.0424539036963}
,
{x:31.2508325934965,y: 30.0421399953997}
,
{x:31.2507470054674,y: 30.0419727628153}
,
{x:31.2506659284983,y: 30.0418136887309}
,
{x:31.2505120280791,y: 30.0415564235799}
,
{x:31.2504169110478,y: 30.0414012154453}
,
{x:31.2503393552542,y: 30.0413070070363}
,
{x:31.2501786634228,y: 30.0411711816243}
,
{x:31.2500225600556,y: 30.0410394699656}
,
{x:31.2498711143117,y: 30.0409078183116}
,
{x:31.249715298721,y: 30.040759904029}
,
{x:31.2494681651502,y: 30.0405054460678}
,
{x:31.249313203472,y: 30.0403089279937}
,
{x:31.2491961552056,y: 30.0401712608199}
,
{x:31.2491782568025,y: 30.0401305586948}
,
{x:31.2488360127629,y: 30.0391230223492}
,
{x:31.2482514239407,y: 30.0392717345005}
,
{x:31.2482283491201,y: 30.0392192612018}
,
{x:31.2469757390022,y: 30.0394842627844}
,
{x:31.2460840354966,y: 30.0396966870965}
,
{x:31.245839181923,y: 30.0392917443987}
,
{x:31.2455688651846,y: 30.0389699280962}
,
{x:31.2449870089468,y: 30.0386230879418}
,
{x:31.2449065507647,y: 30.0387628624547}
,
{x:31.24369453148,y: 30.038767546851}
,
{x:31.24335871791,y: 30.0387578448803}
,
{x:31.2433447901914,y: 30.0388672073375}
,
{x:31.2432307306749,y: 30.0388709004886}
,
{x:31.2432088550848,y: 30.0387506262344}
,
{x:31.2430588971351,y: 30.0387486229139}
,
{x:31.2430487417704,y: 30.0386441573206}
,
{x:31.2428940733859,y: 30.0386649257423}
,
{x:31.2427660855849,y: 30.0386821131025}
,
{x:31.2414714863998,y: 30.0389465027485}
,
{x:31.2398149513555,y: 30.0393207980188}
,
{x:31.2396670269497,y: 30.039543130642}
,
{x:31.2395765001485,y: 30.039573217599}
,
{x:31.2394926154831,y: 30.0395668778889}
,
{x:31.2392611713269,y: 30.0394229321831}
,
{x:31.2391773790374,y: 30.0394113785561}
,
{x:31.2381149700194,y: 30.0396449867031}
,
{x:31.2372318965863,y: 30.0398391532125}
,
{x:31.2362382938993,y: 30.0400449273377}
,
{x:31.2345571073545,y: 30.0404546119586}
,
{x:31.2350019634717,y: 30.042016910019}
,
{x:31.2353217973281,y: 30.0434084887803}
,
{x:31.2356141754872,y: 30.0442478504248}
,
{x:31.2357028356885,y: 30.0446906558743}
,
{x:31.235751803857,y: 30.044777141181}
,
{x:31.2358405002916,y: 30.0449337889597}
,
{x:31.2366446038694,y: 30.046140723178}
,
{x:31.2370686423319,y: 30.0467976478502}
,
{x:31.2376252831061,y: 30.0475899604859}
,
{x:31.2377040691722,y: 30.0476036000149}
,
{x:31.2378771786136,y: 30.0476550272003}
,
{x:31.2379464871504,y: 30.0477264624922}
,
{x:31.2379640478332,y: 30.0478584393315}
,
{x:31.237952316763,y: 30.0479734512805}
,
{x:31.2379178006094,y: 30.0480516965458}
,
{x:31.2379993868893,y: 30.048192341185}
,
{x:31.2389619032435,y: 30.0495210021079}
,
{x:31.2397442082521,y: 30.0506678207206}
,
{x:31.2408084725022,y: 30.0522968678847}
,
{x:31.2411365185026,y: 30.0528280895095}
,
{x:31.2411420763304,y: 30.0528278065758}
,
{x:31.2417380733573,y: 30.0527974333301}
,
{x:31.2418509251198,y: 30.0527916830873}
,
{x:31.2434940834943,y: 30.0527268922515}
,
{x:31.2458268215153,y: 30.0526555102933}
,
{x:31.2458301456688,y: 30.0526547967626}
,
{x:31.2460012789201,y: 30.0526180454013}
,
{x:31.2462061924114,y: 30.052606251117}
,
{x:31.2461913731171,y: 30.0520249556736}
,
{x:31.2461971518057,y: 30.0519342347627}
,
{x:31.2462234272132,y: 30.0518655800079}
,
{x:31.2463212822056,y: 30.0517651936116}
,
{x:31.2463721048764,y: 30.0517259220354}
,
{x:31.2465195023869,y: 30.0516588826875}
,
{x:31.2467080296061,y: 30.0516287105016}
,
{x:31.2467374574842,y: 30.051618205655}
,
{x:31.2467546115453,y: 30.0515930128399}
,
{x:31.2467592229464,y: 30.051447314449}
,
{x:31.2467640343688,y: 30.0512953246823}
,
{x:31.2467436075225,y: 30.0505577834668}
,
{x:31.2467191881926,y: 30.0505211407902}
,
{x:31.2466612268087,y: 30.0504913120571}
,
{x:31.2461735720443,y: 30.050190628451}
,
{x:31.2460155449588,y: 30.0489645822852}
]}
]})
|
/**************************************************************************//**
* @file core_cm7.h
* @brief CMSIS Cortex-M7 Core Peripheral Access Layer Header File
* @version V5.0.3
* @date 09. August 2017
******************************************************************************/
/*
* Copyright (c) 2009-2017 ARM Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef __CORE_CM7_H_GENERIC
#define __CORE_CM7_H_GENERIC
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
\page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
CMSIS violates the following MISRA-C:2004 rules:
\li Required Rule 8.5, object/function definition in header file.<br>
Function definitions in header files are used to allow 'inlining'.
\li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
Unions are used for effective representation of core registers.
\li Advisory Rule 19.7, Function-like macro defined.<br>
Function-like macros are used to allow more efficient code.
*/
/*******************************************************************************
* CMSIS definitions
******************************************************************************/
/**
\ingroup Cortex_M7
@{
*/
#include "cmsis_version.h"
/* CMSIS CM7 definitions */
#define __CM7_CMSIS_VERSION_MAIN (__CM_CMSIS_VERSION_MAIN) /*!< \deprecated [31:16] CMSIS HAL main version */
#define __CM7_CMSIS_VERSION_SUB ( __CM_CMSIS_VERSION_SUB) /*!< \deprecated [15:0] CMSIS HAL sub version */
#define __CM7_CMSIS_VERSION ((__CM7_CMSIS_VERSION_MAIN << 16U) | \
__CM7_CMSIS_VERSION_SUB ) /*!< \deprecated CMSIS HAL version number */
#define __CORTEX_M (7U) /*!< Cortex-M Core */
/** __FPU_USED indicates whether an FPU is used or not.
For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions.
*/
#if defined ( __CC_ARM )
#if defined __TARGET_FPU_VFP
#if defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)
#define __FPU_USED 1U
#else
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#define __FPU_USED 0U
#endif
#else
#define __FPU_USED 0U
#endif
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#if defined __ARM_PCS_VFP
#if defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)
#define __FPU_USED 1U
#else
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#define __FPU_USED 0U
#endif
#else
#define __FPU_USED 0U
#endif
#elif defined ( __GNUC__ )
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#if defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)
#define __FPU_USED 1U
#else
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#define __FPU_USED 0U
#endif
#else
#define __FPU_USED 0U
#endif
#elif defined ( __ICCARM__ )
#if defined __ARMVFP__
#if defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)
#define __FPU_USED 1U
#else
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#define __FPU_USED 0U
#endif
#else
#define __FPU_USED 0U
#endif
#elif defined ( __TI_ARM__ )
#if defined __TI_VFP_SUPPORT__
#if defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)
#define __FPU_USED 1U
#else
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#define __FPU_USED 0U
#endif
#else
#define __FPU_USED 0U
#endif
#elif defined ( __TASKING__ )
#if defined __FPU_VFP__
#if defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)
#define __FPU_USED 1U
#else
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#define __FPU_USED 0U
#endif
#else
#define __FPU_USED 0U
#endif
#elif defined ( __CSMC__ )
#if ( __CSMC__ & 0x400U)
#if defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)
#define __FPU_USED 1U
#else
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#define __FPU_USED 0U
#endif
#else
#define __FPU_USED 0U
#endif
#endif
#include "cmsis_compiler.h" /* CMSIS compiler specific defines */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM7_H_GENERIC */
#ifndef __CMSIS_GENERIC
#ifndef __CORE_CM7_H_DEPENDANT
#define __CORE_CM7_H_DEPENDANT
#ifdef __cplusplus
extern "C" {
#endif
/* check device defines and use defaults */
#if defined __CHECK_DEVICE_DEFINES
#ifndef __CM7_REV
#define __CM7_REV 0x0000U
#warning "__CM7_REV not defined in device header file; using default!"
#endif
#ifndef __FPU_PRESENT
#define __FPU_PRESENT 0U
#warning "__FPU_PRESENT not defined in device header file; using default!"
#endif
#ifndef __MPU_PRESENT
#define __MPU_PRESENT 0U
#warning "__MPU_PRESENT not defined in device header file; using default!"
#endif
#ifndef __ICACHE_PRESENT
#define __ICACHE_PRESENT 0U
#warning "__ICACHE_PRESENT not defined in device header file; using default!"
#endif
#ifndef __DCACHE_PRESENT
#define __DCACHE_PRESENT 0U
#warning "__DCACHE_PRESENT not defined in device header file; using default!"
#endif
#ifndef __DTCM_PRESENT
#define __DTCM_PRESENT 0U
#warning "__DTCM_PRESENT not defined in device header file; using default!"
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 3U
#warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
#endif
#ifndef __Vendor_SysTickConfig
#define __Vendor_SysTickConfig 0U
#warning "__Vendor_SysTickConfig not defined in device header file; using default!"
#endif
#endif
/* IO definitions (access restrictions to peripheral registers) */
/**
\defgroup CMSIS_glob_defs CMSIS Global Defines
<strong>IO Type Qualifiers</strong> are used
\li to specify the access to peripheral variables.
\li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
/* following defines should be used for structure members */
#define __IM volatile const /*! Defines 'read only' structure member permissions */
#define __OM volatile /*! Defines 'write only' structure member permissions */
#define __IOM volatile /*! Defines 'read / write' structure member permissions */
/*@} end of group Cortex_M7 */
/*******************************************************************************
* Register Abstraction
Core Register contain:
- Core Register
- Core NVIC Register
- Core SCB Register
- Core SysTick Register
- Core Debug Register
- Core MPU Register
- Core FPU Register
******************************************************************************/
/**
\defgroup CMSIS_core_register Defines and Type Definitions
\brief Type definitions and defines for Cortex-M processor based devices.
*/
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_CORE Status and Control Registers
\brief Core Register type definitions.
@{
*/
/**
\brief Union type to access the Application Program Status Register (APSR).
*/
typedef union
{
struct
{
uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */
uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */
uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */
uint32_t Q:1; /*!< bit: 27 Saturation condition flag */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} APSR_Type;
/* APSR Register Definitions */
#define APSR_N_Pos 31U /*!< APSR: N Position */
#define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */
#define APSR_Z_Pos 30U /*!< APSR: Z Position */
#define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */
#define APSR_C_Pos 29U /*!< APSR: C Position */
#define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */
#define APSR_V_Pos 28U /*!< APSR: V Position */
#define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */
#define APSR_Q_Pos 27U /*!< APSR: Q Position */
#define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */
#define APSR_GE_Pos 16U /*!< APSR: GE Position */
#define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */
/**
\brief Union type to access the Interrupt Program Status Register (IPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} IPSR_Type;
/* IPSR Register Definitions */
#define IPSR_ISR_Pos 0U /*!< IPSR: ISR Position */
#define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */
/**
\brief Union type to access the Special-Purpose Program Status Registers (xPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:1; /*!< bit: 9 Reserved */
uint32_t ICI_IT_1:6; /*!< bit: 10..15 ICI/IT part 1 */
uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */
uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */
uint32_t T:1; /*!< bit: 24 Thumb bit */
uint32_t ICI_IT_2:2; /*!< bit: 25..26 ICI/IT part 2 */
uint32_t Q:1; /*!< bit: 27 Saturation condition flag */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} xPSR_Type;
/* xPSR Register Definitions */
#define xPSR_N_Pos 31U /*!< xPSR: N Position */
#define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */
#define xPSR_Z_Pos 30U /*!< xPSR: Z Position */
#define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */
#define xPSR_C_Pos 29U /*!< xPSR: C Position */
#define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */
#define xPSR_V_Pos 28U /*!< xPSR: V Position */
#define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */
#define xPSR_Q_Pos 27U /*!< xPSR: Q Position */
#define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */
#define xPSR_ICI_IT_2_Pos 25U /*!< xPSR: ICI/IT part 2 Position */
#define xPSR_ICI_IT_2_Msk (3UL << xPSR_ICI_IT_2_Pos) /*!< xPSR: ICI/IT part 2 Mask */
#define xPSR_T_Pos 24U /*!< xPSR: T Position */
#define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */
#define xPSR_GE_Pos 16U /*!< xPSR: GE Position */
#define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */
#define xPSR_ICI_IT_1_Pos 10U /*!< xPSR: ICI/IT part 1 Position */
#define xPSR_ICI_IT_1_Msk (0x3FUL << xPSR_ICI_IT_1_Pos) /*!< xPSR: ICI/IT part 1 Mask */
#define xPSR_ISR_Pos 0U /*!< xPSR: ISR Position */
#define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */
/**
\brief Union type to access the Control Registers (CONTROL).
*/
typedef union
{
struct
{
uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */
uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */
uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} CONTROL_Type;
/* CONTROL Register Definitions */
#define CONTROL_FPCA_Pos 2U /*!< CONTROL: FPCA Position */
#define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */
#define CONTROL_SPSEL_Pos 1U /*!< CONTROL: SPSEL Position */
#define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */
#define CONTROL_nPRIV_Pos 0U /*!< CONTROL: nPRIV Position */
#define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */
/*@} end of group CMSIS_CORE */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
\brief Type definitions for the NVIC Registers
@{
*/
/**
\brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
*/
typedef struct
{
__IOM uint32_t ISER[8U]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
uint32_t RESERVED0[24U];
__IOM uint32_t ICER[8U]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
uint32_t RSERVED1[24U];
__IOM uint32_t ISPR[8U]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
uint32_t RESERVED2[24U];
__IOM uint32_t ICPR[8U]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
uint32_t RESERVED3[24U];
__IOM uint32_t IABR[8U]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */
uint32_t RESERVED4[56U];
__IOM uint8_t IP[240U]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */
uint32_t RESERVED5[644U];
__OM uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */
} NVIC_Type;
/* Software Triggered Interrupt Register Definitions */
#define NVIC_STIR_INTID_Pos 0U /*!< STIR: INTLINESNUM Position */
#define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */
/*@} end of group CMSIS_NVIC */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SCB System Control Block (SCB)
\brief Type definitions for the System Control Block Registers
@{
*/
/**
\brief Structure type to access the System Control Block (SCB).
*/
typedef struct
{
__IM uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
__IOM uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
__IOM uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */
__IOM uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
__IOM uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
__IOM uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
__IOM uint8_t SHPR[12U]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */
__IOM uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
__IOM uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */
__IOM uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */
__IOM uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */
__IOM uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */
__IOM uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */
__IOM uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */
__IM uint32_t ID_PFR[2U]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */
__IM uint32_t ID_DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */
__IM uint32_t ID_AFR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */
__IM uint32_t ID_MFR[4U]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */
__IM uint32_t ID_ISAR[5U]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */
uint32_t RESERVED0[1U];
__IM uint32_t CLIDR; /*!< Offset: 0x078 (R/ ) Cache Level ID register */
__IM uint32_t CTR; /*!< Offset: 0x07C (R/ ) Cache Type register */
__IM uint32_t CCSIDR; /*!< Offset: 0x080 (R/ ) Cache Size ID Register */
__IOM uint32_t CSSELR; /*!< Offset: 0x084 (R/W) Cache Size Selection Register */
__IOM uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */
uint32_t RESERVED3[93U];
__OM uint32_t STIR; /*!< Offset: 0x200 ( /W) Software Triggered Interrupt Register */
uint32_t RESERVED4[15U];
__IM uint32_t MVFR0; /*!< Offset: 0x240 (R/ ) Media and VFP Feature Register 0 */
__IM uint32_t MVFR1; /*!< Offset: 0x244 (R/ ) Media and VFP Feature Register 1 */
__IM uint32_t MVFR2; /*!< Offset: 0x248 (R/ ) Media and VFP Feature Register 2 */
uint32_t RESERVED5[1U];
__OM uint32_t ICIALLU; /*!< Offset: 0x250 ( /W) I-Cache Invalidate All to PoU */
uint32_t RESERVED6[1U];
__OM uint32_t ICIMVAU; /*!< Offset: 0x258 ( /W) I-Cache Invalidate by MVA to PoU */
__OM uint32_t DCIMVAC; /*!< Offset: 0x25C ( /W) D-Cache Invalidate by MVA to PoC */
__OM uint32_t DCISW; /*!< Offset: 0x260 ( /W) D-Cache Invalidate by Set-way */
__OM uint32_t DCCMVAU; /*!< Offset: 0x264 ( /W) D-Cache Clean by MVA to PoU */
__OM uint32_t DCCMVAC; /*!< Offset: 0x268 ( /W) D-Cache Clean by MVA to PoC */
__OM uint32_t DCCSW; /*!< Offset: 0x26C ( /W) D-Cache Clean by Set-way */
__OM uint32_t DCCIMVAC; /*!< Offset: 0x270 ( /W) D-Cache Clean and Invalidate by MVA to PoC */
__OM uint32_t DCCISW; /*!< Offset: 0x274 ( /W) D-Cache Clean and Invalidate by Set-way */
uint32_t RESERVED7[6U];
__IOM uint32_t ITCMCR; /*!< Offset: 0x290 (R/W) Instruction Tightly-Coupled Memory Control Register */
__IOM uint32_t DTCMCR; /*!< Offset: 0x294 (R/W) Data Tightly-Coupled Memory Control Registers */
__IOM uint32_t AHBPCR; /*!< Offset: 0x298 (R/W) AHBP Control Register */
__IOM uint32_t CACR; /*!< Offset: 0x29C (R/W) L1 Cache Control Register */
__IOM uint32_t AHBSCR; /*!< Offset: 0x2A0 (R/W) AHB Slave Control Register */
uint32_t RESERVED8[1U];
__IOM uint32_t ABFSR; /*!< Offset: 0x2A8 (R/W) Auxiliary Bus Fault Status Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24U /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20U /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_ARCHITECTURE_Pos 16U /*!< SCB CPUID: ARCHITECTURE Position */
#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
#define SCB_CPUID_PARTNO_Pos 4U /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0U /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31U /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28U /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27U /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26U /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25U /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23U /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22U /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12U /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_RETTOBASE_Pos 11U /*!< SCB ICSR: RETTOBASE Position */
#define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0U /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */
/* SCB Vector Table Offset Register Definitions */
#define SCB_VTOR_TBLOFF_Pos 7U /*!< SCB VTOR: TBLOFF Position */
#define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16U /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16U /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15U /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_PRIGROUP_Pos 8U /*!< SCB AIRCR: PRIGROUP Position */
#define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2U /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1U /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
#define SCB_AIRCR_VECTRESET_Pos 0U /*!< SCB AIRCR: VECTRESET Position */
#define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4U /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2U /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1U /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_BP_Pos 18U /*!< SCB CCR: Branch prediction enable bit Position */
#define SCB_CCR_BP_Msk (1UL << SCB_CCR_BP_Pos) /*!< SCB CCR: Branch prediction enable bit Mask */
#define SCB_CCR_IC_Pos 17U /*!< SCB CCR: Instruction cache enable bit Position */
#define SCB_CCR_IC_Msk (1UL << SCB_CCR_IC_Pos) /*!< SCB CCR: Instruction cache enable bit Mask */
#define SCB_CCR_DC_Pos 16U /*!< SCB CCR: Cache enable bit Position */
#define SCB_CCR_DC_Msk (1UL << SCB_CCR_DC_Pos) /*!< SCB CCR: Cache enable bit Mask */
#define SCB_CCR_STKALIGN_Pos 9U /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_BFHFNMIGN_Pos 8U /*!< SCB CCR: BFHFNMIGN Position */
#define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */
#define SCB_CCR_DIV_0_TRP_Pos 4U /*!< SCB CCR: DIV_0_TRP Position */
#define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3U /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
#define SCB_CCR_USERSETMPEND_Pos 1U /*!< SCB CCR: USERSETMPEND Position */
#define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */
#define SCB_CCR_NONBASETHRDENA_Pos 0U /*!< SCB CCR: NONBASETHRDENA Position */
#define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_USGFAULTENA_Pos 18U /*!< SCB SHCSR: USGFAULTENA Position */
#define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */
#define SCB_SHCSR_BUSFAULTENA_Pos 17U /*!< SCB SHCSR: BUSFAULTENA Position */
#define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */
#define SCB_SHCSR_MEMFAULTENA_Pos 16U /*!< SCB SHCSR: MEMFAULTENA Position */
#define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */
#define SCB_SHCSR_SVCALLPENDED_Pos 15U /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
#define SCB_SHCSR_BUSFAULTPENDED_Pos 14U /*!< SCB SHCSR: BUSFAULTPENDED Position */
#define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */
#define SCB_SHCSR_MEMFAULTPENDED_Pos 13U /*!< SCB SHCSR: MEMFAULTPENDED Position */
#define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */
#define SCB_SHCSR_USGFAULTPENDED_Pos 12U /*!< SCB SHCSR: USGFAULTPENDED Position */
#define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */
#define SCB_SHCSR_SYSTICKACT_Pos 11U /*!< SCB SHCSR: SYSTICKACT Position */
#define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */
#define SCB_SHCSR_PENDSVACT_Pos 10U /*!< SCB SHCSR: PENDSVACT Position */
#define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */
#define SCB_SHCSR_MONITORACT_Pos 8U /*!< SCB SHCSR: MONITORACT Position */
#define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */
#define SCB_SHCSR_SVCALLACT_Pos 7U /*!< SCB SHCSR: SVCALLACT Position */
#define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */
#define SCB_SHCSR_USGFAULTACT_Pos 3U /*!< SCB SHCSR: USGFAULTACT Position */
#define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */
#define SCB_SHCSR_BUSFAULTACT_Pos 1U /*!< SCB SHCSR: BUSFAULTACT Position */
#define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */
#define SCB_SHCSR_MEMFAULTACT_Pos 0U /*!< SCB SHCSR: MEMFAULTACT Position */
#define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */
/* SCB Configurable Fault Status Register Definitions */
#define SCB_CFSR_USGFAULTSR_Pos 16U /*!< SCB CFSR: Usage Fault Status Register Position */
#define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */
#define SCB_CFSR_BUSFAULTSR_Pos 8U /*!< SCB CFSR: Bus Fault Status Register Position */
#define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */
#define SCB_CFSR_MEMFAULTSR_Pos 0U /*!< SCB CFSR: Memory Manage Fault Status Register Position */
#define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
/* MemManage Fault Status Register (part of SCB Configurable Fault Status Register) */
#define SCB_CFSR_MMARVALID_Pos (SCB_SHCSR_MEMFAULTACT_Pos + 7U) /*!< SCB CFSR (MMFSR): MMARVALID Position */
#define SCB_CFSR_MMARVALID_Msk (1UL << SCB_CFSR_MMARVALID_Pos) /*!< SCB CFSR (MMFSR): MMARVALID Mask */
#define SCB_CFSR_MLSPERR_Pos (SCB_SHCSR_MEMFAULTACT_Pos + 5U) /*!< SCB CFSR (MMFSR): MLSPERR Position */
#define SCB_CFSR_MLSPERR_Msk (1UL << SCB_CFSR_MLSPERR_Pos) /*!< SCB CFSR (MMFSR): MLSPERR Mask */
#define SCB_CFSR_MSTKERR_Pos (SCB_SHCSR_MEMFAULTACT_Pos + 4U) /*!< SCB CFSR (MMFSR): MSTKERR Position */
#define SCB_CFSR_MSTKERR_Msk (1UL << SCB_CFSR_MSTKERR_Pos) /*!< SCB CFSR (MMFSR): MSTKERR Mask */
#define SCB_CFSR_MUNSTKERR_Pos (SCB_SHCSR_MEMFAULTACT_Pos + 3U) /*!< SCB CFSR (MMFSR): MUNSTKERR Position */
#define SCB_CFSR_MUNSTKERR_Msk (1UL << SCB_CFSR_MUNSTKERR_Pos) /*!< SCB CFSR (MMFSR): MUNSTKERR Mask */
#define SCB_CFSR_DACCVIOL_Pos (SCB_SHCSR_MEMFAULTACT_Pos + 1U) /*!< SCB CFSR (MMFSR): DACCVIOL Position */
#define SCB_CFSR_DACCVIOL_Msk (1UL << SCB_CFSR_DACCVIOL_Pos) /*!< SCB CFSR (MMFSR): DACCVIOL Mask */
#define SCB_CFSR_IACCVIOL_Pos (SCB_SHCSR_MEMFAULTACT_Pos + 0U) /*!< SCB CFSR (MMFSR): IACCVIOL Position */
#define SCB_CFSR_IACCVIOL_Msk (1UL /*<< SCB_CFSR_IACCVIOL_Pos*/) /*!< SCB CFSR (MMFSR): IACCVIOL Mask */
/* BusFault Status Register (part of SCB Configurable Fault Status Register) */
#define SCB_CFSR_BFARVALID_Pos (SCB_CFSR_BUSFAULTSR_Pos + 7U) /*!< SCB CFSR (BFSR): BFARVALID Position */
#define SCB_CFSR_BFARVALID_Msk (1UL << SCB_CFSR_BFARVALID_Pos) /*!< SCB CFSR (BFSR): BFARVALID Mask */
#define SCB_CFSR_LSPERR_Pos (SCB_CFSR_BUSFAULTSR_Pos + 5U) /*!< SCB CFSR (BFSR): LSPERR Position */
#define SCB_CFSR_LSPERR_Msk (1UL << SCB_CFSR_LSPERR_Pos) /*!< SCB CFSR (BFSR): LSPERR Mask */
#define SCB_CFSR_STKERR_Pos (SCB_CFSR_BUSFAULTSR_Pos + 4U) /*!< SCB CFSR (BFSR): STKERR Position */
#define SCB_CFSR_STKERR_Msk (1UL << SCB_CFSR_STKERR_Pos) /*!< SCB CFSR (BFSR): STKERR Mask */
#define SCB_CFSR_UNSTKERR_Pos (SCB_CFSR_BUSFAULTSR_Pos + 3U) /*!< SCB CFSR (BFSR): UNSTKERR Position */
#define SCB_CFSR_UNSTKERR_Msk (1UL << SCB_CFSR_UNSTKERR_Pos) /*!< SCB CFSR (BFSR): UNSTKERR Mask */
#define SCB_CFSR_IMPRECISERR_Pos (SCB_CFSR_BUSFAULTSR_Pos + 2U) /*!< SCB CFSR (BFSR): IMPRECISERR Position */
#define SCB_CFSR_IMPRECISERR_Msk (1UL << SCB_CFSR_IMPRECISERR_Pos) /*!< SCB CFSR (BFSR): IMPRECISERR Mask */
#define SCB_CFSR_PRECISERR_Pos (SCB_CFSR_BUSFAULTSR_Pos + 1U) /*!< SCB CFSR (BFSR): PRECISERR Position */
#define SCB_CFSR_PRECISERR_Msk (1UL << SCB_CFSR_PRECISERR_Pos) /*!< SCB CFSR (BFSR): PRECISERR Mask */
#define SCB_CFSR_IBUSERR_Pos (SCB_CFSR_BUSFAULTSR_Pos + 0U) /*!< SCB CFSR (BFSR): IBUSERR Position */
#define SCB_CFSR_IBUSERR_Msk (1UL << SCB_CFSR_IBUSERR_Pos) /*!< SCB CFSR (BFSR): IBUSERR Mask */
/* UsageFault Status Register (part of SCB Configurable Fault Status Register) */
#define SCB_CFSR_DIVBYZERO_Pos (SCB_CFSR_USGFAULTSR_Pos + 9U) /*!< SCB CFSR (UFSR): DIVBYZERO Position */
#define SCB_CFSR_DIVBYZERO_Msk (1UL << SCB_CFSR_DIVBYZERO_Pos) /*!< SCB CFSR (UFSR): DIVBYZERO Mask */
#define SCB_CFSR_UNALIGNED_Pos (SCB_CFSR_USGFAULTSR_Pos + 8U) /*!< SCB CFSR (UFSR): UNALIGNED Position */
#define SCB_CFSR_UNALIGNED_Msk (1UL << SCB_CFSR_UNALIGNED_Pos) /*!< SCB CFSR (UFSR): UNALIGNED Mask */
#define SCB_CFSR_NOCP_Pos (SCB_CFSR_USGFAULTSR_Pos + 3U) /*!< SCB CFSR (UFSR): NOCP Position */
#define SCB_CFSR_NOCP_Msk (1UL << SCB_CFSR_NOCP_Pos) /*!< SCB CFSR (UFSR): NOCP Mask */
#define SCB_CFSR_INVPC_Pos (SCB_CFSR_USGFAULTSR_Pos + 2U) /*!< SCB CFSR (UFSR): INVPC Position */
#define SCB_CFSR_INVPC_Msk (1UL << SCB_CFSR_INVPC_Pos) /*!< SCB CFSR (UFSR): INVPC Mask */
#define SCB_CFSR_INVSTATE_Pos (SCB_CFSR_USGFAULTSR_Pos + 1U) /*!< SCB CFSR (UFSR): INVSTATE Position */
#define SCB_CFSR_INVSTATE_Msk (1UL << SCB_CFSR_INVSTATE_Pos) /*!< SCB CFSR (UFSR): INVSTATE Mask */
#define SCB_CFSR_UNDEFINSTR_Pos (SCB_CFSR_USGFAULTSR_Pos + 0U) /*!< SCB CFSR (UFSR): UNDEFINSTR Position */
#define SCB_CFSR_UNDEFINSTR_Msk (1UL << SCB_CFSR_UNDEFINSTR_Pos) /*!< SCB CFSR (UFSR): UNDEFINSTR Mask */
/* SCB Hard Fault Status Register Definitions */
#define SCB_HFSR_DEBUGEVT_Pos 31U /*!< SCB HFSR: DEBUGEVT Position */
#define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */
#define SCB_HFSR_FORCED_Pos 30U /*!< SCB HFSR: FORCED Position */
#define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */
#define SCB_HFSR_VECTTBL_Pos 1U /*!< SCB HFSR: VECTTBL Position */
#define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */
/* SCB Debug Fault Status Register Definitions */
#define SCB_DFSR_EXTERNAL_Pos 4U /*!< SCB DFSR: EXTERNAL Position */
#define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */
#define SCB_DFSR_VCATCH_Pos 3U /*!< SCB DFSR: VCATCH Position */
#define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */
#define SCB_DFSR_DWTTRAP_Pos 2U /*!< SCB DFSR: DWTTRAP Position */
#define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */
#define SCB_DFSR_BKPT_Pos 1U /*!< SCB DFSR: BKPT Position */
#define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */
#define SCB_DFSR_HALTED_Pos 0U /*!< SCB DFSR: HALTED Position */
#define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */
/* SCB Cache Level ID Register Definitions */
#define SCB_CLIDR_LOUU_Pos 27U /*!< SCB CLIDR: LoUU Position */
#define SCB_CLIDR_LOUU_Msk (7UL << SCB_CLIDR_LOUU_Pos) /*!< SCB CLIDR: LoUU Mask */
#define SCB_CLIDR_LOC_Pos 24U /*!< SCB CLIDR: LoC Position */
#define SCB_CLIDR_LOC_Msk (7UL << SCB_CLIDR_LOC_Pos) /*!< SCB CLIDR: LoC Mask */
/* SCB Cache Type Register Definitions */
#define SCB_CTR_FORMAT_Pos 29U /*!< SCB CTR: Format Position */
#define SCB_CTR_FORMAT_Msk (7UL << SCB_CTR_FORMAT_Pos) /*!< SCB CTR: Format Mask */
#define SCB_CTR_CWG_Pos 24U /*!< SCB CTR: CWG Position */
#define SCB_CTR_CWG_Msk (0xFUL << SCB_CTR_CWG_Pos) /*!< SCB CTR: CWG Mask */
#define SCB_CTR_ERG_Pos 20U /*!< SCB CTR: ERG Position */
#define SCB_CTR_ERG_Msk (0xFUL << SCB_CTR_ERG_Pos) /*!< SCB CTR: ERG Mask */
#define SCB_CTR_DMINLINE_Pos 16U /*!< SCB CTR: DminLine Position */
#define SCB_CTR_DMINLINE_Msk (0xFUL << SCB_CTR_DMINLINE_Pos) /*!< SCB CTR: DminLine Mask */
#define SCB_CTR_IMINLINE_Pos 0U /*!< SCB CTR: ImInLine Position */
#define SCB_CTR_IMINLINE_Msk (0xFUL /*<< SCB_CTR_IMINLINE_Pos*/) /*!< SCB CTR: ImInLine Mask */
/* SCB Cache Size ID Register Definitions */
#define SCB_CCSIDR_WT_Pos 31U /*!< SCB CCSIDR: WT Position */
#define SCB_CCSIDR_WT_Msk (1UL << SCB_CCSIDR_WT_Pos) /*!< SCB CCSIDR: WT Mask */
#define SCB_CCSIDR_WB_Pos 30U /*!< SCB CCSIDR: WB Position */
#define SCB_CCSIDR_WB_Msk (1UL << SCB_CCSIDR_WB_Pos) /*!< SCB CCSIDR: WB Mask */
#define SCB_CCSIDR_RA_Pos 29U /*!< SCB CCSIDR: RA Position */
#define SCB_CCSIDR_RA_Msk (1UL << SCB_CCSIDR_RA_Pos) /*!< SCB CCSIDR: RA Mask */
#define SCB_CCSIDR_WA_Pos 28U /*!< SCB CCSIDR: WA Position */
#define SCB_CCSIDR_WA_Msk (1UL << SCB_CCSIDR_WA_Pos) /*!< SCB CCSIDR: WA Mask */
#define SCB_CCSIDR_NUMSETS_Pos 13U /*!< SCB CCSIDR: NumSets Position */
#define SCB_CCSIDR_NUMSETS_Msk (0x7FFFUL << SCB_CCSIDR_NUMSETS_Pos) /*!< SCB CCSIDR: NumSets Mask */
#define SCB_CCSIDR_ASSOCIATIVITY_Pos 3U /*!< SCB CCSIDR: Associativity Position */
#define SCB_CCSIDR_ASSOCIATIVITY_Msk (0x3FFUL << SCB_CCSIDR_ASSOCIATIVITY_Pos) /*!< SCB CCSIDR: Associativity Mask */
#define SCB_CCSIDR_LINESIZE_Pos 0U /*!< SCB CCSIDR: LineSize Position */
#define SCB_CCSIDR_LINESIZE_Msk (7UL /*<< SCB_CCSIDR_LINESIZE_Pos*/) /*!< SCB CCSIDR: LineSize Mask */
/* SCB Cache Size Selection Register Definitions */
#define SCB_CSSELR_LEVEL_Pos 1U /*!< SCB CSSELR: Level Position */
#define SCB_CSSELR_LEVEL_Msk (7UL << SCB_CSSELR_LEVEL_Pos) /*!< SCB CSSELR: Level Mask */
#define SCB_CSSELR_IND_Pos 0U /*!< SCB CSSELR: InD Position */
#define SCB_CSSELR_IND_Msk (1UL /*<< SCB_CSSELR_IND_Pos*/) /*!< SCB CSSELR: InD Mask */
/* SCB Software Triggered Interrupt Register Definitions */
#define SCB_STIR_INTID_Pos 0U /*!< SCB STIR: INTID Position */
#define SCB_STIR_INTID_Msk (0x1FFUL /*<< SCB_STIR_INTID_Pos*/) /*!< SCB STIR: INTID Mask */
/* SCB D-Cache Invalidate by Set-way Register Definitions */
#define SCB_DCISW_WAY_Pos 30U /*!< SCB DCISW: Way Position */
#define SCB_DCISW_WAY_Msk (3UL << SCB_DCISW_WAY_Pos) /*!< SCB DCISW: Way Mask */
#define SCB_DCISW_SET_Pos 5U /*!< SCB DCISW: Set Position */
#define SCB_DCISW_SET_Msk (0x1FFUL << SCB_DCISW_SET_Pos) /*!< SCB DCISW: Set Mask */
/* SCB D-Cache Clean by Set-way Register Definitions */
#define SCB_DCCSW_WAY_Pos 30U /*!< SCB DCCSW: Way Position */
#define SCB_DCCSW_WAY_Msk (3UL << SCB_DCCSW_WAY_Pos) /*!< SCB DCCSW: Way Mask */
#define SCB_DCCSW_SET_Pos 5U /*!< SCB DCCSW: Set Position */
#define SCB_DCCSW_SET_Msk (0x1FFUL << SCB_DCCSW_SET_Pos) /*!< SCB DCCSW: Set Mask */
/* SCB D-Cache Clean and Invalidate by Set-way Register Definitions */
#define SCB_DCCISW_WAY_Pos 30U /*!< SCB DCCISW: Way Position */
#define SCB_DCCISW_WAY_Msk (3UL << SCB_DCCISW_WAY_Pos) /*!< SCB DCCISW: Way Mask */
#define SCB_DCCISW_SET_Pos 5U /*!< SCB DCCISW: Set Position */
#define SCB_DCCISW_SET_Msk (0x1FFUL << SCB_DCCISW_SET_Pos) /*!< SCB DCCISW: Set Mask */
/* Instruction Tightly-Coupled Memory Control Register Definitions */
#define SCB_ITCMCR_SZ_Pos 3U /*!< SCB ITCMCR: SZ Position */
#define SCB_ITCMCR_SZ_Msk (0xFUL << SCB_ITCMCR_SZ_Pos) /*!< SCB ITCMCR: SZ Mask */
#define SCB_ITCMCR_RETEN_Pos 2U /*!< SCB ITCMCR: RETEN Position */
#define SCB_ITCMCR_RETEN_Msk (1UL << SCB_ITCMCR_RETEN_Pos) /*!< SCB ITCMCR: RETEN Mask */
#define SCB_ITCMCR_RMW_Pos 1U /*!< SCB ITCMCR: RMW Position */
#define SCB_ITCMCR_RMW_Msk (1UL << SCB_ITCMCR_RMW_Pos) /*!< SCB ITCMCR: RMW Mask */
#define SCB_ITCMCR_EN_Pos 0U /*!< SCB ITCMCR: EN Position */
#define SCB_ITCMCR_EN_Msk (1UL /*<< SCB_ITCMCR_EN_Pos*/) /*!< SCB ITCMCR: EN Mask */
/* Data Tightly-Coupled Memory Control Register Definitions */
#define SCB_DTCMCR_SZ_Pos 3U /*!< SCB DTCMCR: SZ Position */
#define SCB_DTCMCR_SZ_Msk (0xFUL << SCB_DTCMCR_SZ_Pos) /*!< SCB DTCMCR: SZ Mask */
#define SCB_DTCMCR_RETEN_Pos 2U /*!< SCB DTCMCR: RETEN Position */
#define SCB_DTCMCR_RETEN_Msk (1UL << SCB_DTCMCR_RETEN_Pos) /*!< SCB DTCMCR: RETEN Mask */
#define SCB_DTCMCR_RMW_Pos 1U /*!< SCB DTCMCR: RMW Position */
#define SCB_DTCMCR_RMW_Msk (1UL << SCB_DTCMCR_RMW_Pos) /*!< SCB DTCMCR: RMW Mask */
#define SCB_DTCMCR_EN_Pos 0U /*!< SCB DTCMCR: EN Position */
#define SCB_DTCMCR_EN_Msk (1UL /*<< SCB_DTCMCR_EN_Pos*/) /*!< SCB DTCMCR: EN Mask */
/* AHBP Control Register Definitions */
#define SCB_AHBPCR_SZ_Pos 1U /*!< SCB AHBPCR: SZ Position */
#define SCB_AHBPCR_SZ_Msk (7UL << SCB_AHBPCR_SZ_Pos) /*!< SCB AHBPCR: SZ Mask */
#define SCB_AHBPCR_EN_Pos 0U /*!< SCB AHBPCR: EN Position */
#define SCB_AHBPCR_EN_Msk (1UL /*<< SCB_AHBPCR_EN_Pos*/) /*!< SCB AHBPCR: EN Mask */
/* L1 Cache Control Register Definitions */
#define SCB_CACR_FORCEWT_Pos 2U /*!< SCB CACR: FORCEWT Position */
#define SCB_CACR_FORCEWT_Msk (1UL << SCB_CACR_FORCEWT_Pos) /*!< SCB CACR: FORCEWT Mask */
#define SCB_CACR_ECCEN_Pos 1U /*!< SCB CACR: ECCEN Position */
#define SCB_CACR_ECCEN_Msk (1UL << SCB_CACR_ECCEN_Pos) /*!< SCB CACR: ECCEN Mask */
#define SCB_CACR_SIWT_Pos 0U /*!< SCB CACR: SIWT Position */
#define SCB_CACR_SIWT_Msk (1UL /*<< SCB_CACR_SIWT_Pos*/) /*!< SCB CACR: SIWT Mask */
/* AHBS Control Register Definitions */
#define SCB_AHBSCR_INITCOUNT_Pos 11U /*!< SCB AHBSCR: INITCOUNT Position */
#define SCB_AHBSCR_INITCOUNT_Msk (0x1FUL << SCB_AHBPCR_INITCOUNT_Pos) /*!< SCB AHBSCR: INITCOUNT Mask */
#define SCB_AHBSCR_TPRI_Pos 2U /*!< SCB AHBSCR: TPRI Position */
#define SCB_AHBSCR_TPRI_Msk (0x1FFUL << SCB_AHBPCR_TPRI_Pos) /*!< SCB AHBSCR: TPRI Mask */
#define SCB_AHBSCR_CTL_Pos 0U /*!< SCB AHBSCR: CTL Position*/
#define SCB_AHBSCR_CTL_Msk (3UL /*<< SCB_AHBPCR_CTL_Pos*/) /*!< SCB AHBSCR: CTL Mask */
/* Auxiliary Bus Fault Status Register Definitions */
#define SCB_ABFSR_AXIMTYPE_Pos 8U /*!< SCB ABFSR: AXIMTYPE Position*/
#define SCB_ABFSR_AXIMTYPE_Msk (3UL << SCB_ABFSR_AXIMTYPE_Pos) /*!< SCB ABFSR: AXIMTYPE Mask */
#define SCB_ABFSR_EPPB_Pos 4U /*!< SCB ABFSR: EPPB Position*/
#define SCB_ABFSR_EPPB_Msk (1UL << SCB_ABFSR_EPPB_Pos) /*!< SCB ABFSR: EPPB Mask */
#define SCB_ABFSR_AXIM_Pos 3U /*!< SCB ABFSR: AXIM Position*/
#define SCB_ABFSR_AXIM_Msk (1UL << SCB_ABFSR_AXIM_Pos) /*!< SCB ABFSR: AXIM Mask */
#define SCB_ABFSR_AHBP_Pos 2U /*!< SCB ABFSR: AHBP Position*/
#define SCB_ABFSR_AHBP_Msk (1UL << SCB_ABFSR_AHBP_Pos) /*!< SCB ABFSR: AHBP Mask */
#define SCB_ABFSR_DTCM_Pos 1U /*!< SCB ABFSR: DTCM Position*/
#define SCB_ABFSR_DTCM_Msk (1UL << SCB_ABFSR_DTCM_Pos) /*!< SCB ABFSR: DTCM Mask */
#define SCB_ABFSR_ITCM_Pos 0U /*!< SCB ABFSR: ITCM Position*/
#define SCB_ABFSR_ITCM_Msk (1UL /*<< SCB_ABFSR_ITCM_Pos*/) /*!< SCB ABFSR: ITCM Mask */
/*@} end of group CMSIS_SCB */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
\brief Type definitions for the System Control and ID Register not in the SCB
@{
*/
/**
\brief Structure type to access the System Control and ID Register not in the SCB.
*/
typedef struct
{
uint32_t RESERVED0[1U];
__IM uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */
__IOM uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */
} SCnSCB_Type;
/* Interrupt Controller Type Register Definitions */
#define SCnSCB_ICTR_INTLINESNUM_Pos 0U /*!< ICTR: INTLINESNUM Position */
#define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */
/* Auxiliary Control Register Definitions */
#define SCnSCB_ACTLR_DISITMATBFLUSH_Pos 12U /*!< ACTLR: DISITMATBFLUSH Position */
#define SCnSCB_ACTLR_DISITMATBFLUSH_Msk (1UL << SCnSCB_ACTLR_DISITMATBFLUSH_Pos) /*!< ACTLR: DISITMATBFLUSH Mask */
#define SCnSCB_ACTLR_DISRAMODE_Pos 11U /*!< ACTLR: DISRAMODE Position */
#define SCnSCB_ACTLR_DISRAMODE_Msk (1UL << SCnSCB_ACTLR_DISRAMODE_Pos) /*!< ACTLR: DISRAMODE Mask */
#define SCnSCB_ACTLR_FPEXCODIS_Pos 10U /*!< ACTLR: FPEXCODIS Position */
#define SCnSCB_ACTLR_FPEXCODIS_Msk (1UL << SCnSCB_ACTLR_FPEXCODIS_Pos) /*!< ACTLR: FPEXCODIS Mask */
#define SCnSCB_ACTLR_DISFOLD_Pos 2U /*!< ACTLR: DISFOLD Position */
#define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */
#define SCnSCB_ACTLR_DISMCYCINT_Pos 0U /*!< ACTLR: DISMCYCINT Position */
#define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */
/*@} end of group CMSIS_SCnotSCB */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SysTick System Tick Timer (SysTick)
\brief Type definitions for the System Timer Registers.
@{
*/
/**
\brief Structure type to access the System Timer (SysTick).
*/
typedef struct
{
__IOM uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
__IOM uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
__IOM uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
__IM uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16U /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2U /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1U /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0U /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0U /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0U /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31U /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30U /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0U /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */
/*@} end of group CMSIS_SysTick */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM)
\brief Type definitions for the Instrumentation Trace Macrocell (ITM)
@{
*/
/**
\brief Structure type to access the Instrumentation Trace Macrocell Register (ITM).
*/
typedef struct
{
__OM union
{
__OM uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */
__OM uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */
__OM uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */
} PORT [32U]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */
uint32_t RESERVED0[864U];
__IOM uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */
uint32_t RESERVED1[15U];
__IOM uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */
uint32_t RESERVED2[15U];
__IOM uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */
uint32_t RESERVED3[29U];
__OM uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */
__IM uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */
__IOM uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */
uint32_t RESERVED4[43U];
__OM uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */
__IM uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */
uint32_t RESERVED5[6U];
__IM uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */
__IM uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */
__IM uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */
__IM uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */
__IM uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */
__IM uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */
__IM uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */
__IM uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */
__IM uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */
__IM uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */
__IM uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */
__IM uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */
} ITM_Type;
/* ITM Trace Privilege Register Definitions */
#define ITM_TPR_PRIVMASK_Pos 0U /*!< ITM TPR: PRIVMASK Position */
#define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */
/* ITM Trace Control Register Definitions */
#define ITM_TCR_BUSY_Pos 23U /*!< ITM TCR: BUSY Position */
#define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */
#define ITM_TCR_TraceBusID_Pos 16U /*!< ITM TCR: ATBID Position */
#define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */
#define ITM_TCR_GTSFREQ_Pos 10U /*!< ITM TCR: Global timestamp frequency Position */
#define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */
#define ITM_TCR_TSPrescale_Pos 8U /*!< ITM TCR: TSPrescale Position */
#define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */
#define ITM_TCR_SWOENA_Pos 4U /*!< ITM TCR: SWOENA Position */
#define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */
#define ITM_TCR_DWTENA_Pos 3U /*!< ITM TCR: DWTENA Position */
#define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */
#define ITM_TCR_SYNCENA_Pos 2U /*!< ITM TCR: SYNCENA Position */
#define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */
#define ITM_TCR_TSENA_Pos 1U /*!< ITM TCR: TSENA Position */
#define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */
#define ITM_TCR_ITMENA_Pos 0U /*!< ITM TCR: ITM Enable bit Position */
#define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */
/* ITM Integration Write Register Definitions */
#define ITM_IWR_ATVALIDM_Pos 0U /*!< ITM IWR: ATVALIDM Position */
#define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */
/* ITM Integration Read Register Definitions */
#define ITM_IRR_ATREADYM_Pos 0U /*!< ITM IRR: ATREADYM Position */
#define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */
/* ITM Integration Mode Control Register Definitions */
#define ITM_IMCR_INTEGRATION_Pos 0U /*!< ITM IMCR: INTEGRATION Position */
#define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */
/* ITM Lock Status Register Definitions */
#define ITM_LSR_ByteAcc_Pos 2U /*!< ITM LSR: ByteAcc Position */
#define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */
#define ITM_LSR_Access_Pos 1U /*!< ITM LSR: Access Position */
#define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */
#define ITM_LSR_Present_Pos 0U /*!< ITM LSR: Present Position */
#define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */
/*@}*/ /* end of group CMSIS_ITM */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_DWT Data Watchpoint and Trace (DWT)
\brief Type definitions for the Data Watchpoint and Trace (DWT)
@{
*/
/**
\brief Structure type to access the Data Watchpoint and Trace Register (DWT).
*/
typedef struct
{
__IOM uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */
__IOM uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */
__IOM uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */
__IOM uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */
__IOM uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */
__IOM uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */
__IOM uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */
__IM uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */
__IOM uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */
__IOM uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */
__IOM uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */
uint32_t RESERVED0[1U];
__IOM uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */
__IOM uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */
__IOM uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */
uint32_t RESERVED1[1U];
__IOM uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */
__IOM uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */
__IOM uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */
uint32_t RESERVED2[1U];
__IOM uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */
__IOM uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */
__IOM uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */
uint32_t RESERVED3[981U];
__OM uint32_t LAR; /*!< Offset: 0xFB0 ( W) Lock Access Register */
__IM uint32_t LSR; /*!< Offset: 0xFB4 (R ) Lock Status Register */
} DWT_Type;
/* DWT Control Register Definitions */
#define DWT_CTRL_NUMCOMP_Pos 28U /*!< DWT CTRL: NUMCOMP Position */
#define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */
#define DWT_CTRL_NOTRCPKT_Pos 27U /*!< DWT CTRL: NOTRCPKT Position */
#define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */
#define DWT_CTRL_NOEXTTRIG_Pos 26U /*!< DWT CTRL: NOEXTTRIG Position */
#define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */
#define DWT_CTRL_NOCYCCNT_Pos 25U /*!< DWT CTRL: NOCYCCNT Position */
#define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */
#define DWT_CTRL_NOPRFCNT_Pos 24U /*!< DWT CTRL: NOPRFCNT Position */
#define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */
#define DWT_CTRL_CYCEVTENA_Pos 22U /*!< DWT CTRL: CYCEVTENA Position */
#define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */
#define DWT_CTRL_FOLDEVTENA_Pos 21U /*!< DWT CTRL: FOLDEVTENA Position */
#define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */
#define DWT_CTRL_LSUEVTENA_Pos 20U /*!< DWT CTRL: LSUEVTENA Position */
#define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */
#define DWT_CTRL_SLEEPEVTENA_Pos 19U /*!< DWT CTRL: SLEEPEVTENA Position */
#define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */
#define DWT_CTRL_EXCEVTENA_Pos 18U /*!< DWT CTRL: EXCEVTENA Position */
#define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */
#define DWT_CTRL_CPIEVTENA_Pos 17U /*!< DWT CTRL: CPIEVTENA Position */
#define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */
#define DWT_CTRL_EXCTRCENA_Pos 16U /*!< DWT CTRL: EXCTRCENA Position */
#define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */
#define DWT_CTRL_PCSAMPLENA_Pos 12U /*!< DWT CTRL: PCSAMPLENA Position */
#define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */
#define DWT_CTRL_SYNCTAP_Pos 10U /*!< DWT CTRL: SYNCTAP Position */
#define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */
#define DWT_CTRL_CYCTAP_Pos 9U /*!< DWT CTRL: CYCTAP Position */
#define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */
#define DWT_CTRL_POSTINIT_Pos 5U /*!< DWT CTRL: POSTINIT Position */
#define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */
#define DWT_CTRL_POSTPRESET_Pos 1U /*!< DWT CTRL: POSTPRESET Position */
#define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */
#define DWT_CTRL_CYCCNTENA_Pos 0U /*!< DWT CTRL: CYCCNTENA Position */
#define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */
/* DWT CPI Count Register Definitions */
#define DWT_CPICNT_CPICNT_Pos 0U /*!< DWT CPICNT: CPICNT Position */
#define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */
/* DWT Exception Overhead Count Register Definitions */
#define DWT_EXCCNT_EXCCNT_Pos 0U /*!< DWT EXCCNT: EXCCNT Position */
#define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */
/* DWT Sleep Count Register Definitions */
#define DWT_SLEEPCNT_SLEEPCNT_Pos 0U /*!< DWT SLEEPCNT: SLEEPCNT Position */
#define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */
/* DWT LSU Count Register Definitions */
#define DWT_LSUCNT_LSUCNT_Pos 0U /*!< DWT LSUCNT: LSUCNT Position */
#define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */
/* DWT Folded-instruction Count Register Definitions */
#define DWT_FOLDCNT_FOLDCNT_Pos 0U /*!< DWT FOLDCNT: FOLDCNT Position */
#define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */
/* DWT Comparator Mask Register Definitions */
#define DWT_MASK_MASK_Pos 0U /*!< DWT MASK: MASK Position */
#define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */
/* DWT Comparator Function Register Definitions */
#define DWT_FUNCTION_MATCHED_Pos 24U /*!< DWT FUNCTION: MATCHED Position */
#define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */
#define DWT_FUNCTION_DATAVADDR1_Pos 16U /*!< DWT FUNCTION: DATAVADDR1 Position */
#define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */
#define DWT_FUNCTION_DATAVADDR0_Pos 12U /*!< DWT FUNCTION: DATAVADDR0 Position */
#define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */
#define DWT_FUNCTION_DATAVSIZE_Pos 10U /*!< DWT FUNCTION: DATAVSIZE Position */
#define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */
#define DWT_FUNCTION_LNK1ENA_Pos 9U /*!< DWT FUNCTION: LNK1ENA Position */
#define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */
#define DWT_FUNCTION_DATAVMATCH_Pos 8U /*!< DWT FUNCTION: DATAVMATCH Position */
#define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */
#define DWT_FUNCTION_CYCMATCH_Pos 7U /*!< DWT FUNCTION: CYCMATCH Position */
#define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */
#define DWT_FUNCTION_EMITRANGE_Pos 5U /*!< DWT FUNCTION: EMITRANGE Position */
#define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */
#define DWT_FUNCTION_FUNCTION_Pos 0U /*!< DWT FUNCTION: FUNCTION Position */
#define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */
/*@}*/ /* end of group CMSIS_DWT */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_TPI Trace Port Interface (TPI)
\brief Type definitions for the Trace Port Interface (TPI)
@{
*/
/**
\brief Structure type to access the Trace Port Interface Register (TPI).
*/
typedef struct
{
__IOM uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */
__IOM uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */
uint32_t RESERVED0[2U];
__IOM uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */
uint32_t RESERVED1[55U];
__IOM uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */
uint32_t RESERVED2[131U];
__IM uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */
__IOM uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */
__IM uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */
uint32_t RESERVED3[759U];
__IM uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */
__IM uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */
__IM uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */
uint32_t RESERVED4[1U];
__IM uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */
__IM uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */
__IOM uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */
uint32_t RESERVED5[39U];
__IOM uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */
__IOM uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */
uint32_t RESERVED7[8U];
__IM uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */
__IM uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */
} TPI_Type;
/* TPI Asynchronous Clock Prescaler Register Definitions */
#define TPI_ACPR_PRESCALER_Pos 0U /*!< TPI ACPR: PRESCALER Position */
#define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */
/* TPI Selected Pin Protocol Register Definitions */
#define TPI_SPPR_TXMODE_Pos 0U /*!< TPI SPPR: TXMODE Position */
#define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */
/* TPI Formatter and Flush Status Register Definitions */
#define TPI_FFSR_FtNonStop_Pos 3U /*!< TPI FFSR: FtNonStop Position */
#define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */
#define TPI_FFSR_TCPresent_Pos 2U /*!< TPI FFSR: TCPresent Position */
#define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */
#define TPI_FFSR_FtStopped_Pos 1U /*!< TPI FFSR: FtStopped Position */
#define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */
#define TPI_FFSR_FlInProg_Pos 0U /*!< TPI FFSR: FlInProg Position */
#define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */
/* TPI Formatter and Flush Control Register Definitions */
#define TPI_FFCR_TrigIn_Pos 8U /*!< TPI FFCR: TrigIn Position */
#define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */
#define TPI_FFCR_EnFCont_Pos 1U /*!< TPI FFCR: EnFCont Position */
#define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */
/* TPI TRIGGER Register Definitions */
#define TPI_TRIGGER_TRIGGER_Pos 0U /*!< TPI TRIGGER: TRIGGER Position */
#define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */
/* TPI Integration ETM Data Register Definitions (FIFO0) */
#define TPI_FIFO0_ITM_ATVALID_Pos 29U /*!< TPI FIFO0: ITM_ATVALID Position */
#define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */
#define TPI_FIFO0_ITM_bytecount_Pos 27U /*!< TPI FIFO0: ITM_bytecount Position */
#define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */
#define TPI_FIFO0_ETM_ATVALID_Pos 26U /*!< TPI FIFO0: ETM_ATVALID Position */
#define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */
#define TPI_FIFO0_ETM_bytecount_Pos 24U /*!< TPI FIFO0: ETM_bytecount Position */
#define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */
#define TPI_FIFO0_ETM2_Pos 16U /*!< TPI FIFO0: ETM2 Position */
#define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */
#define TPI_FIFO0_ETM1_Pos 8U /*!< TPI FIFO0: ETM1 Position */
#define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */
#define TPI_FIFO0_ETM0_Pos 0U /*!< TPI FIFO0: ETM0 Position */
#define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */
/* TPI ITATBCTR2 Register Definitions */
#define TPI_ITATBCTR2_ATREADY_Pos 0U /*!< TPI ITATBCTR2: ATREADY Position */
#define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */
/* TPI Integration ITM Data Register Definitions (FIFO1) */
#define TPI_FIFO1_ITM_ATVALID_Pos 29U /*!< TPI FIFO1: ITM_ATVALID Position */
#define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */
#define TPI_FIFO1_ITM_bytecount_Pos 27U /*!< TPI FIFO1: ITM_bytecount Position */
#define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */
#define TPI_FIFO1_ETM_ATVALID_Pos 26U /*!< TPI FIFO1: ETM_ATVALID Position */
#define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */
#define TPI_FIFO1_ETM_bytecount_Pos 24U /*!< TPI FIFO1: ETM_bytecount Position */
#define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */
#define TPI_FIFO1_ITM2_Pos 16U /*!< TPI FIFO1: ITM2 Position */
#define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */
#define TPI_FIFO1_ITM1_Pos 8U /*!< TPI FIFO1: ITM1 Position */
#define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */
#define TPI_FIFO1_ITM0_Pos 0U /*!< TPI FIFO1: ITM0 Position */
#define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */
/* TPI ITATBCTR0 Register Definitions */
#define TPI_ITATBCTR0_ATREADY_Pos 0U /*!< TPI ITATBCTR0: ATREADY Position */
#define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */
/* TPI Integration Mode Control Register Definitions */
#define TPI_ITCTRL_Mode_Pos 0U /*!< TPI ITCTRL: Mode Position */
#define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */
/* TPI DEVID Register Definitions */
#define TPI_DEVID_NRZVALID_Pos 11U /*!< TPI DEVID: NRZVALID Position */
#define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */
#define TPI_DEVID_MANCVALID_Pos 10U /*!< TPI DEVID: MANCVALID Position */
#define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */
#define TPI_DEVID_PTINVALID_Pos 9U /*!< TPI DEVID: PTINVALID Position */
#define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */
#define TPI_DEVID_MinBufSz_Pos 6U /*!< TPI DEVID: MinBufSz Position */
#define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */
#define TPI_DEVID_AsynClkIn_Pos 5U /*!< TPI DEVID: AsynClkIn Position */
#define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */
#define TPI_DEVID_NrTraceInput_Pos 0U /*!< TPI DEVID: NrTraceInput Position */
#define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */
/* TPI DEVTYPE Register Definitions */
#define TPI_DEVTYPE_MajorType_Pos 4U /*!< TPI DEVTYPE: MajorType Position */
#define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */
#define TPI_DEVTYPE_SubType_Pos 0U /*!< TPI DEVTYPE: SubType Position */
#define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */
/*@}*/ /* end of group CMSIS_TPI */
#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1U)
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_MPU Memory Protection Unit (MPU)
\brief Type definitions for the Memory Protection Unit (MPU)
@{
*/
/**
\brief Structure type to access the Memory Protection Unit (MPU).
*/
typedef struct
{
__IM uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */
__IOM uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */
__IOM uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */
__IOM uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */
__IOM uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */
__IOM uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */
__IOM uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */
__IOM uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */
__IOM uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */
__IOM uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */
__IOM uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */
} MPU_Type;
#define MPU_TYPE_RALIASES 4U
/* MPU Type Register Definitions */
#define MPU_TYPE_IREGION_Pos 16U /*!< MPU TYPE: IREGION Position */
#define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */
#define MPU_TYPE_DREGION_Pos 8U /*!< MPU TYPE: DREGION Position */
#define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */
#define MPU_TYPE_SEPARATE_Pos 0U /*!< MPU TYPE: SEPARATE Position */
#define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */
/* MPU Control Register Definitions */
#define MPU_CTRL_PRIVDEFENA_Pos 2U /*!< MPU CTRL: PRIVDEFENA Position */
#define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */
#define MPU_CTRL_HFNMIENA_Pos 1U /*!< MPU CTRL: HFNMIENA Position */
#define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */
#define MPU_CTRL_ENABLE_Pos 0U /*!< MPU CTRL: ENABLE Position */
#define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */
/* MPU Region Number Register Definitions */
#define MPU_RNR_REGION_Pos 0U /*!< MPU RNR: REGION Position */
#define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */
/* MPU Region Base Address Register Definitions */
#define MPU_RBAR_ADDR_Pos 5U /*!< MPU RBAR: ADDR Position */
#define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */
#define MPU_RBAR_VALID_Pos 4U /*!< MPU RBAR: VALID Position */
#define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */
#define MPU_RBAR_REGION_Pos 0U /*!< MPU RBAR: REGION Position */
#define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */
/* MPU Region Attribute and Size Register Definitions */
#define MPU_RASR_ATTRS_Pos 16U /*!< MPU RASR: MPU Region Attribute field Position */
#define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */
#define MPU_RASR_XN_Pos 28U /*!< MPU RASR: ATTRS.XN Position */
#define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */
#define MPU_RASR_AP_Pos 24U /*!< MPU RASR: ATTRS.AP Position */
#define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */
#define MPU_RASR_TEX_Pos 19U /*!< MPU RASR: ATTRS.TEX Position */
#define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */
#define MPU_RASR_S_Pos 18U /*!< MPU RASR: ATTRS.S Position */
#define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */
#define MPU_RASR_C_Pos 17U /*!< MPU RASR: ATTRS.C Position */
#define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */
#define MPU_RASR_B_Pos 16U /*!< MPU RASR: ATTRS.B Position */
#define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */
#define MPU_RASR_SRD_Pos 8U /*!< MPU RASR: Sub-Region Disable Position */
#define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */
#define MPU_RASR_SIZE_Pos 1U /*!< MPU RASR: Region Size Field Position */
#define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */
#define MPU_RASR_ENABLE_Pos 0U /*!< MPU RASR: Region enable bit Position */
#define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */
/*@} end of group CMSIS_MPU */
#endif /* defined (__MPU_PRESENT) && (__MPU_PRESENT == 1U) */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_FPU Floating Point Unit (FPU)
\brief Type definitions for the Floating Point Unit (FPU)
@{
*/
/**
\brief Structure type to access the Floating Point Unit (FPU).
*/
typedef struct
{
uint32_t RESERVED0[1U];
__IOM uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */
__IOM uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */
__IOM uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */
__IM uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */
__IM uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */
__IM uint32_t MVFR2; /*!< Offset: 0x018 (R/ ) Media and FP Feature Register 2 */
} FPU_Type;
/* Floating-Point Context Control Register Definitions */
#define FPU_FPCCR_ASPEN_Pos 31U /*!< FPCCR: ASPEN bit Position */
#define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */
#define FPU_FPCCR_LSPEN_Pos 30U /*!< FPCCR: LSPEN Position */
#define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */
#define FPU_FPCCR_MONRDY_Pos 8U /*!< FPCCR: MONRDY Position */
#define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */
#define FPU_FPCCR_BFRDY_Pos 6U /*!< FPCCR: BFRDY Position */
#define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */
#define FPU_FPCCR_MMRDY_Pos 5U /*!< FPCCR: MMRDY Position */
#define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */
#define FPU_FPCCR_HFRDY_Pos 4U /*!< FPCCR: HFRDY Position */
#define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */
#define FPU_FPCCR_THREAD_Pos 3U /*!< FPCCR: processor mode bit Position */
#define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */
#define FPU_FPCCR_USER_Pos 1U /*!< FPCCR: privilege level bit Position */
#define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */
#define FPU_FPCCR_LSPACT_Pos 0U /*!< FPCCR: Lazy state preservation active bit Position */
#define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */
/* Floating-Point Context Address Register Definitions */
#define FPU_FPCAR_ADDRESS_Pos 3U /*!< FPCAR: ADDRESS bit Position */
#define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */
/* Floating-Point Default Status Control Register Definitions */
#define FPU_FPDSCR_AHP_Pos 26U /*!< FPDSCR: AHP bit Position */
#define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */
#define FPU_FPDSCR_DN_Pos 25U /*!< FPDSCR: DN bit Position */
#define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */
#define FPU_FPDSCR_FZ_Pos 24U /*!< FPDSCR: FZ bit Position */
#define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */
#define FPU_FPDSCR_RMode_Pos 22U /*!< FPDSCR: RMode bit Position */
#define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */
/* Media and FP Feature Register 0 Definitions */
#define FPU_MVFR0_FP_rounding_modes_Pos 28U /*!< MVFR0: FP rounding modes bits Position */
#define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */
#define FPU_MVFR0_Short_vectors_Pos 24U /*!< MVFR0: Short vectors bits Position */
#define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */
#define FPU_MVFR0_Square_root_Pos 20U /*!< MVFR0: Square root bits Position */
#define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */
#define FPU_MVFR0_Divide_Pos 16U /*!< MVFR0: Divide bits Position */
#define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */
#define FPU_MVFR0_FP_excep_trapping_Pos 12U /*!< MVFR0: FP exception trapping bits Position */
#define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */
#define FPU_MVFR0_Double_precision_Pos 8U /*!< MVFR0: Double-precision bits Position */
#define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */
#define FPU_MVFR0_Single_precision_Pos 4U /*!< MVFR0: Single-precision bits Position */
#define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */
#define FPU_MVFR0_A_SIMD_registers_Pos 0U /*!< MVFR0: A_SIMD registers bits Position */
#define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */
/* Media and FP Feature Register 1 Definitions */
#define FPU_MVFR1_FP_fused_MAC_Pos 28U /*!< MVFR1: FP fused MAC bits Position */
#define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */
#define FPU_MVFR1_FP_HPFP_Pos 24U /*!< MVFR1: FP HPFP bits Position */
#define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */
#define FPU_MVFR1_D_NaN_mode_Pos 4U /*!< MVFR1: D_NaN mode bits Position */
#define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */
#define FPU_MVFR1_FtZ_mode_Pos 0U /*!< MVFR1: FtZ mode bits Position */
#define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */
/* Media and FP Feature Register 2 Definitions */
/*@} end of group CMSIS_FPU */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
\brief Type definitions for the Core Debug Registers
@{
*/
/**
\brief Structure type to access the Core Debug Register (CoreDebug).
*/
typedef struct
{
__IOM uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */
__OM uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */
__IOM uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */
__IOM uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */
} CoreDebug_Type;
/* Debug Halting Control and Status Register Definitions */
#define CoreDebug_DHCSR_DBGKEY_Pos 16U /*!< CoreDebug DHCSR: DBGKEY Position */
#define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */
#define CoreDebug_DHCSR_S_RESET_ST_Pos 25U /*!< CoreDebug DHCSR: S_RESET_ST Position */
#define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */
#define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24U /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
#define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
#define CoreDebug_DHCSR_S_LOCKUP_Pos 19U /*!< CoreDebug DHCSR: S_LOCKUP Position */
#define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */
#define CoreDebug_DHCSR_S_SLEEP_Pos 18U /*!< CoreDebug DHCSR: S_SLEEP Position */
#define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */
#define CoreDebug_DHCSR_S_HALT_Pos 17U /*!< CoreDebug DHCSR: S_HALT Position */
#define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */
#define CoreDebug_DHCSR_S_REGRDY_Pos 16U /*!< CoreDebug DHCSR: S_REGRDY Position */
#define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */
#define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5U /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
#define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
#define CoreDebug_DHCSR_C_MASKINTS_Pos 3U /*!< CoreDebug DHCSR: C_MASKINTS Position */
#define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */
#define CoreDebug_DHCSR_C_STEP_Pos 2U /*!< CoreDebug DHCSR: C_STEP Position */
#define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */
#define CoreDebug_DHCSR_C_HALT_Pos 1U /*!< CoreDebug DHCSR: C_HALT Position */
#define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */
#define CoreDebug_DHCSR_C_DEBUGEN_Pos 0U /*!< CoreDebug DHCSR: C_DEBUGEN Position */
#define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
/* Debug Core Register Selector Register Definitions */
#define CoreDebug_DCRSR_REGWnR_Pos 16U /*!< CoreDebug DCRSR: REGWnR Position */
#define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */
#define CoreDebug_DCRSR_REGSEL_Pos 0U /*!< CoreDebug DCRSR: REGSEL Position */
#define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */
/* Debug Exception and Monitor Control Register Definitions */
#define CoreDebug_DEMCR_TRCENA_Pos 24U /*!< CoreDebug DEMCR: TRCENA Position */
#define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */
#define CoreDebug_DEMCR_MON_REQ_Pos 19U /*!< CoreDebug DEMCR: MON_REQ Position */
#define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */
#define CoreDebug_DEMCR_MON_STEP_Pos 18U /*!< CoreDebug DEMCR: MON_STEP Position */
#define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */
#define CoreDebug_DEMCR_MON_PEND_Pos 17U /*!< CoreDebug DEMCR: MON_PEND Position */
#define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */
#define CoreDebug_DEMCR_MON_EN_Pos 16U /*!< CoreDebug DEMCR: MON_EN Position */
#define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */
#define CoreDebug_DEMCR_VC_HARDERR_Pos 10U /*!< CoreDebug DEMCR: VC_HARDERR Position */
#define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */
#define CoreDebug_DEMCR_VC_INTERR_Pos 9U /*!< CoreDebug DEMCR: VC_INTERR Position */
#define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */
#define CoreDebug_DEMCR_VC_BUSERR_Pos 8U /*!< CoreDebug DEMCR: VC_BUSERR Position */
#define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */
#define CoreDebug_DEMCR_VC_STATERR_Pos 7U /*!< CoreDebug DEMCR: VC_STATERR Position */
#define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */
#define CoreDebug_DEMCR_VC_CHKERR_Pos 6U /*!< CoreDebug DEMCR: VC_CHKERR Position */
#define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */
#define CoreDebug_DEMCR_VC_NOCPERR_Pos 5U /*!< CoreDebug DEMCR: VC_NOCPERR Position */
#define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */
#define CoreDebug_DEMCR_VC_MMERR_Pos 4U /*!< CoreDebug DEMCR: VC_MMERR Position */
#define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */
#define CoreDebug_DEMCR_VC_CORERESET_Pos 0U /*!< CoreDebug DEMCR: VC_CORERESET Position */
#define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */
/*@} end of group CMSIS_CoreDebug */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_core_bitfield Core register bit field macros
\brief Macros for use with bit field definitions (xxx_Pos, xxx_Msk).
@{
*/
/**
\brief Mask and shift a bit field value for use in a register bit range.
\param[in] field Name of the register bit field.
\param[in] value Value of the bit field. This parameter is interpreted as an uint32_t type.
\return Masked and shifted value.
*/
#define _VAL2FLD(field, value) (((uint32_t)(value) << field ## _Pos) & field ## _Msk)
/**
\brief Mask and shift a register value to extract a bit filed value.
\param[in] field Name of the register bit field.
\param[in] value Value of register. This parameter is interpreted as an uint32_t type.
\return Masked and shifted bit field value.
*/
#define _FLD2VAL(field, value) (((uint32_t)(value) & field ## _Msk) >> field ## _Pos)
/*@} end of group CMSIS_core_bitfield */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_core_base Core Definitions
\brief Definitions for base addresses, unions, and structures.
@{
*/
/* Memory mapping of Core Hardware */
#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
#define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */
#define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */
#define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */
#define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
#define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */
#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
#define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */
#define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */
#define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */
#define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */
#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1U)
#define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */
#define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */
#endif
#define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */
#define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */
/*@} */
/*******************************************************************************
* Hardware Abstraction Layer
Core Function Interface contains:
- Core NVIC Functions
- Core SysTick Functions
- Core Debug Functions
- Core Register Access Functions
******************************************************************************/
/**
\defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
*/
/* ########################## NVIC functions #################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_NVICFunctions NVIC Functions
\brief Functions that manage interrupts and exceptions via the NVIC.
@{
*/
#ifdef CMSIS_NVIC_VIRTUAL
#ifndef CMSIS_NVIC_VIRTUAL_HEADER_FILE
#define CMSIS_NVIC_VIRTUAL_HEADER_FILE "cmsis_nvic_virtual.h"
#endif
#include CMSIS_NVIC_VIRTUAL_HEADER_FILE
#else
#define NVIC_SetPriorityGrouping __NVIC_SetPriorityGrouping
#define NVIC_GetPriorityGrouping __NVIC_GetPriorityGrouping
#define NVIC_EnableIRQ __NVIC_EnableIRQ
#define NVIC_GetEnableIRQ __NVIC_GetEnableIRQ
#define NVIC_DisableIRQ __NVIC_DisableIRQ
#define NVIC_GetPendingIRQ __NVIC_GetPendingIRQ
#define NVIC_SetPendingIRQ __NVIC_SetPendingIRQ
#define NVIC_ClearPendingIRQ __NVIC_ClearPendingIRQ
#define NVIC_GetActive __NVIC_GetActive
#define NVIC_SetPriority __NVIC_SetPriority
#define NVIC_GetPriority __NVIC_GetPriority
#define NVIC_SystemReset __NVIC_SystemReset
#endif /* CMSIS_NVIC_VIRTUAL */
#ifdef CMSIS_VECTAB_VIRTUAL
#ifndef CMSIS_VECTAB_VIRTUAL_HEADER_FILE
#define CMSIS_VECTAB_VIRTUAL_HEADER_FILE "cmsis_vectab_virtual.h"
#endif
#include CMSIS_VECTAB_VIRTUAL_HEADER_FILE
#else
#define NVIC_SetVector __NVIC_SetVector
#define NVIC_GetVector __NVIC_GetVector
#endif /* (CMSIS_VECTAB_VIRTUAL) */
#define NVIC_USER_IRQ_OFFSET 16
/**
\brief Set Priority Grouping
\details Sets the priority grouping field using the required unlock sequence.
The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field.
Only values from 0..7 are used.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
\param [in] PriorityGroup Priority grouping field.
*/
__STATIC_INLINE void __NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
{
uint32_t reg_value;
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */
reg_value = SCB->AIRCR; /* read old register configuration */
reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */
reg_value = (reg_value |
((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) |
(PriorityGroupTmp << 8U) ); /* Insert write key and priorty group */
SCB->AIRCR = reg_value;
}
/**
\brief Get Priority Grouping
\details Reads the priority grouping field from the NVIC Interrupt Controller.
\return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field).
*/
__STATIC_INLINE uint32_t __NVIC_GetPriorityGrouping(void)
{
return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos));
}
/**
\brief Enable Interrupt
\details Enables a device specific interrupt in the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_EnableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
}
/**
\brief Get Interrupt Enable status
\details Returns a device specific interrupt enable status from the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt is not enabled.
\return 1 Interrupt is enabled.
\note IRQn must not be negative.
*/
__STATIC_INLINE uint32_t __NVIC_GetEnableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
else
{
return(0U);
}
}
/**
\brief Disable Interrupt
\details Disables a device specific interrupt in the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_DisableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
__DSB();
__ISB();
}
}
/**
\brief Get Pending Interrupt
\details Reads the NVIC pending register and returns the pending bit for the specified device specific interrupt.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt status is not pending.
\return 1 Interrupt status is pending.
\note IRQn must not be negative.
*/
__STATIC_INLINE uint32_t __NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
else
{
return(0U);
}
}
/**
\brief Set Pending Interrupt
\details Sets the pending bit of a device specific interrupt in the NVIC pending register.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
}
/**
\brief Clear Pending Interrupt
\details Clears the pending bit of a device specific interrupt in the NVIC pending register.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
}
/**
\brief Get Active Interrupt
\details Reads the active register in the NVIC and returns the active bit for the device specific interrupt.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt status is not active.
\return 1 Interrupt status is active.
\note IRQn must not be negative.
*/
__STATIC_INLINE uint32_t __NVIC_GetActive(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
else
{
return(0U);
}
}
/**
\brief Set Interrupt Priority
\details Sets the priority of a device specific interrupt or a processor exception.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\param [in] priority Priority to set.
\note The priority cannot be set for every processor exception.
*/
__STATIC_INLINE void __NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL);
}
else
{
SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL);
}
}
/**
\brief Get Interrupt Priority
\details Reads the priority of a device specific interrupt or a processor exception.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\return Interrupt Priority.
Value is aligned automatically to the implemented priority bits of the microcontroller.
*/
__STATIC_INLINE uint32_t __NVIC_GetPriority(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8U - __NVIC_PRIO_BITS)));
}
else
{
return(((uint32_t)SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8U - __NVIC_PRIO_BITS)));
}
}
/**
\brief Encode Priority
\details Encodes the priority for an interrupt with the given priority group,
preemptive priority value, and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
\param [in] PriorityGroup Used priority group.
\param [in] PreemptPriority Preemptive priority value (starting from 0).
\param [in] SubPriority Subpriority value (starting from 0).
\return Encoded priority. Value can be used in the function \ref NVIC_SetPriority().
*/
__STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp);
SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS));
return (
((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) |
((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL)))
);
}
/**
\brief Decode Priority
\details Decodes an interrupt priority value with a given priority group to
preemptive priority value and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set.
\param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority().
\param [in] PriorityGroup Used priority group.
\param [out] pPreemptPriority Preemptive priority value (starting from 0).
\param [out] pSubPriority Subpriority value (starting from 0).
*/
__STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* const pPreemptPriority, uint32_t* const pSubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp);
SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS));
*pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL);
*pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL);
}
/**
\brief Set Interrupt Vector
\details Sets an interrupt vector in SRAM based interrupt vector table.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
VTOR must been relocated to SRAM before.
\param [in] IRQn Interrupt number
\param [in] vector Address of interrupt handler function
*/
__STATIC_INLINE void __NVIC_SetVector(IRQn_Type IRQn, uint32_t vector)
{
uint32_t *vectors = (uint32_t *)SCB->VTOR;
vectors[(int32_t)IRQn + NVIC_USER_IRQ_OFFSET] = vector;
}
/**
\brief Get Interrupt Vector
\details Reads an interrupt vector from interrupt vector table.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\return Address of interrupt handler function
*/
__STATIC_INLINE uint32_t __NVIC_GetVector(IRQn_Type IRQn)
{
uint32_t *vectors = (uint32_t *)SCB->VTOR;
return vectors[(int32_t)IRQn + NVIC_USER_IRQ_OFFSET];
}
/**
\brief System Reset
\details Initiates a system reset request to reset the MCU.
*/
__STATIC_INLINE void __NVIC_SystemReset(void)
{
__DSB(); /* Ensure all outstanding memory accesses included
buffered write are completed before reset */
SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) |
(SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) |
SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */
__DSB(); /* Ensure completion of memory access */
for(;;) /* wait until reset */
{
__NOP();
}
}
/*@} end of CMSIS_Core_NVICFunctions */
/* ########################## MPU functions #################################### */
#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1U)
#include "mpu_armv7.h"
#endif
/* ########################## FPU functions #################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_FpuFunctions FPU Functions
\brief Function that provides FPU type.
@{
*/
/**
\brief get FPU type
\details returns the FPU type
\returns
- \b 0: No FPU
- \b 1: Single precision FPU
- \b 2: Double + Single precision FPU
*/
__STATIC_INLINE uint32_t SCB_GetFPUType(void)
{
uint32_t mvfr0;
mvfr0 = SCB->MVFR0;
if ((mvfr0 & (FPU_MVFR0_Single_precision_Msk | FPU_MVFR0_Double_precision_Msk)) == 0x220U)
{
return 2U; /* Double + Single precision FPU */
}
else if ((mvfr0 & (FPU_MVFR0_Single_precision_Msk | FPU_MVFR0_Double_precision_Msk)) == 0x020U)
{
return 1U; /* Single precision FPU */
}
else
{
return 0U; /* No FPU */
}
}
/*@} end of CMSIS_Core_FpuFunctions */
/* ########################## Cache functions #################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_CacheFunctions Cache Functions
\brief Functions that configure Instruction and Data cache.
@{
*/
/* Cache Size ID Register Macros */
#define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos)
#define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos )
/**
\brief Enable I-Cache
\details Turns on I-Cache
*/
__STATIC_INLINE void SCB_EnableICache (void)
{
#if defined (__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
__DSB();
__ISB();
SCB->ICIALLU = 0UL; /* invalidate I-Cache */
__DSB();
__ISB();
SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; /* enable I-Cache */
__DSB();
__ISB();
#endif
}
/**
\brief Disable I-Cache
\details Turns off I-Cache
*/
__STATIC_INLINE void SCB_DisableICache (void)
{
#if defined (__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
__DSB();
__ISB();
SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; /* disable I-Cache */
SCB->ICIALLU = 0UL; /* invalidate I-Cache */
__DSB();
__ISB();
#endif
}
/**
\brief Invalidate I-Cache
\details Invalidates I-Cache
*/
__STATIC_INLINE void SCB_InvalidateICache (void)
{
#if defined (__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
__DSB();
__ISB();
SCB->ICIALLU = 0UL;
__DSB();
__ISB();
#endif
}
/**
\brief Enable D-Cache
\details Turns on D-Cache
*/
__STATIC_INLINE void SCB_EnableDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
SCB->CSSELR = 0U; /*(0U << 1U) | 0U;*/ /* Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCISW = (((sets << SCB_DCISW_SET_Pos) & SCB_DCISW_SET_Msk) |
((ways << SCB_DCISW_WAY_Pos) & SCB_DCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; /* enable D-Cache */
__DSB();
__ISB();
#endif
}
/**
\brief Disable D-Cache
\details Turns off D-Cache
*/
__STATIC_INLINE void SCB_DisableDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
register uint32_t ccsidr;
register uint32_t sets;
register uint32_t ways;
SCB->CSSELR = 0U; /*(0U << 1U) | 0U;*/ /* Level 1 data cache */
__DSB();
SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; /* disable D-Cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* clean & invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCCISW = (((sets << SCB_DCCISW_SET_Pos) & SCB_DCCISW_SET_Msk) |
((ways << SCB_DCCISW_WAY_Pos) & SCB_DCCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief Invalidate D-Cache
\details Invalidates D-Cache
*/
__STATIC_INLINE void SCB_InvalidateDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
SCB->CSSELR = 0U; /*(0U << 1U) | 0U;*/ /* Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCISW = (((sets << SCB_DCISW_SET_Pos) & SCB_DCISW_SET_Msk) |
((ways << SCB_DCISW_WAY_Pos) & SCB_DCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief Clean D-Cache
\details Cleans D-Cache
*/
__STATIC_INLINE void SCB_CleanDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
SCB->CSSELR = 0U; /*(0U << 1U) | 0U;*/ /* Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* clean D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCCSW = (((sets << SCB_DCCSW_SET_Pos) & SCB_DCCSW_SET_Msk) |
((ways << SCB_DCCSW_WAY_Pos) & SCB_DCCSW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief Clean & Invalidate D-Cache
\details Cleans and Invalidates D-Cache
*/
__STATIC_INLINE void SCB_CleanInvalidateDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
SCB->CSSELR = 0U; /*(0U << 1U) | 0U;*/ /* Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* clean & invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCCISW = (((sets << SCB_DCCISW_SET_Pos) & SCB_DCCISW_SET_Msk) |
((ways << SCB_DCCISW_WAY_Pos) & SCB_DCCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief D-Cache Invalidate by address
\details Invalidates D-Cache for the given address
\param[in] addr address (aligned to 32-byte boundary)
\param[in] dsize size of memory block (in number of bytes)
*/
__STATIC_INLINE void SCB_InvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
int32_t op_size = dsize;
uint32_t op_addr = (uint32_t)addr;
int32_t linesize = 32; /* in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) */
__DSB();
while (op_size > 0) {
SCB->DCIMVAC = op_addr;
op_addr += (uint32_t)linesize;
op_size -= linesize;
}
__DSB();
__ISB();
#endif
}
/**
\brief D-Cache Clean by address
\details Cleans D-Cache for the given address
\param[in] addr address (aligned to 32-byte boundary)
\param[in] dsize size of memory block (in number of bytes)
*/
__STATIC_INLINE void SCB_CleanDCache_by_Addr (uint32_t *addr, int32_t dsize)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
int32_t op_size = dsize;
uint32_t op_addr = (uint32_t) addr;
int32_t linesize = 32; /* in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) */
__DSB();
while (op_size > 0) {
SCB->DCCMVAC = op_addr;
op_addr += (uint32_t)linesize;
op_size -= linesize;
}
__DSB();
__ISB();
#endif
}
/**
\brief D-Cache Clean and Invalidate by address
\details Cleans and invalidates D_Cache for the given address
\param[in] addr address (aligned to 32-byte boundary)
\param[in] dsize size of memory block (in number of bytes)
*/
__STATIC_INLINE void SCB_CleanInvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
int32_t op_size = dsize;
uint32_t op_addr = (uint32_t) addr;
int32_t linesize = 32; /* in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) */
__DSB();
while (op_size > 0) {
SCB->DCCIMVAC = op_addr;
op_addr += (uint32_t)linesize;
op_size -= linesize;
}
__DSB();
__ISB();
#endif
}
/*@} end of CMSIS_Core_CacheFunctions */
/* ################################## SysTick function ############################################ */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_SysTickFunctions SysTick Functions
\brief Functions that configure the System.
@{
*/
#if defined (__Vendor_SysTickConfig) && (__Vendor_SysTickConfig == 0U)
/**
\brief System Tick Configuration
\details Initializes the System Timer and its interrupt, and starts the System Tick Timer.
Counter is in free running mode to generate periodic interrupts.
\param [in] ticks Number of ticks between two interrupts.
\return 0 Function succeeded.
\return 1 Function failed.
\note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
must contain a vendor-specific implementation of this function.
*/
__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk)
{
return (1UL); /* Reload value impossible */
}
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0UL); /* Function successful */
}
#endif
/*@} end of CMSIS_Core_SysTickFunctions */
/* ##################################### Debug In/Output function ########################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_core_DebugFunctions ITM Functions
\brief Functions that access the ITM debug interface.
@{
*/
extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */
#define ITM_RXBUFFER_EMPTY ((int32_t)0x5AA55AA5U) /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */
/**
\brief ITM Send Character
\details Transmits a character via the ITM channel 0, and
\li Just returns when no debugger is connected that has booked the output.
\li Is blocking when a debugger is connected, but the previous character sent has not been transmitted.
\param [in] ch Character to transmit.
\returns Character to transmit.
*/
__STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch)
{
if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */
((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */
{
while (ITM->PORT[0U].u32 == 0UL)
{
__NOP();
}
ITM->PORT[0U].u8 = (uint8_t)ch;
}
return (ch);
}
/**
\brief ITM Receive Character
\details Inputs a character via the external variable \ref ITM_RxBuffer.
\return Received character.
\return -1 No character pending.
*/
__STATIC_INLINE int32_t ITM_ReceiveChar (void)
{
int32_t ch = -1; /* no character available */
if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY)
{
ch = ITM_RxBuffer;
ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */
}
return (ch);
}
/**
\brief ITM Check Character
\details Checks whether a character is pending for reading in the variable \ref ITM_RxBuffer.
\return 0 No character available.
\return 1 Character available.
*/
__STATIC_INLINE int32_t ITM_CheckChar (void)
{
if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY)
{
return (0); /* no character available */
}
else
{
return (1); /* character available */
}
}
/*@} end of CMSIS_core_DebugFunctions */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM7_H_DEPENDANT */
#endif /* __CMSIS_GENERIC */
|
import os
import pprint
from dbt.adapters.factory import load_plugin
from dbt.clients.system import load_file_contents
from dbt.clients.yaml_helper import load_yaml_text
from dbt.contracts.project import ProfileConfig
from dbt.exceptions import DbtProfileError
from dbt.exceptions import DbtProjectError
from dbt.exceptions import ValidationException
from dbt.exceptions import RuntimeException
from dbt.logger import GLOBAL_LOGGER as logger
from dbt.utils import parse_cli_vars
from .renderer import ConfigRenderer
DEFAULT_THREADS = 1
DEFAULT_SEND_ANONYMOUS_USAGE_STATS = True
DEFAULT_USE_COLORS = True
DEFAULT_PROFILES_DIR = os.path.join(os.path.expanduser('~'), '.dbt')
PROFILES_DIR = os.path.expanduser(
os.environ.get('DBT_PROFILES_DIR', DEFAULT_PROFILES_DIR)
)
INVALID_PROFILE_MESSAGE = """
dbt encountered an error while trying to read your profiles.yml file.
{error_string}
"""
NO_SUPPLIED_PROFILE_ERROR = """\
dbt cannot run because no profile was specified for this dbt project.
To specify a profile for this project, add a line like the this to
your dbt_project.yml file:
profile: [profile name]
Here, [profile name] should be replaced with a profile name
defined in your profiles.yml file. You can find profiles.yml here:
{profiles_file}/profiles.yml
""".format(profiles_file=PROFILES_DIR)
def read_profile(profiles_dir):
path = os.path.join(profiles_dir, 'profiles.yml')
contents = None
if os.path.isfile(path):
try:
contents = load_file_contents(path, strip=False)
return load_yaml_text(contents)
except ValidationException as e:
msg = INVALID_PROFILE_MESSAGE.format(error_string=e)
raise ValidationException(msg)
return {}
class UserConfig(object):
def __init__(self, send_anonymous_usage_stats, use_colors):
self.send_anonymous_usage_stats = send_anonymous_usage_stats
self.use_colors = use_colors
@classmethod
def from_dict(cls, cfg=None):
if cfg is None:
cfg = {}
send_anonymous_usage_stats = cfg.get(
'send_anonymous_usage_stats',
DEFAULT_SEND_ANONYMOUS_USAGE_STATS
)
use_colors = cfg.get(
'use_colors',
DEFAULT_USE_COLORS
)
return cls(send_anonymous_usage_stats, use_colors)
def to_dict(self):
return {
'send_anonymous_usage_stats': self.send_anonymous_usage_stats,
'use_colors': self.use_colors,
}
@classmethod
def from_directory(cls, directory):
user_cfg = None
profile = read_profile(directory)
if profile:
user_cfg = profile.get('config', {})
return cls.from_dict(user_cfg)
class Profile(object):
def __init__(self, profile_name, target_name, config, threads,
credentials):
self.profile_name = profile_name
self.target_name = target_name
if isinstance(config, dict):
config = UserConfig.from_dict(config)
self.config = config
self.threads = threads
self.credentials = credentials
def to_profile_info(self, serialize_credentials=False):
"""Unlike to_project_config, this dict is not a mirror of any existing
on-disk data structure. It's used when creating a new profile from an
existing one.
:param serialize_credentials bool: If True, serialize the credentials.
Otherwise, the Credentials object will be copied.
:returns dict: The serialized profile.
"""
result = {
'profile_name': self.profile_name,
'target_name': self.target_name,
'config': self.config.to_dict(),
'threads': self.threads,
'credentials': self.credentials.incorporate(),
}
if serialize_credentials:
result['credentials'] = result['credentials'].serialize()
return result
def __str__(self):
return pprint.pformat(self.to_profile_info())
def __eq__(self, other):
if not (isinstance(other, self.__class__) and
isinstance(self, other.__class__)):
return False
return False
return self.to_profile_info() == other.to_profile_info()
def validate(self):
if self.credentials:
self.credentials.validate()
try:
ProfileConfig(**self.to_profile_info(serialize_credentials=True))
except ValidationException as exc:
raise DbtProfileError(str(exc))
@staticmethod
def _credentials_from_profile(profile, profile_name, target_name):
# credentials carry their 'type' in their actual type, not their
# attributes. We do want this in order to pick our Credentials class.
if 'type' not in profile:
raise DbtProfileError(
'required field "type" not found in profile {} and target {}'
.format(profile_name, target_name))
typename = profile.pop('type')
try:
cls = load_plugin(typename)
credentials = cls(**profile)
except RuntimeException as e:
raise DbtProfileError(
'Credentials in profile "{}", target "{}" invalid: {}'
.format(profile_name, target_name, str(e))
)
return credentials
@staticmethod
def pick_profile_name(args_profile_name, project_profile_name=None):
profile_name = project_profile_name
if args_profile_name is not None:
profile_name = args_profile_name
if profile_name is None:
raise DbtProjectError(NO_SUPPLIED_PROFILE_ERROR)
return profile_name
@staticmethod
def _get_profile_data(profile, profile_name, target_name):
if 'outputs' not in profile:
raise DbtProfileError(
"outputs not specified in profile '{}'".format(profile_name)
)
outputs = profile['outputs']
if target_name not in outputs:
outputs = '\n'.join(' - {}'.format(output)
for output in outputs)
msg = ("The profile '{}' does not have a target named '{}'. The "
"valid target names for this profile are:\n{}"
.format(profile_name, target_name, outputs))
raise DbtProfileError(msg, result_type='invalid_target')
profile_data = outputs[target_name]
return profile_data
@classmethod
def from_credentials(cls, credentials, threads, profile_name, target_name,
user_cfg=None):
"""Create a profile from an existing set of Credentials and the
remaining information.
:param credentials dict: The credentials dict for this profile.
:param threads int: The number of threads to use for connections.
:param profile_name str: The profile name used for this profile.
:param target_name str: The target name used for this profile.
:param user_cfg Optional[dict]: The user-level config block from the
raw profiles, if specified.
:raises DbtProfileError: If the profile is invalid.
:returns Profile: The new Profile object.
"""
config = UserConfig.from_dict(user_cfg)
profile = cls(
profile_name=profile_name,
target_name=target_name,
config=config,
threads=threads,
credentials=credentials
)
profile.validate()
return profile
@classmethod
def render_profile(cls, raw_profile, profile_name, target_override,
cli_vars):
"""This is a containment zone for the hateful way we're rendering
profiles.
"""
renderer = ConfigRenderer(cli_vars=cli_vars)
# rendering profiles is a bit complex. Two constraints cause trouble:
# 1) users should be able to use environment/cli variables to specify
# the target in their profile.
# 2) Missing environment/cli variables in profiles/targets that don't
# end up getting selected should not cause errors.
# so first we'll just render the target name, then we use that rendered
# name to extract a profile that we can render.
if target_override is not None:
target_name = target_override
elif 'target' in raw_profile:
# render the target if it was parsed from yaml
target_name = renderer.render_value(raw_profile['target'])
else:
target_name = 'default'
logger.debug(
"target not specified in profile '{}', using '{}'"
.format(profile_name, target_name)
)
raw_profile_data = cls._get_profile_data(
raw_profile, profile_name, target_name
)
profile_data = renderer.render_profile_data(raw_profile_data)
return target_name, profile_data
@classmethod
def from_raw_profile_info(cls, raw_profile, profile_name, cli_vars,
user_cfg=None, target_override=None,
threads_override=None):
"""Create a profile from its raw profile information.
(this is an intermediate step, mostly useful for unit testing)
:param raw_profile dict: The profile data for a single profile, from
disk as yaml and its values rendered with jinja.
:param profile_name str: The profile name used.
:param cli_vars dict: The command-line variables passed as arguments,
as a dict.
:param user_cfg Optional[dict]: The global config for the user, if it
was present.
:param target_override Optional[str]: The target to use, if provided on
the command line.
:param threads_override Optional[str]: The thread count to use, if
provided on the command line.
:raises DbtProfileError: If the profile is invalid or missing, or the
target could not be found
:returns Profile: The new Profile object.
"""
# user_cfg is not rendered since it only contains booleans.
# TODO: should it be, and the values coerced to bool?
target_name, profile_data = cls.render_profile(
raw_profile, profile_name, target_override, cli_vars
)
# valid connections never include the number of threads, but it's
# stored on a per-connection level in the raw configs
threads = profile_data.pop('threads', DEFAULT_THREADS)
if threads_override is not None:
threads = threads_override
credentials = cls._credentials_from_profile(
profile_data, profile_name, target_name
)
return cls.from_credentials(
credentials=credentials,
profile_name=profile_name,
target_name=target_name,
threads=threads,
user_cfg=user_cfg
)
@classmethod
def from_raw_profiles(cls, raw_profiles, profile_name, cli_vars,
target_override=None, threads_override=None):
"""
:param raw_profiles dict: The profile data, from disk as yaml.
:param profile_name str: The profile name to use.
:param cli_vars dict: The command-line variables passed as arguments,
as a dict.
:param target_override Optional[str]: The target to use, if provided on
the command line.
:param threads_override Optional[str]: The thread count to use, if
provided on the command line.
:raises DbtProjectError: If there is no profile name specified in the
project or the command line arguments
:raises DbtProfileError: If the profile is invalid or missing, or the
target could not be found
:returns Profile: The new Profile object.
"""
if profile_name not in raw_profiles:
raise DbtProjectError(
"Could not find profile named '{}'".format(profile_name)
)
# First, we've already got our final decision on profile name, and we
# don't render keys, so we can pluck that out
raw_profile = raw_profiles[profile_name]
user_cfg = raw_profiles.get('config')
return cls.from_raw_profile_info(
raw_profile=raw_profile,
profile_name=profile_name,
cli_vars=cli_vars,
user_cfg=user_cfg,
target_override=target_override,
threads_override=threads_override,
)
@classmethod
def from_args(cls, args, project_profile_name=None, cli_vars=None):
"""Given the raw profiles as read from disk and the name of the desired
profile if specified, return the profile component of the runtime
config.
:param args argparse.Namespace: The arguments as parsed from the cli.
:param cli_vars dict: The command-line variables passed as arguments,
as a dict.
:param project_profile_name Optional[str]: The profile name, if
specified in a project.
:raises DbtProjectError: If there is no profile name specified in the
project or the command line arguments, or if the specified profile
is not found
:raises DbtProfileError: If the profile is invalid or missing, or the
target could not be found.
:returns Profile: The new Profile object.
"""
if cli_vars is None:
cli_vars = parse_cli_vars(getattr(args, 'vars', '{}'))
threads_override = getattr(args, 'threads', None)
target_override = getattr(args, 'target', None)
raw_profiles = read_profile(args.profiles_dir)
profile_name = cls.pick_profile_name(args.profile,
project_profile_name)
return cls.from_raw_profiles(
raw_profiles=raw_profiles,
profile_name=profile_name,
cli_vars=cli_vars,
target_override=target_override,
threads_override=threads_override
)
|
var searchData=
[
['december',['December',['../namespace_tool_box.html#a02b7f221324576ea6af4c3a320dfd804a82331503174acbae012b2004f6431fa5',1,'ToolBox']]]
];
|
from django.core.management.base import BaseCommand, CommandError
from charts.models import ChartConfig
class Command(BaseCommand):
help = "Delete all ChartConfig objects"
def handle(self, *args, **options):
all = ChartConfig.objects.all()
self.stdout.write("{} ChartConfig Type objects will be deleted".format(all.count()))
all.delete()
self.stdout.write("All ChartConfig objects are gone")
|
from aioauth_client import OAuth2Client
class DiscordClient(OAuth2Client):
access_token_url = 'https://discordapp.com/api/oauth2/token'
authorize_url = 'https://discordapp.com/api/oauth2/authorize'
base_url = 'https://discordapp.com/api/v6/'
name = 'discord'
user_info_url = 'https://discordapp.com/api/v6/users/@me'
@staticmethod
def user_parse(data):
yield 'id', data.get('id')
yield 'username', data.get('username')
yield 'discriminator', data.get('discriminator')
yield 'picture', "https://cdn.discordapp.com/avatars/{}/{}.png".format(
data.get('id'), data.get('avatar'))
def request(self, method, url, headers=None, **aio_kwargs):
"""Request OAuth2 resource."""
url = self._get_url(url)
headers = headers or {'Accept': 'application/json'}
if self.access_token:
headers['Authorization'] = "Bearer {}".format(self.access_token)
return self._request(method, url, headers=headers, **aio_kwargs)
|
import threading
from MvCameraControl_class import *
def Save_jpg(cam, stOutFrame, buf_cache):
if buf_cache is None:
return
buf_save_image = None
file_path = str(stOutFrame.stFrameInfo.nFrameNum) + ".jpg"
n_save_image_size = stOutFrame.stFrameInfo.nWidth * stOutFrame.stFrameInfo.nHeight * 3 + 2048
if buf_save_image is None:
buf_save_image = (c_ubyte * n_save_image_size)()
stParam = MV_SAVE_IMAGE_PARAM_EX()
stParam.enImageType = MV_Image_Jpeg # ch:需要保存的图像类型 | en:Image format to save
stParam.enPixelType = stOutFrame.stFrameInfo.enPixelType # ch:相机对应的像素格式 | en:Camera pixel type
stParam.nWidth = stOutFrame.stFrameInfo.nWidth # ch:相机对应的宽 | en:Width
stParam.nHeight = stOutFrame.stFrameInfo.nHeight # ch:相机对应的高 | en:Height
stParam.nDataLen = stOutFrame.stFrameInfo.nFrameLen
stParam.pData = cast(buf_cache, POINTER(c_ubyte))
stParam.pImageBuffer = cast(byref(buf_save_image), POINTER(c_ubyte))
stParam.nBufferSize = n_save_image_size # ch:存储节点的大小 | en:Buffer node size
stParam.nJpgQuality = 80 # ch:jpg编码,仅在保存Jpg图像时有效。保存BMP时SDK内忽略该参数
return_code = cam.MV_CC_SaveImageEx2(stParam)
if return_code != 0:
return
file_open = open(file_path.encode('ascii'), 'wb+')
img_buff = (c_ubyte * stParam.nImageLen)()
try:
cdll.msvcrt.memcpy(byref(img_buff), stParam.pImageBuffer, stParam.nImageLen)
file_open.write(img_buff)
except:
b_save_jpg = False
raise Exception("get one frame failed")
# 为线程定义一个函数
def work_thread(cam, pData=0, nDataSize=0):
stOutFrame = MV_FRAME_OUT()
memset(byref(stOutFrame), 0, sizeof(stOutFrame))
cam.MV_CC_GetImageBuffer(stOutFrame, 1000)
buf_cache = (c_ubyte * stOutFrame.stFrameInfo.nFrameLen)()
cdll.msvcrt.memcpy(byref(buf_cache), stOutFrame.pBufAddr, stOutFrame.stFrameInfo.nFrameLen)
if stOutFrame.pBufAddr is not None:
print("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (
stOutFrame.stFrameInfo.nWidth, stOutFrame.stFrameInfo.nHeight, stOutFrame.stFrameInfo.nFrameNum))
Save_jpg(cam, stOutFrame, buf_cache)
nRet = cam.MV_CC_FreeImageBuffer(stOutFrame)
else:
print("no data")
pass
def GetCam():
deviceList = MV_CC_DEVICE_INFO_LIST()
tLayerType = MV_GIGE_DEVICE | MV_USB_DEVICE
# ch:枚举设备 | en:Enum device
ret = MvCamera.MV_CC_EnumDevices(tLayerType, deviceList)
if ret != 0:
print("enum devices fail! ret[0x%x]" % ret)
sys.exit()
if deviceList.nDeviceNum == 0:
print("find no device!")
sys.exit()
print("Find %d devices!" % deviceList.nDeviceNum)
for i in range(0, deviceList.nDeviceNum):
mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE:
print("\ngige device: [%d]" % i)
strModeName = ""
for per in mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName:
strModeName = strModeName + chr(per)
print("device model name: %s" % strModeName)
nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
print("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
print("\nu3v device: [%d]" % i)
strModeName = ""
for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName:
if per == 0:
break
strModeName = strModeName + chr(per)
print("device model name: %s" % strModeName)
strSerialNumber = ""
for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber:
if per == 0:
break
strSerialNumber = strSerialNumber + chr(per)
print("user serial number: %s" % strSerialNumber)
nConnectionNum = input("please input the number of the device to connect:")
if int(nConnectionNum) >= deviceList.nDeviceNum:
print("input error!")
sys.exit()
if int(nConnectionNum) >= deviceList.nDeviceNum:
print("input error!")
sys.exit()
# ch:创建相机实例 | en:Creat Camera Object
cam = MvCamera()
return deviceList, nConnectionNum, cam
def OpenCam(deviceList, nConnectionNum, cam):
# ch:选择设备并创建句柄 | en:Select device and create handle
stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents
ret = cam.MV_CC_CreateHandle(stDeviceList)
if ret != 0:
print("create handle fail! ret[0x%x]" % ret)
sys.exit()
# ch:打开设备 | en:Open device
ret = cam.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
if ret != 0:
print("open device fail! ret[0x%x]" % ret)
sys.exit()
# ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
if stDeviceList.nTLayerType == MV_GIGE_DEVICE:
nPacketSize = cam.MV_CC_GetOptimalPacketSize()
if int(nPacketSize) > 0:
ret = cam.MV_CC_SetIntValue("GevSCPSPacketSize", nPacketSize)
if ret != 0:
print("Warning: Set Packet Size fail! ret[0x%x]" % ret)
else:
print("Warning: Get Packet Size fail! ret[0x%x]" % nPacketSize)
stBool = c_bool(False)
ret = cam.MV_CC_GetBoolValue("AcquisitionFrameRateEnable", stBool)
if ret != 0:
print("get AcquisitionFrameRateEnable fail! ret[0x%x]" % ret)
sys.exit()
# ch:设置触发模式为off | en:Set trigger mode as off
ret = cam.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF)
if ret != 0:
print("set trigger mode fail! ret[0x%x]" % ret)
sys.exit()
return
def OpenStreaming(cam):
# ch:开始取流 | en:Start grab image
ret = cam.MV_CC_StartGrabbing()
if ret != 0:
print("start grabbing fail! ret[0x%x]" % ret)
sys.exit()
try:
print("press a key to stop grabbing.")
hThreadHandle = threading.Thread(target=work_thread, args=(cam, None, None))
hThreadHandle.start()
except:
print("error: unable to start thread")
hThreadHandle.join()
def CloseStreaming(cam):
# ch:停止取流 | en:Stop grab image
ret = cam.MV_CC_StopGrabbing()
if ret != 0:
print("stop grabbing fail! ret[0x%x]" % ret)
sys.exit()
def CloseCam(cam):
# ch:关闭设备 | Close device
ret = cam.MV_CC_CloseDevice()
if ret != 0:
print("close deivce fail! ret[0x%x]" % ret)
sys.exit()
# ch:销毁句柄 | Destroy handle
ret = cam.MV_CC_DestroyHandle()
if ret != 0:
print("destroy handle fail! ret[0x%x]" % ret)
sys.exit()
|
/**
* Copyright IBM Corp. 2019, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*
* Code generated by @carbon/icon-build-helpers. DO NOT EDIT.
*/
'use strict';
var Icon = require('../Icon-1083255b.js');
var React = require('react');
require('@carbon/icon-helpers');
require('prop-types');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var _path, _path2;
var UndefinedFilled16 = /*#__PURE__*/React__default['default'].forwardRef(function UndefinedFilled16(_ref, ref) {
var children = _ref.children,
rest = Icon._objectWithoutProperties(_ref, ["children"]);
return /*#__PURE__*/React__default['default'].createElement(Icon.Icon, Icon._extends({
width: 16,
height: 16,
viewBox: "0 0 32 32",
xmlns: "http://www.w3.org/2000/svg",
fill: "currentColor",
ref: ref
}, rest), _path || (_path = /*#__PURE__*/React__default['default'].createElement("path", {
d: "M29.4162,14.5905,17.41,2.5838a1.9937,1.9937,0,0,0-2.8192,0L2.5838,14.5905a1.9934,1.9934,0,0,0,0,2.819L14.5905,29.4162a1.9937,1.9937,0,0,0,2.8192,0L29.4162,17.41A1.9934,1.9934,0,0,0,29.4162,14.5905ZM21,18H11V14H21Z"
})), _path2 || (_path2 = /*#__PURE__*/React__default['default'].createElement("path", {
fill: "none",
d: "M11 14H21V18H11z",
"data-icon-path": "inner-path"
})), children);
});
module.exports = UndefinedFilled16;
|
import pytest
from syft.frameworks.torch.he.fv.util.numth import is_prime
from syft.frameworks.torch.he.fv.util.operations import multiply_many_except
from syft.frameworks.torch.he.fv.modulus import CoeffModulus
from syft.frameworks.torch.he.fv.encryption_params import EncryptionParams
from syft.frameworks.torch.he.fv.modulus import SeqLevelType
from syft.frameworks.torch.he.fv.context import Context
from syft.frameworks.torch.he.fv.util.operations import poly_add_mod
from syft.frameworks.torch.he.fv.util.operations import poly_mul_mod
from syft.frameworks.torch.he.fv.util.operations import poly_negate_mod
from syft.frameworks.torch.he.fv.util.operations import get_significant_count
from syft.frameworks.torch.he.fv.integer_encoder import IntegerEncoder
from syft.frameworks.torch.he.fv.key_generator import KeyGenerator
from syft.frameworks.torch.he.fv.util.base_converter import BaseConvertor
from syft.frameworks.torch.he.fv.util.rns_base import RNSBase
from syft.frameworks.torch.he.fv.util.operations import invert_mod
from syft.frameworks.torch.he.fv.util.operations import xgcd
from syft.frameworks.torch.he.fv.util.operations import reverse_bit
from syft.frameworks.torch.he.fv.encryptor import Encryptor
from syft.frameworks.torch.he.fv.decryptor import Decryptor
from syft.frameworks.torch.he.fv.evaluator import Evaluator
from syft.frameworks.torch.he.fv.secret_key import SecretKey
@pytest.mark.parametrize(
"num, status",
[
(0, False),
(2, True),
(3, True),
(4, False),
(5, True),
(221, False),
(65537, True),
(65536, False),
(59399, True),
(72307, True),
(36893488147419103, True),
(36893488147419107, False),
(72307 * 59399, False),
],
)
def test_is_prime(num, status):
assert is_prime(num) == status
@pytest.mark.parametrize(
"value, result", [(0, 0), (2, 1), (3, 3), (4, 1), (255, 255), (256, 1), (172, 53)]
)
def test_reverse_bit(value, result):
assert reverse_bit(value) == result
@pytest.mark.parametrize(
"poly_modulus, plain_modulus, coeff_bit_sizes",
[(128, 2, [30, 40, 50]), (1024, 64, [30, 60, 60]), (64, 64, [30])],
)
def test_EncryptionParams(poly_modulus, plain_modulus, coeff_bit_sizes):
params = EncryptionParams(
poly_modulus, CoeffModulus().create(poly_modulus, coeff_bit_sizes), plain_modulus
)
for i in range(len(coeff_bit_sizes)):
assert is_prime(params.coeff_modulus[i])
def test_CoeffModulus_create():
coeffModulus = CoeffModulus()
assert len(coeffModulus.create(2, [])) == 0
cm = coeffModulus.create(2, [3])
assert len(cm) == 1
assert cm[0] == 5
cm = coeffModulus.create(2, [3, 4])
assert len(cm) == 2
assert cm[0] == 5
assert cm[1] == 13
cm = coeffModulus.create(2, [3, 5, 4, 5])
assert len(cm) == 4
assert cm[0] == 5
assert cm[1] == 17
assert cm[2] == 13
assert cm[3] == 29
cm = coeffModulus.create(32, [30, 40, 30, 30, 40])
assert len(cm) == 5
assert cm[0] % 64 == 1
assert cm[1] % 64 == 1
assert cm[2] % 64 == 1
assert cm[3] % 64 == 1
assert cm[4] % 64 == 1
@pytest.mark.parametrize(
"poly_modulus, SeqLevelType, result",
[
(1024, SeqLevelType.TC128, 1),
(1024, SeqLevelType.TC192, 1),
(1024, SeqLevelType.TC256, 1),
(2048, SeqLevelType.TC128, 1),
(2048, SeqLevelType.TC192, 1),
(2048, SeqLevelType.TC256, 1),
(4096, SeqLevelType.TC128, 3),
(4096, SeqLevelType.TC192, 3),
(4096, SeqLevelType.TC256, 1),
(8192, SeqLevelType.TC128, 5),
(8192, SeqLevelType.TC192, 4),
(8192, SeqLevelType.TC256, 3),
(16384, SeqLevelType.TC128, 9),
(16384, SeqLevelType.TC192, 6),
(16384, SeqLevelType.TC256, 5),
(32768, SeqLevelType.TC128, 16),
(32768, SeqLevelType.TC192, 11),
(32768, SeqLevelType.TC256, 9),
],
)
def test_CoeffModulus_bfv_default(poly_modulus, SeqLevelType, result):
coeffModulus = CoeffModulus()
assert len(coeffModulus.bfv_default(poly_modulus, SeqLevelType)) == result
@pytest.mark.parametrize(
"op1, op2, coeff_mod, poly_mod, result",
[
([0, 0], [0, 0], 3, 2, [0, 0]),
([1, 2, 3, 4], [2, 3, 4, 5], 3, 4, [0, 2, 1, 0]),
([1, 2, 3, 4], [2, 3, 4, 5], 1, 4, [0, 0, 0, 0]),
([1, 2, 3, 4, 5], [1, -4], 3, 5, [2, 1, 0, 1, 2]),
([4, 4], [-4, -4, -4, -4], 4, 4, [0, 0, 0, 0]),
],
)
def test_poly_add_mod(op1, op2, coeff_mod, poly_mod, result):
assert poly_add_mod(op1, op2, coeff_mod, poly_mod) == result
@pytest.mark.parametrize(
"op1, op2, coeff_mod, poly_mod, result",
[
([1, 1], [2, 1], 5, 2, [1, 3]),
([1, 2, 3, 4], [2, 3, 4, 5], 5, 4, [3, 1, 1, 0]),
([1, 2, 3, 4, 5], [1, -4], 3, 5, [0, 1, 1, 1, 1]),
([4, 4], [-4, -4, -4, -4], 4, 4, [0, 0, 0, 0]),
],
)
def test_poly_mul_mod(op1, op2, coeff_mod, poly_mod, result):
assert poly_mul_mod(op1, op2, coeff_mod, poly_mod) == result
@pytest.mark.parametrize("op1, mod, result", [([2, 3], 7, [5, 4]), ([0, 0], 7, [0, 0])])
def test_poly_negate_mod(op1, mod, result):
assert poly_negate_mod(op1, mod) == result
@pytest.mark.parametrize(
"ptr, result",
[
([0, 0], 0),
([1, 0], 1),
([2, 0], 1),
([0xFFFFFFFFFFFFFFFF, 0], 1),
([0, 1], 2),
([0xFFFFFFFFFFFFFFFF, 1], 2),
([0xFFFFFFFFFFFFFFFF, 0x8000000000000000], 2),
([0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF], 2),
],
)
def test_get_significant_count(ptr, result):
assert result == get_significant_count(ptr)
@pytest.mark.parametrize(
"poly_mod, coeff_mod, plain_mod, sk, max_power, result",
[
(2, [11], 2, [[1, 1]], 2, [[[1, 1]], [[0, 2]]]),
(4, [11], 4, [[1, 0, 10, 10]], 3, [[[1, 0, 10, 10]], [[0, 9, 8, 9]], [[6, 4, 6, 0]]]),
(
8,
[131],
8,
[[1, 0, 130, 130, 0, 130, 0, 1]],
4,
[
[[1, 0, 130, 130, 0, 130, 0, 1]],
[[130, 2, 130, 129, 3, 0, 0, 4]],
[[126, 10, 6, 125, 6, 4, 124, 1]],
[[107, 4, 22, 107, 118, 16, 113, 111]],
],
),
(
8,
[131],
8,
[[1, 130, 0, 130, 130, 0, 0, 0]],
4,
[
[[1, 130, 0, 130, 130, 0, 0, 0]],
[[0, 129, 1, 129, 0, 2, 1, 2]],
[[4, 1, 6, 130, 4, 3, 0, 3]],
[[14, 0, 8, 123, 0, 123, 123, 0]],
],
),
],
)
def test_get_sufficient_sk_power(poly_mod, coeff_mod, plain_mod, sk, max_power, result):
ctx = Context(EncryptionParams(poly_mod, coeff_mod, plain_mod))
sk = SecretKey(sk)
decrypter = Decryptor(ctx, sk)
output = decrypter._get_sufficient_sk_power(max_power)
assert output == result
@pytest.mark.parametrize(
"poly_mod, coeff_mod, plain_mod, sk, ct, result",
[
(2, [17], 2, [[1, 1]], [[[1, 1]], [[1, 1]], [[1, 1]]], [[16, 5]]),
(2, [17], 2, [[1, 1]], [[[1, 1]], [[2, 3]], [[15, 5]]], [[7, 2]]),
(
4,
[31],
4,
[[1, 30, 30, 0]],
[[[189, 231, 179, 412]], [[12, 10, 0, 11]], [[134, 234, 11, 199]]],
[[29, 25, 25, 22]],
),
(
4,
[1031],
4,
[[0, 1, 1030, 1030]],
[[[1, 2, 3, 4]], [[1, 2, 3, 4]], [[1, 2, 3, 4]], [[1, 2, 3, 4]]],
[[32, 32, 4, 1019]],
),
(
4,
[1031],
4,
[[1030, 1, 1, 1030]],
[[[1, 1, 1, 1]], [[1, 2, 3, 4]], [[4, 3, 2, 1]], [[0, 0, 0, 0]]],
[[1026, 1030, 1028, 13]],
),
],
)
def test_mul_ct_sk(poly_mod, coeff_mod, plain_mod, sk, ct, result):
ctx = Context(EncryptionParams(poly_mod, coeff_mod, plain_mod))
sk = SecretKey(sk)
decrypter = Decryptor(ctx, sk)
output = decrypter._mul_ct_sk(ct)
assert output == result
@pytest.mark.parametrize(
"plain_modulus, value",
[
(0xFFFFFFFFFFFFFFF, 1),
(0xFFFFFFFFFFFFFFF, 2),
(0xFFFFFFFFFFFFFFF, -3),
(0xFFFFFFFFFFFFFFF, 64),
(0xFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF),
(0xFFFFFFFFFFFFFFF, 0x80F02),
(1024, 64),
],
)
def test_integer_encoder(plain_modulus, value):
enc_param = EncryptionParams(
16, CoeffModulus().create(plain_modulus, [100, 100, 100]), plain_modulus
)
ctx = Context(enc_param)
encoder = IntegerEncoder(ctx)
poly = encoder.encode(value)
assert value == encoder.decode(poly)
@pytest.mark.parametrize(
"operand, count, exp, result",
[
([0, 0, 0], 2, 0, 0),
([0, 0, 0], 3, 0, 0),
([0, 0, 0], 2, 0, 0),
([2, 3, 5], 2, 0, 3),
([2, 3, 5], 2, 1, 2),
([2, 3, 5], 3, 0, 15),
([2, 3, 5], 3, 1, 10),
([2, 3, 5], 3, 2, 6),
],
)
def test_multiply_many_except(operand, count, exp, result):
assert multiply_many_except(operand, count, exp) == result
@pytest.mark.parametrize(
"x, y, result",
[
(7, 7, [7, 0, 1]),
(2, 2, [2, 0, 1]),
(1, 1, [1, 0, 1]),
(1, 2, [1, 1, 0]),
(5, 6, [1, -1, 1]),
(13, 19, [1, 3, -2]),
(14, 21, [7, -1, 1]),
(2, 1, [1, 0, 1]),
(6, 5, [1, 1, -1]),
(19, 13, [1, -2, 3]),
(21, 14, [7, 1, -1]),
],
)
def test_xgcd(x, y, result):
assert result == xgcd(x, y)
@pytest.mark.parametrize(
"input, modulus, result", [(1, 2, 1), (3, 2, 1), (0xFFFFFF, 2, 1), (5, 19, 4), (4, 19, 5)]
)
def test_invert_mod(input, modulus, result):
assert result == invert_mod(input, modulus)
@pytest.mark.parametrize(
"ibase, obase, input, output",
[
([3], [2], [[0, 1, 2]], [[0, 1, 0]]),
([2, 3], [2], [[0, 1, 0], [0, 1, 2]], [[0, 1, 0]]),
([2, 3], [2, 3], [[1, 1, 0], [1, 2, 2]], [[1, 1, 0], [1, 2, 2]]),
([2, 3], [3, 4, 5], [[0, 1, 1], [0, 1, 2]], [[0, 1, 2], [0, 3, 1], [0, 2, 0]]),
],
)
def test_fast_convert_list(ibase, obase, input, output):
base_converter = BaseConvertor(RNSBase(ibase), RNSBase(obase))
result = base_converter.fast_convert_list(input, 3)
for i in range(len(result)):
for j in range(len(result[0])):
assert result[i][j] == output[i][j]
@pytest.mark.parametrize(
"poly_modulus, plain_modulus, coeff_bit_sizes, integer",
[
(64, 64, [40], 0x12345678),
(4096, 64, [40], 0),
(1024, 64, [40], 1),
(64, 64, [40], 2),
(64, 64, [40], 0x7FFFFFFFFFFFFFFD),
(4096, 64, [40], 0x7FFFFFFFFFFFFFFE),
(64, 64, [40], 0x7FFFFFFFFFFFFFFF),
(4096, 64, [40], 314159265),
(128, 128, [40, 40], 0x12345678),
(2048, 128, [40, 40], 0),
(1024, 128, [40, 40], 1),
(2048, 128, [40, 40], 2),
(128, 128, [40, 40], 0x7FFFFFFFFFFFFFFD),
(128, 128, [40, 40], 0x7FFFFFFFFFFFFFFE),
(4096, 128, [40, 40], 0x7FFFFFFFFFFFFFFF),
(128, 128, [40, 40], 314159265),
(256, 256, [40, 40, 40], 0x12345678),
(1024, 256, [40, 40, 40], 0),
(256, 256, [40, 40, 40], 1),
(256, 256, [40, 40, 40], 2),
(4096, 256, [40, 40, 40], 0x7FFFFFFFFFFFFFFD),
(1024, 256, [40, 40, 40], 0x7FFFFFFFFFFFFFFE),
(256, 256, [40, 40, 40], 0x7FFFFFFFFFFFFFFF),
(4096, 256, [40, 40, 40], 314159265),
],
)
def test_fv_encryption_decrption_asymmetric(poly_modulus, plain_modulus, coeff_bit_sizes, integer):
ctx = Context(
EncryptionParams(
poly_modulus, CoeffModulus().create(poly_modulus, coeff_bit_sizes), plain_modulus
)
)
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
assert integer == encoder.decode(decryptor.decrypt(encryptor.encrypt(encoder.encode(integer))))
@pytest.mark.parametrize(
"poly_modulus, plain_modulus, coeff_bit_sizes, integer",
[
(64, 64, [40], 0x12345678),
(4096, 64, [40], 0),
(1024, 64, [40], 1),
(64, 64, [40], 2),
(1024, 64, [40], 0x7FFFFFFFFFFFFFFD),
(4096, 64, [40], 0x7FFFFFFFFFFFFFFE),
(64, 64, [40], 0x7FFFFFFFFFFFFFFF),
(4096, 64, [40], 314159265),
(1024, 128, [40, 40], 0x12345678),
(2048, 128, [40, 40], 0),
(1024, 128, [40, 40], 1),
(2048, 128, [40, 40], 2),
(1024, 128, [40, 40], 0x7FFFFFFFFFFFFFFD),
(128, 128, [40, 40], 0x7FFFFFFFFFFFFFFE),
(4096, 128, [40, 40], 0x7FFFFFFFFFFFFFFF),
(128, 128, [40, 40], 314159265),
(4096, 256, [40, 40, 40], 0x12345678),
(1024, 256, [40, 40, 40], 0),
(256, 256, [40, 40, 40], 1),
(256, 256, [40, 40, 40], 2),
(4096, 256, [40, 40, 40], 0x7FFFFFFFFFFFFFFD),
(1024, 256, [40, 40, 40], 0x7FFFFFFFFFFFFFFE),
(64, 256, [40, 40, 40], 0x7FFFFFFFFFFFFFFF),
(4096, 256, [40, 40, 40], 314159265),
],
)
def test_fv_encryption_decrption_symmetric(poly_modulus, plain_modulus, coeff_bit_sizes, integer):
ctx = Context(
EncryptionParams(
poly_modulus, CoeffModulus().create(poly_modulus, coeff_bit_sizes), plain_modulus
)
)
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[0]) # keys[0] = secret_key
decryptor = Decryptor(ctx, keys[0])
assert integer == encoder.decode(decryptor.decrypt(encryptor.encrypt(encoder.encode(integer))))
@pytest.mark.parametrize(
"poly_modulus, plain_modulus, seq_level, integer",
[
(1024, 1024, SeqLevelType.TC128, 0x12345678),
(4096, 1024, SeqLevelType.TC192, 0),
(4096, 1024, SeqLevelType.TC256, 1),
(1024, 1024, SeqLevelType.TC128, 2),
(1024, 1024, SeqLevelType.TC128, 0x7FFFFFFFFFFFFFFD),
(2048, 1024, SeqLevelType.TC192, 0x7FFFFFFFFFFFFFFE),
(1024, 1024, SeqLevelType.TC128, 0x7FFFFFFFFFFFFFFF),
(1024, 512, SeqLevelType.TC128, 314159265),
(2048, 2048, SeqLevelType.TC256, 0x12345678),
],
)
def test_fv_encryption_decrption_standard_seq_level(
poly_modulus, plain_modulus, seq_level, integer
):
ctx = Context(
EncryptionParams(
poly_modulus, CoeffModulus().bfv_default(poly_modulus, seq_level), plain_modulus
)
)
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
assert integer == encoder.decode(decryptor.decrypt(encryptor.encrypt(encoder.encode(integer))))
def test_fv_encryption_decrption_without_changing_parameters():
ctx = Context(EncryptionParams(1024, CoeffModulus().create(1024, [30, 30]), 1024))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
values = [0, 1, -1, 100, -100, 1000]
for value in values:
# Checking simple encryption-decryption with same parameters.
assert value == encoder.decode(decryptor.decrypt(encryptor.encrypt(encoder.encode(value))))
# Checking the decryption of same ciphertext 3 times (checking for ciphertext deepcopy).
ct = encryptor.encrypt(encoder.encode(value))
for _ in range(3):
assert value == encoder.decode(decryptor.decrypt(ct))
@pytest.mark.parametrize(
"int1, int2", [(0, 0), (-1, 1), (100, -10), (1000, 100), (-1000, 100), (-100, -100)]
)
def test_fv_add_cipher_cipher(int1, int2):
ctx = Context(EncryptionParams(1024, CoeffModulus().create(1024, [30, 30]), 1024))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
evaluator = Evaluator(ctx)
op1 = encryptor.encrypt(encoder.encode(int1))
op2 = encryptor.encrypt(encoder.encode(int2))
assert (
int1 + int2
== encoder.decode(decryptor.decrypt(evaluator._add_cipher_cipher(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.add(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.add(op2, op1)))
)
@pytest.mark.parametrize(
"int1, int2", [(0, 0), (-1, 1), (100, -10), (1000, 100), (-1000, 100), (-100, -100)]
)
def test_fv_add_cipher_plain(int1, int2):
ctx = Context(EncryptionParams(1024, CoeffModulus().create(1024, [30, 30]), 1024))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
evaluator = Evaluator(ctx)
op1 = encryptor.encrypt(encoder.encode(int1))
op2 = encoder.encode(int2)
assert (
int1 + int2
== encoder.decode(decryptor.decrypt(evaluator._add_cipher_plain(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.add(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.add(op2, op1)))
)
@pytest.mark.parametrize(
"int1, int2", [(0, 0), (-1, 1), (100, -10), (1000, 100), (-1000, 100), (-100, -100)]
)
def test_fv_add_plain_plain(int1, int2):
ctx = Context(EncryptionParams(1024, CoeffModulus().create(1024, [30, 30]), 1024))
encoder = IntegerEncoder(ctx)
evaluator = Evaluator(ctx)
op1 = encoder.encode(int1)
op2 = encoder.encode(int2)
assert (
int1 + int2
== encoder.decode(evaluator._add_plain_plain(op1, op2))
== encoder.decode(evaluator.add(op1, op2))
== encoder.decode(evaluator.add(op2, op1))
)
@pytest.mark.parametrize("val", [(0), (-1), (100), (-1000), (-123), (99), (0xFFF), (0xFFFFFF)])
def test_fv_negate_cipher(val):
ctx = Context(EncryptionParams(1024, CoeffModulus().create(1024, [30, 30]), 1024))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
evaluator = Evaluator(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
op = encryptor.encrypt(encoder.encode(val))
assert -val == encoder.decode(decryptor.decrypt(evaluator.negate(op)))
@pytest.mark.parametrize(
"int1, int2", [(0, 0), (-1, 1), (100, -10), (1000, 100), (-1000, 100), (-100, -100)]
)
def test_fv_sub_cipher_cipher(int1, int2):
ctx = Context(EncryptionParams(1024, CoeffModulus().create(1024, [30, 30]), 1024))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
evaluator = Evaluator(ctx)
op1 = encryptor.encrypt(encoder.encode(int1))
op2 = encryptor.encrypt(encoder.encode(int2))
assert (
int1 - int2
== encoder.decode(decryptor.decrypt(evaluator._sub_cipher_cipher(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.sub(op1, op2)))
== -encoder.decode(decryptor.decrypt(evaluator.sub(op2, op1)))
)
@pytest.mark.parametrize(
"int1, int2", [(0, 0), (-1, 1), (100, -10), (1000, 100), (-1000, 100), (-100, -100)]
)
def test_fv_sub_cipher_plain(int1, int2):
ctx = Context(EncryptionParams(1024, CoeffModulus().create(1024, [30, 30]), 1024))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
evaluator = Evaluator(ctx)
op1 = encryptor.encrypt(encoder.encode(int1))
op2 = encoder.encode(int2)
assert (
int1 - int2
== encoder.decode(decryptor.decrypt(evaluator._sub_cipher_plain(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.sub(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.sub(op2, op1)))
)
@pytest.mark.parametrize(
"int1, int2",
[
(0x12345678, 0x54321),
(-1, 1),
(0, 0),
(100, 10),
(1000, 0),
(-1000, 100),
(-99, -99),
(-99, 99),
],
)
def test_fv_mul_cipher_cipher(int1, int2):
ctx = Context(EncryptionParams(64, CoeffModulus().create(64, [40]), 64))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
evaluator = Evaluator(ctx)
op1 = encryptor.encrypt(encoder.encode(int1))
op2 = encryptor.encrypt(encoder.encode(int2))
assert (
int1 * int2
== encoder.decode(decryptor.decrypt(evaluator._mul_cipher_cipher(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.mul(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.mul(op2, op1)))
)
@pytest.mark.parametrize(
"int1, int2",
[
(0x12345678, 0x54321),
(-1, 1),
(0, 0),
(100, 10),
(1000, 0),
(-1000, 100),
(-99, -99),
(-99, 99),
],
)
def test_fv_mul_cipher_plain(int1, int2):
ctx = Context(EncryptionParams(64, CoeffModulus().create(64, [40]), 64))
keys = KeyGenerator(ctx).keygen()
encoder = IntegerEncoder(ctx)
encryptor = Encryptor(ctx, keys[1]) # keys[1] = public_key
decryptor = Decryptor(ctx, keys[0]) # keys[0] = secret_key
evaluator = Evaluator(ctx)
op1 = encryptor.encrypt(encoder.encode(int1))
op2 = encoder.encode(int2)
assert (
int1 * int2
== encoder.decode(decryptor.decrypt(evaluator._mul_cipher_plain(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.mul(op1, op2)))
== encoder.decode(decryptor.decrypt(evaluator.mul(op2, op1)))
)
@pytest.mark.parametrize(
"int1, int2",
[
(0x12345678, 0x54321),
(-1, 1),
(0, 0),
(100, 10),
(1000, 0),
(-1000, 100),
(-99, -99),
(-99, 99),
],
)
def test_fv_mul_plain_plain(int1, int2):
ctx = Context(EncryptionParams(64, CoeffModulus().create(64, [40]), 64))
encoder = IntegerEncoder(ctx)
evaluator = Evaluator(ctx)
op1 = encoder.encode(int1)
op2 = encoder.encode(int2)
assert (
int1 * int2
== encoder.decode(evaluator._mul_plain_plain(op1, op2))
== encoder.decode(evaluator.mul(op1, op2))
== encoder.decode(evaluator._mul_plain_plain(op2, op1))
)
|
from django.contrib.admin import SimpleListFilter
class InputFilter(SimpleListFilter):
template = 'input_filter.html'
def lookups(self, request, model_admin):
return ((),)
def choices(self, changelist):
all_choice = next(super().choices(changelist))
all_choice['query_parts'] = (
(k, v)
for k, v in changelist.get_filters_params().items()
if k != self.parameter_name
)
yield all_choice
class ParameterFilter(InputFilter):
parameter_name = None
title = None
def queryset(self, request, queryset):
if self.value() is not None and self.parameter_name is not None and self.title is not None:
value = self.value()
filter = {self.parameter_name: value}
return queryset.filter(**filter)
class TitleFilter(ParameterFilter):
parameter_name = "sections__title"
title = "Title"
class PartFilter(ParameterFilter):
parameter_name = "sections__part"
title = "Part"
class SectionFilter(ParameterFilter):
parameter_name = "sections__section"
title = "Section"
|
from dynaconf import settings
print(
'settings from sff file\n',
open(settings.find_file('settings.sff')).read()
)
assert settings.NAME == "Bruno Rocha"
assert settings.EMAIL == 'bruno@rocha.com.from_env'
print("Name is:", settings.NAME)
print("Email is:", settings.EMAIL)
print(settings.get_fresh('NAME'))
|
from aliexpress.api.base import RestApi
class AliexpressOfferRedefiningCopysizetemplateRequest(RestApi):
def __init__(self, domain="gw.api.taobao.com", port=80):
RestApi.__init__(self, domain, port)
self.size_template_id = None
self.target_leaf_id = None
def getapiname(self):
return "aliexpress.offer.redefining.copysizetemplate"
|
def sum_pairs(ints, s):
map = {}
n = len(ints)
index1 = n
index2 = n
checked = set()
for i in range(n):
map[ints[i]] = i
m = n
i = 0
while i < m:
num = ints[i]
dif = s - num
if dif in map and map[dif] != i and num not in checked:
checked.add(dif)
j = map[dif]
if j < index2:
index1 = i
index2 = j
m = j
i += 1
if index1 >= n or index2 >= n:
return None
return [ints[index1], ints[index2]]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from hcalendar import hCalendar
try:
import urllib.request as urllib2
except:
import urllib2
def parsePage(url):
print('-'*79)
print(url)
file = urllib2.urlopen(urllib2.Request(url, headers={'User-agent': 'WebGCal'}))
hcal = hCalendar(file)
for cal in hcal:
for event in cal:
print('-'*79)
for attr in dir(event):
print('%s: %s' % (attr, repr(getattr(event, attr))))
parsePage('http://web.archive.org/web/20140213063519/http://ufxtract.com/testsuite/hcalendar/hcalendar1.htm')
parsePage('http://web.archive.org/web/20130602094644/http://ufxtract.com/testsuite/hcalendar/hcalendar2.htm')
parsePage('http://web.archive.org/web/20110830165439/http://ufxtract.com/testsuite/hcalendar/hcalendar3.htm')
parsePage('http://web.archive.org/web/20110827224530/http://ufxtract.com/testsuite/hcalendar/hcalendar4.htm')
parsePage('http://web.archive.org/web/20110828213628/http://ufxtract.com/testsuite/hcalendar/hcalendar5.htm')
parsePage('http://web.archive.org/web/20110827233032/http://ufxtract.com/testsuite/hcalendar/hcalendar6.htm')
parsePage('http://web.archive.org/web/20110828213623/http://ufxtract.com/testsuite/hcalendar/hcalendar7.htm')
parsePage('http://web.archive.org/web/20110831030559/http://ufxtract.com/testsuite/hcalendar/hcalendar8.htm')
parsePage('http://web.archive.org/web/20110802163338/http://ufxtract.com/testsuite/hcalendar/hcalendar9.htm')
parsePage('http://web.archive.org/web/20110804082640/http://ufxtract.com/testsuite/hcalendar/hcalendar10.htm')
parsePage('http://web.archive.org/web/20110831025245/http://ufxtract.com/testsuite/hcalendar/hcalendar11.htm')
parsePage('http://web.archive.org/web/20110831052906/http://ufxtract.com/testsuite/hcalendar/hcalendar12.htm')
parsePage('http://web.archive.org/web/20110830165503/http://ufxtract.com/testsuite/hcalendar/hcalendar13.htm')
parsePage('http://web.archive.org/web/20130530044503/http://ufxtract.com/testsuite/hcalendar/hcalendar14.htm')
parsePage('http://microformats.org/wiki/hcalendar')
parsePage('http://en.wikipedia.org/wiki/List_of_House_episodes')
parsePage('http://en.wikipedia.org/wiki/List_of_NCIS_episodes')
parsePage('http://en.wikipedia.org/wiki/List_of_Fringe_episodes')
parsePage('http://en.wikipedia.org/wiki/List_of_Scrubs_episodes')
|
//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#ifndef DAWN_OPTIMIZER_REORDERSTRATEGY_H
#define DAWN_OPTIMIZER_REORDERSTRATEGY_H
#include <memory>
namespace dawn {
class OptimizerContext;
namespace iir {
class Stencil;
class StencilInstantiation;
class DependencyGraphStage;
} // namespace iir
/// @brief Abstract class for various reodering strategies
/// @ingroup optimizer
class ReorderStrategy {
public:
virtual ~ReorderStrategy() {}
enum class Kind {
Unknown,
None, ///< Don't perform any reordering
Greedy, ///< Greedy fusing of the stages until max-halo boundary is reached
Partitioning, ///< Use S-cut graph partitioning
Permutations ///< Use Mating and Mutations for genetic Algorithms (this required an
/// existing, correct IIR
};
/// @brief Reorder the stages of the `stencilPtr` according to the implemented strategy
/// @returns New stencil with the reordered stages
virtual std::unique_ptr<iir::Stencil> reorder(iir::StencilInstantiation* instantiation,
const std::unique_ptr<iir::Stencil>& stencilPtr,
OptimizerContext& context) = 0;
};
} // namespace dawn
#endif
|
import rangeModule from '../translators/range';
import { getDateFormatByDifferences } from '../../format_helper';
import dateUtils from '../../core/utils/date';
import { extend } from '../../core/utils/extend';
import { generateDateBreaks } from './datetime_breaks';
import { noop } from '../../core/utils/common';
import vizUtils from '../core/utils';
import { isDefined } from '../../core/utils/type';
import constants from './axes_constants';
const getNextDateUnit = dateUtils.getNextDateUnit;
const correctDateWithUnitBeginning = dateUtils.correctDateWithUnitBeginning;
const _math = Math;
const _max = _math.max;
const TOP = constants.top;
const BOTTOM = constants.bottom;
const LEFT = constants.left;
const RIGHT = constants.right;
const CENTER = constants.center;
const SCALE_BREAK_OFFSET = 3;
const RANGE_RATIO = 0.3;
const WAVED_LINE_CENTER = 2;
const WAVED_LINE_TOP = 0;
const WAVED_LINE_BOTTOM = 4;
const WAVED_LINE_LENGTH = 24;
const TICKS_CORRECTIONS = {
left: -1,
top: -1,
right: 0,
bottom: 0,
center: -0.5
};
function prepareDatesDifferences(datesDifferences, tickInterval) {
let dateUnitInterval;
let i;
if(tickInterval === 'week') {
tickInterval = 'day';
}
if(tickInterval === 'quarter') {
tickInterval = 'month';
}
if(datesDifferences[tickInterval]) {
for(i = 0; i < dateUtils.dateUnitIntervals.length; i++) {
dateUnitInterval = dateUtils.dateUnitIntervals[i];
if(datesDifferences[dateUnitInterval]) {
datesDifferences[dateUnitInterval] = false;
datesDifferences.count--;
}
if(dateUnitInterval === tickInterval) {
break;
}
}
}
}
function sortingBreaks(breaks) {
return breaks.sort(function(a, b) { return a.from - b.from; });
}
function filterBreaks(breaks, viewport, breakStyle) {
const minVisible = viewport.minVisible;
const maxVisible = viewport.maxVisible;
const breakSize = breakStyle ? breakStyle.width : 0;
return breaks.reduce(function(result, currentBreak) {
let from = currentBreak.from;
let to = currentBreak.to;
const lastResult = result[result.length - 1];
let newBreak;
if(!isDefined(from) || !isDefined(to)) {
return result;
}
if(from > to) {
to = [from, from = to][0];
}
if(result.length && from < lastResult.to) {
if(to > lastResult.to) {
lastResult.to = to > maxVisible ? maxVisible : to;
if(lastResult.gapSize) {
lastResult.gapSize = undefined;
lastResult.cumulativeWidth += breakSize;
}
}
} else {
if(((from >= minVisible && from < maxVisible) || (to <= maxVisible && to > minVisible)) && to - from < maxVisible - minVisible) {
from = from >= minVisible ? from : minVisible;
to = to <= maxVisible ? to : maxVisible;
newBreak = {
from: from,
to: to,
cumulativeWidth: (lastResult ? lastResult.cumulativeWidth : 0) + breakSize
};
if(currentBreak.gapSize) {
newBreak.gapSize = dateUtils.convertMillisecondsToDateUnits(to - from);
newBreak.cumulativeWidth = lastResult ? lastResult.cumulativeWidth : 0;
}
result.push(newBreak);
}
}
return result;
}, []);
}
function getMarkerDates(min, max, markerInterval) {
const origMin = min;
let dates;
min = correctDateWithUnitBeginning(min, markerInterval);
max = correctDateWithUnitBeginning(max, markerInterval);
dates = dateUtils.getSequenceByInterval(min, max, markerInterval);
if(dates.length && origMin > dates[0]) {
dates = dates.slice(1);
}
return dates;
}
function getStripHorizontalAlignmentPosition(alignment) {
let position = 'start';
if(alignment === 'center') {
position = 'center';
}
if(alignment === 'right') {
position = 'end';
}
return position;
}
function getStripVerticalAlignmentPosition(alignment) {
let position = 'start';
if(alignment === 'center') {
position = 'center';
}
if(alignment === 'bottom') {
position = 'end';
}
return position;
}
function getMarkerInterval(tickInterval) {
let markerInterval = getNextDateUnit(tickInterval);
if(markerInterval === 'quarter') {
markerInterval = getNextDateUnit(markerInterval);
}
return markerInterval;
}
function getMarkerFormat(curDate, prevDate, tickInterval, markerInterval) {
let format = markerInterval;
const datesDifferences = prevDate && dateUtils.getDatesDifferences(prevDate, curDate);
if(prevDate && tickInterval !== 'year') {
prepareDatesDifferences(datesDifferences, tickInterval);
format = getDateFormatByDifferences(datesDifferences);
}
return format;
}
function getMaxSide(act, boxes) {
return boxes.reduce(function(prevValue, box) {
return _max(prevValue, act(box));
}, 0);
}
function getDistanceByAngle(bBox, rotationAngle) {
rotationAngle = _math.abs(rotationAngle);
rotationAngle = (rotationAngle % 180) >= 90 ? (90 - (rotationAngle % 90)) : (rotationAngle % 90);
const a = rotationAngle * (_math.PI / 180);
if(a >= _math.atan(bBox.height / bBox.width)) {
return bBox.height / _math.abs(_math.sin(a));
} else {
return bBox.width;
}
}
function getMaxConstantLinePadding(constantLines) {
return constantLines.reduce(function(padding, options) {
return _max(padding, options.paddingTopBottom);
}, 0);
}
function getConstantLineLabelMarginForVerticalAlignment(constantLines, alignment, labelHeight) {
return constantLines.some(function(options) {
return options.label.verticalAlignment === alignment;
}) && labelHeight || 0;
}
function getLeftMargin(bBox) {
return _math.abs(bBox.x) || 0;
}
function getRightMargin(bBox) {
return _math.abs(bBox.width - _math.abs(bBox.x)) || 0;
}
function generateRangesOnPoints(points, edgePoints, getRange) {
let i;
let length;
let maxRange = null;
const ranges = [];
let curValue;
let prevValue;
let curRange;
for(i = 1, length = points.length; i < length; i++) {
curValue = points[i];
prevValue = points[i - 1];
curRange = getRange(curValue, prevValue);
if(edgePoints.indexOf(curValue) >= 0) {
if(!maxRange || curRange > maxRange.length) {
maxRange = { start: curValue, end: prevValue, length: curRange };
}
} else {
if(maxRange && curRange < maxRange.length) {
ranges.push(maxRange);
} else {
ranges.push({ start: curValue, end: prevValue, length: curRange });
}
maxRange = null;
}
}
if(maxRange) {
ranges.push(maxRange);
}
return ranges;
}
function generateAutoBreaks({ logarithmBase, type, maxAutoBreakCount }, series, { minVisible, maxVisible }) {
const breaks = [];
const getRange = type === 'logarithmic' ?
(min, max) => { return vizUtils.getLog(max / min, logarithmBase); } :
(min, max) => { return max - min; };
let visibleRange = getRange(minVisible, maxVisible);
const points = series.reduce((result, s) => {
const points = s.getPointsInViewPort();
result[0] = result[0].concat(points[0]);
result[1] = result[1].concat(points[1]);
return result;
}, [[], []]);
const sortedAllPoints = points[0].concat(points[1]).sort((a, b) => b - a);
const edgePoints = points[1].filter(p => points[0].indexOf(p) < 0);
let minDiff = RANGE_RATIO * visibleRange;
const ranges = generateRangesOnPoints(sortedAllPoints, edgePoints, getRange).sort((a, b) => b.length - a.length);
const epsilon = _math.min.apply(null, ranges.map(r => r.length)) / 1000;
const _maxAutoBreakCount = isDefined(maxAutoBreakCount) ? _math.min(maxAutoBreakCount, ranges.length) : ranges.length;
for(let i = 0; i < _maxAutoBreakCount; i++) {
if(ranges[i].length >= minDiff) {
if(visibleRange <= ranges[i].length) {
break;
}
visibleRange -= ranges[i].length;
if(visibleRange > epsilon || visibleRange < -epsilon) {
breaks.push({ from: ranges[i].start, to: ranges[i].end });
minDiff = RANGE_RATIO * visibleRange;
}
} else {
break;
}
}
sortingBreaks(breaks);
return breaks;
}
module.exports = {
linear: {
_getStep: function(boxes, rotationAngle) {
const spacing = this._options.label.minSpacing;
const func = this._isHorizontal ?
function(box) { return box.width + spacing; }
: function(box) { return box.height; };
let maxLabelLength = getMaxSide(func, boxes);
if(rotationAngle) {
maxLabelLength = getDistanceByAngle({ width: maxLabelLength, height: this._getMaxLabelHeight(boxes, 0) }, rotationAngle);
}
return constants.getTicksCountInRange(this._majorTicks, this._isHorizontal ? 'x' : 'y', maxLabelLength);
},
_getMaxLabelHeight: function(boxes, spacing) {
return getMaxSide(function(box) { return box.height; }, boxes) + spacing;
},
_validateOverlappingMode: function(mode, displayMode) {
if(this._isHorizontal && (displayMode === 'rotate' || displayMode === 'stagger') || !this._isHorizontal) {
return constants.validateOverlappingMode(mode);
}
return mode;
},
_validateDisplayMode: function(mode) {
return this._isHorizontal ? mode : 'standard';
},
getMarkerTrackers: function() {
return this._markerTrackers;
},
_getSharpParam: function(opposite) {
return this._isHorizontal ^ opposite ? 'h' : 'v';
},
_createAxisElement: function() {
return this._renderer.path([], 'line');
},
_updateAxisElementPosition: function() {
const axisCoord = this._axisPosition;
const canvas = this._getCanvasStartEnd();
this._axisElement.attr({
points: this._isHorizontal ? [canvas.start, axisCoord, canvas.end, axisCoord] : [axisCoord, canvas.start, axisCoord, canvas.end]
});
},
_getTranslatedCoord: function(value, offset) {
return this._translator.translate(value, offset);
},
_initAxisPositions: function() {
const that = this;
const position = that._options.position;
that._axisPosition = that._orthogonalPositions[position === 'top' || position === 'left' ? 'start' : 'end'];
},
_getTickMarkPoints(coords, length, tickOptions) {
const isHorizontal = this._isHorizontal;
const options = this._options;
let tickStartCoord;
if(isDefined(options.tickOrientation)) {
tickStartCoord = TICKS_CORRECTIONS[options.tickOrientation] * length;
} else {
let shift = tickOptions.shift || 0;
if(options.position === 'left' || options.position === 'top') {
shift = -shift;
}
tickStartCoord = shift + this.getTickStartPositionShift(length);
}
return [
coords.x + (isHorizontal ? 0 : tickStartCoord),
coords.y + (isHorizontal ? tickStartCoord : 0),
coords.x + (isHorizontal ? 0 : tickStartCoord + length),
coords.y + (isHorizontal ? tickStartCoord + length : 0)
];
},
getTickStartPositionShift(length) {
const options = this._options;
return (length % 2 === 1 ?
(options.width % 2 === 0 && (options.position === 'left' || options.position === 'top') ||
options.width % 2 === 1 && (options.position === 'right' || options.position === 'bottom') ? Math.floor(-length / 2) : -Math.floor(length / 2)) :
(-length / 2 + (options.width % 2 === 0 ? 0 : (options.position === 'bottom' || options.position === 'right' ? -1 : 1))));
},
_getTitleCoords: function() {
const that = this;
const horizontal = that._isHorizontal;
let x = that._axisPosition;
let y = that._axisPosition;
const align = that._options.title.alignment;
const canvas = that._getCanvasStartEnd();
const fromStartToEnd = horizontal || that._options.position === LEFT;
const canvasStart = fromStartToEnd ? canvas.start : canvas.end;
const canvasEnd = fromStartToEnd ? canvas.end : canvas.start;
const coord = align === LEFT ? canvasStart : align === RIGHT ? canvasEnd : (canvas.start + (canvas.end - canvas.start) / 2);
if(horizontal) {
x = coord;
} else {
y = coord;
}
return { x: x, y: y };
},
_drawTitleText: function(group, coords) {
const options = this._options;
const titleOptions = options.title;
const attrs = { opacity: titleOptions.opacity, align: titleOptions.alignment, 'class': titleOptions.cssClass };
if(!titleOptions.text || !group) {
return;
}
coords = coords || this._getTitleCoords();
if(!this._isHorizontal) {
attrs.rotate = options.position === LEFT ? 270 : 90;
}
const text = this._renderer
.text(titleOptions.text, coords.x, coords.y)
.css(vizUtils.patchFontOptions(titleOptions.font))
.attr(attrs)
.append(group);
this._checkTitleOverflow(text);
return text;
},
_updateTitleCoords: function() {
this._title && this._title.element.attr(this._getTitleCoords());
},
_drawTitle: function() {
const title = this._drawTitleText(this._axisTitleGroup);
if(title) {
this._title = {
element: title
};
}
},
_measureTitle: function() {
if(this._title) {
if(this._title.bBox && !this._title.originalSize) {
this._title.originalSize = this._title.bBox;
}
this._title.bBox = this._title.element.getBBox();
}
},
_drawDateMarker: function(date, options, range) {
const that = this;
const markerOptions = that._options.marker;
const invert = that._translator.getBusinessRange().invert;
const textIndent = markerOptions.width + markerOptions.textLeftIndent;
let pathElement;
if(options.x === null) return;
if(!options.withoutStick) {
pathElement = that._renderer.path([options.x, options.y, options.x, options.y + markerOptions.separatorHeight], 'line')
.attr({ 'stroke-width': markerOptions.width, stroke: markerOptions.color, 'stroke-opacity': markerOptions.opacity, sharp: 'h' })
.append(that._axisElementsGroup);
}
const text = String(that.formatLabel(date, options.labelOptions, range));
return {
date: date,
x: options.x,
y: options.y,
cropped: options.withoutStick,
label: that._renderer.text(text, options.x, options.y)
.css(vizUtils.patchFontOptions(markerOptions.label.font))
.append(that._axisElementsGroup),
line: pathElement,
getEnd: function() {
return this.x + (invert ? -1 : 1) * (textIndent + this.labelBBox.width);
},
setTitle: function() {
this.title = text;
},
hideLabel: function() {
this.label.dispose();
this.label = null;
this.title = text;
},
hide: function() {
if(pathElement) {
pathElement.dispose();
pathElement = null;
}
this.label.dispose();
this.label = null;
this.hidden = true;
}
};
},
_drawDateMarkers: function() {
const that = this;
const options = that._options;
const translator = that._translator;
const viewport = that._getViewportRange();
const minBound = viewport.minVisible;
let dateMarkers = [];
let dateMarker;
function draw(markerDate, format, withoutStick) {
return that._drawDateMarker(markerDate, {
x: translator.translate(markerDate),
y: markersAreaTop,
labelOptions: that._getLabelFormatOptions(format),
withoutStick: withoutStick
}, viewport);
}
if(viewport.isEmpty() || !options.marker.visible || options.argumentType !== 'datetime' || options.type === 'discrete' || that._majorTicks.length <= 1) {
return [];
}
const markersAreaTop = that._axisPosition + options.marker.topIndent;
const tickInterval = dateUtils.getDateUnitInterval(this._tickInterval);
const markerInterval = getMarkerInterval(tickInterval);
const markerDates = getMarkerDates(minBound, viewport.maxVisible, markerInterval);
if(markerDates.length > 1
|| (markerDates.length === 1 && minBound < markerDates[0])) {
dateMarkers = markerDates.reduce(function(markers, curDate, i, dates) {
const marker = draw(curDate, getMarkerFormat(curDate, dates[i - 1] || (minBound < curDate && minBound), tickInterval, markerInterval));
marker && markers.push(marker);
return markers;
}, []);
if(minBound < markerDates[0]) {
dateMarker = draw(minBound, getMarkerFormat(minBound, markerDates[0], tickInterval, markerInterval), true);
dateMarker && dateMarkers.unshift(dateMarker);
}
}
return dateMarkers;
},
_adjustDateMarkers: function(offset) {
offset = offset || 0;
const that = this;
const markerOptions = this._options.marker;
const textIndent = markerOptions.width + markerOptions.textLeftIndent;
const invert = this._translator.getBusinessRange().invert;
const canvas = that._getCanvasStartEnd();
const dateMarkers = this._dateMarkers;
if(!dateMarkers.length) {
return offset;
}
if(dateMarkers[0].cropped) {
if(!this._checkMarkersPosition(invert, dateMarkers[1], dateMarkers[0])) {
dateMarkers[0].hideLabel();
}
}
let prevDateMarker;
dateMarkers.forEach(function(marker, i, markers) {
if(marker.cropped) {
return;
}
if(invert ? marker.getEnd() < canvas.end : marker.getEnd() > canvas.end) {
marker.hideLabel();
} else if(that._checkMarkersPosition(invert, marker, prevDateMarker)) {
prevDateMarker = marker;
} else {
marker.hide();
}
});
this._dateMarkers.forEach(function(marker) {
if(marker.label) {
const labelBBox = marker.labelBBox;
const dy = marker.y + markerOptions.textTopIndent - labelBBox.y;
marker.label.attr({
translateX: invert ? marker.x - textIndent - labelBBox.x - labelBBox.width : marker.x + textIndent - labelBBox.x,
translateY: dy + offset
});
}
if(marker.line) {
marker.line.attr({
translateY: offset
});
}
});
that._initializeMarkersTrackers(offset);
return offset + markerOptions.topIndent + markerOptions.separatorHeight;
},
_checkMarkersPosition: function(invert, dateMarker, prevDateMarker) {
if(prevDateMarker === undefined) {
return true;
}
return invert ? (dateMarker.x < prevDateMarker.getEnd()) : (dateMarker.x > prevDateMarker.getEnd());
},
_initializeMarkersTrackers: function(offset) {
const that = this;
const separatorHeight = that._options.marker.separatorHeight;
const renderer = that._renderer;
const businessRange = this._translator.getBusinessRange();
const canvas = that._getCanvasStartEnd();
const group = that._axisElementsGroup;
that._markerTrackers = this._dateMarkers
.filter(function(marker) { return !marker.hidden; })
.map(function(marker, i, markers) {
const nextMarker = markers[i + 1] ||
{
x: canvas.end,
date: businessRange.max
};
const x = marker.x;
const y = marker.y + offset;
const markerTracker = renderer.path([
x, y,
x, y + separatorHeight,
nextMarker.x, y + separatorHeight,
nextMarker.x, y,
x, y
], 'area').attr({
'stroke-width': 1,
stroke: 'grey',
fill: 'grey',
opacity: 0.0001
}).append(group);
markerTracker.data('range', { startValue: marker.date, endValue: nextMarker.date });
if(marker.title) {
markerTracker.setTitle(marker.title);
}
return markerTracker;
});
},
_getLabelFormatOptions: function(formatString) {
const that = this;
let markerLabelOptions = that._markerLabelOptions;
if(!markerLabelOptions) {
that._markerLabelOptions = markerLabelOptions = extend(true, {}, that._options.marker.label);
}
if(!isDefined(that._options.marker.label.format)) {
markerLabelOptions.format = formatString;
}
return markerLabelOptions;
},
_adjustConstantLineLabels: function(constantLines) {
const that = this;
const axisPosition = that._options.position;
const canvas = that.getCanvas();
const canvasLeft = canvas.left;
const canvasRight = canvas.width - canvas.right;
const canvasTop = canvas.top;
const canvasBottom = canvas.height - canvas.bottom;
const verticalCenter = canvasTop + (canvasBottom - canvasTop) / 2;
const horizontalCenter = canvasLeft + (canvasRight - canvasLeft) / 2;
let maxLabel = 0;
constantLines.forEach(function(item) {
const isHorizontal = that._isHorizontal;
const linesOptions = item.options;
const paddingTopBottom = linesOptions.paddingTopBottom;
const paddingLeftRight = linesOptions.paddingLeftRight;
const labelOptions = linesOptions.label;
const labelVerticalAlignment = labelOptions.verticalAlignment;
const labelHorizontalAlignment = labelOptions.horizontalAlignment;
const labelIsInside = labelOptions.position === 'inside';
const label = item.label;
const box = item.labelBBox;
let translateX;
let translateY;
if(label === null || box.isEmpty) {
return;
}
if(isHorizontal) {
if(labelIsInside) {
if(labelHorizontalAlignment === LEFT) {
translateX = item.coord - paddingLeftRight - box.x - box.width;
} else {
translateX = item.coord + paddingLeftRight - box.x;
}
switch(labelVerticalAlignment) {
case CENTER:
translateY = verticalCenter - box.y - box.height / 2;
break;
case BOTTOM:
translateY = canvasBottom - paddingTopBottom - box.y - box.height;
break;
default:
translateY = canvasTop + paddingTopBottom - box.y;
break;
}
} else {
if(axisPosition === labelVerticalAlignment) {
maxLabel = _max(maxLabel, box.height + paddingTopBottom);
}
translateX = item.coord - box.x - box.width / 2;
if(labelVerticalAlignment === BOTTOM) {
translateY = canvasBottom + paddingTopBottom - box.y;
} else {
translateY = canvasTop - paddingTopBottom - box.y - box.height;
}
}
} else {
if(labelIsInside) {
if(labelVerticalAlignment === BOTTOM) {
translateY = item.coord + paddingTopBottom - box.y;
} else {
translateY = item.coord - paddingTopBottom - box.y - box.height;
}
switch(labelHorizontalAlignment) {
case CENTER:
translateX = horizontalCenter - box.x - box.width / 2;
break;
case RIGHT:
translateX = canvasRight - paddingLeftRight - box.x - box.width;
break;
default:
translateX = canvasLeft + paddingLeftRight - box.x;
break;
}
} else {
if(axisPosition === labelHorizontalAlignment) {
maxLabel = _max(maxLabel, box.width + paddingLeftRight);
}
translateY = item.coord - box.y - box.height / 2;
if(labelHorizontalAlignment === RIGHT) {
translateX = canvasRight + paddingLeftRight - box.x;
} else {
translateX = canvasLeft - paddingLeftRight - box.x - box.width;
}
}
}
label.attr({
translateX: translateX,
translateY: translateY
});
});
return maxLabel;
},
_drawConstantLinesForEstimating: function(constantLines) {
const that = this;
const renderer = this._renderer;
const group = renderer.g();
constantLines.forEach(function(options) {
that._drawConstantLineLabelText(options.label.text, 0, 0, options.label, group).attr({ align: 'center' });
});
return group.append(renderer.root);
},
_estimateLabelHeight: function(bBox, labelOptions) {
let height = bBox.height;
const drawingType = labelOptions.drawingType;
if(this._validateDisplayMode(drawingType) === 'stagger' || this._validateOverlappingMode(labelOptions.overlappingBehavior, drawingType) === 'stagger') {
height = height * 2 + labelOptions.staggeringSpacing;
}
if(this._validateDisplayMode(drawingType) === 'rotate' || this._validateOverlappingMode(labelOptions.overlappingBehavior, drawingType) === 'rotate') {
const sinCos = vizUtils.getCosAndSin(labelOptions.rotationAngle);
height = height * sinCos.cos + bBox.width * sinCos.sin;
}
return height && (height + labelOptions.indentFromAxis || 0) || 0;
},
estimateMargins: function(canvas) {
this.updateCanvas(canvas);
const that = this;
const range = that._getViewportRange();
const ticksData = this._createTicksAndLabelFormat(range);
const ticks = ticksData.ticks;
const tickInterval = ticksData.tickInterval;
const options = this._options;
const constantLineOptions = that._outsideConstantLines.filter(l => l.labelOptions.visible).map(l => l.options);
const rootElement = that._renderer.root;
const labelIsVisible = options.label.visible && !range.isEmpty() && ticks.length;
const labelValue = labelIsVisible && that.formatLabel(ticks[ticks.length - 1], options.label, undefined, undefined, tickInterval, ticks);
const labelElement = labelIsVisible && that._renderer.text(labelValue, 0, 0)
.css(that._textFontStyles)
.attr(that._textOptions)
.append(rootElement);
const titleElement = that._drawTitleText(rootElement, { x: 0, y: 0 });
const constantLinesLabelsElement = that._drawConstantLinesForEstimating(constantLineOptions);
const labelBox = labelElement && labelElement.getBBox() || { x: 0, y: 0, width: 0, height: 0 };
const titleBox = titleElement && titleElement.getBBox() || { x: 0, y: 0, width: 0, height: 0 };
const constantLinesBox = constantLinesLabelsElement.getBBox();
const titleHeight = titleBox.height ? titleBox.height + options.title.margin : 0;
const labelHeight = that._estimateLabelHeight(labelBox, options.label);
const constantLinesHeight = constantLinesBox.height ? constantLinesBox.height + getMaxConstantLinePadding(constantLineOptions) : 0;
const height = labelHeight + titleHeight;
const margins = {
left: _max(getLeftMargin(labelBox), getLeftMargin(constantLinesBox)),
right: _max(getRightMargin(labelBox), getRightMargin(constantLinesBox)),
top: (options.position === 'top' ? height : 0) + getConstantLineLabelMarginForVerticalAlignment(constantLineOptions, 'top', constantLinesHeight),
bottom: (options.position !== 'top' ? height : 0) + getConstantLineLabelMarginForVerticalAlignment(constantLineOptions, 'bottom', constantLinesHeight)
};
labelElement && labelElement.remove();
titleElement && titleElement.remove();
constantLinesLabelsElement && constantLinesLabelsElement.remove();
return margins;
},
_checkAlignmentConstantLineLabels: function(labelOptions) {
const position = labelOptions.position;
let verticalAlignment = (labelOptions.verticalAlignment || '').toLowerCase();
let horizontalAlignment = (labelOptions.horizontalAlignment || '').toLowerCase();
if(this._isHorizontal) {
if(position === 'outside') {
verticalAlignment = verticalAlignment === BOTTOM ? BOTTOM : TOP;
horizontalAlignment = CENTER;
} else {
verticalAlignment = verticalAlignment === CENTER ? CENTER : (verticalAlignment === BOTTOM ? BOTTOM : TOP);
horizontalAlignment = horizontalAlignment === LEFT ? LEFT : RIGHT;
}
} else {
if(position === 'outside') {
verticalAlignment = CENTER;
horizontalAlignment = horizontalAlignment === LEFT ? LEFT : RIGHT;
} else {
verticalAlignment = verticalAlignment === BOTTOM ? BOTTOM : TOP;
horizontalAlignment = horizontalAlignment === RIGHT ? RIGHT : (horizontalAlignment === CENTER ? CENTER : LEFT);
}
}
labelOptions.verticalAlignment = verticalAlignment;
labelOptions.horizontalAlignment = horizontalAlignment;
},
_getConstantLineLabelsCoords: function(value, lineLabelOptions) {
const that = this;
let x = value;
let y = value;
if(that._isHorizontal) {
y = that._orthogonalPositions[lineLabelOptions.verticalAlignment === 'top' ? 'start' : 'end'];
} else {
x = that._orthogonalPositions[lineLabelOptions.horizontalAlignment === 'right' ? 'end' : 'start'];
}
return { x: x, y: y };
},
_getAdjustedStripLabelCoords: function(strip) {
const stripOptions = strip.options;
const paddingTopBottom = stripOptions.paddingTopBottom;
const paddingLeftRight = stripOptions.paddingLeftRight;
const horizontalAlignment = stripOptions.label.horizontalAlignment;
const verticalAlignment = stripOptions.label.verticalAlignment;
const box = strip.labelBBox;
const labelHeight = box.height;
const labelWidth = box.width;
const labelCoords = strip.labelCoords;
let y = labelCoords.y - box.y;
let x = labelCoords.x - box.x;
if(verticalAlignment === TOP) {
y += paddingTopBottom;
} else if(verticalAlignment === CENTER) {
y -= labelHeight / 2;
} else if(verticalAlignment === BOTTOM) {
y -= paddingTopBottom + labelHeight;
}
if(horizontalAlignment === LEFT) {
x += paddingLeftRight;
} else if(horizontalAlignment === CENTER) {
x -= labelWidth / 2;
} else if(horizontalAlignment === RIGHT) {
x -= paddingLeftRight + labelWidth;
}
return { translateX: x, translateY: y };
},
_adjustTitle: function(offset) {
offset = offset || 0;
if(!this._title) {
return;
}
const that = this;
const options = that._options;
const position = options.position;
const margin = options.title.margin;
const title = that._title;
const boxTitle = title.bBox;
const x = boxTitle.x;
const y = boxTitle.y;
const width = boxTitle.width;
const height = boxTitle.height;
const axisPosition = that._axisPosition;
const loCoord = axisPosition - margin - offset;
const hiCoord = axisPosition + margin + offset;
const params = {};
if(that._isHorizontal) {
if(position === TOP) {
params.translateY = loCoord - (y + height);
} else {
params.translateY = hiCoord - y;
}
} else {
if(position === LEFT) {
params.translateX = loCoord - (x + width);
} else {
params.translateX = hiCoord - x;
}
}
title.element.attr(params);
},
_checkTitleOverflow: function(titleElement) {
if(!this._title && !titleElement) {
return;
}
const canvasLength = this._getScreenDelta();
const title = titleElement ? { bBox: titleElement.getBBox(), element: titleElement } : this._title;
const titleOptions = this._options.title;
const boxTitle = title.bBox;
if((this._isHorizontal ? boxTitle.width : boxTitle.height) > canvasLength) {
title.element.setMaxSize(canvasLength, undefined, {
wordWrap: titleOptions.wordWrap || 'none',
textOverflow: titleOptions.textOverflow || 'ellipsis'
});
this._wrapped = (titleOptions.wordWrap && titleOptions.wordWrap !== 'none');
} else {
const moreThanOriginalSize = title.originalSize && canvasLength > (this._isHorizontal ? title.originalSize.width : title.originalSize.height);
!this._wrapped && moreThanOriginalSize && title.element.restoreText();
}
},
coordsIn: function(x, y) {
const canvas = this.getCanvas();
const isHorizontal = this._options.isHorizontal;
const position = this._options.position;
const coord = isHorizontal ? y : x;
if(isHorizontal && (x < canvas.left || x > (canvas.width - canvas.right))
|| !isHorizontal && (y < canvas.top || y > (canvas.height - canvas.bottom))) {
return false;
}
if(isHorizontal && position === constants.top || !isHorizontal && position === constants.left) {
return coord < canvas[position];
}
return coord > canvas[isHorizontal ? 'height' : 'width'] - canvas[position];
},
_boundaryTicksVisibility: {
min: true,
max: true
},
_setVisualRange(visualRange, allowPartialUpdate) {
const range = this.adjustRange(vizUtils.getVizRangeObject(visualRange));
if(allowPartialUpdate) {
isDefined(range.startValue) && (this._viewport.startValue = range.startValue);
isDefined(range.endValue) && (this._viewport.endValue = range.endValue);
} else {
this._viewport = range;
}
},
applyVisualRangeSetter(visualRangeSetter) {
this._visualRange = visualRangeSetter;
},
adjust(alignToBounds) {
const that = this;
const seriesData = that._seriesData;
let viewport = { min: seriesData.min, max: seriesData.max };
if(!alignToBounds) {
viewport = that._series.filter(s => s.isVisible()).reduce((range, s) => {
const seriesRange = s.getViewport();
range.min = isDefined(seriesRange.min) ? (range.min < seriesRange.min ? range.min : seriesRange.min) : range.min;
range.max = isDefined(seriesRange.max) ? (range.max > seriesRange.max ? range.max : seriesRange.max) : range.max;
if(s.showZero) {
range = new rangeModule.Range(range);
range.correctValueZeroLevel();
}
return range;
}, {});
}
if(isDefined(viewport.min) && isDefined(viewport.max)) {
seriesData.minVisible = viewport.min;
seriesData.maxVisible = viewport.max;
}
that._translator.updateBusinessRange(that.adjustViewport(seriesData));
that._breaks = that._getScaleBreaks(that._options, {
minVisible: seriesData.minVisible,
maxVisible: seriesData.maxVisible
}, that._series, that.isArgumentAxis);
},
hasWrap() {
return this._wrapped;
},
getAxisPosition() {
return this._axisPosition;
},
_getStick: function() {
return !this._options.valueMarginsEnabled;
},
_getStripLabelCoords: function(from, to, stripLabelOptions) {
const that = this;
const orthogonalPositions = that._orthogonalPositions;
const isHorizontal = that._isHorizontal;
const horizontalAlignment = stripLabelOptions.horizontalAlignment;
const verticalAlignment = stripLabelOptions.verticalAlignment;
let x;
let y;
if(isHorizontal) {
if(horizontalAlignment === CENTER) {
x = from + (to - from) / 2;
} else if(horizontalAlignment === LEFT) {
x = from;
} else if(horizontalAlignment === RIGHT) {
x = to;
}
y = orthogonalPositions[getStripVerticalAlignmentPosition(verticalAlignment)];
} else {
x = orthogonalPositions[getStripHorizontalAlignmentPosition(horizontalAlignment)];
if(verticalAlignment === TOP) {
y = from;
} else if(verticalAlignment === CENTER) {
y = to + (from - to) / 2;
} else if(verticalAlignment === BOTTOM) {
y = to;
}
}
return { x: x, y: y };
},
_getTranslatedValue: function(value, offset) {
const pos1 = this._translator.translate(value, offset, this._options.type === 'semidiscrete' && this._options.tickInterval);
const pos2 = this._axisPosition;
const isHorizontal = this._isHorizontal;
return {
x: isHorizontal ? pos1 : pos2,
y: isHorizontal ? pos2 : pos1
};
},
areCoordsOutsideAxis: function(coords) {
const coord = this._isHorizontal ? coords.x : coords.y;
const visibleArea = this.getVisibleArea();
if(coord < visibleArea[0] || coord > visibleArea[1]) {
return true;
}
return false;
},
_getSkippedCategory: function(ticks) {
let skippedCategory;
if(this._options.type === constants.discrete && this._tickOffset && ticks.length !== 0) {
skippedCategory = ticks[ticks.length - 1];
}
return skippedCategory;
},
_getScaleBreaks: function(axisOptions, viewport, series, isArgumentAxis) {
const that = this;
let breaks = (axisOptions.breaks || []).map(function(b) {
return {
from: that.parser(b.startValue),
to: that.parser(b.endValue)
};
});
if(axisOptions.type !== 'discrete' && axisOptions.dataType === 'datetime' && axisOptions.workdaysOnly) {
breaks = breaks.concat(generateDateBreaks(viewport.minVisible,
viewport.maxVisible,
axisOptions.workWeek,
axisOptions.singleWorkdays,
axisOptions.holidays));
}
if(!isArgumentAxis && axisOptions.type !== 'discrete' && axisOptions.dataType !== 'datetime'
&& axisOptions.autoBreaksEnabled && axisOptions.maxAutoBreakCount !== 0) {
breaks = breaks.concat(generateAutoBreaks(axisOptions, series, viewport));
}
return filterBreaks(sortingBreaks(breaks), viewport, axisOptions.breakStyle);
},
_drawBreak: function(translatedEnd, positionFrom, positionTo, width, options, group) {
const that = this;
const breakStart = translatedEnd - (!that._translator.isInverted() ? width + 1 : 0);
const attr = {
'stroke-width': 1,
stroke: options.borderColor,
sharp: !options.isWaved ? options.isHorizontal ? 'h' : 'v' : undefined
};
const spaceAttr = {
stroke: options.color,
'stroke-width': width
};
const getPoints = that._isHorizontal ? rotateLine : function(p) { return p; };
const drawer = getLineDrawer(that._renderer, group, getPoints, positionFrom, breakStart, positionTo, options.isWaved);
drawer(width / 2, spaceAttr);
drawer(0, attr);
drawer(width, attr);
},
_createBreakClipRect: function(from, to) {
const that = this;
const canvas = that._canvas;
const clipWidth = to - from;
let clipRect;
if(that._isHorizontal) {
clipRect = that._renderer.clipRect(canvas.left, from, canvas.width, clipWidth);
} else {
clipRect = that._renderer.clipRect(from, canvas.top, clipWidth, canvas.height);
}
that._breaksElements = that._breaksElements || [];
that._breaksElements.push(clipRect);
return clipRect.id;
},
_createBreaksGroup: function(clipFrom, clipTo) {
const that = this;
const group = that._renderer.g().attr({
'class': that._axisCssPrefix + 'breaks',
'clip-path': that._createBreakClipRect(clipFrom, clipTo)
}).append(that._scaleBreaksGroup);
that._breaksElements = that._breaksElements || [];
that._breaksElements.push(group);
return group;
},
_disposeBreaksGroup: function() {
(this._breaksElements || []).forEach(function(clipRect) {
clipRect.dispose();
});
this._breaksElements = null;
},
drawScaleBreaks: function(customCanvas) {
const that = this;
const options = that._options;
const breakStyle = options.breakStyle;
const position = options.position;
let positionFrom;
let positionTo;
const breaks = that._translator.getBusinessRange().breaks || [];
let additionGroup;
let additionBreakFrom;
let additionBreakTo;
that._disposeBreaksGroup();
if(!(breaks && breaks.length)) {
return;
}
const breakOptions = {
color: that._options.containerColor,
borderColor: breakStyle.color,
isHorizontal: that._isHorizontal,
isWaved: breakStyle.line.toLowerCase() !== 'straight'
};
if(customCanvas) {
positionFrom = customCanvas.start;
positionTo = customCanvas.end;
} else {
positionFrom = that._orthogonalPositions.start - (options.visible && !that._axisShift && (position === 'left' || position === 'top') ? SCALE_BREAK_OFFSET : 0);
positionTo = that._orthogonalPositions.end + (options.visible && (position === 'right' || position === 'bottom') ? SCALE_BREAK_OFFSET : 0);
}
const mainGroup = that._createBreaksGroup(positionFrom, positionTo);
if(that._axisShift && options.visible) {
additionBreakFrom = that._axisPosition - that._axisShift - SCALE_BREAK_OFFSET;
additionBreakTo = additionBreakFrom + SCALE_BREAK_OFFSET * 2;
additionGroup = that._createBreaksGroup(additionBreakFrom, additionBreakTo);
}
breaks.forEach(function(br) {
if(!br.gapSize) {
const breakCoord = that._getTranslatedCoord(br.to);
that._drawBreak(breakCoord, positionFrom, positionTo, breakStyle.width, breakOptions, mainGroup);
if(that._axisShift && options.visible) {
that._drawBreak(breakCoord, additionBreakFrom, additionBreakTo, breakStyle.width, breakOptions, additionGroup);
}
}
});
},
_getSpiderCategoryOption: noop,
shift: function(margins) {
const that = this;
const options = that._options;
const isHorizontal = options.isHorizontal;
const axesSpacing = that.getMultipleAxesSpacing();
const constantLinesGroups = that._axisConstantLineGroups;
function shiftGroup(side, group) {
const attr = {
translateX: 0,
translateY: 0
};
const shift = margins[side] ? margins[side] + axesSpacing : 0;
attr[isHorizontal ? 'translateY' : 'translateX'] = (side === 'left' || side === 'top' ? -1 : 1) * shift;
(group[side] || group).attr(attr);
return shift;
}
that._axisShift = shiftGroup(options.position, that._axisGroup);
(isHorizontal ? ['top', 'bottom'] : ['left', 'right']).forEach(side => {
shiftGroup(side, constantLinesGroups.above);
shiftGroup(side, constantLinesGroups.under);
});
}
}
};
function getLineDrawer(renderer, root, rotatePoints, positionFrom, breakStart, positionTo, isWaved) {
const elementType = isWaved ? 'bezier' : 'line';
const group = renderer.g().append(root);
return function(offset, attr) {
renderer.path(rotatePoints(getPoints(positionFrom, breakStart, positionTo, offset, isWaved)), elementType).attr(attr).append(group);
};
}
function getPoints(positionFrom, breakStart, positionTo, offset, isWaved) {
if(!isWaved) {
return [positionFrom, breakStart + offset, positionTo, breakStart + offset];
}
breakStart += offset;
let currentPosition;
const topPoint = breakStart + WAVED_LINE_TOP;
const centerPoint = breakStart + WAVED_LINE_CENTER;
const bottomPoint = breakStart + WAVED_LINE_BOTTOM;
const points = [[positionFrom, centerPoint]];
for(currentPosition = positionFrom; currentPosition < positionTo + WAVED_LINE_LENGTH; currentPosition += WAVED_LINE_LENGTH) {
points.push([
currentPosition + 6, topPoint,
currentPosition + 6, topPoint,
currentPosition + 12, centerPoint,
currentPosition + 18, bottomPoint,
currentPosition + 18, bottomPoint,
currentPosition + 24, centerPoint
]);
}
return [].concat.apply([], points);
}
function rotateLine(lineCoords) {
const points = [];
let i;
for(i = 0; i < lineCoords.length; i += 2) {
points.push(lineCoords[i + 1]);
points.push(lineCoords[i]);
}
return points;
}
|
import {useState} from 'react';
import From from './creation/from/From';
import TopBar from './TopBar/TopBar';
import Drawer from './Drawer/Drawer';
import './App.css';
import Interval from './creation/interval/Interval';
import Welcome from './welcome/Welcome';
import Map from './operators/map/Map';
import Scan from './operators/scan/Scan';
import Reduce from './operators/reduce/Reduce';
import Pluck from './operators/pluck/Pluck';
import SwitchMap from './operators/switchMap/SwitchMap';
function App() {
const [toggle, setToggle] = useState(false);
const [selectedMenu, setSelectedMenu] = useState('welcome');
const toggleDrawer = (open) => {
setToggle(open)
}
return (
<div className="App">
<TopBar onMenuClick={() => setToggle(!toggle)}/>
<Drawer toggle={toggle}
toggleDrawer={(open) => toggleDrawer(open)}
onMenuSelect={(menu) => setSelectedMenu(menu)}
/>
<div className="app__body">
{
selectedMenu === 'welcome' &&
<Welcome/>
}
{
selectedMenu === 'from' &&
<From/>
}
{
selectedMenu === 'interval' &&
<Interval/>
}
{
selectedMenu === 'map' &&
<Map/>
}
{
selectedMenu === 'scan' &&
<Scan/>
}
{
selectedMenu === 'reduce' &&
<Reduce/>
}
{
selectedMenu === 'pluck' &&
<Pluck/>
}
{
selectedMenu === 'switchMap' &&
<SwitchMap/>
}
</div>
</div>
);
}
export default App;
|
!function(){function t(t){return function(t){if(Array.isArray(t))return r(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||function(t,e){if(!t)return;if("string"==typeof t)return r(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r(t,e)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(t,r){(null==r||r>t.length)&&(r=t.length);for(var e=0,n=new Array(r);e<r;e++)n[e]=t[e];return n}(window.webpackJsonp=window.webpackJsonp||[]).push([[59],{YBs9:function(r,e,n){"use strict";n.r(e),n.d(e,"scopeCss",(function(){return S}));var o=")(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)",c=new RegExp("(-shadowcsshost"+o,"gim"),s=new RegExp("(-shadowcsscontext"+o,"gim"),a=new RegExp("(-shadowcssslotted"+o,"gim"),i=/-shadowcsshost-no-combinator([^\s]*)/,u=[/::shadow/g,/::content/g],l=/-shadowcsshost/gim,h=/:host/gim,f=/::slotted/gim,p=/:host-context/gim,d=/\/\*\s*[\s\S]*?\*\//g,g=/\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g,m=/(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g,v=/([{}])/g,w=function(t,r){var e=b(t),n=0;return e.escapedString.replace(m,(function(){var t=arguments.length<=2?void 0:arguments[2],o="",c=arguments.length<=4?void 0:arguments[4],s="";c&&c.startsWith("{%BLOCK%")&&(o=e.blocks[n++],c=c.substring("%BLOCK%".length+1),s="{");var a=r({selector:t,content:o});return"".concat(arguments.length<=1?void 0:arguments[1]).concat(a.selector).concat(arguments.length<=3?void 0:arguments[3]).concat(s).concat(a.content).concat(c)}))},b=function(t){for(var r=t.split(v),e=[],n=[],o=0,c=[],s=0;s<r.length;s++){var a=r[s];"}"===a&&o--,o>0?c.push(a):(c.length>0&&(n.push(c.join("")),e.push("%BLOCK%"),c=[]),e.push(a)),"{"===a&&o++}return c.length>0&&(n.push(c.join("")),e.push("%BLOCK%")),{escapedString:e.join(""),blocks:n}},x=function(t,r,e){return t.replace(r,(function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(r[2]){for(var o=r[2].split(","),c=[],s=0;s<o.length;s++){var a=o[s].trim();if(!a)break;c.push(e("-shadowcsshost-no-combinator",a,r[3]))}return c.join(",")}return"-shadowcsshost-no-combinator"+r[3]}))},_=function(t,r,e){return t+r.replace("-shadowcsshost","")+e},y=function(t,r,e){return r.indexOf("-shadowcsshost")>-1?_(t,r,e):t+r+e+", "+r+" "+t+e},S=function(r,e,n){var o=e+"-h",m=e+"-s",v=r.match(g)||[];r=r.replace(d,"");var b=[];if(n){var S=function(t){var r="/*!@___".concat(b.length,"___*/");return b.push({placeholder:r,comment:"/*!@".concat(t.selector,"*/")}),t.selector=r+t.selector,t};r=w(r,(function(t){return"@"!==t.selector[0]?S(t):t.selector.startsWith("@media")||t.selector.startsWith("@supports")||t.selector.startsWith("@page")||t.selector.startsWith("@document")?(t.content=w(t.content,S),t):t}))}var O=function(t,r,e,n,o){var d=function(t,r){var e="."+r+" > ",n=[];return t=t.replace(a,(function(){for(var t=arguments.length,r=new Array(t),o=0;o<t;o++)r[o]=arguments[o];if(r[2]){for(var c=r[2].trim(),s=e+c+r[3],a="",i=r[4]-1;i>=0;i--){var u=r[5][i];if("}"===u||","===u)break;a=u+a}var l=a+s,h="".concat(a.trimRight()).concat(s.trim());return l.trim()!==h.trim()&&n.push({orgSelector:l,updatedSelector:"".concat(h,", ").concat(l)}),s}return"-shadowcsshost-no-combinator"+r[3]})),{selectors:n,cssText:t}}(t=function(t){return x(t,s,y)}(t=function(t){return x(t,c,_)}(t=t.replace(p,"-shadowcsscontext").replace(h,"-shadowcsshost").replace(f,"-shadowcssslotted"))),n);return t=function(t){return u.reduce((function(t,r){return t.replace(r," ")}),t)}(t=d.cssText),r&&(t=function t(r,e,n,o,c){return w(r,(function(r){var c=r.selector,s=r.content;return"@"!==r.selector[0]?c=function(t,r,e,n){return t.split(",").map((function(t){return n&&t.indexOf("."+n)>-1?t.trim():function(t,r){return!function(t){return t=t.replace(/\[/g,"\\[").replace(/\]/g,"\\]"),new RegExp("^("+t+")([>\\s~+[.,{:][\\s\\S]*)?$","m")}(r).test(t)}(t,r)?function(t,r,e){for(var n,o="."+(r=r.replace(/\[is=([^\]]*)\]/g,(function(t){return arguments.length<=1?void 0:arguments[1]}))),c=function(t){var n=t.trim();if(!n)return"";if(t.indexOf("-shadowcsshost-no-combinator")>-1)n=function(t,r,e){if(l.lastIndex=0,l.test(t)){var n="."+e;return t.replace(i,(function(t,r){return r.replace(/([^:]*)(:*)(.*)/,(function(t,r,e,o){return r+n+e+o}))})).replace(l,n+" ")}return r+" "+t}(t,r,e);else{var c=t.replace(l,"");if(c.length>0){var s=c.match(/([^:]*)(:*)(.*)/);s&&(n=s[1]+o+s[2]+s[3])}}return n},s=function(t){var r=[],e=0;return{content:(t=t.replace(/(\[[^\]]*\])/g,(function(t,n){var o="__ph-".concat(e,"__");return r.push(n),e++,o}))).replace(/(:nth-[-\w]+)(\([^)]+\))/g,(function(t,n,o){var c="__ph-".concat(e,"__");return r.push(o),e++,n+c})),placeholders:r}}(t),a="",u=0,h=/( |>|\+|~(?!=))\s*/g,f=!((t=s.content).indexOf("-shadowcsshost-no-combinator")>-1);null!==(n=h.exec(t));){var p=n[1],d=t.slice(u,n.index).trim();f=f||d.indexOf("-shadowcsshost-no-combinator")>-1,a+="".concat(f?c(d):d," ").concat(p," "),u=h.lastIndex}var g,m=t.substring(u);return a+=(f=f||m.indexOf("-shadowcsshost-no-combinator")>-1)?c(m):m,g=s.placeholders,a.replace(/__ph-(\d+)__/g,(function(t,r){return g[+r]}))}(t,r,e).trim():t.trim()})).join(", ")}(r.selector,e,n,o):(r.selector.startsWith("@media")||r.selector.startsWith("@supports")||r.selector.startsWith("@page")||r.selector.startsWith("@document"))&&(s=t(r.content,e,n,o)),{selector:c.replace(/\s{2,}/g," ").trim(),content:s}}))}(t,r,e,n)),{cssText:(t=(t=t.replace(/-shadowcsshost-no-combinator/g,"."+e)).replace(/>\s*\*\s+([^{, ]+)/gm," $1 ")).trim(),slottedSelectors:d.selectors}}(r,e,o,m);return r=[O.cssText].concat(t(v)).join("\n"),n&&b.forEach((function(t){var e=t.placeholder,n=t.comment;r=r.replace(e,n)})),O.slottedSelectors.forEach((function(t){r=r.replace(t.orgSelector,t.updatedSelector)})),r}}}])}();
|
import logging
import json
import gevent
import redis
import redis.connection
redis.connection.socket = gevent.socket # make redis play well with gevent
from aspireblock.lib import config, util
DEFAULT_REDIS_CACHE_PERIOD = 60 # in seconds
logger = logging.getLogger(__name__)
block_info_cache = {}
##
# REDIS-RELATED
##
def get_redis_connection():
logger.info("Connecting to redis @ %s" % config.REDIS_CONNECT)
return redis.StrictRedis(host=config.REDIS_CONNECT, port=config.REDIS_PORT, db=config.REDIS_DATABASE)
def get_value(key):
if not config.REDIS_CLIENT:
logger.debug("Cache MISS: {}".format(key))
return None
result = config.REDIS_CLIENT.get(key)
logger.debug("Cache {}: {}".format('HIT' if result is not None else 'MISS', key))
return json.loads(result.decode('utf8')) if result is not None else result
def set_value(key, value, cache_period=DEFAULT_REDIS_CACHE_PERIOD):
logger.debug("Caching key {} -- period: {}".format(key, cache_period))
if not config.REDIS_CLIENT:
return
config.REDIS_CLIENT.setex(key, cache_period, json.dumps(value))
##
# NOT REDIS RELATED
##
def get_block_info(block_index, prefetch=0, min_message_index=None):
global block_info_cache
if block_index in block_info_cache:
return block_info_cache[block_index]
block_info_cache.clear()
blocks = util.call_jsonrpc_api(
'get_blocks',
{'block_indexes': list(range(block_index, block_index + prefetch)),
'min_message_index': min_message_index},
abort_on_error=True, use_cache=False)['result']
for block in blocks:
block_info_cache[block['block_index']] = block
return block_info_cache[block_index]
def clear_block_info_cache():
global block_info_cache
block_info_cache.clear()
|
# coding: utf-8
"""
Talend Management Console Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.step_error_handler import StepErrorHandler # noqa: E501
from swagger_client.rest import ApiException
class TestStepErrorHandler(unittest.TestCase):
"""StepErrorHandler unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testStepErrorHandler(self):
"""Test StepErrorHandler"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.step_error_handler.StepErrorHandler() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
"""Tests for coverage.py's results analysis."""
import pytest
from coverage.results import Numbers, should_fail_under
from tests.coveragetest import CoverageTest
class NumbersTest(CoverageTest):
"""Tests for coverage.py's numeric measurement summaries."""
run_in_temp_dir = False
def test_basic(self):
n1 = Numbers(n_files=1, n_statements=200, n_missing=20)
self.assertEqual(n1.n_statements, 200)
self.assertEqual(n1.n_executed, 180)
self.assertEqual(n1.n_missing, 20)
self.assertEqual(n1.pc_covered, 90)
def test_addition(self):
n1 = Numbers(n_files=1, n_statements=200, n_missing=20)
n2 = Numbers(n_files=1, n_statements=10, n_missing=8)
n3 = n1 + n2
self.assertEqual(n3.n_files, 2)
self.assertEqual(n3.n_statements, 210)
self.assertEqual(n3.n_executed, 182)
self.assertEqual(n3.n_missing, 28)
self.assertAlmostEqual(n3.pc_covered, 86.666666666)
def test_sum(self):
n1 = Numbers(n_files=1, n_statements=200, n_missing=20)
n2 = Numbers(n_files=1, n_statements=10, n_missing=8)
n3 = sum([n1, n2])
self.assertEqual(n3.n_files, 2)
self.assertEqual(n3.n_statements, 210)
self.assertEqual(n3.n_executed, 182)
self.assertEqual(n3.n_missing, 28)
self.assertAlmostEqual(n3.pc_covered, 86.666666666)
def test_pc_covered_str(self):
# Numbers._precision is a global, which is bad.
Numbers.set_precision(0)
n0 = Numbers(n_files=1, n_statements=1000, n_missing=0)
n1 = Numbers(n_files=1, n_statements=1000, n_missing=1)
n999 = Numbers(n_files=1, n_statements=1000, n_missing=999)
n1000 = Numbers(n_files=1, n_statements=1000, n_missing=1000)
self.assertEqual(n0.pc_covered_str, "100")
self.assertEqual(n1.pc_covered_str, "99")
self.assertEqual(n999.pc_covered_str, "1")
self.assertEqual(n1000.pc_covered_str, "0")
def test_pc_covered_str_precision(self):
# Numbers._precision is a global, which is bad.
Numbers.set_precision(1)
n0 = Numbers(n_files=1, n_statements=10000, n_missing=0)
n1 = Numbers(n_files=1, n_statements=10000, n_missing=1)
n9999 = Numbers(n_files=1, n_statements=10000, n_missing=9999)
n10000 = Numbers(n_files=1, n_statements=10000, n_missing=10000)
self.assertEqual(n0.pc_covered_str, "100.0")
self.assertEqual(n1.pc_covered_str, "99.9")
self.assertEqual(n9999.pc_covered_str, "0.1")
self.assertEqual(n10000.pc_covered_str, "0.0")
Numbers.set_precision(0)
def test_covered_ratio(self):
n = Numbers(n_files=1, n_statements=200, n_missing=47)
self.assertEqual(n.ratio_covered, (153, 200))
n = Numbers(
n_files=1, n_statements=200, n_missing=47,
n_branches=10, n_missing_branches=3, n_partial_branches=1000,
)
self.assertEqual(n.ratio_covered, (160, 210))
@pytest.mark.parametrize("total, fail_under, precision, result", [
# fail_under==0 means anything is fine!
(0, 0, 0, False),
(0.001, 0, 0, False),
# very small fail_under is possible to fail.
(0.001, 0.01, 0, True),
# Rounding should work properly.
(42.1, 42, 0, False),
(42.1, 43, 0, True),
(42.857, 42, 0, False),
(42.857, 43, 0, False),
(42.857, 44, 0, True),
(42.857, 42.856, 3, False),
(42.857, 42.858, 3, True),
# If you don't specify precision, your fail-under is rounded.
(42.857, 42.856, 0, False),
# Values near 100 should only be treated as 100 if they are 100.
(99.8, 100, 0, True),
(100.0, 100, 0, False),
(99.8, 99.7, 1, False),
(99.88, 99.90, 2, True),
(99.999, 100, 1, True),
(99.999, 100, 2, True),
(99.999, 100, 3, True),
])
def test_should_fail_under(total, fail_under, precision, result):
assert should_fail_under(float(total), float(fail_under), precision) == result
|
/**
* eZmax API Definition (Full)
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.7
* Contact: support-api@ezmax.ca
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
import EzsignfoldertypeListElement from './EzsignfoldertypeListElement';
/**
* The EzsignfoldertypeGetListV1ResponseMPayloadAllOf model module.
* @module eZmaxAPI/model/EzsignfoldertypeGetListV1ResponseMPayloadAllOf
* @version 1.1.7
*/
class EzsignfoldertypeGetListV1ResponseMPayloadAllOf {
/**
* Constructs a new <code>EzsignfoldertypeGetListV1ResponseMPayloadAllOf</code>.
* @alias module:eZmaxAPI/model/EzsignfoldertypeGetListV1ResponseMPayloadAllOf
* @param a_objEzsignfoldertype {Array.<module:eZmaxAPI/model/EzsignfoldertypeListElement>}
*/
constructor(a_objEzsignfoldertype) {
EzsignfoldertypeGetListV1ResponseMPayloadAllOf.initialize(this, a_objEzsignfoldertype);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, a_objEzsignfoldertype) {
obj['a_objEzsignfoldertype'] = a_objEzsignfoldertype;
}
/**
* Constructs a <code>EzsignfoldertypeGetListV1ResponseMPayloadAllOf</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:eZmaxAPI/model/EzsignfoldertypeGetListV1ResponseMPayloadAllOf} obj Optional instance to populate.
* @return {module:eZmaxAPI/model/EzsignfoldertypeGetListV1ResponseMPayloadAllOf} The populated <code>EzsignfoldertypeGetListV1ResponseMPayloadAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new EzsignfoldertypeGetListV1ResponseMPayloadAllOf();
if (data.hasOwnProperty('a_objEzsignfoldertype')) {
obj['a_objEzsignfoldertype'] = ApiClient.convertToType(data['a_objEzsignfoldertype'], [EzsignfoldertypeListElement]);
}
}
return obj;
}
/**
* Returns
* @return {Array.<module:eZmaxAPI/model/EzsignfoldertypeListElement>}
*/
getAObjEzsignfoldertype() {
return this.a_objEzsignfoldertype;
}
/**
* Sets
* @param {Array.<module:eZmaxAPI/model/EzsignfoldertypeListElement>} a_objEzsignfoldertype
*/
setAObjEzsignfoldertype(a_objEzsignfoldertype) {
this['a_objEzsignfoldertype'] = a_objEzsignfoldertype;
}
}
/**
*
* @member {Array.<module:eZmaxAPI/model/EzsignfoldertypeListElement>} a_objEzsignfoldertype
*/
EzsignfoldertypeGetListV1ResponseMPayloadAllOf.prototype['a_objEzsignfoldertype'] = undefined;
export default EzsignfoldertypeGetListV1ResponseMPayloadAllOf;
|
#pragma once
#include "DrawableObjectGroup.h"
/*
UNO
CardBackObjectGroup class:
Creates a visual representing the back of a card.
@author Peter Mitchell
@version 2022.1
*/
class CardBackGroupObject
: public DrawableObjectGroup
{
public:
// Initialises the generic Card back visual.
CardBackGroupObject(const sf::Vector2f& initialPosition, const sf::Font& font);
virtual ~CardBackGroupObject() = default;
// Moves the object to the specified position and then draws it. Use this for drawing instead because the CardBackGroupObject is generic and shared between instances.
void drawAt(const sf::Vector2f& position, sf::RenderWindow& renderWindow);
};
|
from operator import attrgetter
from django.test import TestCase
from robber import expect
from data.factories import OfficerFactory, AllegationFactory
from search.queries import BaseModelQuery, OfficerQuery, CrQuery, TrrQuery
from trr.factories import TRRFactory
class BaseModelQueryTestCase(TestCase):
def test_queryset_raise_NotImplementedError(self):
expect(lambda: BaseModelQuery(ids=[]).queryset()).to.throw(NotImplementedError)
class OfficerQueryTestCase(TestCase):
def test_query(self):
officer_1 = OfficerFactory(id=8562)
officer_2 = OfficerFactory(id=8563)
OfficerFactory(id=8564)
results = sorted(list(OfficerQuery(ids=[8562, 8563]).query()), key=attrgetter('id'))
expect(results).to.eq([officer_1, officer_2])
class CrQueryTestCase(TestCase):
def test_query(self):
allegation_1 = AllegationFactory(crid='C123')
allegation_2 = AllegationFactory(crid='C456')
AllegationFactory(crid='789')
results = sorted(list(CrQuery(ids=['C123', 'C456']).query()), key=attrgetter('crid'))
expect(results).to.eq([allegation_1, allegation_2])
class TrrQueryTestCase(TestCase):
def test_query(self):
trr_1 = TRRFactory(id=123)
trr_2 = TRRFactory(id=456)
TRRFactory(id=789)
results = sorted(list(TrrQuery(ids=[123, 456]).query()), key=attrgetter('id'))
expect(results).to.eq([trr_1, trr_2])
|
'use strict';
const externalHelpers = require('handlebars-helpers')(['comparison']);
function moveNumberToEnd(str) {
if (str && str.replace) {
return str.replace(/^(\d+) ([^\d]+)$/, '$2 $1');
}
return str;
}
module.exports = { ...externalHelpers, moveNumberToEnd };
|
import sys
from data_formatting_utils import subtokenize_code, subtokenize_comment
sys.path.append('../')
sys.path.append('../comment_update')
from data_utils import DiffASTExample
from diff_utils import compute_minimal_comment_diffs, compute_code_diffs
# NOTE: Javalang will need to installed for this
def build_test_example():
example_id = 'test-id-0'
label = 1
comment_type = 'Return'
old_comment_raw = '@return the highest score'
old_comment_subtokens = subtokenize_comment(old_comment_raw).split()
new_comment_raw = '@return the lowest score'
new_comment_subtokens = subtokenize_comment(new_comment_raw).split()
span_minimal_diff_comment_subtokens, _, _ = compute_minimal_comment_diffs(
old_comment_subtokens, new_comment_subtokens)
old_code_raw = 'public int getBestScore()\n{\n\treturn Collections.max(scores);\n}'
old_code_subtokens = subtokenize_code(old_code_raw).split()
new_code_raw = 'public int getBestScore()\n{\n\treturn Collections.min(scores);\n}'
new_code_subtokens = subtokenize_code(new_code_raw).split()
span_diff_code_subtokens, token_diff_code_subtokens, _ = compute_code_diffs(old_code_subtokens, new_code_subtokens)
# TODO: Add code for parsing ASTs
old_ast = None
new_ast = None
diff_ast = None
return DiffASTExample(example_id, label, comment_type, old_comment_raw, old_comment_subtokens, new_comment_raw,
new_comment_subtokens, span_minimal_diff_comment_subtokens, old_code_raw, old_code_subtokens, new_code_raw,
new_code_subtokens, span_diff_code_subtokens, token_diff_code_subtokens, old_ast, new_ast, diff_ast)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from setuptools import setup
setup(name='jiagu',
version='0.1.8',
description='Jiagu Natural Language Processing',
author='Yener(Zheng Wenyu)',
author_email='help@ownthink.com',
url='https://github.com/ownthink/Jiagu',
license='MIT',
install_requires=['tensorflow==1.6.0', 'numpy>=1.12.1'],
packages=['jiagu'],
package_dir={'jiagu': 'jiagu'},
package_data={'jiagu': ['*.*', 'cluster/*', 'data/*', 'model/*',
'normal/*', 'segment/*', 'segment/dict/*',
'sentiment/*', 'sentiment/model/*', 'topic/*']}
)
|
#!/usr/bin/env python3
# Uncomment the following to lazily import everything.
from ev3dev2.auto import *
#from ev3dev2 import get_current_platform, Device, list_device_names, list_devices
#from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D
#from ev3dev2.motor import LargeMotor, MediumMotor, MoveTank, MoveSteering
#from ev3dev2.motor import SpeedPercent, SpeedNativeUnits, SpeedRPS, SpeedRPM, SpeedDPS, SpeedDPM
#from ev3dev2.sensor.lego import TouchSensor, InfraredSensor, ColorSensor
#from ev3dev2.led import Leds
#from time import sleep,
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'horizontalrule', 'no', {
toolbar: 'Sett inn horisontal linje'
} );
|
'''
core script of psii system
Created on Jan 12, 2017
@author: Zongyang
'''
import os, sys, json
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
def main():
in_dir = '/Users/nijiang/Desktop/pythonTest/PSII_clowderTest/t1'
hist_path = os.path.join(in_dir, 'hist.png')
map_path = os.path.join(in_dir, 'imgMap.png')
frames = {}
for i in range(0, 101):
file_ends = "{0:0>4}".format(i)+'.png'
frames[i] = os.path.join(in_dir, '0e568025-5a74-43e0-9567-45b02310f6f5_rawData'+file_ends)
psii_analysis(frames, hist_path, map_path)
#create_ps2_images(in_dir)
return
def create_ps2_images(in_dir):
list_dirs = os.walk(in_dir)
out_dir = os.path.join(in_dir, 'images')
os.mkdir(out_dir)
img_width = 1936
img_height = 1216
for root, dirs, files in list_dirs:
for file_path in files:
if not file_path.endswith('.bin'):
continue
if file_path.endswith('0101.bin'):
continue
input_path = os.path.join(in_dir, file_path)
out_path = os.path.join(out_dir, file_path)
out_path = out_path[:-3] + 'png'
load_PSII_data(input_path, img_height, img_width, out_path)
return
def load_PSII_data(file_path, height, width, out_file):
try:
im = np.fromfile(file_path, np.dtype('uint8')).reshape([height, width])
Image.fromarray(im).save(out_file)
return im.astype('u1')
except Exception as ex:
fail('Error processing image "%s": %s' % (file_path,str(ex)))
def load_PSII_png(file_path, height, width):
try:
im = Image.open(file_path)
pix = np.array(im).astype('uint8')
return pix
except Exception as ex:
fail('Error loading image "%s": %s' % (file_path,str(ex)))
def psii_analysis(frames, hist_path, coloredImg_path):
img_width = 1936
img_height = 1216
fdark = load_PSII_png(frames[0], img_height, img_width)
fmin = load_PSII_png(frames[1], img_height, img_width)
# Calculate the maximum fluorescence for each frame
fave = []
fave.append(np.max(fdark))
# Calculate the maximum value for frames 2 through 100. Bin file 101 is an XML file that lists the frame times
for i in range(2, 101):
img = load_PSII_png(frames[i], img_height, img_width)
fave.append(np.max(img))
# Assign the first image with the most fluorescence as F-max
fmax = load_PSII_png(frames[np.where(fave == np.max(fave))[0][0]], img_height, img_width)
# Calculate F-variable (F-max - F-min)
fv = np.subtract(fmax, fmin)
# Calculate Fv/Fm (F-variable / F-max)
fvfm = np.divide(fv.astype('float'), fmax.astype('float'))
# Fv/Fm will generate invalid values, such as division by zero
# Convert invalid values to zero. Valid values will be between 0 and 1
fvfm[np.where(np.isnan(fvfm))] = 0
fvfm[np.where(np.isinf(fvfm))] = 0
fvfm[np.where(fvfm > 1.0)] = 0
fig, ax = plt.subplots()
# Plot Fv/Fm (pseudocolored)
plt.imshow(fvfm, cmap="viridis")
plt.show()
plt.savefig(coloredImg_path)
plt.close()
# Calculate histogram of Fv/Fm values from the whole image
hist, bins = np.histogram(fvfm, bins=20)
# Plot Fv/Fm histogram
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.xlabel("Fv/Fm")
plt.ylabel("Pixels")
plt.show()
plt.savefig(hist_path)
plt.close()
return
def fail(reason):
print >> sys.stderr, reason
def load_json(meta_path):
try:
with open(meta_path, 'r') as fin:
return json.load(fin)
except Exception as ex:
fail('Corrupt metadata file, ' + str(ex))
def lower_keys(in_dict):
if type(in_dict) is dict:
out_dict = {}
for key, item in in_dict.items():
out_dict[key.lower()] = lower_keys(item)
return out_dict
elif type(in_dict) is list:
return [lower_keys(obj) for obj in in_dict]
else:
return in_dict
if __name__ == "__main__":
main()
|
__author__ = 'Lin, Ke-fei, Samuel Gratzl'
__authoremail__ = 'kfei@kfei.net, samuel_gratzl@gmx.at'
__version__ = '0.4.0'
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras optimizers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.keras.python import keras
from tensorflow.contrib.keras.python.keras import testing_utils
from tensorflow.python.platform import test
from tensorflow.python.training.adam import AdamOptimizer
def _get_model(input_dim, num_hidden, output_dim):
model = keras.models.Sequential()
model.add(keras.layers.Dense(num_hidden,
activation='relu',
input_shape=(input_dim,)))
model.add(keras.layers.Dense(output_dim, activation='softmax'))
return model
def _test_optimizer(optimizer, target=0.75):
np.random.seed(1337)
(x_train, y_train), _ = testing_utils.get_test_data(train_samples=1000,
test_samples=200,
input_shape=(10,),
num_classes=2)
y_train = keras.utils.to_categorical(y_train)
model = _get_model(x_train.shape[1], 20, y_train.shape[1])
model.compile(loss='categorical_crossentropy',
optimizer=optimizer,
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=2, batch_size=16, verbose=0)
assert history.history['acc'][-1] >= target
config = keras.optimizers.serialize(optimizer)
optim = keras.optimizers.deserialize(config)
new_config = keras.optimizers.serialize(optim)
new_config['class_name'] = new_config['class_name'].lower()
assert config == new_config
class KerasOptimizersTest(test.TestCase):
def test_sgd(self):
with self.test_session():
_test_optimizer(keras.optimizers.SGD(lr=0.01,
momentum=0.9,
nesterov=True))
def test_rmsprop(self):
with self.test_session():
_test_optimizer(keras.optimizers.RMSprop())
_test_optimizer(keras.optimizers.RMSprop(decay=1e-3))
def test_adagrad(self):
with self.test_session():
_test_optimizer(keras.optimizers.Adagrad())
_test_optimizer(keras.optimizers.Adagrad(decay=1e-3))
def test_adadelta(self):
with self.test_session():
_test_optimizer(keras.optimizers.Adadelta(), target=0.6)
_test_optimizer(keras.optimizers.Adadelta(decay=1e-3), target=0.6)
def test_adam(self):
with self.test_session():
_test_optimizer(keras.optimizers.Adam())
_test_optimizer(keras.optimizers.Adam(decay=1e-3))
def test_adamax(self):
with self.test_session():
_test_optimizer(keras.optimizers.Adamax())
_test_optimizer(keras.optimizers.Adamax(decay=1e-3))
def test_nadam(self):
with self.test_session():
_test_optimizer(keras.optimizers.Nadam())
def test_clipnorm(self):
with self.test_session():
_test_optimizer(keras.optimizers.SGD(lr=0.01,
momentum=0.9,
clipnorm=0.5))
def test_clipvalue(self):
with self.test_session():
_test_optimizer(keras.optimizers.SGD(lr=0.01,
momentum=0.9,
clipvalue=0.5))
def test_tfoptimizer(self):
optimizer = keras.optimizers.TFOptimizer(AdamOptimizer)
model = keras.models.Sequential()
model.add(keras.layers.Dense(
2, input_shape=(3,), kernel_constraint=keras.constraints.MaxNorm(1)))
# This is possible
model.compile(loss='mean_squared_error', optimizer=optimizer)
# TF optimizers do not support weights constraints
with self.assertRaises(ValueError):
model.fit(np.random.random((5, 3)),
np.random.random((5, 2)),
epochs=1,
batch_size=5,
verbose=0)
# not supported
with self.assertRaises(NotImplementedError):
_ = optimizer.weights
with self.assertRaises(NotImplementedError):
optimizer.get_config()
with self.assertRaises(NotImplementedError):
optimizer.from_config(None)
if __name__ == '__main__':
test.main()
|
"""
excel2py - turn a spreadsheet open in Excel into a Python program
It is controlled by a config file, traditionally a yaml file with
the same name as the Excel file. This tells it which sheets are
inputs, outputs and calculations.
By Michael Grazebrook of Joined Up Finance Ltd
21 Aug 2018
"""
from excel2py.config import config
from excel2py.excel_to_py import ExcelToPy
def main():
cfg = config(__doc__)
app = ExcelToPy(cfg)
app.generate()
if __name__ == "__main__":
main()
|
import pytest
from wemake_python_styleguide.compat.constants import PY38
from wemake_python_styleguide.violations.refactoring import (
NestedTernaryViolation,
)
from wemake_python_styleguide.visitors.ast.compares import (
WrongConditionalVisitor,
)
wrong_compare1 = 'x > (a if b else c)'
wrong_compare2 = '(a if b else c) > x'
wrong_compare3 = 'x == (a if b else c)'
wrong_compare4 = '(a if b else c) == x == y'
wrong_compare5 = 'x == (a if b else c) == y'
wrong_compare6 = 'x != (a if b else c)'
wrong_compare7 = 'x != call(a if b else c)'
wrong_boolop1 = 'x and (a if b else c)'
wrong_boolop2 = 'x or (a if b else c)'
wrong_boolop3 = '(a if b else c) or x'
wrong_boolop4 = 'x and (a if b else c) or y'
wrong_boolop5 = 'x and y or (a if b else c)'
wrong_boolop6 = '(a if b else c) and x or y'
wrong_boolop7 = 'call(a if b else c) and x or y'
wrong_binop1 = 'x + (a if b else c)'
wrong_binop2 = 'x - (a if b else c)'
wrong_binop3 = '(a if b else c) / y'
wrong_binop4 = 'x + (a if b else c) - y'
wrong_binop5 = 'x + y - (a if b else c)'
wrong_binop6 = '(a if b else c) * x / y'
wrong_binop7 = 'some(a if b else c) * x / y'
wrong_unary1 = '+(a if b else c)'
wrong_unary2 = '-(a if b else c)'
wrong_unary3 = '~(a if b else c)'
wrong_unary4 = 'not (a if b else c)'
wrong_ternary1 = 'a if (b if some else c) else d'
wrong_ternary2 = 'a if call(b if some else c) else d'
wrong_ternary3 = 'a if b else (c if some else d)'
wrong_ternary4 = '(a if some else b) if c else d'
wrong_if1 = 'if a if b else c: ...'
wrong_if2 = 'if call(a if b else c): ...'
wrong_if3 = 'if attr.call(a if b else c): ...'
wrong_if4 = 'if x := 1 if True else 2: ...'
# Correct:
correct_if1 = """
if x:
y = a if b else c
print(a if b else c, end=a if b else c)
d = {'key': a if b else c}
"""
correct_if2 = """
if x:
a if b else c
"""
correct_unary1 = '-a if b else c'
correct_unary2 = 'a if -b else c'
correct_unary3 = 'a if b else -c'
correct_unary4 = 'not a if b else c'
correct_binop1 = 'a + x if b else c'
correct_binop2 = 'a if b + x else c'
correct_binop3 = 'a if b else c + x'
correct_boolop1 = 'a and x if b else c'
correct_boolop2 = 'a if b and x else c'
correct_boolop3 = 'a if b else c and x'
correct_compare1 = 'a > x if b else c'
correct_compare2 = 'a if b > x else c'
correct_compare3 = 'a if b else c < x'
@pytest.mark.parametrize('code', [
correct_if1,
correct_if2,
correct_unary1,
correct_unary2,
correct_unary3,
correct_unary4,
correct_binop1,
correct_binop2,
correct_binop3,
correct_boolop1,
correct_boolop2,
correct_boolop3,
correct_compare1,
correct_compare2,
correct_compare3,
])
def test_non_nested_ternary(
assert_errors,
parse_ast_tree,
code,
default_options,
):
"""Testing that ternary can be used work well."""
tree = parse_ast_tree(code)
visitor = WrongConditionalVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [])
@pytest.mark.parametrize('code', [
wrong_compare1,
wrong_compare2,
wrong_compare3,
wrong_compare4,
wrong_compare5,
wrong_compare6,
wrong_binop7,
wrong_boolop1,
wrong_boolop2,
wrong_boolop3,
wrong_boolop4,
wrong_boolop5,
wrong_boolop6,
wrong_boolop7,
wrong_binop1,
wrong_binop2,
wrong_binop3,
wrong_binop4,
wrong_binop5,
wrong_binop6,
wrong_binop7,
wrong_unary1,
wrong_unary2,
wrong_unary3,
wrong_unary4,
wrong_ternary1,
wrong_ternary2,
wrong_ternary3,
wrong_ternary4,
wrong_if1,
wrong_if2,
wrong_if3,
pytest.param(
wrong_if3,
marks=pytest.mark.skipif(not PY38, reason='walrus appeared in 3.8'),
),
])
def test_nested_ternary(
assert_errors,
parse_ast_tree,
code,
default_options,
):
"""Testing that ternary can be used work well."""
tree = parse_ast_tree(code)
visitor = WrongConditionalVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [NestedTernaryViolation])
|
/**
* book list Page script
*/
import pageData from '../../lib/freeData.js'
Page({
data: {
pageData: pageData
},
onLoad(){
console.log(pageData);
}
})
|
# creating a comand line interface
import argparse
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
import sys
dic = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'}
now = datetime.now()
date = now.strftime("%Y-%m-%d_%H-%M-%S")
listaFinal = []
parser = argparse.ArgumentParser(description='Raspador dos resumos dos Simpósios Nacionais de História da Associação Nacional de História - Anpuh.\n'
'O programa raspa todos os resumos dos SNH 27, 28, 29, 30 e 31, respectivamente dos anos de 2013, 2015, 2017, 2019 e 2021.\n'
'Desenvolvido no âmbito do Laboratório de Humanidades Digitais da UFBA e parte do Repositório Digital das Humanidades (PT-BR) - REDHBR.')
parser.add_argument('-y','--years', nargs='+', metavar='', required=True, help='Lista de anos a serem raspados. Exemplo: 2013 2015 2017 2019 2021. Essa opção é obrigatória.')
parser.add_argument('-o', '--output', metavar='', help='Nome do arquivo de saída no formato .csv. Se essa opção não for definida, o título do arquivo será `<AAAA-MM-DD_HH-MM-SS>.csv', default=f'{date}.csv')
args = parser.parse_args()
def cleanAbstract(abstract):
'''
Função que limpa o resumo do evento
'''
abstract = abstract.replace('\n', ' ')
abstract = abstract.replace('Resumo:','')
abstract = abstract.replace('\nOcultar','')
abstract = abstract.replace('RESUMO','')
return abstract
def saveDF(listaFinal, output):
'''
Função que salva o DataFrame com os resumos dos simpósios Nacionais de História da Anpuh
'''
df = pd.DataFrame(listaFinal, columns=['Ano', 'Evento', 'Cidade', 'ST', 'Coordenadores', 'Autor(es)/Instituições', 'Título', 'Resumo'])
df.to_csv(f'{output}')
def getAbstract(bs, year):
'''
Função que raspa os resumos de cada simpósio Nacional de História
'''
year = int(year)
if year == 2013:
city = 'Natal'
event = 'XXVII'
if year == 2015:
city = 'Florianópolis'
event = 'XXVIII'
if year == 2017:
city = "Brasília"
event = 'XXIX'
if year == 2019:
city = 'Recife'
event = 'XXX'
if year == 2021:
city = 'Rio de Janeiro'
event = 'XXXI'
if year in [2013, 2015]:
STContent = bs.find(class_='content-interna')
elif year in [2017, 2019]:
STContent = bs.find(id='conteudo-spacer')
else:
STContent = bs.find(class_='col-xl-9 col-lg-8 pl-4 pr-4 pt-3 pb-3 w-100')
if year == 2021:
STInfos = STContent.find(class_='container')
STtitle = STInfos.find('h3').text
coordinators = STInfos.find('b').text
ST_table = STInfos.find('table')
sts = ST_table.find_all('tr')
for paper in sts:
author = paper.find('i').text
title = paper.find('b').text
abstract = paper.find(style='display:none;font-size:11px;').text.strip()
abstract = cleanAbstract(abstract)
listaInterna = [year, event, city, STtitle, coordinators, author, title, abstract]
listaFinal.append(listaInterna)
else:
STInfos = STContent.find_all('table')
STInfosGeral = STInfos[0]
sttest = STInfosGeral.find_all('tr')
STtitle = sttest[0].find('h3').text
try:
coordinators = sttest[1].find('b').text
except:
coordinators = 'Não foi definido'
#finds 'h4' in STContent
programacao = STContent.find('h4')
if programacao is None:
print(f'Não foi encontrada nenhuma programação para o st {STtitle}')
#creates a txt file with the error and saves it
with open(f'ERROR_{date}.txt', 'a') as f:
f.write(f'Não foi encontrada nenhuma programação para o st {STtitle}\n')
f.close()
else:
stsTable = programacao.find_next_sibling()
sts = stsTable.find_all('td')
for paper in sts:
author = paper.find('i').text
title = paper.find('b').text
if year in [2013, 2015]:
abstract = paper.find(style='font-size:11px;').text.strip()
abstract = cleanAbstract(abstract)
else:
abstract = paper.find(style='display:none;font-size:11px;').text.strip()
abstract = cleanAbstract(abstract)
listaInterna = [year, event, city, STtitle, coordinators, author, title, abstract]
listaFinal.append(listaInterna)
def stList(bs, className, year):
'''
Função que raspa a lista de Simpósios Temáticos
'''
print(f'Raspando todos os resumos referentes ao ano {year}\n'
'Isso pode demorar um pouco...')
STBoxe = bs.find('table', class_= className)
STtrs = STBoxe.find_all('tr')
#find all trs in STtrs
for st in STtrs:
STInfos = st.find_all('td')
STInfos = STInfos[0]
if STInfos.find('h4'):
STtitle = STInfos.find('h4')
STlink = STtitle.find('a')['href']
reqopen = Request(STlink)
req = urlopen(reqopen)
soup = BeautifulSoup(req.read(), 'lxml')
getAbstract(soup, year)
elif STInfos.find('h3'):
STtitle = STInfos.find('h3')
STlink = STtitle.find('a')['href']
reqopen = Request(STlink)
req = urlopen(reqopen)
soup = BeautifulSoup(req.read(), 'lxml')
getAbstract(soup, year)
else:
pass
def request (url, dic, year):
'''
Função que acessa a URL com urlopen e faz o parse do html com BeautifulSoup
'''
reqopen = Request(url, headers=dic)
req = urlopen(reqopen)
bs = BeautifulSoup(req.read(), 'lxml')
stList(bs, 'txtConteudo', year)
def baseUrl(snhYears):
'''
Função para definir a URL base para a raspagem dos resumos
'''
for year in snhYears:
url = f'http://snh{year}.anpuh.org/simposio/public'
request(url,dic, year)
def main():
baseUrl(args.years)
saveDF(listaFinal, args.output)
if __name__ == '__main__':
main()
|
from flask import Flask
app = Flask(__name__)
@app.route("/hello")
def hello():
return "hello"
|
/*
jCanvas v16.06.06
Copyright 2016 Caleb Evans
Released under the MIT license
*/
(function(g,U,J){"object"===typeof module&&"object"===typeof module.exports?module.exports=function(g,U){return J(g,U)}:J(g,U)})("undefined"!==typeof window?window.jQuery:{},"undefined"!==typeof window?window:this,function(g,U){function J(d){for(var c in d)d.hasOwnProperty(c)&&(this[c]=d[c]);return this}function na(){Z(this,na.baseDefaults)}function ja(d){return"string"===aa(d)}function va(d){return!isNaN(wa(d))&&!isNaN(ba(d))}function K(d){return d&&d.getContext?d.getContext("2d"):null}function ka(d){var c,
a,b;for(c in d)d.hasOwnProperty(c)&&(b=d[c],a=aa(b),"string"===a&&va(b)&&"text"!==c&&(d[c]=ba(b)));void 0!==d.text&&(d.text=String(d.text))}function la(d){d=Z({},d);d.masks=d.masks.slice(0);return d}function fa(d,c){var a;d.save();a=la(c.transforms);c.savedTransforms.push(a)}function xa(d,c,a,b){a[b]&&(da(a[b])?c[b]=a[b].call(d,a):c[b]=a[b])}function S(d,c,a){xa(d,c,a,"fillStyle");xa(d,c,a,"strokeStyle");c.lineWidth=a.strokeWidth;a.rounded?c.lineCap=c.lineJoin="round":(c.lineCap=a.strokeCap,c.lineJoin=
a.strokeJoin,c.miterLimit=a.miterLimit);a.strokeDash||(a.strokeDash=[]);c.setLineDash&&c.setLineDash(a.strokeDash);c.webkitLineDash=a.strokeDash;c.lineDashOffset=c.webkitLineDashOffset=c.mozDashOffset=a.strokeDashOffset;c.shadowOffsetX=a.shadowX;c.shadowOffsetY=a.shadowY;c.shadowBlur=a.shadowBlur;c.shadowColor=a.shadowColor;c.globalAlpha=a.opacity;c.globalCompositeOperation=a.compositing;a.imageSmoothing&&(c.imageSmoothingEnabled=c.mozImageSmoothingEnabled=a.imageSmoothingEnabled)}function ya(d,c,
a){a.mask&&(a.autosave&&fa(d,c),d.clip(),c.transforms.masks.push(a._args))}function W(d,c,a){a.closed&&c.closePath();a.shadowStroke&&0!==a.strokeWidth?(c.stroke(),c.fill(),c.shadowColor="transparent",c.shadowBlur=0,c.stroke()):(c.fill(),"transparent"!==a.fillStyle&&(c.shadowColor="transparent"),0!==a.strokeWidth&&c.stroke());a.closed||c.closePath();a._transformed&&c.restore();a.mask&&(d=H(d),ya(c,d,a))}function Q(d,c,a,b,f){a._toRad=a.inDegrees?F/180:1;a._transformed=!0;c.save();a.fromCenter||a._centered||
void 0===b||(void 0===f&&(f=b),a.x+=b/2,a.y+=f/2,a._centered=!0);a.rotate&&za(c,a,null);1===a.scale&&1===a.scaleX&&1===a.scaleY||Aa(c,a,null);(a.translate||a.translateX||a.translateY)&&Ba(c,a,null)}function H(d){var c=ca.dataCache,a;c._canvas===d&&c._data?a=c._data:(a=g.data(d,"jCanvas"),a||(a={canvas:d,layers:[],layer:{names:{},groups:{}},eventHooks:{},intersecting:[],lastIntersected:null,cursor:g(d).css("cursor"),drag:{layer:null,dragging:!1},event:{type:null,x:null,y:null},events:{},transforms:la(oa),
savedTransforms:[],animating:!1,animated:null,pixelRatio:1,scaled:!1},g.data(d,"jCanvas",a)),c._canvas=d,c._data=a);return a}function Ca(d,c,a){for(var b in Y.events)Y.events.hasOwnProperty(b)&&(a[b]||a.cursors&&a.cursors[b])&&Da(d,c,a,b);c.events.mouseout||(d.bind("mouseout.jCanvas",function(){var a=c.drag.layer,b;a&&(c.drag={},O(d,c,a,"dragcancel"));for(b=0;b<c.layers.length;b+=1)a=c.layers[b],a._hovered&&d.triggerLayerEvent(c.layers[b],"mouseout");d.drawLayers()}),c.events.mouseout=!0)}function Da(d,
c,a,b){Y.events[b](d,c);a._event=!0}function Ea(d,c,a){var b,f,e;if(a.draggable||a.cursors){b=["mousedown","mousemove","mouseup"];for(e=0;e<b.length;e+=1)f=b[e],Da(d,c,a,f);a._event=!0}}function pa(d,c,a,b){d=c.layer.names;b?void 0!==b.name&&ja(a.name)&&a.name!==b.name&&delete d[a.name]:b=a;ja(b.name)&&(d[b.name]=a)}function qa(d,c,a,b){d=c.layer.groups;var f,e,h,g;if(!b)b=a;else if(void 0!==b.groups&&null!==a.groups)for(e=0;e<a.groups.length;e+=1)if(f=a.groups[e],c=d[f]){for(g=0;g<c.length;g+=1)if(c[g]===
a){h=g;c.splice(g,1);break}0===c.length&&delete d[f]}if(void 0!==b.groups&&null!==b.groups)for(e=0;e<b.groups.length;e+=1)f=b.groups[e],c=d[f],c||(c=d[f]=[],c.name=f),void 0===h&&(h=c.length),c.splice(h,0,a)}function ra(d,c,a,b,f){b[a]&&c._running&&!c._running[a]&&(c._running[a]=!0,b[a].call(d[0],c,f),c._running[a]=!1)}function O(d,c,a,b,f){if(!(a.disableEvents||a.intangible&&-1!==g.inArray(b,Ua))){if("mouseout"!==b){var e;a.cursors&&(e=a.cursors[b]);-1!==g.inArray(e,V.cursors)&&(e=V.prefix+e);e&&
d.css({cursor:e})}ra(d,a,b,a,f);ra(d,a,b,c.eventHooks,f);ra(d,a,b,Y.eventHooks,f)}}function N(d,c,a,b){var f,e=c._layer?a:c;c._args=a;if(c.draggable||c.dragGroups)c.layer=!0,c.draggable=!0;c._method||(c._method=b?b:c.method?g.fn[c.method]:c.type?g.fn[X.drawings[c.type]]:function(){});if(c.layer&&!c._layer){if(a=g(d),b=H(d),f=b.layers,null===e.name||ja(e.name)&&void 0===b.layer.names[e.name])ka(c),e=new J(c),e.canvas=d,e.layer=!0,e._layer=!0,e._running={},e.data=null!==e.data?Z({},e.data):{},e.groups=
null!==e.groups?e.groups.slice(0):[],pa(a,b,e),qa(a,b,e),Ca(a,b,e),Ea(a,b,e),c._event=e._event,e._method===g.fn.drawText&&a.measureText(e),null===e.index&&(e.index=f.length),f.splice(e.index,0,e),c._args=e,O(a,b,e,"add")}else c.layer||ka(c);return e}function Fa(d,c){var a,b;for(b=0;b<V.props.length;b+=1)a=V.props[b],void 0!==d[a]&&(d["_"+a]=d[a],V.propsObj[a]=!0,c&&delete d[a])}function Va(d,c,a){var b,f,e,h;for(b in a)if(a.hasOwnProperty(b)&&(f=a[b],da(f)&&(a[b]=f.call(d,c,b)),"object"===aa(f)&&
Ga(f))){for(e in f)f.hasOwnProperty(e)&&(h=f[e],void 0!==c[b]&&(c[b+"."+e]=c[b][e],a[b+"."+e]=h));delete a[b]}return a}function Ha(d){var c,a,b=[],f=1;"transparent"===d?d="rgba(0, 0, 0, 0)":d.match(/^([a-z]+|#[0-9a-f]+)$/gi)&&(a=Ia.head,c=a.style.color,a.style.color=d,d=g.css(a,"color"),a.style.color=c);d.match(/^rgb/gi)&&(b=d.match(/(\d+(\.\d+)?)/gi),d.match(/%/gi)&&(f=2.55),b[0]*=f,b[1]*=f,b[2]*=f,b[3]=void 0!==b[3]?ba(b[3]):1);return b}function Wa(d){var c=3,a;"array"!==aa(d.start)&&(a=d.start.slice(0),
d.start=Ha(d.start),console.log(a,"=>",d.start),d.end=Ha(d.end));d.now=[];if(1!==d.start[3]||1!==d.end[3])c=4;for(a=0;a<c;a+=1)d.now[a]=d.start[a]+(d.end[a]-d.start[a])*d.pos,3>a&&(d.now[a]=Xa(d.now[a]));1!==d.start[3]||1!==d.end[3]?d.now="rgba( "+d.now.join(",")+" )":(d.now.slice(0,3),d.now="rgb( "+d.now.join(",")+" )");d.elem.nodeName?d.elem.style[d.prop]=d.now:d.elem[d.prop]=d.now}function Ya(d){X.touchEvents[d]&&(d=X.touchEvents[d]);return d}function Za(d){Y.events[d]=function(c,a){function b(a){h.x=
a.offsetX;h.y=a.offsetY;h.type=f;h.event=a;c.drawLayers({resetFire:!0});a.preventDefault()}var f,e,h;h=a.event;f="mouseover"===d||"mouseout"===d?"mousemove":d;e=Ya(f);a.events[f]||(e!==f?c.bind(f+".jCanvas "+e+".jCanvas",b):c.bind(f+".jCanvas",b),a.events[f]=!0)}}function T(d,c,a){var b,f,e,h;if(a=a._args)d=H(d),b=d.event,null!==b.x&&null!==b.y&&(e=b.x*d.pixelRatio,h=b.y*d.pixelRatio,f=c.isPointInPath(e,h)||c.isPointInStroke&&c.isPointInStroke(e,h)),c=d.transforms,a.eventX=b.x,a.eventY=b.y,a.event=
b.event,b=d.transforms.rotate,e=a.eventX,h=a.eventY,0!==b?(a._eventX=e*L(-b)-h*P(-b),a._eventY=h*L(-b)+e*P(-b)):(a._eventX=e,a._eventY=h),a._eventX/=c.scaleX,a._eventY/=c.scaleY,f&&d.intersecting.push(a),a.intersects=!!f}function za(d,c,a){c._toRad=c.inDegrees?F/180:1;d.translate(c.x,c.y);d.rotate(c.rotate*c._toRad);d.translate(-c.x,-c.y);a&&(a.rotate+=c.rotate*c._toRad)}function Aa(d,c,a){1!==c.scale&&(c.scaleX=c.scaleY=c.scale);d.translate(c.x,c.y);d.scale(c.scaleX,c.scaleY);d.translate(-c.x,-c.y);
a&&(a.scaleX*=c.scaleX,a.scaleY*=c.scaleY)}function Ba(d,c,a){c.translate&&(c.translateX=c.translateY=c.translate);d.translate(c.translateX,c.translateY);a&&(a.translateX+=c.translateX,a.translateY+=c.translateY)}function Ja(d){for(;0>d;)d+=2*F;return d}function Ka(d,c,a,b){var f,e,h,g,n,t,z;a===b?z=t=0:(t=a.x,z=a.y);b.inDegrees||360!==b.end||(b.end=2*F);b.start*=a._toRad;b.end*=a._toRad;b.start-=F/2;b.end-=F/2;n=F/180;b.ccw&&(n*=-1);f=b.x+b.radius*L(b.start+n);e=b.y+b.radius*P(b.start+n);h=b.x+b.radius*
L(b.start);g=b.y+b.radius*P(b.start);ga(d,c,a,b,f,e,h,g);c.arc(b.x+t,b.y+z,b.radius,b.start,b.end,b.ccw);f=b.x+b.radius*L(b.end+n);n=b.y+b.radius*P(b.end+n);e=b.x+b.radius*L(b.end);h=b.y+b.radius*P(b.end);ha(d,c,a,b,e,h,f,n)}function La(d,c,a,b,f,e,h,g){var n,t;b.arrowRadius&&!a.closed&&(t=$a(g-e,h-f),t-=F,d=a.strokeWidth*L(t),n=a.strokeWidth*P(t),a=h+b.arrowRadius*L(t+b.arrowAngle/2),f=g+b.arrowRadius*P(t+b.arrowAngle/2),e=h+b.arrowRadius*L(t-b.arrowAngle/2),b=g+b.arrowRadius*P(t-b.arrowAngle/2),
c.moveTo(a-d,f-n),c.lineTo(h-d,g-n),c.lineTo(e-d,b-n),c.moveTo(h-d,g-n),c.lineTo(h+d,g+n),c.moveTo(h,g))}function ga(d,c,a,b,f,e,h,g){b._arrowAngleConverted||(b.arrowAngle*=a._toRad,b._arrowAngleConverted=!0);b.startArrow&&La(d,c,a,b,f,e,h,g)}function ha(d,c,a,b,f,e,h,g){b._arrowAngleConverted||(b.arrowAngle*=a._toRad,b._arrowAngleConverted=!0);b.endArrow&&La(d,c,a,b,f,e,h,g)}function Ma(d,c,a,b){var f,e,h;f=2;ga(d,c,a,b,b.x2+a.x,b.y2+a.y,b.x1+a.x,b.y1+a.y);for(void 0!==b.x1&&void 0!==b.y1&&c.moveTo(b.x1+
a.x,b.y1+a.y);;)if(e=b["x"+f],h=b["y"+f],void 0!==e&&void 0!==h)c.lineTo(e+a.x,h+a.y),f+=1;else break;--f;ha(d,c,a,b,b["x"+(f-1)]+a.x,b["y"+(f-1)]+a.y,b["x"+f]+a.x,b["y"+f]+a.y)}function Na(d,c,a,b){var f,e,h,g,n;f=2;ga(d,c,a,b,b.cx1+a.x,b.cy1+a.y,b.x1+a.x,b.y1+a.y);for(void 0!==b.x1&&void 0!==b.y1&&c.moveTo(b.x1+a.x,b.y1+a.y);;)if(e=b["x"+f],h=b["y"+f],g=b["cx"+(f-1)],n=b["cy"+(f-1)],void 0!==e&&void 0!==h&&void 0!==g&&void 0!==n)c.quadraticCurveTo(g+a.x,n+a.y,e+a.x,h+a.y),f+=1;else break;--f;ha(d,
c,a,b,b["cx"+(f-1)]+a.x,b["cy"+(f-1)]+a.y,b["x"+f]+a.x,b["y"+f]+a.y)}function Oa(d,c,a,b){var f,e,h,g,n,t,z,E;f=2;e=1;ga(d,c,a,b,b.cx1+a.x,b.cy1+a.y,b.x1+a.x,b.y1+a.y);for(void 0!==b.x1&&void 0!==b.y1&&c.moveTo(b.x1+a.x,b.y1+a.y);;)if(h=b["x"+f],g=b["y"+f],n=b["cx"+e],t=b["cy"+e],z=b["cx"+(e+1)],E=b["cy"+(e+1)],void 0!==h&&void 0!==g&&void 0!==n&&void 0!==t&&void 0!==z&&void 0!==E)c.bezierCurveTo(n+a.x,t+a.y,z+a.x,E+a.y,h+a.x,g+a.y),f+=1,e+=2;else break;--f;e-=2;ha(d,c,a,b,b["cx"+(e+1)]+a.x,b["cy"+
(e+1)]+a.y,b["x"+f]+a.x,b["y"+f]+a.y)}function Pa(d,c,a){c*=d._toRad;c-=F/2;return a*L(c)}function Qa(d,c,a){c*=d._toRad;c-=F/2;return a*P(c)}function Ra(d,c,a,b){var f,e,h,g,n,t,z;a===b?n=g=0:(g=a.x,n=a.y);f=1;e=g=t=b.x+g;h=n=z=b.y+n;ga(d,c,a,b,e+Pa(a,b.a1,b.l1),h+Qa(a,b.a1,b.l1),e,h);for(void 0!==b.x&&void 0!==b.y&&c.moveTo(e,h);;)if(e=b["a"+f],h=b["l"+f],void 0!==e&&void 0!==h)g=t,n=z,t+=Pa(a,e,h),z+=Qa(a,e,h),c.lineTo(t,z),f+=1;else break;ha(d,c,a,b,g,n,t,z)}function sa(d,c,a){isNaN(wa(a.fontSize))||
(a.fontSize+="px");c.font=a.fontStyle+" "+a.fontSize+" "+a.fontFamily}function ta(d,c,a,b){var f,e;f=ca.propCache;if(f.text===a.text&&f.fontStyle===a.fontStyle&&f.fontSize===a.fontSize&&f.fontFamily===a.fontFamily&&f.maxWidth===a.maxWidth&&f.lineHeight===a.lineHeight)a.width=f.width,a.height=f.height;else{a.width=c.measureText(b[0]).width;for(e=1;e<b.length;e+=1)f=c.measureText(b[e]).width,f>a.width&&(a.width=f);c=d.style.fontSize;d.style.fontSize=a.fontSize;a.height=ba(g.css(d,"fontSize"))*b.length*
a.lineHeight;d.style.fontSize=c}}function Sa(d,c){var a=c.maxWidth,b=String(c.text).split("\n"),f=[],e,h,g,n,t;for(g=0;g<b.length;g+=1){n=b[g];t=n.split(" ");e=[];h="";if(1===t.length||d.measureText(n).width<a)e=[n];else{for(n=0;n<t.length;n+=1)d.measureText(h+t[n]).width>a&&(""!==h&&e.push(h),h=""),h+=t[n],n!==t.length-1&&(h+=" ");e.push(h)}f=f.concat(e.join("\n").replace(/( (\n))|( $)/gi,"$2").split("\n"))}return f}var Ia=U.document,Ta=U.Image,ab=U.getComputedStyle,ea=U.Math,wa=U.Number,ba=U.parseFloat,
ma,Z=g.extend,ia=g.inArray,aa=function(d){return Object.prototype.toString.call(d).slice(8,-1).toLowerCase()},da=g.isFunction,Ga=g.isPlainObject,F=ea.PI,Xa=ea.round,bb=ea.abs,P=ea.sin,L=ea.cos,$a=ea.atan2,ua=U.Array.prototype.slice,cb=g.event.fix,X={},ca={dataCache:{},propCache:{},imageCache:{}},oa={rotate:0,scaleX:1,scaleY:1,translateX:0,translateY:0,masks:[]},V={},Ua="mousedown mousemove mouseup mouseover mouseout touchstart touchmove touchend".split(" "),Y={events:{},eventHooks:{},future:{}};na.baseDefaults=
{align:"center",arrowAngle:90,arrowRadius:0,autosave:!0,baseline:"middle",bringToFront:!1,ccw:!1,closed:!1,compositing:"source-over",concavity:0,cornerRadius:0,count:1,cropFromCenter:!0,crossOrigin:null,cursors:null,disableEvents:!1,draggable:!1,dragGroups:null,groups:null,data:null,dx:null,dy:null,end:360,eventX:null,eventY:null,fillStyle:"transparent",fontStyle:"normal",fontSize:"12pt",fontFamily:"sans-serif",fromCenter:!0,height:null,imageSmoothing:!0,inDegrees:!0,intangible:!1,index:null,letterSpacing:null,
lineHeight:1,layer:!1,mask:!1,maxWidth:null,miterLimit:10,name:null,opacity:1,r1:null,r2:null,radius:0,repeat:"repeat",respectAlign:!1,restrictDragToAxis:null,rotate:0,rounded:!1,scale:1,scaleX:1,scaleY:1,shadowBlur:0,shadowColor:"transparent",shadowStroke:!1,shadowX:0,shadowY:0,sHeight:null,sides:0,source:"",spread:0,start:0,strokeCap:"butt",strokeDash:null,strokeDashOffset:0,strokeJoin:"miter",strokeStyle:"transparent",strokeWidth:1,sWidth:null,sx:null,sy:null,text:"",translate:0,translateX:0,translateY:0,
type:null,visible:!0,width:null,x:0,y:0};ma=new na;J.prototype=ma;Y.extend=function(d){d.name&&(d.props&&Z(ma,d.props),g.fn[d.name]=function a(b){var f,e,h,g;for(e=0;e<this.length;e+=1)if(f=this[e],h=K(f))g=new J(b),N(f,g,b,a),S(f,h,g),d.fn.call(f,h,g);return this},d.type&&(X.drawings[d.type]=d.name));return g.fn[d.name]};g.fn.getEventHooks=function(){var d;d={};0!==this.length&&(d=this[0],d=H(d),d=d.eventHooks);return d};g.fn.setEventHooks=function(d){var c,a;for(c=0;c<this.length;c+=1)g(this[c]),
a=H(this[c]),Z(a.eventHooks,d);return this};g.fn.getLayers=function(d){var c,a,b,f,e=[];if(0!==this.length)if(c=this[0],a=H(c),a=a.layers,da(d))for(f=0;f<a.length;f+=1)b=a[f],d.call(c,b)&&e.push(b);else e=a;return e};g.fn.getLayer=function(d){var c,a,b,f;if(0!==this.length)if(c=this[0],a=H(c),c=a.layers,f=aa(d),d&&d.layer)b=d;else if("number"===f)0>d&&(d=c.length+d),b=c[d];else if("regexp"===f)for(a=0;a<c.length;a+=1){if(ja(c[a].name)&&c[a].name.match(d)){b=c[a];break}}else b=a.layer.names[d];return b};
g.fn.getLayerGroup=function(d){var c,a,b,f=aa(d);if(0!==this.length)if(c=this[0],"array"===f)b=d;else if("regexp"===f)for(a in c=H(c),c=c.layer.groups,c){if(a.match(d)){b=c[a];break}}else c=H(c),b=c.layer.groups[d];return b};g.fn.getLayerIndex=function(d){var c=this.getLayers();d=this.getLayer(d);return ia(d,c)};g.fn.setLayer=function(d,c){var a,b,f,e,h,M,n;for(b=0;b<this.length;b+=1)if(a=g(this[b]),f=H(this[b]),e=g(this[b]).getLayer(d)){pa(a,f,e,c);qa(a,f,e,c);ka(c);for(h in c)c.hasOwnProperty(h)&&
(M=c[h],n=aa(M),"object"===n&&Ga(M)?(e[h]=Z({},M),ka(e[h])):"array"===n?e[h]=M.slice(0):"string"===n?0===M.indexOf("+=")?e[h]+=ba(M.substr(2)):0===M.indexOf("-=")?e[h]-=ba(M.substr(2)):!isNaN(M)&&va(M)&&"text"!==h?e[h]=ba(M):e[h]=M:e[h]=M);Ca(a,f,e);Ea(a,f,e);!1===g.isEmptyObject(c)&&O(a,f,e,"change",c)}return this};g.fn.setLayers=function(d,c){var a,b,f,e;for(b=0;b<this.length;b+=1)for(a=g(this[b]),f=a.getLayers(c),e=0;e<f.length;e+=1)a.setLayer(f[e],d);return this};g.fn.setLayerGroup=function(d,
c){var a,b,f,e;for(b=0;b<this.length;b+=1)if(a=g(this[b]),f=a.getLayerGroup(d))for(e=0;e<f.length;e+=1)a.setLayer(f[e],c);return this};g.fn.moveLayer=function(d,c){var a,b,f,e,h;for(b=0;b<this.length;b+=1)if(a=g(this[b]),f=H(this[b]),e=f.layers,h=a.getLayer(d))h.index=ia(h,e),e.splice(h.index,1),e.splice(c,0,h),0>c&&(c=e.length+c),h.index=c,O(a,f,h,"move");return this};g.fn.removeLayer=function(d){var c,a,b,f,e;for(a=0;a<this.length;a+=1)if(c=g(this[a]),b=H(this[a]),f=c.getLayers(),e=c.getLayer(d))e.index=
ia(e,f),f.splice(e.index,1),delete e._layer,pa(c,b,e,{name:null}),qa(c,b,e,{groups:null}),O(c,b,e,"remove");return this};g.fn.removeLayers=function(d){var c,a,b,f,e,h;for(a=0;a<this.length;a+=1){c=g(this[a]);b=H(this[a]);f=c.getLayers(d);for(h=0;h<f.length;h+=1)e=f[h],c.removeLayer(e),--h;b.layer.names={};b.layer.groups={}}return this};g.fn.removeLayerGroup=function(d){var c,a,b,f;if(void 0!==d)for(a=0;a<this.length;a+=1)if(c=g(this[a]),H(this[a]),c.getLayers(),b=c.getLayerGroup(d))for(b=b.slice(0),
f=0;f<b.length;f+=1)c.removeLayer(b[f]);return this};g.fn.addLayerToGroup=function(d,c){var a,b,f,e=[c];for(b=0;b<this.length;b+=1)a=g(this[b]),f=a.getLayer(d),f.groups&&(e=f.groups.slice(0),-1===ia(c,f.groups)&&e.push(c)),a.setLayer(f,{groups:e});return this};g.fn.removeLayerFromGroup=function(d,c){var a,b,f,e=[],h;for(b=0;b<this.length;b+=1)a=g(this[b]),f=a.getLayer(d),f.groups&&(h=ia(c,f.groups),-1!==h&&(e=f.groups.slice(0),e.splice(h,1),a.setLayer(f,{groups:e})));return this};V.cursors=["grab",
"grabbing","zoom-in","zoom-out"];V.prefix=function(){var d=ab(Ia.documentElement,"");return"-"+(ua.call(d).join("").match(/-(moz|webkit|ms)-/)||""===d.OLink&&["","o"])[1]+"-"}();g.fn.triggerLayerEvent=function(d,c){var a,b,f;for(b=0;b<this.length;b+=1)a=g(this[b]),f=H(this[b]),(d=a.getLayer(d))&&O(a,f,d,c);return this};g.fn.drawLayer=function(d){var c,a,b;for(c=0;c<this.length;c+=1)b=g(this[c]),(a=K(this[c]))&&(a=b.getLayer(d))&&a.visible&&a._method&&(a._next=null,a._method.call(b,a));return this};
g.fn.drawLayers=function(d){var c,a,b=d||{},f,e,h,M,n,t,z,E;(M=b.index)||(M=0);for(c=0;c<this.length;c+=1)if(d=g(this[c]),a=K(this[c])){n=H(this[c]);!1!==b.clear&&d.clearCanvas();a=n.layers;for(h=M;h<a.length;h+=1)if(f=a[h],f.index=h,b.resetFire&&(f._fired=!1),t=d,z=f,e=h+1,z&&z.visible&&z._method&&(z._next=e?e:null,z._method.call(t,z)),f._masks=n.transforms.masks.slice(0),f._method===g.fn.drawImage&&f.visible){E=!0;break}if(E)break;f=n;var x=e=z=t=void 0;t=null;for(z=f.intersecting.length-1;0<=z;--z)if(t=
f.intersecting[z],t._masks){for(x=t._masks.length-1;0<=x;--x)if(e=t._masks[x],!e.intersects){t.intersects=!1;break}if(t.intersects&&!t.intangible)break}t&&t.intangible&&(t=null);f=t;t=n.event;z=t.type;if(n.drag.layer){e=d;var x=n,C=z,u=void 0,m=void 0,k=void 0,y=k=void 0,B=void 0,k=u=u=k=void 0,k=x.drag,y=(m=k.layer)&&m.dragGroups||[],u=x.layers;if("mousemove"===C||"touchmove"===C){if(k.dragging||(k.dragging=!0,m.dragging=!0,m.bringToFront&&(u.splice(m.index,1),m.index=u.push(m)),m._startX=m.x,m._startY=
m.y,m._endX=m._eventX,m._endY=m._eventY,O(e,x,m,"dragstart")),k.dragging)for(u=m._eventX-(m._endX-m._startX),k=m._eventY-(m._endY-m._startY),m.dx=u-m.x,m.dy=k-m.y,"y"!==m.restrictDragToAxis&&(m.x=u),"x"!==m.restrictDragToAxis&&(m.y=k),O(e,x,m,"drag"),u=0;u<y.length;u+=1)if(k=y[u],B=x.layer.groups[k],m.groups&&B)for(k=0;k<B.length;k+=1)B[k]!==m&&("y"!==m.restrictDragToAxis&&"y"!==B[k].restrictDragToAxis&&(B[k].x+=m.dx),"x"!==m.restrictDragToAxis&&"x"!==B[k].restrictDragToAxis&&(B[k].y+=m.dy))}else if("mouseup"===
C||"touchend"===C)k.dragging&&(m.dragging=!1,k.dragging=!1,O(e,x,m,"dragstop")),x.drag={}}e=n.lastIntersected;null===e||f===e||!e._hovered||e._fired||n.drag.dragging||(n.lastIntersected=null,e._fired=!0,e._hovered=!1,O(d,n,e,"mouseout"),d.css({cursor:n.cursor}));f&&(f[z]||X.mouseEvents[z]&&(z=X.mouseEvents[z]),f._event&&f.intersects&&(n.lastIntersected=f,!(f.mouseover||f.mouseout||f.cursors)||n.drag.dragging||f._hovered||f._fired||(f._fired=!0,f._hovered=!0,O(d,n,f,"mouseover")),f._fired||(f._fired=
!0,t.type=null,O(d,n,f,z)),!f.draggable||f.disableEvents||"mousedown"!==z&&"touchstart"!==z||(n.drag.layer=f)));null!==f||n.drag.dragging||d.css({cursor:n.cursor});h===a.length&&(n.intersecting.length=0,n.transforms=la(oa),n.savedTransforms.length=0)}return this};g.fn.addLayer=function(d){var c,a;for(c=0;c<this.length;c+=1)if(a=K(this[c]))a=new J(d),a.layer=!0,N(this[c],a,d);return this};V.props=["width","height","opacity","lineHeight"];V.propsObj={};g.fn.animateLayer=function(){function d(a,b,c){return function(){var d,
f;for(f=0;f<V.props.length;f+=1)d=V.props[f],c[d]=c["_"+d];for(var h in c)c.hasOwnProperty(h)&&-1!==h.indexOf(".")&&delete c[h];b.animating&&b.animated!==c||a.drawLayers();c._animating=!1;b.animating=!1;b.animated=null;e[4]&&e[4].call(a[0],c);O(a,b,c,"animateend")}}function c(a,b,c){return function(d,f){var h,g,m=!1;"_"===f.prop[0]&&(m=!0,f.prop=f.prop.replace("_",""),c[f.prop]=c["_"+f.prop]);-1!==f.prop.indexOf(".")&&(h=f.prop.split("."),g=h[0],h=h[1],c[g]&&(c[g][h]=f.now));c._pos!==f.pos&&(c._pos=
f.pos,c._animating||b.animating||(c._animating=!0,b.animating=!0,b.animated=c),b.animating&&b.animated!==c||a.drawLayers());e[5]&&e[5].call(a[0],d,f,c);O(a,b,c,"animate",f);m&&(f.prop="_"+f.prop)}}var a,b,f,e=ua.call(arguments,0),h,M;"object"===aa(e[2])?(e.splice(2,0,e[2].duration||null),e.splice(3,0,e[3].easing||null),e.splice(4,0,e[4].complete||null),e.splice(5,0,e[5].step||null)):(void 0===e[2]?(e.splice(2,0,null),e.splice(3,0,null),e.splice(4,0,null)):da(e[2])&&(e.splice(2,0,null),e.splice(3,
0,null)),void 0===e[3]?(e[3]=null,e.splice(4,0,null)):da(e[3])&&e.splice(3,0,null));for(b=0;b<this.length;b+=1)if(a=g(this[b]),f=K(this[b]))f=H(this[b]),(h=a.getLayer(e[0]))&&h._method!==g.fn.draw&&(M=Z({},e[1]),M=Va(this[b],h,M),Fa(M,!0),Fa(h),h.style=V.propsObj,g(h).animate(M,{duration:e[2],easing:g.easing[e[3]]?e[3]:null,complete:d(a,f,h),step:c(a,f,h)}),O(a,f,h,"animatestart"));return this};g.fn.animateLayerGroup=function(d){var c,a,b=ua.call(arguments,0),f,e;for(a=0;a<this.length;a+=1)if(c=g(this[a]),
f=c.getLayerGroup(d))for(e=0;e<f.length;e+=1)b[0]=f[e],c.animateLayer.apply(c,b);return this};g.fn.delayLayer=function(d,c){var a,b,f,e;c=c||0;for(b=0;b<this.length;b+=1)if(a=g(this[b]),f=H(this[b]),e=a.getLayer(d))g(e).delay(c),O(a,f,e,"delay");return this};g.fn.delayLayerGroup=function(d,c){var a,b,f,e,h;c=c||0;for(b=0;b<this.length;b+=1)if(a=g(this[b]),f=a.getLayerGroup(d))for(h=0;h<f.length;h+=1)e=f[h],a.delayLayer(e,c);return this};g.fn.stopLayer=function(d,c){var a,b,f,e;for(b=0;b<this.length;b+=
1)if(a=g(this[b]),f=H(this[b]),e=a.getLayer(d))g(e).stop(c),O(a,f,e,"stop");return this};g.fn.stopLayerGroup=function(d,c){var a,b,f,e,h;for(b=0;b<this.length;b+=1)if(a=g(this[b]),f=a.getLayerGroup(d))for(h=0;h<f.length;h+=1)e=f[h],a.stopLayer(e,c);return this};(function(d){var c;for(c=0;c<d.length;c+=1)g.fx.step[d[c]]=Wa})("color backgroundColor borderColor borderTopColor borderRightColor borderBottomColor borderLeftColor fillStyle outlineColor strokeStyle shadowColor".split(" "));X.touchEvents=
{mousedown:"touchstart",mouseup:"touchend",mousemove:"touchmove"};X.mouseEvents={touchstart:"mousedown",touchend:"mouseup",touchmove:"mousemove"};(function(d){var c;for(c=0;c<d.length;c+=1)Za(d[c])})("click dblclick mousedown mouseup mousemove mouseover mouseout touchstart touchmove touchend contextmenu".split(" "));g.event.fix=function(d){var c,a;d=cb.call(g.event,d);if(c=d.originalEvent)if(a=c.changedTouches,void 0!==d.pageX&&void 0===d.offsetX){if(c=g(d.currentTarget).offset())d.offsetX=d.pageX-
c.left,d.offsetY=d.pageY-c.top}else a&&(c=g(d.currentTarget).offset())&&(d.offsetX=a[0].pageX-c.left,d.offsetY=a[0].pageY-c.top);return d};X.drawings={arc:"drawArc",bezier:"drawBezier",ellipse:"drawEllipse","function":"draw",image:"drawImage",line:"drawLine",path:"drawPath",polygon:"drawPolygon",slice:"drawSlice",quadratic:"drawQuadratic",rectangle:"drawRect",text:"drawText",vector:"drawVector",save:"saveCanvas",restore:"restoreCanvas",rotate:"rotateCanvas",scale:"scaleCanvas",translate:"translateCanvas"};
g.fn.draw=function c(a){var b,f,e=new J(a);if(X.drawings[e.type]&&"function"!==e.type)this[X.drawings[e.type]](a);else for(b=0;b<this.length;b+=1)if(g(this[b]),f=K(this[b]))e=new J(a),N(this[b],e,a,c),e.visible&&e.fn&&e.fn.call(this[b],f,e);return this};g.fn.clearCanvas=function a(b){var f,e,h=new J(b);for(f=0;f<this.length;f+=1)if(e=K(this[f]))null===h.width||null===h.height?(e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,this[f].width,this[f].height),e.restore()):(N(this[f],h,b,a),Q(this[f],
e,h,h.width,h.height),e.clearRect(h.x-h.width/2,h.y-h.height/2,h.width,h.height),h._transformed&&e.restore());return this};g.fn.saveCanvas=function b(f){var e,h,g,n,t;for(e=0;e<this.length;e+=1)if(h=K(this[e]))for(n=H(this[e]),g=new J(f),N(this[e],g,f,b),t=0;t<g.count;t+=1)fa(h,n);return this};g.fn.restoreCanvas=function f(e){var h,g,n,t,z;for(h=0;h<this.length;h+=1)if(g=K(this[h]))for(t=H(this[h]),n=new J(e),N(this[h],n,e,f),z=0;z<n.count;z+=1){var E=g,x=t;0===x.savedTransforms.length?x.transforms=
la(oa):(E.restore(),x.transforms=x.savedTransforms.pop())}return this};g.fn.rotateCanvas=function e(h){var g,n,t,z;for(g=0;g<this.length;g+=1)if(n=K(this[g]))z=H(this[g]),t=new J(h),N(this[g],t,h,e),t.autosave&&fa(n,z),za(n,t,z.transforms);return this};g.fn.scaleCanvas=function h(g){var n,t,z,E;for(n=0;n<this.length;n+=1)if(t=K(this[n]))E=H(this[n]),z=new J(g),N(this[n],z,g,h),z.autosave&&fa(t,E),Aa(t,z,E.transforms);return this};g.fn.translateCanvas=function M(g){var t,z,E,x;for(t=0;t<this.length;t+=
1)if(z=K(this[t]))x=H(this[t]),E=new J(g),N(this[t],E,g,M),E.autosave&&fa(z,x),Ba(z,E,x.transforms);return this};g.fn.drawRect=function n(g){var z,E,x,C,u,m,k,y,B;for(z=0;z<this.length;z+=1)if(E=K(this[z]))x=new J(g),N(this[z],x,g,n),x.visible&&(Q(this[z],E,x,x.width,x.height),S(this[z],E,x),E.beginPath(),x.width&&x.height&&(C=x.x-x.width/2,u=x.y-x.height/2,(y=bb(x.cornerRadius))?(m=x.x+x.width/2,k=x.y+x.height/2,0>x.width&&(B=C,C=m,m=B),0>x.height&&(B=u,u=k,k=B),0>m-C-2*y&&(y=(m-C)/2),0>k-u-2*y&&
(y=(k-u)/2),E.moveTo(C+y,u),E.lineTo(m-y,u),E.arc(m-y,u+y,y,3*F/2,2*F,!1),E.lineTo(m,k-y),E.arc(m-y,k-y,y,0,F/2,!1),E.lineTo(C+y,k),E.arc(C+y,k-y,y,F/2,F,!1),E.lineTo(C,u+y),E.arc(C+y,u+y,y,F,3*F/2,!1),x.closed=!0):E.rect(C,u,x.width,x.height)),T(this[z],E,x),W(this[z],E,x));return this};g.fn.drawArc=function t(g){var E,x,C;for(E=0;E<this.length;E+=1)if(x=K(this[E]))C=new J(g),N(this[E],C,g,t),C.visible&&(Q(this[E],x,C,2*C.radius),S(this[E],x,C),x.beginPath(),Ka(this[E],x,C,C),T(this[E],x,C),W(this[E],
x,C));return this};g.fn.drawEllipse=function z(g){var x,C,u,m,k;for(x=0;x<this.length;x+=1)if(C=K(this[x]))u=new J(g),N(this[x],u,g,z),u.visible&&(Q(this[x],C,u,u.width,u.height),S(this[x],C,u),m=4/3*u.width,k=u.height,C.beginPath(),C.moveTo(u.x,u.y-k/2),C.bezierCurveTo(u.x-m/2,u.y-k/2,u.x-m/2,u.y+k/2,u.x,u.y+k/2),C.bezierCurveTo(u.x+m/2,u.y+k/2,u.x+m/2,u.y-k/2,u.x,u.y-k/2),T(this[x],C,u),u.closed=!0,W(this[x],C,u));return this};g.fn.drawPolygon=function E(g){var C,u,m,k,y,B,w,A,p,l;for(C=0;C<this.length;C+=
1)if(u=K(this[C]))if(m=new J(g),N(this[C],m,g,E),m.visible){Q(this[C],u,m,2*m.radius);S(this[C],u,m);y=2*F/m.sides;B=y/2;k=B+F/2;w=m.radius*L(B);u.beginPath();for(l=0;l<m.sides;l+=1)A=m.x+m.radius*L(k),p=m.y+m.radius*P(k),u.lineTo(A,p),m.concavity&&(A=m.x+(w+-w*m.concavity)*L(k+B),p=m.y+(w+-w*m.concavity)*P(k+B),u.lineTo(A,p)),k+=y;T(this[C],u,m);m.closed=!0;W(this[C],u,m)}return this};g.fn.drawSlice=function x(C){var u,m,k,y,B;for(u=0;u<this.length;u+=1)if(g(this[u]),m=K(this[u]))k=new J(C),N(this[u],
k,C,x),k.visible&&(Q(this[u],m,k,2*k.radius),S(this[u],m,k),k.start*=k._toRad,k.end*=k._toRad,k.start-=F/2,k.end-=F/2,k.start=Ja(k.start),k.end=Ja(k.end),k.end<k.start&&(k.end+=2*F),y=(k.start+k.end)/2,B=k.radius*k.spread*L(y),y=k.radius*k.spread*P(y),k.x+=B,k.y+=y,m.beginPath(),m.arc(k.x,k.y,k.radius,k.start,k.end,k.ccw),m.lineTo(k.x,k.y),T(this[u],m,k),k.closed=!0,W(this[u],m,k));return this};g.fn.drawLine=function C(g){var m,k,y;for(m=0;m<this.length;m+=1)if(k=K(this[m]))y=new J(g),N(this[m],y,
g,C),y.visible&&(Q(this[m],k,y),S(this[m],k,y),k.beginPath(),Ma(this[m],k,y,y),T(this[m],k,y),W(this[m],k,y));return this};g.fn.drawQuadratic=function u(g){var k,y,B;for(k=0;k<this.length;k+=1)if(y=K(this[k]))B=new J(g),N(this[k],B,g,u),B.visible&&(Q(this[k],y,B),S(this[k],y,B),y.beginPath(),Na(this[k],y,B,B),T(this[k],y,B),W(this[k],y,B));return this};g.fn.drawBezier=function m(g){var y,B,w;for(y=0;y<this.length;y+=1)if(B=K(this[y]))w=new J(g),N(this[y],w,g,m),w.visible&&(Q(this[y],B,w),S(this[y],
B,w),B.beginPath(),Oa(this[y],B,w,w),T(this[y],B,w),W(this[y],B,w));return this};g.fn.drawVector=function k(g){var B,w,A;for(B=0;B<this.length;B+=1)if(w=K(this[B]))A=new J(g),N(this[B],A,g,k),A.visible&&(Q(this[B],w,A),S(this[B],w,A),w.beginPath(),Ra(this[B],w,A,A),T(this[B],w,A),W(this[B],w,A));return this};g.fn.drawPath=function y(g){var w,A,p,l,v;for(w=0;w<this.length;w+=1)if(A=K(this[w]))if(p=new J(g),N(this[w],p,g,y),p.visible){Q(this[w],A,p);S(this[w],A,p);A.beginPath();for(l=1;;)if(v=p["p"+
l],void 0!==v)v=new J(v),"line"===v.type?Ma(this[w],A,p,v):"quadratic"===v.type?Na(this[w],A,p,v):"bezier"===v.type?Oa(this[w],A,p,v):"vector"===v.type?Ra(this[w],A,p,v):"arc"===v.type&&Ka(this[w],A,p,v),l+=1;else break;T(this[w],A,p);W(this[w],A,p)}return this};g.fn.drawText=function B(w){var A,p,l,v,D,r,G,R,I,H;for(A=0;A<this.length;A+=1)if(g(this[A]),p=K(this[A]))if(l=new J(w),v=N(this[A],l,w,B),l.visible){p.textBaseline=l.baseline;p.textAlign=l.align;sa(this[A],p,l);D=null!==l.maxWidth?Sa(p,l):
l.text.toString().split("\n");ta(this[A],p,l,D);v&&(v.width=l.width,v.height=l.height);Q(this[A],p,l,l.width,l.height);S(this[A],p,l);G=l.x;"left"===l.align?l.respectAlign?l.x+=l.width/2:G-=l.width/2:"right"===l.align&&(l.respectAlign?l.x-=l.width/2:G+=l.width/2);if(l.radius)for(G=ba(l.fontSize),null===l.letterSpacing&&(l.letterSpacing=G/500),v=0;v<D.length;v+=1){p.save();p.translate(l.x,l.y);r=D[v];l.flipArcText&&(r=r.split(""),r.reverse(),r=r.join(""));R=r.length;p.rotate(-(F*l.letterSpacing*(R-
1))/2);for(H=0;H<R;H+=1)I=r[H],0!==H&&p.rotate(F*l.letterSpacing),p.save(),p.translate(0,-l.radius),l.flipArcText&&p.scale(-1,-1),p.fillText(I,0,0),"transparent"!==l.fillStyle&&(p.shadowColor="transparent"),0!==l.strokeWidth&&p.strokeText(I,0,0),p.restore();l.radius-=G;l.letterSpacing+=G/(1E3*F);p.restore()}else for(v=0;v<D.length;v+=1)r=D[v],R=l.y+v*l.height/D.length-(D.length-1)*l.height/D.length/2,p.shadowColor=l.shadowColor,p.fillText(r,G,R),"transparent"!==l.fillStyle&&(p.shadowColor="transparent"),
0!==l.strokeWidth&&p.strokeText(r,G,R);R=0;"top"===l.baseline?R+=l.height/2:"bottom"===l.baseline&&(R-=l.height/2);l._event&&(p.beginPath(),p.rect(l.x-l.width/2,l.y-l.height/2+R,l.width,l.height),T(this[A],p,l),p.closePath());l._transformed&&p.restore()}ca.propCache=l;return this};g.fn.measureText=function(g){var w,A;w=this.getLayer(g);if(!w||w&&!w._layer)w=new J(g);if(g=K(this[0]))sa(this[0],g,w),A=Sa(g,w),ta(this[0],g,w,A);return w};g.fn.drawImage=function w(A){function p(l,w,p,q,r){return function(){var v=
g(l);null===q.width&&null===q.sWidth&&(q.width=q.sWidth=I.width);null===q.height&&null===q.sHeight&&(q.height=q.sHeight=I.height);r&&(r.width=q.width,r.height=q.height);null!==q.sWidth&&null!==q.sHeight&&null!==q.sx&&null!==q.sy?(null===q.width&&(q.width=q.sWidth),null===q.height&&(q.height=q.sHeight),q.cropFromCenter&&(q.sx+=q.sWidth/2,q.sy+=q.sHeight/2),0>q.sy-q.sHeight/2&&(q.sy=q.sHeight/2),q.sy+q.sHeight/2>I.height&&(q.sy=I.height-q.sHeight/2),0>q.sx-q.sWidth/2&&(q.sx=q.sWidth/2),q.sx+q.sWidth/
2>I.width&&(q.sx=I.width-q.sWidth/2),Q(l,w,q,q.width,q.height),S(l,w,q),w.drawImage(I,q.sx-q.sWidth/2,q.sy-q.sHeight/2,q.sWidth,q.sHeight,q.x-q.width/2,q.y-q.height/2,q.width,q.height)):(Q(l,w,q,q.width,q.height),S(l,w,q),w.drawImage(I,q.x-q.width/2,q.y-q.height/2,q.width,q.height));w.beginPath();w.rect(q.x-q.width/2,q.y-q.height/2,q.width,q.height);T(l,w,q);w.closePath();q._transformed&&w.restore();ya(w,p,q);q.layer?O(v,p,r,"load"):q.load&&q.load.call(v[0],r);q.layer&&(r._masks=p.transforms.masks.slice(0),
q._next&&v.drawLayers({clear:!1,resetFire:!0,index:q._next}))}}var l,v,D,r,G,R,I,F,L,P=ca.imageCache;for(v=0;v<this.length;v+=1)if(l=this[v],D=K(this[v]))r=H(this[v]),G=new J(A),R=N(this[v],G,A,w),G.visible&&(L=G.source,F=L.getContext,L.src||F?I=L:L&&(P[L]&&P[L].complete?I=P[L]:(I=new Ta,L.match(/^data:/i)||(I.crossOrigin=G.crossOrigin),I.src=L,P[L]=I)),I&&(I.complete||F?p(l,D,r,G,R)():(I.onload=p(l,D,r,G,R),I.src=I.src)));return this};g.fn.createPattern=function(w){function A(){r=l.createPattern(D,
v.repeat);v.load&&v.load.call(p[0],r)}var p=this,l,v,D,r,G;(l=K(p[0]))?(v=new J(w),G=v.source,da(G)?(D=g("<canvas />")[0],D.width=v.width,D.height=v.height,w=K(D),G.call(D,w),A()):(w=G.getContext,G.src||w?D=G:(D=new Ta,G.match(/^data:/i)||(D.crossOrigin=v.crossOrigin),D.src=G),D.complete||w?A():(D.onload=A,D.src=D.src))):r=null;return r};g.fn.createGradient=function(g){var A,p=[],l,v,D,r,G,H,I;g=new J(g);if(A=K(this[0])){g.x1=g.x1||0;g.y1=g.y1||0;g.x2=g.x2||0;g.y2=g.y2||0;A=null!==g.r1&&null!==g.r2?
A.createRadialGradient(g.x1,g.y1,g.r1,g.x2,g.y2,g.r2):A.createLinearGradient(g.x1,g.y1,g.x2,g.y2);for(r=1;void 0!==g["c"+r];r+=1)void 0!==g["s"+r]?p.push(g["s"+r]):p.push(null);l=p.length;null===p[0]&&(p[0]=0);null===p[l-1]&&(p[l-1]=1);for(r=0;r<l;r+=1){if(null!==p[r]){H=1;I=0;v=p[r];for(G=r+1;G<l;G+=1)if(null!==p[G]){D=p[G];break}else H+=1;v>D&&(p[G]=p[r])}else null===p[r]&&(I+=1,p[r]=v+(D-v)/H*I);A.addColorStop(p[r],g["c"+(r+1)])}}else A=null;return A};g.fn.setPixels=function A(g){var l,v,D,r,G,
H,I,F,L;for(v=0;v<this.length;v+=1)if(l=this[v],D=K(l)){r=new J(g);N(l,r,g,A);Q(this[v],D,r,r.width,r.height);if(null===r.width||null===r.height)r.width=l.width,r.height=l.height,r.x=r.width/2,r.y=r.height/2;if(0!==r.width&&0!==r.height){H=D.getImageData(r.x-r.width/2,r.y-r.height/2,r.width,r.height);I=H.data;L=I.length;if(r.each)for(F=0;F<L;F+=4)G={r:I[F],g:I[F+1],b:I[F+2],a:I[F+3]},r.each.call(l,G,r),I[F]=G.r,I[F+1]=G.g,I[F+2]=G.b,I[F+3]=G.a;D.putImageData(H,r.x-r.width/2,r.y-r.height/2);D.restore()}}return this};
g.fn.getCanvasImage=function(g,p){var l,v=null;0!==this.length&&(l=this[0],l.toDataURL&&(void 0===p&&(p=1),v=l.toDataURL("image/"+g,p)));return v};g.fn.detectPixelRatio=function(A){var p,l,v,D,r,G,F;for(l=0;l<this.length;l+=1)p=this[l],g(this[l]),v=K(p),F=H(this[l]),F.scaled||(D=U.devicePixelRatio||1,r=v.webkitBackingStorePixelRatio||v.mozBackingStorePixelRatio||v.msBackingStorePixelRatio||v.oBackingStorePixelRatio||v.backingStorePixelRatio||1,D/=r,1!==D&&(r=p.width,G=p.height,p.width=r*D,p.height=
G*D,p.style.width=r+"px",p.style.height=G+"px",v.scale(D,D)),F.pixelRatio=D,F.scaled=!0,A&&A.call(p,D));return this};Y.clearCache=function(){for(var g in ca)ca.hasOwnProperty(g)&&(ca[g]={})};g.support.canvas=void 0!==g("<canvas />")[0].getContext;Z(Y,{defaults:ma,setGlobalProps:S,transformShape:Q,detectEvents:T,closePath:W,setCanvasFont:sa,measureText:ta});g.jCanvas=Y;g.jCanvasObject=J});
|
import React from "react";
import axios from "axios";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { withRouter } from "react-router";
import { NavLink } from "react-router-dom";
const NavigationComponent = props => {
const dynamicLink = (route, linkText) => {
return (
<div className="nav-link-wrapper">
<NavLink to={route} activeClassName="nav-link-active">
{linkText}
</NavLink>
</div>
);
};
const handleSignOut = () => {
axios
.delete("https://api.devcamp.space/logout", { withCredentials: true })
.then(response => {
if (response.status === 200) {
props.history.push("/");
props.handleSuccessfulLogout();
}
return response.data;
})
.catch(error => {
console.log("Error signing out", error);
});
};
return (
<div className="nav-wrapper">
<div className="left-side">
<div className="nav-link-wrapper">
<NavLink exact to="/" activeClassName="nav-link-active">
Home
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink to="/about-me" activeClassName="nav-link-active">
About
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink to="/contact" activeClassName="nav-link-active">
Contact
</NavLink>
</div>
<div className="nav-link-wrapper">
<NavLink to="/blog" activeClassName="nav-link-active">
Blog
</NavLink>
</div>
{props.loggedInStatus === "LOGGED_IN"
? dynamicLink("/portfolio-manager", "Portfolio Manager")
: null}
</div>
<div className="right-side">
JENSEN FELT
{props.loggedInStatus === "LOGGED_IN" ? (
<a onClick={handleSignOut}>
<FontAwesomeIcon icon="sign-out-alt" />
</a>
) : null}
</div>
</div>
);
};
export default withRouter(NavigationComponent);
|
import React from "react";
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
// @material-ui/icons
import Face from "@material-ui/icons/Face";
import Chat from "@material-ui/icons/Chat";
import Build from "@material-ui/icons/Build";
// core components
import GridContainer from "components/Grid/GridContainer.js";
import GridItem from "components/Grid/GridItem.js";
import CustomTabs from "components/CustomTabs/CustomTabs.js";
import styles from "assets/jss/material-kit-react/views/componentsSections/tabsStyle.js";
const useStyles = makeStyles(styles);
export default function SectionTabs() {
const classes = useStyles();
return (
<div className={classes.section}>
<div className={classes.container}>
<div id="nav-tabs">
<br/>
<br/>
<h3>Navigation Tabs</h3>
<GridContainer>
<GridItem xs={12} sm={12} md={6}>
<h3>
<small>Tabs with Icons on Card</small>
</h3>
<CustomTabs
headerColor="primary"
tabs={[
{
tabName: "Profile",
tabIcon: Face,
tabContent: (
<p className={classes.textCenter}>
I think that’s a responsibility that I have, to push
possibilities, to show people, this is the level that
things could be at. So when you get something that has
the name Kanye West on it, it’s supposed to be pushing
the furthest possibilities. I will be the leader of a
company that ends up being worth billions of dollars,
because I got the answers. I understand culture. I am
the nucleus.
</p>
)
},
{
tabName: "Messages",
tabIcon: Chat,
tabContent: (
<p className={classes.textCenter}>
I think that’s a responsibility that I have, to push
possibilities, to show people, this is the level that
things could be at. I will be the leader of a company
that ends up being worth billions of dollars, because I
got the answers. I understand culture. I am the nucleus.
I think that’s a responsibility that I have, to push
possibilities, to show people, this is the level that
things could be at.
</p>
)
},
{
tabName: "Settings",
tabIcon: Build,
tabContent: (
<p className={classes.textCenter}>
think that’s a responsibility that I have, to push
possibilities, to show people, this is the level that
things could be at. So when you get something that has
the name Kanye West on it, it’s supposed to be pushing
the furthest possibilities. I will be the leader of a
company that ends up being worth billions of dollars,
because I got the answers. I understand culture. I am
the nucleus.
</p>
)
}
]}
/>
</GridItem>
</GridContainer>
</div>
</div>
</div>
);
}
|
from .django_tool_provider import DjangoToolProvider
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 15:13:13 2019
@author: Christian
"""
import numpy as np
import matplotlib.pyplot as plt
import hysteresis as hys
from OpenSeesAnalysis import runAnalysis
from scipy.interpolate import interp1d
# Here we get our data from
# Run an opensees analysis using the runAnalysis Comand
k = 3.2*10**6
xy = runAnalysis(k)
# There are 2 repeats at each load protocol step, and 9 steps in total.
lpSteps = [2]*9
# =============================================================================
# Find the backbone
# =============================================================================
# Function: get envelope curve
myHys = hys.Hysteresis(xy)
myHys.plotVsIndex(True)
# Get the backbone
backbone = hys.getBackboneCurve(myHys, lpSteps)
# Check if the outputs make sense with a plot
fig, ax = plt.subplots()
myHys.plot()
backbone.plot()
|
#pragma once
namespace DAVA
{
class FilePath;
class Scene;
class FBXImporter
{
public:
static Scene* ConstructSceneFromFBX(const FilePath& fbxPath);
static bool ConvertToSC2(const FilePath& fbxPath, const FilePath& sc2Path);
static bool ConvertAnimations(const FilePath& fbxPath);
};
};
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _default = (0, _createSvgIcon.default)(_react.default.createElement("path", {
d: "M4 9h12c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm0 4h12c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm0 4h12c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm15 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"
}), 'TocRounded');
exports.default = _default;
|
/**
*
* File Name: libkern/stdlib/free.c
* Title : Kernel Library
* Project : PINE64 ROCK64 Bare-Metal
* Author : Copyright (C) 2021 Johannes Krottmayer <krjdev@gmail.com>
* Created : 2021-01-25
* Modified :
* Revised :
* Version : 0.1.0.0
* License : ISC (see LICENSE.txt)
*
* NOTE: This code is currently below version 1.0, and therefore is considered
* to be lacking in some functionality or documentation, or may not be fully
* tested. Nonetheless, you can expect most functions to work.
*
*/
#include <heap.h>
void free(void *ptr)
{
if (!ptr)
return;
heap_free(ptr);
}
|
#asyncio2.py to build and run coroutines in parallel
import asyncio
import time
async def say(delay, msg):
await asyncio.sleep(delay)
print(msg)
async def main ():
task1 = asyncio.create_task( say(1, 'Good'))
task2 = asyncio.create_task( say(1, 'Morning'))
print("Started at ", time.strftime("%X"))
await task1
await task2
print("Stopped at ", time.strftime("%X"))
asyncio.run(main())
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_EHPC_MODEL_LISTNODESNOPAGINGRESULT_H_
#define ALIBABACLOUD_EHPC_MODEL_LISTNODESNOPAGINGRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/ehpc/EHPCExport.h>
namespace AlibabaCloud
{
namespace EHPC
{
namespace Model
{
class ALIBABACLOUD_EHPC_EXPORT ListNodesNoPagingResult : public ServiceResult
{
public:
struct NodeInfo
{
struct TotalResources
{
int memory;
int cpu;
int gpu;
};
struct UsedResources
{
int memory;
int cpu;
int gpu;
};
std::string status;
std::string imageOwnerAlias;
bool expired;
std::vector<std::string> roles;
std::string addTime;
UsedResources usedResources;
bool createdByEhpc;
std::string version;
TotalResources totalResources;
std::string expiredTime;
std::string imageId;
std::string id;
std::string regionId;
std::string lockReason;
std::string hostName;
std::string spotStrategy;
};
ListNodesNoPagingResult();
explicit ListNodesNoPagingResult(const std::string &payload);
~ListNodesNoPagingResult();
int getTotalCount()const;
int getPageSize()const;
int getPageNumber()const;
std::vector<NodeInfo> getNodes()const;
protected:
void parse(const std::string &payload);
private:
int totalCount_;
int pageSize_;
int pageNumber_;
std::vector<NodeInfo> nodes_;
};
}
}
}
#endif // !ALIBABACLOUD_EHPC_MODEL_LISTNODESNOPAGINGRESULT_H_
|
import unittest
from django.apps import apps
from django.contrib.sites.models import Site
from allauth import app_settings as allauth_app_settings
from rest_framework.test import APIClient
from rest_framework.authtoken.models import Token
from main.models import Profile, University, Course
class UserViewTest(unittest.TestCase):
def setUp(self):
Site.objects.create(name='studnet', domain='studnet')
User = apps.get_model(allauth_app_settings.USER_MODEL)
self.user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
self.profile = Profile.objects.create(user=self.user)
# self.unis = University.objects.create(name='PUT', city='Poznań')
self.client = APIClient()
token = Token.objects.create(user=self.user)
self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
self.client.login(username='john', password='johnpassword')
def test_univerities_endpoint(self):
r = self.client.get('/api/v1/univerities/')
self.assertEqual(r.status_code, 200)
self.assertEqual(r.data['count'], 0)
self.assertEqual(r.data['results'], [])
University.objects.create(name='PUT', city='Poznań')
r = self.client.get('/api/v1/univerities/')
self.assertEqual(r.status_code, 200)
self.assertEqual(r.data['count'], 1)
self.assertEqual(r.data['results'][0]['name'], 'PUT')
def test_courses_endpoint(self):
r = self.client.get('/api/v1/courses/')
self.assertEqual(r.status_code, 200)
self.assertEqual(r.data['count'], 0)
self.assertEqual(r.data['results'], [])
Course.objects.create(name='Computer Science')
r = self.client.get('/api/v1/courses/')
self.assertEqual(r.status_code, 200)
self.assertEqual(r.data['count'], 1)
self.assertEqual(r.data['results'][0]['name'], 'Computer Science')
|
/*
** SQLCipher
** crypto.h developed by Stephen Lombardo (Zetetic LLC)
** sjlombardo at zetetic dot net
** http://zetetic.net
**
** Copyright (c) 2008, ZETETIC LLC
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the ZETETIC LLC nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
*/
/* BEGIN SQLCIPHER */
#ifdef SQLITE_HAS_CODEC
#ifndef CRYPTO_H
#define CRYPTO_H
#if !defined (SQLCIPHER_CRYPTO_CC) \
&& !defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT) \
&& !defined (SQLCIPHER_CRYPTO_OPENSSL) \
&& !defined (SQLCIPHER_CRYPTO_MBEDTLS)
#define SQLCIPHER_CRYPTO_OPENSSL
#endif
#define FILE_HEADER_SZ 16
#ifndef CIPHER_VERSION
#ifdef SQLCIPHER_FIPS
#define CIPHER_VERSION "3.4.1 FIPS"
#else
#define CIPHER_VERSION "3.4.1"
#endif
#endif
#ifndef CIPHER
#define CIPHER "aes-256-cbc"
#endif
#define CIPHER_DECRYPT 0
#define CIPHER_ENCRYPT 1
#define CIPHER_READ_CTX 0
#define CIPHER_WRITE_CTX 1
#define CIPHER_READWRITE_CTX 2
#ifndef PBKDF2_ITER
#define PBKDF2_ITER 64000
#endif
/* possible flags for cipher_ctx->flags */
#define CIPHER_FLAG_HMAC 0x01
#define CIPHER_FLAG_LE_PGNO 0x02
#define CIPHER_FLAG_BE_PGNO 0x04
#ifndef DEFAULT_CIPHER_FLAGS
#define DEFAULT_CIPHER_FLAGS CIPHER_FLAG_HMAC | CIPHER_FLAG_LE_PGNO
#endif
/* by default, sqlcipher will use a reduced number of iterations to generate
the HMAC key / or transform a raw cipher key
*/
#ifndef FAST_PBKDF2_ITER
#define FAST_PBKDF2_ITER 2
#endif
/* this if a fixed random array that will be xor'd with the database salt to ensure that the
salt passed to the HMAC key derivation function is not the same as that used to derive
the encryption key. This can be overridden at compile time but it will make the resulting
binary incompatible with the default builds when using HMAC. A future version of SQLcipher
will likely allow this to be defined at runtime via pragma */
#ifndef HMAC_SALT_MASK
#define HMAC_SALT_MASK 0x3a
#endif
#ifndef CIPHER_MAX_IV_SZ
#define CIPHER_MAX_IV_SZ 16
#endif
#ifndef CIPHER_MAX_KEY_SZ
#define CIPHER_MAX_KEY_SZ 64
#endif
#ifdef CODEC_DEBUG
#define CODEC_TRACE(X) {printf X;fflush(stdout);}
#else
#define CODEC_TRACE(X)
#endif
#ifdef CODEC_DEBUG_PAGEDATA
#define CODEC_HEXDUMP(DESC,BUFFER,LEN) \
{ \
int __pctr; \
printf(DESC); \
for(__pctr=0; __pctr < LEN; __pctr++) { \
if(__pctr % 16 == 0) printf("\n%05x: ",__pctr); \
printf("%02x ",((unsigned char*) BUFFER)[__pctr]); \
} \
printf("\n"); \
fflush(stdout); \
}
#else
#define CODEC_HEXDUMP(DESC,BUFFER,LEN)
#endif
/* extensions defined in pager.c */
void sqlite3pager_get_codec(Pager *pPager, void **ctx);
int sqlite3pager_is_mj_pgno(Pager *pPager, Pgno pgno);
sqlite3_file *sqlite3Pager_get_fd(Pager *pPager);
void sqlite3pager_sqlite3PagerSetCodec(
Pager *pPager,
void *(*xCodec)(void*,void*,Pgno,int),
void (*xCodecSizeChng)(void*,int,int),
void (*xCodecFree)(void*),
void *pCodec
);
void sqlite3pager_sqlite3PagerSetError(Pager *pPager, int error);
/* end extensions defined in pager.c */
/*
** Simple shared routines for converting hex char strings to binary data
*/
static int cipher_hex2int(char c) {
return (c>='0' && c<='9') ? (c)-'0' :
(c>='A' && c<='F') ? (c)-'A'+10 :
(c>='a' && c<='f') ? (c)-'a'+10 : 0;
}
static void cipher_hex2bin(const unsigned char *hex, int sz, unsigned char *out){
int i;
for(i = 0; i < sz; i += 2){
out[i/2] = (cipher_hex2int(hex[i])<<4) | cipher_hex2int(hex[i+1]);
}
}
static void cipher_bin2hex(const unsigned char* in, int sz, char *out) {
int i;
for(i=0; i < sz; i++) {
sqlite3_snprintf(3, out + (i*2), "%02x ", in[i]);
}
}
static int cipher_isHex(const unsigned char *hex, int sz){
int i;
for(i = 0; i < sz; i++) {
unsigned char c = hex[i];
if ((c < '0' || c > '9') &&
(c < 'A' || c > 'F') &&
(c < 'a' || c > 'f')) {
return 0;
}
}
return 1;
}
/* extensions defined in crypto_impl.c */
typedef struct codec_ctx codec_ctx;
/* activation and initialization */
void sqlcipher_activate();
void sqlcipher_deactivate();
int sqlcipher_codec_ctx_init(codec_ctx **, Db *, Pager *, sqlite3_file *, const void *, int);
void sqlcipher_codec_ctx_free(codec_ctx **);
int sqlcipher_codec_key_derive(codec_ctx *);
int sqlcipher_codec_key_copy(codec_ctx *, int);
/* page cipher implementation */
int sqlcipher_page_cipher(codec_ctx *, int, Pgno, int, int, unsigned char *, unsigned char *);
/* context setters & getters */
void sqlcipher_codec_ctx_set_error(codec_ctx *, int);
int sqlcipher_codec_ctx_set_pass(codec_ctx *, const void *, int, int);
void sqlcipher_codec_get_keyspec(codec_ctx *, void **zKey, int *nKey);
int sqlcipher_codec_ctx_set_pagesize(codec_ctx *, int);
int sqlcipher_codec_ctx_get_pagesize(codec_ctx *);
int sqlcipher_codec_ctx_get_reservesize(codec_ctx *);
void sqlcipher_set_default_pagesize(int page_size);
int sqlcipher_get_default_pagesize();
void sqlcipher_set_default_kdf_iter(int iter);
int sqlcipher_get_default_kdf_iter();
int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *, int, int);
int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx, int);
void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx);
int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *, int, int);
int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *, int);
int sqlcipher_codec_ctx_set_cipher(codec_ctx *, const char *, int);
const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx, int for_ctx);
void* sqlcipher_codec_ctx_get_data(codec_ctx *);
void sqlcipher_exportFunc(sqlite3_context *, int, sqlite3_value **);
void sqlcipher_set_default_use_hmac(int use);
int sqlcipher_get_default_use_hmac();
void sqlcipher_set_hmac_salt_mask(unsigned char mask);
unsigned char sqlcipher_get_hmac_salt_mask();
int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use);
int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx, int for_ctx);
int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag);
int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag);
int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag, int for_ctx);
const char* sqlcipher_codec_get_cipher_provider(codec_ctx *ctx);
int sqlcipher_codec_ctx_migrate(codec_ctx *ctx);
int sqlcipher_codec_add_random(codec_ctx *ctx, const char *data, int random_sz);
int sqlcipher_cipher_profile(sqlite3 *db, const char *destination);
static void sqlcipher_profile_callback(void *file, const char *sql, sqlite3_uint64 run_time);
static int sqlcipher_codec_get_store_pass(codec_ctx *ctx);
static void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey);
static void sqlcipher_codec_set_store_pass(codec_ctx *ctx, int value);
int sqlcipher_codec_fips_status(codec_ctx *ctx);
const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx);
#endif
#endif
/* END SQLCIPHER */
|
/*
* Elliptic curve J-PAKE
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* References in the code are to the Thread v1.0 Specification,
* available to members of the Thread Group http://threadgroup.org/
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_ECJPAKE_C)
#include "mbedtls/ecjpake.h"
#include "mbedtls/platform_util.h"
#include <string.h>
#if !defined(MBEDTLS_ECJPAKE_ALT)
/* Parameter validation macros based on platform_util.h */
#define ECJPAKE_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA )
#define ECJPAKE_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
/*
* Convert a mbedtls_ecjpake_role to identifier string
*/
static const char * const ecjpake_id[] = {
"client",
"server"
};
#define ID_MINE ( ecjpake_id[ ctx->role ] )
#define ID_PEER ( ecjpake_id[ 1 - ctx->role ] )
/*
* Initialize context
*/
void mbedtls_ecjpake_init( mbedtls_ecjpake_context *ctx )
{
ECJPAKE_VALIDATE( ctx != NULL );
ctx->md_info = NULL;
mbedtls_ecp_group_init( &ctx->grp );
ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED;
mbedtls_ecp_point_init( &ctx->Xm1 );
mbedtls_ecp_point_init( &ctx->Xm2 );
mbedtls_ecp_point_init( &ctx->Xp1 );
mbedtls_ecp_point_init( &ctx->Xp2 );
mbedtls_ecp_point_init( &ctx->Xp );
mbedtls_mpi_init( &ctx->xm1 );
mbedtls_mpi_init( &ctx->xm2 );
mbedtls_mpi_init( &ctx->s );
}
/*
* Free context
*/
void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx )
{
if( ctx == NULL )
return;
ctx->md_info = NULL;
mbedtls_ecp_group_free( &ctx->grp );
mbedtls_ecp_point_free( &ctx->Xm1 );
mbedtls_ecp_point_free( &ctx->Xm2 );
mbedtls_ecp_point_free( &ctx->Xp1 );
mbedtls_ecp_point_free( &ctx->Xp2 );
mbedtls_ecp_point_free( &ctx->Xp );
mbedtls_mpi_free( &ctx->xm1 );
mbedtls_mpi_free( &ctx->xm2 );
mbedtls_mpi_free( &ctx->s );
}
/*
* Setup context
*/
int mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx,
mbedtls_ecjpake_role role,
mbedtls_md_type_t hash,
mbedtls_ecp_group_id curve,
const unsigned char *secret,
size_t len )
{
int ret;
ECJPAKE_VALIDATE_RET( ctx != NULL );
ECJPAKE_VALIDATE_RET( role == MBEDTLS_ECJPAKE_CLIENT ||
role == MBEDTLS_ECJPAKE_SERVER );
ECJPAKE_VALIDATE_RET( secret != NULL || len == 0 );
ctx->role = role;
if( ( ctx->md_info = mbedtls_md_info_from_type( hash ) ) == NULL )
return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE );
MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &ctx->grp, curve ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->s, secret, len ) );
cleanup:
if( ret != 0 )
mbedtls_ecjpake_free( ctx );
return( ret );
}
/*
* Check if context is ready for use
*/
int mbedtls_ecjpake_check( const mbedtls_ecjpake_context *ctx )
{
ECJPAKE_VALIDATE_RET( ctx != NULL );
if( ctx->md_info == NULL ||
ctx->grp.id == MBEDTLS_ECP_DP_NONE ||
ctx->s.p == NULL )
{
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
return( 0 );
}
/*
* Write a point plus its length to a buffer
*/
static int ecjpake_write_len_point( unsigned char **p,
const unsigned char *end,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *P )
{
int ret;
size_t len;
/* Need at least 4 for length plus 1 for point */
if( end < *p || end - *p < 5 )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
ret = mbedtls_ecp_point_write_binary( grp, P, pf,
&len, *p + 4, end - ( *p + 4 ) );
if( ret != 0 )
return( ret );
(*p)[0] = (unsigned char)( ( len >> 24 ) & 0xFF );
(*p)[1] = (unsigned char)( ( len >> 16 ) & 0xFF );
(*p)[2] = (unsigned char)( ( len >> 8 ) & 0xFF );
(*p)[3] = (unsigned char)( ( len ) & 0xFF );
*p += 4 + len;
return( 0 );
}
/*
* Size of the temporary buffer for ecjpake_hash:
* 3 EC points plus their length, plus ID and its length (4 + 6 bytes)
*/
#define ECJPAKE_HASH_BUF_LEN ( 3 * ( 4 + MBEDTLS_ECP_MAX_PT_LEN ) + 4 + 6 )
/*
* Compute hash for ZKP (7.4.2.2.2.1)
*/
static int ecjpake_hash( const mbedtls_md_info_t *md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
const mbedtls_ecp_point *V,
const mbedtls_ecp_point *X,
const char *id,
mbedtls_mpi *h )
{
int ret;
unsigned char buf[ECJPAKE_HASH_BUF_LEN];
unsigned char *p = buf;
const unsigned char *end = buf + sizeof( buf );
const size_t id_len = strlen( id );
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
/* Write things to temporary buffer */
MBEDTLS_MPI_CHK( ecjpake_write_len_point( &p, end, grp, pf, G ) );
MBEDTLS_MPI_CHK( ecjpake_write_len_point( &p, end, grp, pf, V ) );
MBEDTLS_MPI_CHK( ecjpake_write_len_point( &p, end, grp, pf, X ) );
if( end - p < 4 )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
*p++ = (unsigned char)( ( id_len >> 24 ) & 0xFF );
*p++ = (unsigned char)( ( id_len >> 16 ) & 0xFF );
*p++ = (unsigned char)( ( id_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( id_len ) & 0xFF );
if( end < p || (size_t)( end - p ) < id_len )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
memcpy( p, id, id_len );
p += id_len;
/* Compute hash */
mbedtls_md( md_info, buf, p - buf, hash );
/* Turn it into an integer mod n */
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( h, hash,
mbedtls_md_get_size( md_info ) ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( h, h, &grp->N ) );
cleanup:
return( ret );
}
/*
* Parse a ECShnorrZKP (7.4.2.2.2) and verify it (7.4.2.3.3)
*/
static int ecjpake_zkp_read( const mbedtls_md_info_t *md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
const mbedtls_ecp_point *X,
const char *id,
const unsigned char **p,
const unsigned char *end )
{
int ret;
mbedtls_ecp_point V, VV;
mbedtls_mpi r, h;
size_t r_len;
mbedtls_ecp_point_init( &V );
mbedtls_ecp_point_init( &VV );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &h );
/*
* struct {
* ECPoint V;
* opaque r<1..2^8-1>;
* } ECSchnorrZKP;
*/
if( end < *p )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
MBEDTLS_MPI_CHK( mbedtls_ecp_tls_read_point( grp, &V, p, end - *p ) );
if( end < *p || (size_t)( end - *p ) < 1 )
{
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
r_len = *(*p)++;
if( end < *p || (size_t)( end - *p ) < r_len )
{
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &r, *p, r_len ) );
*p += r_len;
/*
* Verification
*/
MBEDTLS_MPI_CHK( ecjpake_hash( md_info, grp, pf, G, &V, X, id, &h ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( (mbedtls_ecp_group *) grp,
&VV, &h, X, &r, G ) );
if( mbedtls_ecp_point_cmp( &VV, &V ) != 0 )
{
ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
goto cleanup;
}
cleanup:
mbedtls_ecp_point_free( &V );
mbedtls_ecp_point_free( &VV );
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &h );
return( ret );
}
/*
* Generate ZKP (7.4.2.3.2) and write it as ECSchnorrZKP (7.4.2.2.2)
*/
static int ecjpake_zkp_write( const mbedtls_md_info_t *md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
const mbedtls_mpi *x,
const mbedtls_ecp_point *X,
const char *id,
unsigned char **p,
const unsigned char *end,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_ecp_point V;
mbedtls_mpi v;
mbedtls_mpi h; /* later recycled to hold r */
size_t len;
if( end < *p )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
mbedtls_ecp_point_init( &V );
mbedtls_mpi_init( &v );
mbedtls_mpi_init( &h );
/* Compute signature */
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair_base( (mbedtls_ecp_group *) grp,
G, &v, &V, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( ecjpake_hash( md_info, grp, pf, G, &V, X, id, &h ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &h, &h, x ) ); /* x*h */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &h, &v, &h ) ); /* v - x*h */
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &h, &h, &grp->N ) ); /* r */
/* Write it out */
MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_point( grp, &V,
pf, &len, *p, end - *p ) );
*p += len;
len = mbedtls_mpi_size( &h ); /* actually r */
if( end < *p || (size_t)( end - *p ) < 1 + len || len > 255 )
{
ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
goto cleanup;
}
*(*p)++ = (unsigned char)( len & 0xFF );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, *p, len ) ); /* r */
*p += len;
cleanup:
mbedtls_ecp_point_free( &V );
mbedtls_mpi_free( &v );
mbedtls_mpi_free( &h );
return( ret );
}
/*
* Parse a ECJPAKEKeyKP (7.4.2.2.1) and check proof
* Output: verified public key X
*/
static int ecjpake_kkp_read( const mbedtls_md_info_t *md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
mbedtls_ecp_point *X,
const char *id,
const unsigned char **p,
const unsigned char *end )
{
int ret;
if( end < *p )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/*
* struct {
* ECPoint X;
* ECSchnorrZKP zkp;
* } ECJPAKEKeyKP;
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_tls_read_point( grp, X, p, end - *p ) );
if( mbedtls_ecp_is_zero( X ) )
{
ret = MBEDTLS_ERR_ECP_INVALID_KEY;
goto cleanup;
}
MBEDTLS_MPI_CHK( ecjpake_zkp_read( md_info, grp, pf, G, X, id, p, end ) );
cleanup:
return( ret );
}
/*
* Generate an ECJPAKEKeyKP
* Output: the serialized structure, plus private/public key pair
*/
static int ecjpake_kkp_write( const mbedtls_md_info_t *md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
mbedtls_mpi *x,
mbedtls_ecp_point *X,
const char *id,
unsigned char **p,
const unsigned char *end,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
size_t len;
if( end < *p )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
/* Generate key (7.4.2.3.1) and write it out */
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair_base( (mbedtls_ecp_group *) grp, G, x, X,
f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_point( grp, X,
pf, &len, *p, end - *p ) );
*p += len;
/* Generate and write proof */
MBEDTLS_MPI_CHK( ecjpake_zkp_write( md_info, grp, pf, G, x, X, id,
p, end, f_rng, p_rng ) );
cleanup:
return( ret );
}
/*
* Read a ECJPAKEKeyKPPairList (7.4.2.3) and check proofs
* Ouputs: verified peer public keys Xa, Xb
*/
static int ecjpake_kkpp_read( const mbedtls_md_info_t *md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
mbedtls_ecp_point *Xa,
mbedtls_ecp_point *Xb,
const char *id,
const unsigned char *buf,
size_t len )
{
int ret;
const unsigned char *p = buf;
const unsigned char *end = buf + len;
/*
* struct {
* ECJPAKEKeyKP ecjpake_key_kp_pair_list[2];
* } ECJPAKEKeyKPPairList;
*/
MBEDTLS_MPI_CHK( ecjpake_kkp_read( md_info, grp, pf, G, Xa, id, &p, end ) );
MBEDTLS_MPI_CHK( ecjpake_kkp_read( md_info, grp, pf, G, Xb, id, &p, end ) );
if( p != end )
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
cleanup:
return( ret );
}
/*
* Generate a ECJPAKEKeyKPPairList
* Outputs: the serialized structure, plus two private/public key pairs
*/
static int ecjpake_kkpp_write( const mbedtls_md_info_t *md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
mbedtls_mpi *xm1,
mbedtls_ecp_point *Xa,
mbedtls_mpi *xm2,
mbedtls_ecp_point *Xb,
const char *id,
unsigned char *buf,
size_t len,
size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
unsigned char *p = buf;
const unsigned char *end = buf + len;
MBEDTLS_MPI_CHK( ecjpake_kkp_write( md_info, grp, pf, G, xm1, Xa, id,
&p, end, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( ecjpake_kkp_write( md_info, grp, pf, G, xm2, Xb, id,
&p, end, f_rng, p_rng ) );
*olen = p - buf;
cleanup:
return( ret );
}
/*
* Read and process the first round message
*/
int mbedtls_ecjpake_read_round_one( mbedtls_ecjpake_context *ctx,
const unsigned char *buf,
size_t len )
{
ECJPAKE_VALIDATE_RET( ctx != NULL );
ECJPAKE_VALIDATE_RET( buf != NULL );
return( ecjpake_kkpp_read( ctx->md_info, &ctx->grp, ctx->point_format,
&ctx->grp.G,
&ctx->Xp1, &ctx->Xp2, ID_PEER,
buf, len ) );
}
/*
* Generate and write the first round message
*/
int mbedtls_ecjpake_write_round_one( mbedtls_ecjpake_context *ctx,
unsigned char *buf, size_t len, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ECJPAKE_VALIDATE_RET( ctx != NULL );
ECJPAKE_VALIDATE_RET( buf != NULL );
ECJPAKE_VALIDATE_RET( olen != NULL );
ECJPAKE_VALIDATE_RET( f_rng != NULL );
return( ecjpake_kkpp_write( ctx->md_info, &ctx->grp, ctx->point_format,
&ctx->grp.G,
&ctx->xm1, &ctx->Xm1, &ctx->xm2, &ctx->Xm2,
ID_MINE, buf, len, olen, f_rng, p_rng ) );
}
/*
* Compute the sum of three points R = A + B + C
*/
static int ecjpake_ecp_add3( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_ecp_point *A,
const mbedtls_ecp_point *B,
const mbedtls_ecp_point *C )
{
int ret;
mbedtls_mpi one;
mbedtls_mpi_init( &one );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &one, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, R, &one, A, &one, B ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, R, &one, R, &one, C ) );
cleanup:
mbedtls_mpi_free( &one );
return( ret );
}
/*
* Read and process second round message (C: 7.4.2.5, S: 7.4.2.6)
*/
int mbedtls_ecjpake_read_round_two( mbedtls_ecjpake_context *ctx,
const unsigned char *buf,
size_t len )
{
int ret;
const unsigned char *p = buf;
const unsigned char *end = buf + len;
mbedtls_ecp_group grp;
mbedtls_ecp_point G; /* C: GB, S: GA */
ECJPAKE_VALIDATE_RET( ctx != NULL );
ECJPAKE_VALIDATE_RET( buf != NULL );
mbedtls_ecp_group_init( &grp );
mbedtls_ecp_point_init( &G );
/*
* Server: GA = X3 + X4 + X1 (7.4.2.6.1)
* Client: GB = X1 + X2 + X3 (7.4.2.5.1)
* Unified: G = Xm1 + Xm2 + Xp1
* We need that before parsing in order to check Xp as we read it
*/
MBEDTLS_MPI_CHK( ecjpake_ecp_add3( &ctx->grp, &G,
&ctx->Xm1, &ctx->Xm2, &ctx->Xp1 ) );
/*
* struct {
* ECParameters curve_params; // only client reading server msg
* ECJPAKEKeyKP ecjpake_key_kp;
* } Client/ServerECJPAKEParams;
*/
if( ctx->role == MBEDTLS_ECJPAKE_CLIENT )
{
MBEDTLS_MPI_CHK( mbedtls_ecp_tls_read_group( &grp, &p, len ) );
if( grp.id != ctx->grp.id )
{
ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
goto cleanup;
}
}
MBEDTLS_MPI_CHK( ecjpake_kkp_read( ctx->md_info, &ctx->grp,
ctx->point_format,
&G, &ctx->Xp, ID_PEER, &p, end ) );
if( p != end )
{
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
cleanup:
mbedtls_ecp_group_free( &grp );
mbedtls_ecp_point_free( &G );
return( ret );
}
/*
* Compute R = +/- X * S mod N, taking care not to leak S
*/
static int ecjpake_mul_secret( mbedtls_mpi *R, int sign,
const mbedtls_mpi *X,
const mbedtls_mpi *S,
const mbedtls_mpi *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_mpi b; /* Blinding value, then s + N * blinding */
mbedtls_mpi_init( &b );
/* b = s + rnd-128-bit * N */
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &b, 16, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &b, &b, N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &b, &b, S ) );
/* R = sign * X * b mod N */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( R, X, &b ) );
R->s *= sign;
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( R, R, N ) );
cleanup:
mbedtls_mpi_free( &b );
return( ret );
}
/*
* Generate and write the second round message (S: 7.4.2.5, C: 7.4.2.6)
*/
int mbedtls_ecjpake_write_round_two( mbedtls_ecjpake_context *ctx,
unsigned char *buf, size_t len, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_ecp_point G; /* C: GA, S: GB */
mbedtls_ecp_point Xm; /* C: Xc, S: Xs */
mbedtls_mpi xm; /* C: xc, S: xs */
unsigned char *p = buf;
const unsigned char *end = buf + len;
size_t ec_len;
ECJPAKE_VALIDATE_RET( ctx != NULL );
ECJPAKE_VALIDATE_RET( buf != NULL );
ECJPAKE_VALIDATE_RET( olen != NULL );
ECJPAKE_VALIDATE_RET( f_rng != NULL );
mbedtls_ecp_point_init( &G );
mbedtls_ecp_point_init( &Xm );
mbedtls_mpi_init( &xm );
/*
* First generate private/public key pair (S: 7.4.2.5.1, C: 7.4.2.6.1)
*
* Client: GA = X1 + X3 + X4 | xs = x2 * s | Xc = xc * GA
* Server: GB = X3 + X1 + X2 | xs = x4 * s | Xs = xs * GB
* Unified: G = Xm1 + Xp1 + Xp2 | xm = xm2 * s | Xm = xm * G
*/
MBEDTLS_MPI_CHK( ecjpake_ecp_add3( &ctx->grp, &G,
&ctx->Xp1, &ctx->Xp2, &ctx->Xm1 ) );
MBEDTLS_MPI_CHK( ecjpake_mul_secret( &xm, 1, &ctx->xm2, &ctx->s,
&ctx->grp.N, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &Xm, &xm, &G, f_rng, p_rng ) );
/*
* Now write things out
*
* struct {
* ECParameters curve_params; // only server writing its message
* ECJPAKEKeyKP ecjpake_key_kp;
* } Client/ServerECJPAKEParams;
*/
if( ctx->role == MBEDTLS_ECJPAKE_SERVER )
{
if( end < p )
{
ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_group( &ctx->grp, &ec_len,
p, end - p ) );
p += ec_len;
}
if( end < p )
{
ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_point( &ctx->grp, &Xm,
ctx->point_format, &ec_len, p, end - p ) );
p += ec_len;
MBEDTLS_MPI_CHK( ecjpake_zkp_write( ctx->md_info, &ctx->grp,
ctx->point_format,
&G, &xm, &Xm, ID_MINE,
&p, end, f_rng, p_rng ) );
*olen = p - buf;
cleanup:
mbedtls_ecp_point_free( &G );
mbedtls_ecp_point_free( &Xm );
mbedtls_mpi_free( &xm );
return( ret );
}
/*
* Derive PMS (7.4.2.7 / 7.4.2.8)
*/
int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx,
unsigned char *buf, size_t len, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_ecp_point K;
mbedtls_mpi m_xm2_s, one;
unsigned char kx[MBEDTLS_ECP_MAX_BYTES];
size_t x_bytes;
ECJPAKE_VALIDATE_RET( ctx != NULL );
ECJPAKE_VALIDATE_RET( buf != NULL );
ECJPAKE_VALIDATE_RET( olen != NULL );
ECJPAKE_VALIDATE_RET( f_rng != NULL );
*olen = mbedtls_md_get_size( ctx->md_info );
if( len < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
mbedtls_ecp_point_init( &K );
mbedtls_mpi_init( &m_xm2_s );
mbedtls_mpi_init( &one );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &one, 1 ) );
/*
* Client: K = ( Xs - X4 * x2 * s ) * x2
* Server: K = ( Xc - X2 * x4 * s ) * x4
* Unified: K = ( Xp - Xp2 * xm2 * s ) * xm2
*/
MBEDTLS_MPI_CHK( ecjpake_mul_secret( &m_xm2_s, -1, &ctx->xm2, &ctx->s,
&ctx->grp.N, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( &ctx->grp, &K,
&one, &ctx->Xp,
&m_xm2_s, &ctx->Xp2 ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &K, &ctx->xm2, &K,
f_rng, p_rng ) );
/* PMS = SHA-256( K.X ) */
x_bytes = ( ctx->grp.pbits + 7 ) / 8;
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &K.X, kx, x_bytes ) );
MBEDTLS_MPI_CHK( mbedtls_md( ctx->md_info, kx, x_bytes, buf ) );
cleanup:
mbedtls_ecp_point_free( &K );
mbedtls_mpi_free( &m_xm2_s );
mbedtls_mpi_free( &one );
return( ret );
}
#undef ID_MINE
#undef ID_PEER
#endif /* ! MBEDTLS_ECJPAKE_ALT */
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif
#if !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \
!defined(MBEDTLS_SHA256_C)
int mbedtls_ecjpake_self_test( int verbose )
{
(void) verbose;
return( 0 );
}
#else
static const unsigned char ecjpake_test_password[] = {
0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x6a, 0x70, 0x61, 0x6b, 0x65, 0x74,
0x65, 0x73, 0x74
};
static const unsigned char ecjpake_test_x1[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x21
};
static const unsigned char ecjpake_test_x2[] = {
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c,
0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x81
};
static const unsigned char ecjpake_test_x3[] = {
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c,
0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x81
};
static const unsigned char ecjpake_test_x4[] = {
0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc,
0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe1
};
static const unsigned char ecjpake_test_cli_one[] = {
0x41, 0x04, 0xac, 0xcf, 0x01, 0x06, 0xef, 0x85, 0x8f, 0xa2, 0xd9, 0x19,
0x33, 0x13, 0x46, 0x80, 0x5a, 0x78, 0xb5, 0x8b, 0xba, 0xd0, 0xb8, 0x44,
0xe5, 0xc7, 0x89, 0x28, 0x79, 0x14, 0x61, 0x87, 0xdd, 0x26, 0x66, 0xad,
0xa7, 0x81, 0xbb, 0x7f, 0x11, 0x13, 0x72, 0x25, 0x1a, 0x89, 0x10, 0x62,
0x1f, 0x63, 0x4d, 0xf1, 0x28, 0xac, 0x48, 0xe3, 0x81, 0xfd, 0x6e, 0xf9,
0x06, 0x07, 0x31, 0xf6, 0x94, 0xa4, 0x41, 0x04, 0x1d, 0xd0, 0xbd, 0x5d,
0x45, 0x66, 0xc9, 0xbe, 0xd9, 0xce, 0x7d, 0xe7, 0x01, 0xb5, 0xe8, 0x2e,
0x08, 0xe8, 0x4b, 0x73, 0x04, 0x66, 0x01, 0x8a, 0xb9, 0x03, 0xc7, 0x9e,
0xb9, 0x82, 0x17, 0x22, 0x36, 0xc0, 0xc1, 0x72, 0x8a, 0xe4, 0xbf, 0x73,
0x61, 0x0d, 0x34, 0xde, 0x44, 0x24, 0x6e, 0xf3, 0xd9, 0xc0, 0x5a, 0x22,
0x36, 0xfb, 0x66, 0xa6, 0x58, 0x3d, 0x74, 0x49, 0x30, 0x8b, 0xab, 0xce,
0x20, 0x72, 0xfe, 0x16, 0x66, 0x29, 0x92, 0xe9, 0x23, 0x5c, 0x25, 0x00,
0x2f, 0x11, 0xb1, 0x50, 0x87, 0xb8, 0x27, 0x38, 0xe0, 0x3c, 0x94, 0x5b,
0xf7, 0xa2, 0x99, 0x5d, 0xda, 0x1e, 0x98, 0x34, 0x58, 0x41, 0x04, 0x7e,
0xa6, 0xe3, 0xa4, 0x48, 0x70, 0x37, 0xa9, 0xe0, 0xdb, 0xd7, 0x92, 0x62,
0xb2, 0xcc, 0x27, 0x3e, 0x77, 0x99, 0x30, 0xfc, 0x18, 0x40, 0x9a, 0xc5,
0x36, 0x1c, 0x5f, 0xe6, 0x69, 0xd7, 0x02, 0xe1, 0x47, 0x79, 0x0a, 0xeb,
0x4c, 0xe7, 0xfd, 0x65, 0x75, 0xab, 0x0f, 0x6c, 0x7f, 0xd1, 0xc3, 0x35,
0x93, 0x9a, 0xa8, 0x63, 0xba, 0x37, 0xec, 0x91, 0xb7, 0xe3, 0x2b, 0xb0,
0x13, 0xbb, 0x2b, 0x41, 0x04, 0xa4, 0x95, 0x58, 0xd3, 0x2e, 0xd1, 0xeb,
0xfc, 0x18, 0x16, 0xaf, 0x4f, 0xf0, 0x9b, 0x55, 0xfc, 0xb4, 0xca, 0x47,
0xb2, 0xa0, 0x2d, 0x1e, 0x7c, 0xaf, 0x11, 0x79, 0xea, 0x3f, 0xe1, 0x39,
0x5b, 0x22, 0xb8, 0x61, 0x96, 0x40, 0x16, 0xfa, 0xba, 0xf7, 0x2c, 0x97,
0x56, 0x95, 0xd9, 0x3d, 0x4d, 0xf0, 0xe5, 0x19, 0x7f, 0xe9, 0xf0, 0x40,
0x63, 0x4e, 0xd5, 0x97, 0x64, 0x93, 0x77, 0x87, 0xbe, 0x20, 0xbc, 0x4d,
0xee, 0xbb, 0xf9, 0xb8, 0xd6, 0x0a, 0x33, 0x5f, 0x04, 0x6c, 0xa3, 0xaa,
0x94, 0x1e, 0x45, 0x86, 0x4c, 0x7c, 0xad, 0xef, 0x9c, 0xf7, 0x5b, 0x3d,
0x8b, 0x01, 0x0e, 0x44, 0x3e, 0xf0
};
static const unsigned char ecjpake_test_srv_one[] = {
0x41, 0x04, 0x7e, 0xa6, 0xe3, 0xa4, 0x48, 0x70, 0x37, 0xa9, 0xe0, 0xdb,
0xd7, 0x92, 0x62, 0xb2, 0xcc, 0x27, 0x3e, 0x77, 0x99, 0x30, 0xfc, 0x18,
0x40, 0x9a, 0xc5, 0x36, 0x1c, 0x5f, 0xe6, 0x69, 0xd7, 0x02, 0xe1, 0x47,
0x79, 0x0a, 0xeb, 0x4c, 0xe7, 0xfd, 0x65, 0x75, 0xab, 0x0f, 0x6c, 0x7f,
0xd1, 0xc3, 0x35, 0x93, 0x9a, 0xa8, 0x63, 0xba, 0x37, 0xec, 0x91, 0xb7,
0xe3, 0x2b, 0xb0, 0x13, 0xbb, 0x2b, 0x41, 0x04, 0x09, 0xf8, 0x5b, 0x3d,
0x20, 0xeb, 0xd7, 0x88, 0x5c, 0xe4, 0x64, 0xc0, 0x8d, 0x05, 0x6d, 0x64,
0x28, 0xfe, 0x4d, 0xd9, 0x28, 0x7a, 0xa3, 0x65, 0xf1, 0x31, 0xf4, 0x36,
0x0f, 0xf3, 0x86, 0xd8, 0x46, 0x89, 0x8b, 0xc4, 0xb4, 0x15, 0x83, 0xc2,
0xa5, 0x19, 0x7f, 0x65, 0xd7, 0x87, 0x42, 0x74, 0x6c, 0x12, 0xa5, 0xec,
0x0a, 0x4f, 0xfe, 0x2f, 0x27, 0x0a, 0x75, 0x0a, 0x1d, 0x8f, 0xb5, 0x16,
0x20, 0x93, 0x4d, 0x74, 0xeb, 0x43, 0xe5, 0x4d, 0xf4, 0x24, 0xfd, 0x96,
0x30, 0x6c, 0x01, 0x17, 0xbf, 0x13, 0x1a, 0xfa, 0xbf, 0x90, 0xa9, 0xd3,
0x3d, 0x11, 0x98, 0xd9, 0x05, 0x19, 0x37, 0x35, 0x14, 0x41, 0x04, 0x19,
0x0a, 0x07, 0x70, 0x0f, 0xfa, 0x4b, 0xe6, 0xae, 0x1d, 0x79, 0xee, 0x0f,
0x06, 0xae, 0xb5, 0x44, 0xcd, 0x5a, 0xdd, 0xaa, 0xbe, 0xdf, 0x70, 0xf8,
0x62, 0x33, 0x21, 0x33, 0x2c, 0x54, 0xf3, 0x55, 0xf0, 0xfb, 0xfe, 0xc7,
0x83, 0xed, 0x35, 0x9e, 0x5d, 0x0b, 0xf7, 0x37, 0x7a, 0x0f, 0xc4, 0xea,
0x7a, 0xce, 0x47, 0x3c, 0x9c, 0x11, 0x2b, 0x41, 0xcc, 0xd4, 0x1a, 0xc5,
0x6a, 0x56, 0x12, 0x41, 0x04, 0x36, 0x0a, 0x1c, 0xea, 0x33, 0xfc, 0xe6,
0x41, 0x15, 0x64, 0x58, 0xe0, 0xa4, 0xea, 0xc2, 0x19, 0xe9, 0x68, 0x31,
0xe6, 0xae, 0xbc, 0x88, 0xb3, 0xf3, 0x75, 0x2f, 0x93, 0xa0, 0x28, 0x1d,
0x1b, 0xf1, 0xfb, 0x10, 0x60, 0x51, 0xdb, 0x96, 0x94, 0xa8, 0xd6, 0xe8,
0x62, 0xa5, 0xef, 0x13, 0x24, 0xa3, 0xd9, 0xe2, 0x78, 0x94, 0xf1, 0xee,
0x4f, 0x7c, 0x59, 0x19, 0x99, 0x65, 0xa8, 0xdd, 0x4a, 0x20, 0x91, 0x84,
0x7d, 0x2d, 0x22, 0xdf, 0x3e, 0xe5, 0x5f, 0xaa, 0x2a, 0x3f, 0xb3, 0x3f,
0xd2, 0xd1, 0xe0, 0x55, 0xa0, 0x7a, 0x7c, 0x61, 0xec, 0xfb, 0x8d, 0x80,
0xec, 0x00, 0xc2, 0xc9, 0xeb, 0x12
};
static const unsigned char ecjpake_test_srv_two[] = {
0x03, 0x00, 0x17, 0x41, 0x04, 0x0f, 0xb2, 0x2b, 0x1d, 0x5d, 0x11, 0x23,
0xe0, 0xef, 0x9f, 0xeb, 0x9d, 0x8a, 0x2e, 0x59, 0x0a, 0x1f, 0x4d, 0x7c,
0xed, 0x2c, 0x2b, 0x06, 0x58, 0x6e, 0x8f, 0x2a, 0x16, 0xd4, 0xeb, 0x2f,
0xda, 0x43, 0x28, 0xa2, 0x0b, 0x07, 0xd8, 0xfd, 0x66, 0x76, 0x54, 0xca,
0x18, 0xc5, 0x4e, 0x32, 0xa3, 0x33, 0xa0, 0x84, 0x54, 0x51, 0xe9, 0x26,
0xee, 0x88, 0x04, 0xfd, 0x7a, 0xf0, 0xaa, 0xa7, 0xa6, 0x41, 0x04, 0x55,
0x16, 0xea, 0x3e, 0x54, 0xa0, 0xd5, 0xd8, 0xb2, 0xce, 0x78, 0x6b, 0x38,
0xd3, 0x83, 0x37, 0x00, 0x29, 0xa5, 0xdb, 0xe4, 0x45, 0x9c, 0x9d, 0xd6,
0x01, 0xb4, 0x08, 0xa2, 0x4a, 0xe6, 0x46, 0x5c, 0x8a, 0xc9, 0x05, 0xb9,
0xeb, 0x03, 0xb5, 0xd3, 0x69, 0x1c, 0x13, 0x9e, 0xf8, 0x3f, 0x1c, 0xd4,
0x20, 0x0f, 0x6c, 0x9c, 0xd4, 0xec, 0x39, 0x22, 0x18, 0xa5, 0x9e, 0xd2,
0x43, 0xd3, 0xc8, 0x20, 0xff, 0x72, 0x4a, 0x9a, 0x70, 0xb8, 0x8c, 0xb8,
0x6f, 0x20, 0xb4, 0x34, 0xc6, 0x86, 0x5a, 0xa1, 0xcd, 0x79, 0x06, 0xdd,
0x7c, 0x9b, 0xce, 0x35, 0x25, 0xf5, 0x08, 0x27, 0x6f, 0x26, 0x83, 0x6c
};
static const unsigned char ecjpake_test_cli_two[] = {
0x41, 0x04, 0x69, 0xd5, 0x4e, 0xe8, 0x5e, 0x90, 0xce, 0x3f, 0x12, 0x46,
0x74, 0x2d, 0xe5, 0x07, 0xe9, 0x39, 0xe8, 0x1d, 0x1d, 0xc1, 0xc5, 0xcb,
0x98, 0x8b, 0x58, 0xc3, 0x10, 0xc9, 0xfd, 0xd9, 0x52, 0x4d, 0x93, 0x72,
0x0b, 0x45, 0x54, 0x1c, 0x83, 0xee, 0x88, 0x41, 0x19, 0x1d, 0xa7, 0xce,
0xd8, 0x6e, 0x33, 0x12, 0xd4, 0x36, 0x23, 0xc1, 0xd6, 0x3e, 0x74, 0x98,
0x9a, 0xba, 0x4a, 0xff, 0xd1, 0xee, 0x41, 0x04, 0x07, 0x7e, 0x8c, 0x31,
0xe2, 0x0e, 0x6b, 0xed, 0xb7, 0x60, 0xc1, 0x35, 0x93, 0xe6, 0x9f, 0x15,
0xbe, 0x85, 0xc2, 0x7d, 0x68, 0xcd, 0x09, 0xcc, 0xb8, 0xc4, 0x18, 0x36,
0x08, 0x91, 0x7c, 0x5c, 0x3d, 0x40, 0x9f, 0xac, 0x39, 0xfe, 0xfe, 0xe8,
0x2f, 0x72, 0x92, 0xd3, 0x6f, 0x0d, 0x23, 0xe0, 0x55, 0x91, 0x3f, 0x45,
0xa5, 0x2b, 0x85, 0xdd, 0x8a, 0x20, 0x52, 0xe9, 0xe1, 0x29, 0xbb, 0x4d,
0x20, 0x0f, 0x01, 0x1f, 0x19, 0x48, 0x35, 0x35, 0xa6, 0xe8, 0x9a, 0x58,
0x0c, 0x9b, 0x00, 0x03, 0xba, 0xf2, 0x14, 0x62, 0xec, 0xe9, 0x1a, 0x82,
0xcc, 0x38, 0xdb, 0xdc, 0xae, 0x60, 0xd9, 0xc5, 0x4c
};
static const unsigned char ecjpake_test_pms[] = {
0xf3, 0xd4, 0x7f, 0x59, 0x98, 0x44, 0xdb, 0x92, 0xa5, 0x69, 0xbb, 0xe7,
0x98, 0x1e, 0x39, 0xd9, 0x31, 0xfd, 0x74, 0x3b, 0xf2, 0x2e, 0x98, 0xf9,
0xb4, 0x38, 0xf7, 0x19, 0xd3, 0xc4, 0xf3, 0x51
};
/* Load my private keys and generate the correponding public keys */
static int ecjpake_test_load( mbedtls_ecjpake_context *ctx,
const unsigned char *xm1, size_t len1,
const unsigned char *xm2, size_t len2 )
{
int ret;
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->xm1, xm1, len1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->xm2, xm2, len2 ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &ctx->Xm1, &ctx->xm1,
&ctx->grp.G, NULL, NULL ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &ctx->Xm2, &ctx->xm2,
&ctx->grp.G, NULL, NULL ) );
cleanup:
return( ret );
}
/* For tests we don't need a secure RNG;
* use the LGC from Numerical Recipes for simplicity */
static int ecjpake_lgc( void *p, unsigned char *out, size_t len )
{
static uint32_t x = 42;
(void) p;
while( len > 0 )
{
size_t use_len = len > 4 ? 4 : len;
x = 1664525 * x + 1013904223;
memcpy( out, &x, use_len );
out += use_len;
len -= use_len;
}
return( 0 );
}
#define TEST_ASSERT( x ) \
do { \
if( x ) \
ret = 0; \
else \
{ \
ret = 1; \
goto cleanup; \
} \
} while( 0 )
/*
* Checkup routine
*/
int mbedtls_ecjpake_self_test( int verbose )
{
int ret;
mbedtls_ecjpake_context cli;
mbedtls_ecjpake_context srv;
unsigned char buf[512], pms[32];
size_t len, pmslen;
mbedtls_ecjpake_init( &cli );
mbedtls_ecjpake_init( &srv );
if( verbose != 0 )
mbedtls_printf( " ECJPAKE test #0 (setup): " );
TEST_ASSERT( mbedtls_ecjpake_setup( &cli, MBEDTLS_ECJPAKE_CLIENT,
MBEDTLS_MD_SHA256, MBEDTLS_ECP_DP_SECP256R1,
ecjpake_test_password,
sizeof( ecjpake_test_password ) ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_setup( &srv, MBEDTLS_ECJPAKE_SERVER,
MBEDTLS_MD_SHA256, MBEDTLS_ECP_DP_SECP256R1,
ecjpake_test_password,
sizeof( ecjpake_test_password ) ) == 0 );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if( verbose != 0 )
mbedtls_printf( " ECJPAKE test #1 (random handshake): " );
TEST_ASSERT( mbedtls_ecjpake_write_round_one( &cli,
buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_read_round_one( &srv, buf, len ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_write_round_one( &srv,
buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_read_round_one( &cli, buf, len ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_write_round_two( &srv,
buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_read_round_two( &cli, buf, len ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_derive_secret( &cli,
pms, sizeof( pms ), &pmslen, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_write_round_two( &cli,
buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_read_round_two( &srv, buf, len ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_derive_secret( &srv,
buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( len == pmslen );
TEST_ASSERT( memcmp( buf, pms, len ) == 0 );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if( verbose != 0 )
mbedtls_printf( " ECJPAKE test #2 (reference handshake): " );
/* Simulate generation of round one */
MBEDTLS_MPI_CHK( ecjpake_test_load( &cli,
ecjpake_test_x1, sizeof( ecjpake_test_x1 ),
ecjpake_test_x2, sizeof( ecjpake_test_x2 ) ) );
MBEDTLS_MPI_CHK( ecjpake_test_load( &srv,
ecjpake_test_x3, sizeof( ecjpake_test_x3 ),
ecjpake_test_x4, sizeof( ecjpake_test_x4 ) ) );
/* Read round one */
TEST_ASSERT( mbedtls_ecjpake_read_round_one( &srv,
ecjpake_test_cli_one,
sizeof( ecjpake_test_cli_one ) ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_read_round_one( &cli,
ecjpake_test_srv_one,
sizeof( ecjpake_test_srv_one ) ) == 0 );
/* Skip generation of round two, read round two */
TEST_ASSERT( mbedtls_ecjpake_read_round_two( &cli,
ecjpake_test_srv_two,
sizeof( ecjpake_test_srv_two ) ) == 0 );
TEST_ASSERT( mbedtls_ecjpake_read_round_two( &srv,
ecjpake_test_cli_two,
sizeof( ecjpake_test_cli_two ) ) == 0 );
/* Server derives PMS */
TEST_ASSERT( mbedtls_ecjpake_derive_secret( &srv,
buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( len == sizeof( ecjpake_test_pms ) );
TEST_ASSERT( memcmp( buf, ecjpake_test_pms, len ) == 0 );
memset( buf, 0, len ); /* Avoid interferences with next step */
/* Client derives PMS */
TEST_ASSERT( mbedtls_ecjpake_derive_secret( &cli,
buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );
TEST_ASSERT( len == sizeof( ecjpake_test_pms ) );
TEST_ASSERT( memcmp( buf, ecjpake_test_pms, len ) == 0 );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
cleanup:
mbedtls_ecjpake_free( &cli );
mbedtls_ecjpake_free( &srv );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
}
if( verbose != 0 )
mbedtls_printf( "\n" );
return( ret );
}
#undef TEST_ASSERT
#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED && MBEDTLS_SHA256_C */
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_ECJPAKE_C */
|
print (_('Guess the number'))
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tbreader/proto/tensor.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from tbreader.proto import resource_handle_pb2 as tbreader_dot_proto_dot_resource__handle__pb2
from tbreader.proto import tensor_shape_pb2 as tbreader_dot_proto_dot_tensor__shape__pb2
from tbreader.proto import types_pb2 as tbreader_dot_proto_dot_types__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='tbreader/proto/tensor.proto',
package='tbreader',
syntax='proto3',
serialized_options=b'\n\030org.tensorflow.frameworkB\014TensorProtosP\001\370\001\001',
serialized_pb=b'\n\x1btbreader/proto/tensor.proto\x12\x08tbreader\x1a$tbreader/proto/resource_handle.proto\x1a!tbreader/proto/tensor_shape.proto\x1a\x1atbreader/proto/types.proto\"\x9d\x03\n\x0bTensorProto\x12!\n\x05\x64type\x18\x01 \x01(\x0e\x32\x12.tbreader.DataType\x12\x30\n\x0ctensor_shape\x18\x02 \x01(\x0b\x32\x1a.tbreader.TensorShapeProto\x12\x16\n\x0eversion_number\x18\x03 \x01(\x05\x12\x16\n\x0etensor_content\x18\x04 \x01(\x0c\x12\x14\n\x08half_val\x18\r \x03(\x05\x42\x02\x10\x01\x12\x15\n\tfloat_val\x18\x05 \x03(\x02\x42\x02\x10\x01\x12\x16\n\ndouble_val\x18\x06 \x03(\x01\x42\x02\x10\x01\x12\x13\n\x07int_val\x18\x07 \x03(\x05\x42\x02\x10\x01\x12\x12\n\nstring_val\x18\x08 \x03(\x0c\x12\x18\n\x0cscomplex_val\x18\t \x03(\x02\x42\x02\x10\x01\x12\x15\n\tint64_val\x18\n \x03(\x03\x42\x02\x10\x01\x12\x14\n\x08\x62ool_val\x18\x0b \x03(\x08\x42\x02\x10\x01\x12\x18\n\x0c\x64\x63omplex_val\x18\x0c \x03(\x01\x42\x02\x10\x01\x12:\n\x13resource_handle_val\x18\x0e \x03(\x0b\x32\x1d.tbreader.ResourceHandleProtoB-\n\x18org.tensorflow.frameworkB\x0cTensorProtosP\x01\xf8\x01\x01\x62\x06proto3'
,
dependencies=[tbreader_dot_proto_dot_resource__handle__pb2.DESCRIPTOR,tbreader_dot_proto_dot_tensor__shape__pb2.DESCRIPTOR,tbreader_dot_proto_dot_types__pb2.DESCRIPTOR,])
_TENSORPROTO = _descriptor.Descriptor(
name='TensorProto',
full_name='tbreader.TensorProto',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='dtype', full_name='tbreader.TensorProto.dtype', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='tensor_shape', full_name='tbreader.TensorProto.tensor_shape', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='version_number', full_name='tbreader.TensorProto.version_number', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='tensor_content', full_name='tbreader.TensorProto.tensor_content', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='half_val', full_name='tbreader.TensorProto.half_val', index=4,
number=13, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='float_val', full_name='tbreader.TensorProto.float_val', index=5,
number=5, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='double_val', full_name='tbreader.TensorProto.double_val', index=6,
number=6, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='int_val', full_name='tbreader.TensorProto.int_val', index=7,
number=7, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='string_val', full_name='tbreader.TensorProto.string_val', index=8,
number=8, type=12, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='scomplex_val', full_name='tbreader.TensorProto.scomplex_val', index=9,
number=9, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='int64_val', full_name='tbreader.TensorProto.int64_val', index=10,
number=10, type=3, cpp_type=2, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='bool_val', full_name='tbreader.TensorProto.bool_val', index=11,
number=11, type=8, cpp_type=7, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='dcomplex_val', full_name='tbreader.TensorProto.dcomplex_val', index=12,
number=12, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=b'\020\001', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='resource_handle_val', full_name='tbreader.TensorProto.resource_handle_val', index=13,
number=14, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=143,
serialized_end=556,
)
_TENSORPROTO.fields_by_name['dtype'].enum_type = tbreader_dot_proto_dot_types__pb2._DATATYPE
_TENSORPROTO.fields_by_name['tensor_shape'].message_type = tbreader_dot_proto_dot_tensor__shape__pb2._TENSORSHAPEPROTO
_TENSORPROTO.fields_by_name['resource_handle_val'].message_type = tbreader_dot_proto_dot_resource__handle__pb2._RESOURCEHANDLEPROTO
DESCRIPTOR.message_types_by_name['TensorProto'] = _TENSORPROTO
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
TensorProto = _reflection.GeneratedProtocolMessageType('TensorProto', (_message.Message,), {
'DESCRIPTOR' : _TENSORPROTO,
'__module__' : 'tbreader.proto.tensor_pb2'
# @@protoc_insertion_point(class_scope:tbreader.TensorProto)
})
_sym_db.RegisterMessage(TensorProto)
DESCRIPTOR._options = None
_TENSORPROTO.fields_by_name['half_val']._options = None
_TENSORPROTO.fields_by_name['float_val']._options = None
_TENSORPROTO.fields_by_name['double_val']._options = None
_TENSORPROTO.fields_by_name['int_val']._options = None
_TENSORPROTO.fields_by_name['scomplex_val']._options = None
_TENSORPROTO.fields_by_name['int64_val']._options = None
_TENSORPROTO.fields_by_name['bool_val']._options = None
_TENSORPROTO.fields_by_name['dcomplex_val']._options = None
# @@protoc_insertion_point(module_scope)
|
/* This file is generated by createIcons.js any changes will be lost. */
import createIcon from '../createIcon';
const WeightIcon = createIcon({
name: 'WeightIcon',
height: 512,
width: 512,
svgPath: 'M448 64h-25.98C438.44 92.28 448 125.01 448 160c0 105.87-86.13 192-192 192S64 265.87 64 160c0-34.99 9.56-67.72 25.98-96H64C28.71 64 0 92.71 0 128v320c0 35.29 28.71 64 64 64h384c35.29 0 64-28.71 64-64V128c0-35.29-28.71-64-64-64zM256 320c88.37 0 160-71.63 160-160S344.37 0 256 0 96 71.63 96 160s71.63 160 160 160zm-.3-151.94l33.58-78.36c3.5-8.17 12.94-11.92 21.03-8.41 8.12 3.48 11.88 12.89 8.41 21l-33.67 78.55C291.73 188 296 197.45 296 208c0 22.09-17.91 40-40 40s-40-17.91-40-40c0-21.98 17.76-39.77 39.7-39.94z',
yOffset: '',
xOffset: '',
transform: ''
});
export default WeightIcon;
|
let data = {
"body": "<path d=\"M880 298.4H521L403.7 186.2a8.15 8.15 0 0 0-5.5-2.2H144c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V330.4c0-17.7-14.3-32-32-32zM840 768H184V256h188.5l119.6 114.4H840V768z\" fill-opacity=\".8\" fill=\"currentColor\"/><path d=\"M372.5 256H184v512h656V370.4H492.1z\" fill-opacity=\".1\" fill=\"currentColor\"/>",
"width": 1024,
"height": 1024
};
export default data;
|
#!/usr/bin/python
#
# File: plotSpeedups.py
#
from ROOT import TCanvas, gROOT, TGraphErrors, TPaveText, TLatex, TFile, gStyle
from PerfHistoryTools import readPerformanceData
### these are the full series
commits = ["68c48276","4e5928c1","019d29a0","b356bad1","2c007289",
"298df455","a860eea3","e569cfb7","9e47e5fd","0877406d"]
# "143d582e","b92b66ba","3af4b3f2","b9437a06","e4c54450","c2f9b8cc","ec7c80a5","1047750f","30635340"]
#commits = ["143d582e","b92b66ba","3af4b3f2","b9437a06","e4c54450","c2f9b8cc","ec7c80a5","1047750f","30635340"]
#commits = ["c4154901", "1f673e0d", "458e6f08"]
shapes = ["Trapezoid"]
algoNames = ["inside", "distToIn", "safeToIn", "contains", "distToOut", "safeToOut"]
implNames = ["vect", "unspec", "spec", "root", "usolids", "geant4"]
#implNames = ["spec", "vect", "cuda"]
refNames = ["insidespec", "distToInspec","safeToInspec","containsspec","distToOutspec","safeToOutspec"]
### read in the data points from external files
#.. loop over available commits, filling perf data into datasets
datasets = {}
i = 0
while i < len(commits):
commit = commits[i]
filename = commit+"/"+commit+"-perf.dat"
#print "commit: <%s> and file=<%s>" % (commit, filename)
readPerformanceData( i+1, filename, datasets )
i = i + 1
#.. show how to loop over data
#for key,val in datasets.iteritems():
# print val._shape, val._algo, val._impl, len(val._data), val._minkey, val._maxkey
# for i in range(len(val._data)):
# print " ",val._data[i]._x,val._data[i]._y,val._data[i]._dy
#.. Prepare plotting canvas
c1 = TCanvas('c1','c1', 900, 600 )
c1.Divide(3,2)
#.. loop over all shapes requested
for shname in shapes:
shoffset = len(shname)
###.. define references for speedups
refGraphs = []
for name in refNames:
for key,value in datasets.iteritems():
if key==shname+name:
#print "Dataset %s: %d datasets between %s and %s" % (key, len(value._data), value._minkey, value._maxkey )
refGraphs.append( value )
### speedupGraphs will contain the normalized datasets
speedupGraphs = []
for i in range(6): speedupGraphs.append([]) # 6 empty lists for each shape, one list per algo
#.. loop over perf data loaded into datasets, to separate the data into the 6 distinct algorithms
for key,dset in datasets.iteritems() :
if dset._shape != shname: continue
algo = dset._algo
impl = dset._impl
#print "shname=%s - Dataset %s %s %s: %d elements between %s and %s" % (shname, dset._shape, algo, impl, len(dset._data), dset._minkey, dset._maxkey )
#.. search perf data for each algorithm requested
for ialgo in range(6):
ilen = shoffset + len(algoNames[ialgo])
if key[shoffset:ilen] == algoNames[ialgo]:
#evoGraph = dset.tgraphNormError()
speedupGraph = dset.tgraphSpeedup( refGraphs[ialgo] )
#.. search perf data for each implementation requested
for iimpl in range(6):
icolor = iimpl+1
if icolor>4: icolor+=1
#ilen2 = len(implNames[iimpl])
if key[ilen:] == implNames[iimpl]:
#print "found:",iimpl, implNames[iimpl]
speedupGraph.SetLineColor(icolor)
speedupGraph.SetMarkerStyle(20+iimpl)
speedupGraph.SetMarkerColor(icolor)
break
speedupGraphs[ialgo].append( speedupGraph )
#.. now plot the 6 separate groups of datasets
for ialgo in range(len(speedupGraphs)):
ipad = ialgo + 1
#.. scan data for ymin,ymax scale adjustment
ymin = 999999.
ymax = -ymin
for igraph in range(len(speedupGraphs[ialgo])):
tmp = speedupGraphs[ialgo][igraph]
npts = tmp.GetN()
x = tmp.GetX()
y = tmp.GetY()
for i in range(npts):
#print "point %i: (%f; %f)" % (i,x[i],y[i])
if y[i]<ymin: ymin = y[i]
if y[i]>ymax: ymax = y[i]
#print "ialgo=%i, igraph=%i, ymin=%f, ymax=%f" % (ialgo,igraph,ymin,ymax)
gPad = c1.cd(ipad)
gPad.SetGrid(1,1)
#gPad.SetLogx(1)
#gPad.SetLogy(1)
frame1 = gPad.DrawFrame(0, 0.01, 1+len(commits), 1.05*ymax)
frame1.SetTitle(algoNames[ialgo])
frame1.GetXaxis().SetTitle("N tracks")
frame1.GetYaxis().SetTitle("Speed-up")
for igra in range(len(speedupGraphs[ialgo])):
tmp = speedupGraphs[ialgo][igra]
#tmp.SetLineColor(ialgo+1)
if(tmp.GetN()>0): tmp.Draw("ELP")
c1.SetTitle("Speed-ups")
c1.Update()
c1.SaveAs("speedups-"+shname+".png")
|
#include "luat_base.h"
#include "luat_fs.h"
#include "luat_spi.h"
#include "luat_malloc.h"
#define LUAT_LOG_TAG "vfs.lfs2"
#include "luat_log.h"
#ifdef LUAT_USE_FS_VFS
// #ifdef LUAT_VFS_USE_LFS2
#include "lfs.h"
FILE* luat_vfs_lfs2_fopen(void* userdata, const char *filename, const char *mode) {
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t *file = (lfs_file_t*)luat_heap_malloc(sizeof(lfs_file_t));
int flag = 0;
/*
"r": 读模式(默认);
"w": 写模式;
"a": 追加模式;
"r+": 更新模式,所有之前的数据都保留;
"w+": 更新模式,所有之前的数据都删除;
"a+": 追加更新模式,所有之前的数据都保留,只允许在文件尾部做写入。
*/
if (!strcmp("r+", mode) || !strcmp("r+b", mode)) {
flag = LFS_O_RDWR | LFS_O_CREAT;
}
else if(!strcmp("w+", mode) || !strcmp("w+b", mode)) {
flag = LFS_O_RDWR | LFS_O_CREAT | LFS_O_TRUNC;
}
else if(!strcmp("a+", mode) || !strcmp("a+b", mode)) {
flag = LFS_O_APPEND | LFS_O_CREAT;
}
else if(!strcmp("w", mode) || !strcmp("wb", mode)) {
flag = LFS_O_RDWR | LFS_O_CREAT | LFS_O_TRUNC;
}
else if(!strcmp("r", mode) || !strcmp("rb", mode)) {
flag = LFS_O_RDONLY;
}
else if(!strcmp("a", mode) || !strcmp("ab", mode)) {
flag = LFS_O_APPEND | LFS_O_CREAT;
}
else {
LLOGW("bad file open mode %s, fallback to 'r'", mode);
flag = LFS_O_RDONLY;
}
int ret = lfs_file_open(fs, file, filename, flag);
if (ret < 0) {
luat_heap_free(file);
return 0;
}
return (FILE*)file;
}
int luat_vfs_lfs2_getc(void* userdata, FILE* stream) {
//LLOGD("posix_getc %p", stream);
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t* file = (lfs_file_t*)stream;
char buff = 0;
int ret = lfs_file_read(fs, file, &buff, 1);
if (ret < 0)
return -1;
return (int)buff;
}
int luat_vfs_lfs2_fseek(void* userdata, FILE* stream, long int offset, int origin) {
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t* file = (lfs_file_t*)stream;
int ret = lfs_file_seek(fs, file, offset, origin);
return ret < 0 ? -1 : 0;
}
int luat_vfs_lfs2_ftell(void* userdata, FILE* stream) {
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t* file = (lfs_file_t*)stream;
int ret = lfs_file_tell(fs, file);
return ret < 0 ? -1 : ret;
}
int luat_vfs_lfs2_fclose(void* userdata, FILE* stream) {
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t* file = (lfs_file_t*)stream;
lfs_file_close(fs, file);
if (file != NULL)
luat_heap_free(file);
return 0;
}
int luat_vfs_lfs2_feof(void* userdata, FILE* stream) {
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t* file = (lfs_file_t*)stream;
if (lfs_file_size(fs, file) <= lfs_file_tell(fs, file))
return 1;
return 0;
}
int luat_vfs_lfs2_ferror(void* userdata, FILE *stream) {
return 0;
}
size_t luat_vfs_lfs2_fread(void* userdata, void *ptr, size_t size, size_t nmemb, FILE *stream) {
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t* file = (lfs_file_t*)stream;
int ret = lfs_file_read(fs, file, ptr, size*nmemb);
return ret < 0 ? 0 : ret;
}
size_t luat_vfs_lfs2_fwrite(void* userdata, const void *ptr, size_t size, size_t nmemb, FILE *stream) {
lfs_t* fs = (lfs_t*)userdata;
lfs_file_t* file = (lfs_file_t*)stream;
int ret = lfs_file_write(fs, file, ptr, size*nmemb);
return ret < 0 ? 0 : ret;
}
int luat_vfs_lfs2_remove(void* userdata, const char *filename) {
lfs_t* fs = (lfs_t*)userdata;
return lfs_remove(fs, filename);
}
int luat_vfs_lfs2_rename(void* userdata, const char *old_filename, const char *new_filename) {
lfs_t* fs = (lfs_t*)userdata;
return lfs_rename(fs, old_filename, new_filename);
}
int luat_vfs_lfs2_fexist(void* userdata, const char *filename) {
FILE* fd = luat_vfs_lfs2_fopen(userdata, filename, "rb");
if (fd) {
luat_vfs_lfs2_fclose(userdata, fd);
return 1;
}
return 0;
}
size_t luat_vfs_lfs2_fsize(void* userdata, const char *filename) {
FILE *fd;
size_t size = 0;
fd = luat_vfs_lfs2_fopen(userdata, filename, "rb");
if (fd) {
size = lfs_file_size((lfs_t*)userdata, (lfs_file_t*)fd);
luat_vfs_lfs2_fclose(userdata, fd);
}
return size;
}
int luat_vfs_lfs2_mkfs(void* userdata, luat_fs_conf_t *conf) {
int ret = 0;
lfs_t* fs = (lfs_t*)userdata;
if (fs != NULL && fs->cfg != NULL) {
ret = lfs_format(fs, fs->cfg);
// LLOGD("lfs2 format ret %d", ret);
if (ret < 0)
return ret;
ret = lfs_mount(fs, fs->cfg);
// LLOGD("lfs2 mount ret %d", ret);
return ret;
}
return -1;
}
int luat_vfs_lfs2_mount(void** userdata, luat_fs_conf_t *conf) {
*userdata = (void*)conf->busname;
return 0;
}
int luat_vfs_lfs2_umount(void* userdata, luat_fs_conf_t *conf) {
LLOGE("not support yet : umount");
return 0;
}
int luat_vfs_lfs2_mkdir(void* userdata, char const* _DirName) {
return -1;
}
int luat_vfs_lfs2_rmdir(void* userdata, char const* _DirName) {
return -1;
}
int luat_vfs_lfs2_lsdir(void* userdata, char const* _DirName, luat_fs_dirent_t* ents, size_t offset, size_t len) {
lfs_t* fs = (lfs_t*)userdata;
int ret , num = 0;
lfs_dir_t *dir;
struct lfs_info info;
// if (fs->filecount > offset) {
// if (offset + len > fs->filecount)
// len = fs->filecount - offset;
dir = luat_heap_malloc(sizeof(lfs_dir_t));
if (dir == NULL) {
// LLOGE("out of memory when lsdir");
return 0;
}
ret = lfs_dir_open(fs, dir, _DirName);
if (ret < 0) {
luat_heap_free(dir);
// LLOGE("no such dir %s _DirName");
return 0;
}
// TODO 使用seek/tell组合更快更省
for (size_t i = 0; i < offset; i++)
{
ret = lfs_dir_read(fs, dir, &info);
if (ret <= 0) {
lfs_dir_close(fs, dir);
luat_heap_free(dir);
return 0;
}
}
for (size_t i = 0; i < len; i++)
{
ret = lfs_dir_read(fs, dir, &info);
if (ret < 0) {
lfs_dir_close(fs, dir);
luat_heap_free(dir);
return 0;
}
if (ret == 0) {
len = i;
break;
}
if (info.type == 2 && (memcmp(info.name, ".", 2) !=0 ||memcmp(info.name, "..", 3)!=0))
continue;
ents[num].d_type = info.type - 1; // lfs file =1, dir=2
strcpy(ents[num].d_name, info.name);
num++;
}
lfs_dir_close(fs, dir);
luat_heap_free(dir);
return num;
// }
return 0;
}
int luat_vfs_lfs2_info(void* userdata, const char* path, luat_fs_info_t *conf) {
lfs_t* fs = (lfs_t*)userdata;
memcpy(conf->filesystem, "lfs", strlen("lfs")+1);
conf->type = 0;
conf->total_block = fs->cfg->block_count;
conf->block_used = lfs_fs_size(fs);
conf->block_size = fs->cfg->block_size;
return 0;
}
#define T(name) .name = luat_vfs_lfs2_##name
const struct luat_vfs_filesystem vfs_fs_lfs2 = {
.name = "lfs2",
.opts = {
T(mkfs),
T(mount),
T(umount),
T(mkdir),
T(rmdir),
T(lsdir),
T(remove),
T(rename),
T(fsize),
T(fexist),
T(info)
},
.fopts = {
T(fopen),
T(getc),
T(fseek),
T(ftell),
T(fclose),
T(feof),
T(ferror),
T(fread),
T(fwrite)
}
};
// #endif
#endif
|
# 3rd party
from coincidence import AdvancedDataRegressionFixture
from domdf_python_tools.paths import PathPlus
# this package
from imgsorter import sort_images
example_photos = PathPlus(__file__).parent / "example_photos"
def test_sort_images(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
):
destination = tmp_pathplus / "photos"
all_example_photos = example_photos.rglob("*.jpg")
sort_images(destination, *all_example_photos)
advanced_data_regression.check(
sorted(p.relative_to(tmp_pathplus).as_posix() for p in destination.iterchildren())
)
def test_sort_images_known_cameras(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
):
destination = tmp_pathplus / "photos"
all_example_photos = example_photos.rglob("*.jpg")
sort_images(destination, *all_example_photos, known_cameras={"VKY-L09": "Smartphone"})
advanced_data_regression.check(
sorted(p.relative_to(tmp_pathplus).as_posix() for p in destination.iterchildren())
)
def test_sort_images_duplicate(
tmp_pathplus: PathPlus,
advanced_data_regression: AdvancedDataRegressionFixture,
):
destination = tmp_pathplus / "photos"
all_example_photos = list(example_photos.rglob("*.jpg"))
sort_images(destination, *all_example_photos)
sort_images(destination, *all_example_photos)
advanced_data_regression.check(
sorted(p.relative_to(tmp_pathplus).as_posix() for p in destination.iterchildren())
)
|
peso = float(input('Qual é seu poso em kg? '))
h = float(input('Qual sua altura em metros? '))
imc = peso / (h ** 2)
print(f'O IMC da pessoa é de {imc:.1f}')
if imc <= 18.5:
print('Você está ABAIXO DO PESO normal!')
elif 18.5 < imc <= 25:
print('Você está no PESO IDEAL!')
elif 25 < imc <= 30:
print('Você está com SOBREPESO!')
elif 30 < imc <= 40:
print('Você está com OBESIDADE!')
else:
print('Você está com OBESIDADE MÓRBIDA!')
|
class SenderKeyName(object):
def __init__(self, groupId, senderAxolotlAddress):
self.groupId = groupId
self.sender = senderAxolotlAddress
def getGroupId(self):
return self.groupId
def getSender(self):
return self.sender
def serialize(self):
return "%s::%s::%s" % (self.groupId, self.sender.getName(), self.sender.getDeviceId())
def __eq__(self, other):
if other is None: return False
if other.__class__ != SenderKeyName: return False
return self.groupId == other.getGroupId() and self.sender == other.getSender()
def __hash__(self):
return hash(self.groupId) ^ hash(self.sender)
|
'use strict';
const webpack = require('webpack');
const config = require('./config');
config.assetUrl = "uiProject/bin-release/web/game/resource/"
const webpackConfig = require('./webpack.config.dev');
const utils = require('./utils');
const merge = require('webpack-merge');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
const chalk = require('chalk');
const env = config.env
let serverConfig = {};
module.exports = async () => {
switch (env) {
case 'dev':
console.log(chalk.green("dev本地服务"));
try {
let location = await utils.intervalPort('127.0.0.1', 8080);
serverConfig = {
mode: 'development',
devtool: 'source-map',
devServer: {
disableHostCheck: true,
historyApiFallback: true,
hot: true,
host: location.host,
port: location.port,
open: false,
overlay: {
warnings: false,
errors: true,
},
proxy: {'/api': ''},
publicPath: '/',
quiet: true,
watchOptions: {
poll: false,
},
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`请访问: http://${ location.host }:${ location.port }`],
},
}),
],
};
} catch (err) {
console.log(chalk.red("遇到错误",err));
}
break;
case 'test':
// 测试环境使用开发配置
serverConfig = {
mode: 'development',
devtool: 'cheap',
}
break;
default:
// 发布环境使用发布配置
serverConfig = {
mode: 'production',
};
}
// 本地运行去掉publicPath
delete webpackConfig.output.publicPath
const res = merge(webpackConfig, serverConfig);
return res
};
|
// Imports
const Discord = require("discord.js");
const Compute = require("@google-cloud/compute");
const discordConfig = require("./discord-config.json");
const gcpConfig = require("./GCP_config.json");
// Initialize
const client = new Discord.Client();
const compute = new Compute({
projectId: gcpConfig.project_id,
keyFilename: "./GCP_config.json",
});
// Global vars
let serverInstance;
let metadataServerInstance;
let statusServerInstance;
let defaultchannel = "711773120330989620"
// Fetch VMs from GCP, async
async function getListOfVMs() {
const options = {
maxResults: 3,
};
const [vms] = await compute.getVMs(options);
serverInstance = vms[0];
metadataServerInstance = serverInstance.metadata;
statusServerInstance = metadataServerInstance.status;
}
//functions
const gcp = require('./modules/functions/gcp.js')
const discord1 = require('./modules/functions/discord.js')
//const discord = require('./modules/functions/discord.js')
async function load(){
let start = await discord1.ConnectDiscord();
console.log("Bot Started")
//discord1.sendMessage("Bot has started")
//gcp.serveraction("minecraftftb1","start")
}
// Listen for messages
client.on("message", async (message) => {
const userMessage = message.content;
console.log("user message" + userMessage)
if (userMessage.startsWith("!server")) {
const code =
userMessage.split(" ")[1] == null ? "" : userMessage.split(" ")[1].trim();
if (code.length == 0 || code == null || code == "") {
discord1.sendMessage("I think you've missed something", userMessage.channel_id)
}
let codelower = code.toLowerCase()
let output;
const servername =
userMessage.split(" ")[2] == null ? "" : userMessage.split(" ")[2].trim();
switch(codelower) {
case "list":
output = await gcp.getserverslist();
discord1.sendMessage(output, userMessage.channel_id)
break;
case "status":
output = await gcp.getserversstatus(servername);
discord1.sendMessage(output, userMessage.channel_id)
break;
case "start":
case "stop":
output = await gcp.serveraction(servername, codelower);
break;
default:
discord1.sendMessage("Couldn't find an action that meets your request...try again later.", userMessage.channel_id)
}
}
});
// Login
client.login(discordConfig.token);
load()
|
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2020 Lucian Copeland for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "common-hal/pulseio/PulseIn.h"
#include "py/runtime.h"
// STATIC void pulsein_handler(uint8_t num) {
// }
void pulsein_reset(void) {
}
void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu_pin_obj_t* pin,
uint16_t maxlen, bool idle_state) {
mp_raise_NotImplementedError(translate("PulseIn not supported on this chip"));
}
bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t* self) {
return false;
}
void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) {
}
void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t* self) {
}
void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t trigger_duration) {
}
void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t* self) {
}
uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_t index) {
return false;
}
uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) {
return false;
}
uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t* self) {
return false;
}
bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t* self) {
return false;
}
uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t* self) {
return false;
}
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[357],{419:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return c})),n.d(t,"metadata",(function(){return i})),n.d(t,"rightToc",(function(){return l})),n.d(t,"default",(function(){return s}));var r=n(3),a=n(7),o=(n(0),n(440)),c={id:"mfa",title:"This should be the Mfa UI"},i={unversionedId:"fallback/mfa",id:"version-v0.2/fallback/mfa",isDocsHomePage:!1,title:"This should be the Mfa UI",description:"You ended up here because you did not set the following configuration value:",source:"@site/versioned_docs/version-v0.2/fallback/mfa.mdx",slug:"/fallback/mfa",permalink:"/kratos/docs/v0.2/fallback/mfa",editUrl:"https://github.com/ory/kratos/edit/master/docs/versioned_docs/version-v0.2/fallback/mfa.mdx",version:"v0.2",lastUpdatedBy:"aeneasr",lastUpdatedAt:1588605498},l=[],u={rightToc:l};function s(e){var t=e.components,n=Object(a.a)(e,["components"]);return Object(o.b)("wrapper",Object(r.a)({},u,n,{components:t,mdxType:"MDXLayout"}),Object(o.b)("p",null,"You ended up here because you did not set the following configuration value:"),Object(o.b)("pre",null,Object(o.b)("code",Object(r.a)({parentName:"pre"},{className:"language-yaml",metastring:'title="path/to/kratos/config.yml',title:'"path/to/kratos/config.yml'}),"urls:\n mfa_ui: http://my-app.com/mfa\n")),Object(o.b)("p",null,"You can set this configuration value using environment variable ",Object(o.b)("inlineCode",{parentName:"p"},"URLS_MFA_UI")," as\nwell!"),Object(o.b)("p",null,"If you don't know what that means, head over to our\n",Object(o.b)("a",Object(r.a)({parentName:"p"},{href:"/kratos/docs/v0.2/self-service/flows/2fa-mfa-multi-factor-authentication"}),"MFA Documentation"),"!"))}s.isMDXComponent=!0},440:function(e,t,n){"use strict";n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return d}));var r=n(0),a=n.n(r);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function l(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n,r,a={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var u=a.a.createContext({}),s=function(e){var t=a.a.useContext(u),n=t;return e&&(n="function"==typeof e?e(t):i(i({},t),e)),n},f=function(e){var t=s(e.components);return a.a.createElement(u.Provider,{value:t},e.children)},p={inlineCode:"code",wrapper:function(e){var t=e.children;return a.a.createElement(a.a.Fragment,{},t)}},m=a.a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,o=e.originalType,c=e.parentName,u=l(e,["components","mdxType","originalType","parentName"]),f=s(n),m=r,d=f["".concat(c,".").concat(m)]||f[m]||p[m]||o;return n?a.a.createElement(d,i(i({ref:t},u),{},{components:n})):a.a.createElement(d,i({ref:t},u))}));function d(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var o=n.length,c=new Array(o);c[0]=m;var i={};for(var l in t)hasOwnProperty.call(t,l)&&(i[l]=t[l]);i.originalType=e,i.mdxType="string"==typeof e?e:r,c[1]=i;for(var u=2;u<o;u++)c[u]=n[u];return a.a.createElement.apply(null,c)}return a.a.createElement.apply(null,n)}m.displayName="MDXCreateElement"}}]);
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.scriptLoader} object, used to load scripts
* asynchronously.
*/
/**
* Load scripts asynchronously.
* @namespace
* @example
*/
CKEDITOR.scriptLoader = (function()
{
var uniqueScripts = {},
waitingList = {};
return /** @lends CKEDITOR.scriptLoader */ {
/**
* Loads one or more external script checking if not already loaded
* previously by this function.
* @param {String|Array} scriptUrl One or more URLs pointing to the
* scripts to be loaded.
* @param {Function} [callback] A function to be called when the script
* is loaded and executed. If a string is passed to "scriptUrl", a
* boolean parameter is passed to the callback, indicating the
* success of the load. If an array is passed instead, two array
* parameters are passed to the callback; the first contains the
* URLs that have been properly loaded, and the second the failed
* ones.
* @param {Object} [scope] The scope ("this" reference) to be used for
* the callback call. Default to {@link CKEDITOR}.
* @param {Boolean} [noCheck] Indicates that the script must be loaded
* anyway, not checking if it has already loaded.
* @param {Boolean} [showBusy] Changes the cursor of the document while
+ * the script is loaded.
* @example
* CKEDITOR.scriptLoader.load( '/myscript.js' );
* @example
* CKEDITOR.scriptLoader.load( '/myscript.js', function( success )
* {
* // Alerts "true" if the script has been properly loaded.
* // HTTP error 404 should return "false".
* alert( success );
* });
* @example
* CKEDITOR.scriptLoader.load( [ '/myscript1.js', '/myscript2.js' ], function( completed, failed )
* {
* alert( 'Number of scripts loaded: ' + completed.length );
* alert( 'Number of failures: ' + failed.length );
* });
*/
load : function( scriptUrl, callback, scope, noCheck, showBusy )
{
var isString = ( typeof scriptUrl == 'string' );
if ( isString )
scriptUrl = [ scriptUrl ];
if ( !scope )
scope = CKEDITOR;
var scriptCount = scriptUrl.length,
completed = [],
failed = [];
var doCallback = function( success )
{
if ( callback )
{
if ( isString )
callback.call( scope, success );
else
callback.call( scope, completed, failed );
}
};
if ( scriptCount === 0 )
{
doCallback( true );
return;
}
var checkLoaded = function( url, success )
{
( success ? completed : failed ).push( url );
if ( --scriptCount <= 0 )
{
showBusy && CKEDITOR.document.getDocumentElement().removeStyle( 'cursor' );
doCallback( success );
}
};
var onLoad = function( url, success )
{
// Mark this script as loaded.
uniqueScripts[ url ] = 1;
// Get the list of callback checks waiting for this file.
var waitingInfo = waitingList[ url ];
delete waitingList[ url ];
// Check all callbacks waiting for this file.
for ( var i = 0 ; i < waitingInfo.length ; i++ )
waitingInfo[ i ]( url, success );
};
var loadScript = function( url )
{
if ( noCheck !== true && uniqueScripts[ url ] )
{
checkLoaded( url, true );
return;
}
var waitingInfo = waitingList[ url ] || ( waitingList[ url ] = [] );
waitingInfo.push( checkLoaded );
// Load it only for the first request.
if ( waitingInfo.length > 1 )
return;
// Create the <script> element.
var script = new CKEDITOR.dom.element( 'script' );
script.setAttributes( {
type : 'text/javascript',
src : url } );
if ( callback )
{
if ( CKEDITOR.env.ie )
{
// FIXME: For IE, we are not able to return false on error (like 404).
/** @ignore */
script.$.onreadystatechange = function ()
{
if ( script.$.readyState == 'loaded' || script.$.readyState == 'complete' )
{
script.$.onreadystatechange = null;
onLoad( url, true );
}
};
}
else
{
/** @ignore */
script.$.onload = function()
{
// Some browsers, such as Safari, may call the onLoad function
// immediately. Which will break the loading sequence. (#3661)
setTimeout( function() { onLoad( url, true ); }, 0 );
};
// FIXME: Opera and Safari will not fire onerror.
/** @ignore */
script.$.onerror = function()
{
onLoad( url, false );
};
}
}
// Append it to <head>.
script.appendTo( CKEDITOR.document.getHead() );
CKEDITOR.fire( 'download', url ); // @Packager.RemoveLine
};
showBusy && CKEDITOR.document.getDocumentElement().setStyle( 'cursor', 'wait' );
for ( var i = 0 ; i < scriptCount ; i++ )
{
loadScript( scriptUrl[ i ] );
}
},
/**
* Executes a JavaScript code into the current document.
* @param {String} code The code to be executed.
* @example
* CKEDITOR.scriptLoader.loadCode( 'var x = 10;' );
* alert( x ); // "10"
*/
loadCode : function( code )
{
// Create the <script> element.
var script = new CKEDITOR.dom.element( 'script' );
script.setAttribute( 'type', 'text/javascript' );
script.appendText( code );
// Append it to <head>.
script.appendTo( CKEDITOR.document.getHead() );
}
};
})();
|
/*
_ ___ ___ _ _ ___ _ _ ___ _ ___ ___
/_\ | _ \ \| | | |_ _| \| |/ _ \| | / _ \ / __|
/ _ \| / |) | |_| || || .` | (_) | |_| (_) | (_ |
/_/ \_\_|_\___/ \___/|___|_|\_|\___/|____\___/ \___|
Log library for Arduino
version 1.0.3
https://github.com/thijse/Arduino-Log
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
*/
#ifndef LOGGING_H
#define LOGGING_H
#include <inttypes.h>
#include <stdarg.h>
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
//#include "StringStream.h"
typedef void (*printfunction)(uint8_t tag, int level, Print*);
//#include <stdint.h>
//#include <stddef.h>
// *************************************************************************
// Uncomment line below to fully disable logging, and reduce project size
// ************************************************************************
//#define DISABLE_LOGGING
#define LOG_LEVEL_SILENT -1
#define LOG_LEVEL_FATAL 0
#define LOG_LEVEL_ALERT 1
#define LOG_LEVEL_CRITICAL 2
#define LOG_LEVEL_ERROR 3
#define LOG_LEVEL_WARNING 4
#define LOG_LEVEL_NOTICE 5
#define LOG_LEVEL_INFO 5
#define LOG_LEVEL_TRACE 6
#define LOG_LEVEL_VERBOSE 7
#define LOG_LEVEL_DEBUG 8
#define LOG_LEVEL_OUTPUT 9
//#define CR "\n"
#define LOGGING_VERSION 1_0_3
/**
* Logging is a helper class to output informations over
* RS232. If you know log4j or log4net, this logging class
* is more or less similar ;-) <br>
* Different loglevels can be used to extend or reduce output
* All methods are able to handle any number of output parameters.
* All methods print out a formated string (like printf).<br>
* To reduce output and program size, reduce loglevel.
*
* Output format string can contain below wildcards. Every wildcard
* must be start with percent sign (\%)
*
* ---- Wildcards
*
* %s replace with an string (char*)
* %c replace with an character
* %d replace with an integer value
* %l replace with an long value
* %x replace and convert integer value into hex
* %X like %x but combine with 0x123AB
* %b replace and convert integer value into binary
* %B like %x but combine with 0b10100011
* %t replace and convert boolean value into "t" or "f"
* %T like %t but convert into "true" or "false"
*
* ---- Loglevels
*
* 0 - LOG_LEVEL_SILENT no output
* 1 - LOG_LEVEL_FATAL fatal errors
* 2 - LOG_LEVEL_ERROR all errors
* 3 - LOG_LEVEL_WARNING errors and warnings
* 4 - LOG_LEVEL_NOTICE errors, warnings and notices
* 5 - LOG_LEVEL_TRACE errors, warnings, notices, traces
* 6 - LOG_LEVEL_VERBOSE subprocesses and steps
* 7 - LOG_LEVEL_DEBUG all
*/
class Logging {
public:
/**
* default Constructor
*/
Logging()
#ifndef DISABLE_LOGGING
// : _level(LOG_LEVEL_SILENT), _showLevel(true)
#endif
{}
/**
* Initializing, must be called as first. Note that if you use
* this variant of Init, you need to initialize the baud rate
* yourself, if printer happens to be a serial port.
*
* \param level - logging levels <= this will be logged.
* \param printer - place that logging output will be sent to.
* \return void
*
*/
void begin(int level, bool showLevel = true);
/**
* Register up to 3 printers to a certain slot
*
* \param slot - index of the printer to register.
* \param printer - place that logging output will be sent to.
* \return void
*
*/
void registerOutput(uint8_t slot, Print* logOutput, int level, bool showLevel);
/**
* Unregister the printer in a certain slot
*
* \param slot - index of the printer to register.
* \return void
*
*/
void unregisterOutput(uint8_t slot);
/**
* Set the log level.
*
* \param level - The new log level.
* \return void
*/
void setLevel(uint8_t slot, int level);
/**
* Get the log level.
*
* \return The current log level.
*/
int getLevel(uint8_t slot) const;
/**
* Set whether to show the log level.
*
* \param showLevel - true if the log level should be shown for each log
* false otherwise.
* \return void
*/
void setShowLevel(uint8_t slot, bool showLevel);
/**
* Get whether the log level is shown during logging
*
* \return true if the log level is be shown for each log
* false otherwise.
*/
bool getShowLevel(uint8_t slot) const;
/**
* Sets a function to be called before each log command.
*
* \param f - The function to be called
* \return void
*/
void setPrefix(printfunction f);
/**
* Sets a function to be called after each log command.
*
* \param f - The function to be called
* \return void
*/
void setSuffix(printfunction f);
/**
* Output a fatal error message. Output message contains
* F: followed by original message
* Fatal error messages are printed out at
* loglevels >= LOG_LEVEL_FATAL
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void fatal(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_FATAL, msg, args...);
#endif
}
/**
* Output an error message. Output message contains
* E: followed by original message
* Error messages are printed out at
* loglevels >= LOG_LEVEL_ERROR
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void error(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_ERROR, msg, args...);
#endif
}
/**
* Output a warning message. Output message contains
* W: followed by original message
* Warning messages are printed out at
* loglevels >= LOG_LEVEL_WARNING
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void warning(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_WARNING, msg, args...);
#endif
}
/**
* Output a notice message. Output message contains
* N: followed by original message
* Notice messages are printed out at
* loglevels >= LOG_LEVEL_NOTICE
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void notice(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_NOTICE, msg, args...);
#endif
}
/**
* Output a trace message. Output message contains
* N: followed by original message
* Trace messages are printed out at
* loglevels >= LOG_LEVEL_TRACE
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void trace(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_TRACE, msg, args...);
#endif
}
/**
* Output a verbose message. Output message contains
* V: followed by original message
* Verbose messages are printed out at
* loglevels >= LOG_LEVEL_VERBOSE
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void verbose(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_VERBOSE, msg, args...);
#endif
}
/**
* Output a debug message. Output message contains
* V: followed by original message
* Debug messages are printed out at
* loglevels >= LOG_LEVEL_DEBUG
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void debug(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_DEBUG, msg, args...);
#endif
}
/**
* Output a normal message. Output message contains
* V: followed by original message
* Output messages are always printed out
*
* \param msg format string to output
* \param ... any number of variables
* \return void
*/
template <class T, typename... Args> void output(uint8_t tag, T msg, Args... args)
{
#ifndef DISABLE_LOGGING
printLevel(tag, LOG_LEVEL_OUTPUT, msg, args...);
#endif
}
private:
void print(Print* logOutput, const char* format, va_list args);
void print(Print* logOutput, const __FlashStringHelper* format, va_list args);
void printFormat(Print* logOutput, const char format, va_list* args);
template <class T> void printLevel(uint8_t tag, int level, T msg, ...)
{
#ifndef DISABLE_LOGGING
for(int i = 0; i < 3; i++) {
if(_logOutput[i] == NULL || level > _level[i]) continue;
if(_prefix != NULL) {
_prefix(tag, level, _logOutput[i]);
}
va_list args;
va_start(args, msg);
print(_logOutput[i], msg, args);
if(_suffix != NULL) {
_suffix(tag, level, _logOutput[i]);
}
}
#endif
}
#ifndef DISABLE_LOGGING
int _level[3];
bool _showLevel[3];
Print* _logOutput[3] = {NULL,NULL,NULL};
printfunction _prefix = NULL;
printfunction _suffix = NULL;
#endif
};
extern Logging Log;
#endif
|
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// Place any jQuery/helper plugins in here.
;(function(b){var a={init:function(c){return this.each(function(){var d=this,h=b(d).empty();d.opt=b.extend(true,{},b.fn.raty.defaults,c);h.data("settings",d.opt);d.opt.number=a.between(d.opt.number,0,20);if(d.opt.path.substring(d.opt.path.length-1,d.opt.path.length)!="/"){d.opt.path+="/";}if(typeof d.opt.score=="function"){d.opt.score=d.opt.score.call(d);}if(d.opt.score){d.opt.score=a.between(d.opt.score,0,d.opt.number);}for(var e=1;e<=d.opt.number;e++){b("<img />",{src:d.opt.path+((!d.opt.score||d.opt.score<e)?d.opt.starOff:d.opt.starOn),alt:e,title:(e<=d.opt.hints.length&&d.opt.hints[e-1]!==null)?d.opt.hints[e-1]:e}).appendTo(d);if(d.opt.space){h.append((e<d.opt.number)?" ":"");}}d.stars=h.children('img:not(".raty-cancel")');d.score=b("<input />",{type:"hidden",name:d.opt.scoreName}).appendTo(d);if(d.opt.score&&d.opt.score>0){d.score.val(d.opt.score);a.roundStar.call(d,d.opt.score);}if(d.opt.iconRange){a.fill.call(d,d.opt.score);}a.setTarget.call(d,d.opt.score,d.opt.targetKeep);var g=d.opt.space?4:0,f=d.opt.width||(d.opt.number*d.opt.size+d.opt.number*g);if(d.opt.cancel){d.cancel=b("<img />",{src:d.opt.path+d.opt.cancelOff,alt:"x",title:d.opt.cancelHint,"class":"raty-cancel"});if(d.opt.cancelPlace=="left"){h.prepend(" ").prepend(d.cancel);}else{h.append(" ").append(d.cancel);}f+=(d.opt.size+g);}if(d.opt.readOnly){a.fixHint.call(d);if(d.cancel){d.cancel.hide();}}else{h.css("cursor","pointer");a.bindAction.call(d);}h.css("width",f);});},between:function(e,d,c){return Math.min(Math.max(parseFloat(e),d),c);},bindAction:function(){var c=this,e=b(c);e.mouseleave(function(){var f=c.score.val()||undefined;a.initialize.call(c,f);a.setTarget.call(c,f,c.opt.targetKeep);if(c.opt.mouseover){c.opt.mouseover.call(c,f);}});var d=c.opt.half?"mousemove":"mouseover";if(c.opt.cancel){c.cancel.mouseenter(function(){b(this).attr("src",c.opt.path+c.opt.cancelOn);c.stars.attr("src",c.opt.path+c.opt.starOff);a.setTarget.call(c,null,true);if(c.opt.mouseover){c.opt.mouseover.call(c,null);}}).mouseleave(function(){b(this).attr("src",c.opt.path+c.opt.cancelOff);if(c.opt.mouseover){c.opt.mouseover.call(c,c.score.val()||null);}}).click(function(f){c.score.removeAttr("value");if(c.opt.click){c.opt.click.call(c,null,f);}});}c.stars.bind(d,function(g){var h=parseInt(this.alt,10);if(c.opt.half){var f=parseFloat((g.pageX-b(this).offset().left)/c.opt.size),i=(f>0.5)?1:0.5;h=parseFloat(this.alt)-1+i;a.fill.call(c,h);if(c.opt.precision){h=h-i+f;}a.showHalf.call(c,h);}else{a.fill.call(c,h);}e.data("score",h);a.setTarget.call(c,h,true);if(c.opt.mouseover){c.opt.mouseover.call(c,h,g);}}).click(function(f){c.score.val((c.opt.half||c.opt.precision)?e.data("score"):this.alt);if(c.opt.click){c.opt.click.call(c,c.score.val(),f);}});},cancel:function(c){return b(this).each(function(){var d=this,e=b(d);if(e.data("readonly")===true){return this;}if(c){a.click.call(d,null);}else{a.score.call(d,null);}d.score.removeAttr("value");});},click:function(c){return b(this).each(function(){if(b(this).data("readonly")===true){return this;}a.initialize.call(this,c);if(this.opt.click){this.opt.click.call(this,c);}else{a.error.call(this,'you must add the "click: function(score, evt) { }" callback.');}a.setTarget.call(this,c,true);});},error:function(c){b(this).html(c);b.error(c);},fill:function(k){var c=this,h=c.stars.length,g=0,d,j,f;for(var e=1;e<=h;e++){d=c.stars.eq(e-1);if(c.opt.iconRange&&c.opt.iconRange.length>g){j=c.opt.iconRange[g];if(c.opt.single){f=(e==k)?(j.on||c.opt.starOn):(j.off||c.opt.starOff);}else{f=(e<=k)?(j.on||c.opt.starOn):(j.off||c.opt.starOff);}if(e<=j.range){d.attr("src",c.opt.path+f);}if(e==j.range){g++;}}else{if(c.opt.single){f=(e==k)?c.opt.starOn:c.opt.starOff;}else{f=(e<=k)?c.opt.starOn:c.opt.starOff;}d.attr("src",c.opt.path+f);}}},fixHint:function(){var c=b(this),e=parseInt(this.score.val(),10),d=this.opt.noRatedMsg;if(!isNaN(e)&&e>0){d=(e<=this.opt.hints.length&&this.opt.hints[e-1]!==null)?this.opt.hints[e-1]:e;}c.data("readonly",true).css("cursor","default").attr("title",d);this.score.attr("readonly","readonly");this.stars.attr("title",d);},getScore:function(){var d=[],c;b(this).each(function(){c=this.score.val();d.push(c?parseFloat(c):undefined);});return(d.length>1)?d:d[0];},readOnly:function(c){return this.each(function(){var d=b(this);if(d.data("readonly")===c){return this;}if(this.cancel){if(c){this.cancel.hide();}else{this.cancel.show();}}if(c){d.unbind();d.children("img").unbind();a.fixHint.call(this);}else{a.bindAction.call(this);a.unfixHint.call(this);}d.data("readonly",c);});},reload:function(){return a.set.call(this,{});},roundStar:function(e){var d=(e-Math.floor(e)).toFixed(2);if(d>this.opt.round.down){var c=this.opt.starOn;if(d<this.opt.round.up&&this.opt.halfShow){c=this.opt.starHalf;}else{if(d<this.opt.round.full){c=this.opt.starOff;}}this.stars.eq(Math.ceil(e)-1).attr("src",this.opt.path+c);}},score:function(){return arguments.length?a.setScore.apply(this,arguments):a.getScore.call(this);},set:function(c){this.each(function(){var d=b(this),f=d.data("settings"),e=d.clone().removeAttr("style").insertBefore(d);d.remove();e.raty(b.extend(f,c));});return b(this.selector);},setScore:function(c){return b(this).each(function(){if(b(this).data("readonly")===true){return this;}a.initialize.call(this,c);a.setTarget.call(this,c,true);});},setTarget:function(e,d){if(this.opt.target){var c=b(this.opt.target);if(c.length==0){a.error.call(this,"target selector invalid or missing!");}var f=e;if(!d||f===undefined){f=this.opt.targetText;}else{if(this.opt.targetType=="hint"){f=(f===null&&this.opt.cancel)?this.opt.cancelHint:this.opt.hints[Math.ceil(f-1)];}else{f=this.opt.precision?parseFloat(f).toFixed(1):parseInt(f,10);}}if(this.opt.targetFormat.indexOf("{score}")<0){a.error.call(this,'template "{score}" missing!');}if(e!==null){f=this.opt.targetFormat.toString().replace("{score}",f);}if(c.is(":input")){c.val(f);}else{c.html(f);}}},showHalf:function(d){var c=(d-Math.floor(d)).toFixed(1);if(c>0&&c<0.6){this.stars.eq(Math.ceil(d)-1).attr("src",this.opt.path+this.opt.starHalf);}},initialize:function(c){c=!c?0:a.between(c,0,this.opt.number);a.fill.call(this,c);if(c>0){if(this.opt.halfShow){a.roundStar.call(this,c);}this.score.val(c);}},unfixHint:function(){for(var c=0;c<this.opt.number;c++){this.stars.eq(c).attr("title",(c<this.opt.hints.length&&this.opt.hints[c]!==null)?this.opt.hints[c]:c);}b(this).data("readonly",false).css("cursor","pointer").removeAttr("title");this.score.attr("readonly","readonly");}};b.fn.raty=function(c){if(a[c]){return a[c].apply(this,Array.prototype.slice.call(arguments,1));}else{if(typeof c==="object"||!c){return a.init.apply(this,arguments);}else{b.error("Method "+c+" does not exist!");}}};b.fn.raty.defaults={cancel:false,cancelHint:"cancel this rating!",cancelOff:"cancel-off.png",cancelOn:"cancel-on.png",cancelPlace:"left",click:undefined,half:false,halfShow:true,hints:["bad","poor","regular","good","gorgeous"],iconRange:undefined,mouseover:undefined,noRatedMsg:"not rated yet",number:5,path:"img/",precision:false,round:{down:0.25,full:0.6,up:0.76},readOnly:false,score:undefined,scoreName:"score",single:false,size:16,space:true,starHalf:"star-half.png",starOff:"star-off.png",starOn:"star-on.png",target:undefined,targetFormat:"{score}",targetKeep:false,targetText:"",targetType:"hint",width:undefined};})(jQuery);
|
import dbus
session_bus = dbus.SessionBus()
dbus_object = session_bus.get_object(bus_name='com.skontar.HexChat', object_path='/com/skontar/HexChat')
interface = dbus.Interface(object=dbus_object, dbus_interface='com.skontar.HexChat')
interface.create_notification('fenikso', 'freenode', '#fedora', 'Title',
'<fenikso>: Velmi žluťoučký kůň www.example.com', 'P')
# interface.quit()
|
import pandas as pd
import math
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import CSVLogger
scaler = MinMaxScaler(feature_range=(0,1))
previous_ts=3
def prepare_data(data):
data['timestamp'] = pd.to_datetime(data['timestamp']).dt.date
dataframe = pd.DataFrame(data=data, index=[data.timestamp], columns=['close'])
close_data = data.filter(['close'])
close_dataset = close_data.values
close_dataset = close_dataset.astype('float32')
#normalizing to scale input data
#scaler = MinMaxScaler(feature_range=(0,1))
close_dataset = scaler.fit_transform(close_dataset)
return close_dataset
def split(close_dataset):
#splitting data into 80% of train data and 20% of test data
Training_size = math.ceil(len(close_dataset)*0.8)
Testing_size = len(close_dataset) - Training_size
train = close_dataset[0:Training_size,:]
test = close_dataset[Training_size:len(close_dataset),:]
return train, test
def model_data(train,test):
Xtrain = []
Ytrain = []
Xtest = []
Ytest = []
#Training data
for i in range(len(train)-previous_ts-1):
x = train[i:(i+previous_ts),0]
Xtrain.append(x)
Ytrain.append(train[i+previous_ts, 0])
#Testing data
for i in range(len(test)-previous_ts-1):
x = test[i:(i+previous_ts),0]
Xtest.append(x)
Ytest.append(test[i+previous_ts, 0])
Xtrain = np.array(Xtrain)
Xtest= np.array(Xtest)
Ytrain = np.array(Ytrain)
Ytest = np.array(Ytest)
Xtrain = np.reshape(Xtrain, (Xtrain.shape[0], 1, Xtrain.shape[1]))
Xtest = np.reshape(Xtest, (Xtest.shape[0], 1, Xtest.shape[1]))
return Xtrain, Ytrain, Xtest, Ytest
def fit_model(Xtrain, Ytrain, Xtest, Ytest, dropdownNeurons, dropdownSteps):
#LSTM Network
model = Sequential()
model.add(LSTM(dropdownNeurons, return_sequences=True, input_shape=(1, previous_ts)))
model.add(Dropout(rate=0.2))
model.add(LSTM(dropdownNeurons, return_sequences=True))
model.add(Dropout(rate=0.2))
model.add(LSTM(dropdownNeurons, return_sequences=False))
model.add(Dropout(rate=0.2))
model.add(Dense(1))
model.compile(loss="mse", optimizer="adam", metrics=['mae'])
csv_logger = CSVLogger('run.csv', append=True, separator=',')
model.fit(Xtrain, Ytrain, validation_data=(Xtest,Ytest), epochs=dropdownSteps, batch_size=16, verbose=2, callbacks=[csv_logger])
return model
def predict_values(model, Xtrain, Ytrain, Xtest, Ytest, close_dataset):
TrainPrediction = model.predict(Xtrain)
TestPrediction = model.predict(Xtest)
TrainPrediction = scaler.inverse_transform(TrainPrediction)
Ytrain = scaler.inverse_transform([Ytrain])
TestPrediction = scaler.inverse_transform(TestPrediction)
Ytest = scaler.inverse_transform([Ytest])
TrainScore = math.sqrt(mean_squared_error(Ytrain[0], TrainPrediction[:,0]))
TestScore = math.sqrt(mean_squared_error(Ytest[0], TestPrediction[:,0]))
return TrainPrediction, Ytrain, TestPrediction, Ytest, TrainScore, TestScore
def plot_data(close_dataset, TrainPrediction, TestPrediction):
trainPredictPlot = np.empty_like(close_dataset)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[previous_ts:len(TrainPrediction)+previous_ts, :] = TrainPrediction
testPredictPlot = np.empty_like(close_dataset)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(TrainPrediction)+(previous_ts*2)+1:len(close_dataset)-1, :] = TestPrediction
inverted_dataset = scaler.inverse_transform(close_dataset)
return inverted_dataset, trainPredictPlot, testPredictPlot
def predict(num_prediction, model, close_dataset):
prediction_list = close_dataset[-previous_ts:]
for _ in range(num_prediction):
x = prediction_list[-previous_ts:]
x = x.reshape(1, 1, previous_ts)
out = model.predict(x)
inversed_data = scaler.inverse_transform(out)
prediction_list = np.append(prediction_list, inversed_data)
prediction_list = prediction_list[previous_ts-1:]
return prediction_list[1]
|
module.exports = {
'extends': [
// 'airbnb',
'prettier',
'prettier/react',
],
'settings': {
'import/resolver': {
'node': {
'paths': ['.']
}
}
},
'env': {
'browser': true,
'node': true,
'jasmine': true
},
'parser': 'babel-eslint',
'plugins': [
'react',
'prettier'
],
'rules': {
'prettier/prettier': [
'error',
{
'printWidth': 120,
'tabWidth': 2,
'singleQuote': true,
'trailingComma': 'es5',
'bracketSpacing': true,
'semi': false,
'useTabs': false,
'jsxBracketSameLine': false,
'parser': 'babylon'
}
],
'import/first': [0],
'no-underscore-dangle': [0],
'import/no-named-as-default-member': [0],
'no-use-before-define': [0],
'no-shadow': [0],
'consistent-return': [0],
'react/prop-types': [0],
'no-return-assign': [0],
'react/no-array-index-key': [0],
'react/prefer-stateless-function': [0],
'import/prefer-default-export': [0],
'import/no-named-as-default': [0],
'global-require': [0],
'camelcase': [0],
'react/no-danger': [0],
'react/no-multi-comp': [0],
'react/jsx-filename-extension': [
1,
{
'extensions': [
'.js',
'.jsx'
]
}
],
'react/forbid-prop-types': [
0
]
}
}
|
"""
Django settings for sopot project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import dj_database_url
# Build paths inside the project like this: BASE_DIR / 'subdir'.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = Path(__file__).resolve().parent.parent
SITE_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', 'TODO: use secret key in deployment')
# SECURITY WARNING: don't run with debug turned on in production!
if os.environ.get('ON_HEROKU', '0') == '0':
DEBUG = True
else:
DEBUG = False
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True # TODO comment out
ALLOWED_HOSTS = [
'127.0.0.1',
#'database-of-proofs-engine.herokuapp.com/',
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
'whitenoise.runserver_nostatic',
'django_bootstrap5',
'cd_editor.apps.CdEditorConfig',
'database.apps.DatabaseConfig',
'django_neomodel',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'sopot.urls'
TEMPLATES_PATH = os.path.join(SETTINGS_PATH, 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_PATH,
os.path.join(TEMPLATES_PATH, 'sopot'),
os.path.join(TEMPLATES_PATH, 'accounts'),
os.path.join(TEMPLATES_PATH, 'cd_editor'),
os.path.join(TEMPLATES_PATH, 'database')],
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'sopot.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
# TODO: try out PostgreSQL in production, i.e. change True to the commented out code;
if os.environ.get('ON_HEROKU', '0') == '0':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
else:
DATABASES = {
# TODO: what does this max_age setting do?
'default' : dj_database_url.config(conn_max_age=600)
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(SITE_ROOT, 'static/'),)
def neo4j_url():
url = os.environ.get('NEO4J_SCHEMA', 'bolt') + "://"
url += os.environ.get('NEO4J_USERNAME', 'neo4j') + ":"
url += os.environ.get('NEO4J_PASSWORD', 'fusion123') + "@"
url += os.environ.get('NEO4J_HOST', 'localhost') + ":"
url += os.environ.get('NEO4J_PORT', '7687')
return url
NEOMODEL_NEO4J_BOLT_URL = neo4j_url()
NEOMODEL_SIGNALS = True
NEOMODEL_FORCE_TIMEZONE = False
NEOMODEL_ENCRYPTED_CONNECTION = False # TODO: how do we switch this on without error?
from neomodel import config # BUGFIX: had to do it this way
config.MAX_POOL_SIZE = 50 # TODO: what does this affect?
#LOGIN_REDIRECT_URL = 'home'
#LOGOUT_REDIRECT_URL = 'home'
# TODO: Enable Click-jacking protection
X_FRAME_OPTIONS = 'ALLOW' # ie set this to "DENY"
# https://docs.djangoproject.com/en/1.11/ref/clickjacking/
MAX_NAMESPACE_LENGTH = 64
MAX_DIAGRAM_NAME_LENGTH = MAX_NAMESPACE_LENGTH
MAX_USERNAME_LENGTH = MAX_NAMESPACE_LENGTH
MAX_CODE_LENGTH = 4096
MAX_GLOBAL_DICT_LENGTH = 512
MAX_PASSWORD_LENGTH = 128
MAX_TEXT_LENGTH = 123
MAX_USER_EDIT_DIAGRAMS = 8
MAX_BAD_CONN_RETRIES = 5
# Activate Django-Heroku.
django_heroku.settings(locals())
#MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
|
//
// YYHDetailOfStoreFrame.h
// XiaoChengJia
//
// Created by yyh2016 on 16/10/12.
// Copyright © 2016年 yyh2016. All rights reserved.
//
#import "YYHBaseModel.h"
#include "YYHDetailOfStoreModel.h"
@interface YYHDetailOfStoreFrame : YYHBaseModel
@property(nonatomic,strong) YYHDetailOfStoreModel *detailStoreModel;
@property(nonatomic,assign,readonly) CGFloat imageAndLabelHeight;
@property(nonatomic,assign,readonly) CGRect instructionFrame;
@property(nonatomic,assign,readonly) CGRect addressFrame;
@end
|
import streamlit as st
import pickle
import numpy as np
from PIL import Image
model2=pickle.load(open('modellr.pkl','rb'))
model4=pickle.load(open('modelrf.pkl','rb'))
model3=pickle.load(open('modellr.pkl','rb'))
model1=pickle.load(open('modellr.pkl','rb'))
def predict_cancer_svm(mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension):
input=np.array([[mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension]])#.astype(np.float64)
prediction=model1.predict(input)
pred=prediction
return float(pred)
def predict_cancer_tree(mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension):
input=np.array([[mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension]])#.astype(np.float64)
prediction=model3.predict(input)
pred=prediction
return float(pred)
def predict_cancer_rf(mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension):
input=np.array([[mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension]])#.astype(np.float64)
prediction=model4.predict(input)
pred=prediction
return float(pred)
def main():
st.title("Built By CodeX MAIT")
status=st.sidebar.radio("Know About Our Model's",("Model 1","Model 2","Model 3"))
if status=='Model 1':
st.sidebar.success('Model 1 Is Made By using Support Vector Machines And Has Testing Accuracy of 0.913')
if status == 'Model 2':
st.sidebar.info('Model 2 Is Made By using Decision Tree Classifier And Has Testing Accuracy of 0.932')
if status == 'Model 3':
st.sidebar.warning('Model 3 Is Made By Using Random Forest Classifier And Has Testing Accuracy of 0.967')
bar= st.sidebar.selectbox("Choose PLot", ["PairPlot", "CountPlot"])
if bar=="PairPlot":
st.success('Pair Plot Showing Relation Between Different Parameters Responsible For Breast Cancer According To Our Data Set')
img = Image.open("pairplot.png")
st.image(img,width=500)
if bar=="CountPlot":
st.success('CountPlot of People with Malignant VS Belign Cells According To Our Data Set')
img = Image.open("countplot.png")
st.image(img,width=500)
html_temp = """
<div style="background-color:#025246 ;padding:10px">
<h1 style="color:white;text-align:center;">Breast Cancer Detection Model</h1>
</div>
"""
st.markdown(html_temp, unsafe_allow_html=True)
img = Image.open("main.jpeg")
st.image(img, width=698)
st.selectbox("Your Gender",["Male","Female","Others"])
st.markdown("Fill Your Information Here")
mean_radius = st.text_input("Mean Radius")
mean_texture = st.text_input("Mean Texture")
mean_perimeter = st.text_input("Mean Perimeter")
mean_area = st.text_input("Mean Area")
mean_smoothness = st.text_input("Mean Smoothness")
mean_compactness = st.text_input("Mean Compactness")
mean_concavity = st.text_input("Mean Concavity")
mean_concavepoints = st.text_input("Mean Concave Points")
mean_symmetry = st.text_input("Mean Symmetry")
mean_fractaldimension = st.text_input("Mean Fractal Dimension")
st.warning('Click Here To Check Your Results')
safe_html="""
<div style="background-color:#F4D03F;padding:10px >
<h2 style="color:white;text-align:center;"> Hey,You Are Not Diagnosed With Breast Cancer</h2>
</div>
"""
danger_html="""
<div style="background-color:#F08080;padding:10px >
<h2 style="color:red ;text-align:center;"> Hey ,You Are Diagnosed with Malignant Breast Cancer</h2>
</div>
"""
if st.button("Model 1"):
output=predict_cancer_rf(mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension)
st.success('')
if output ==1:
st.markdown(danger_html,unsafe_allow_html=True)
else:
st.markdown(safe_html,unsafe_allow_html=True)
st.balloons()
if st.button("Model 2"):
output=predict_cancer_rf(mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension)
st.success('')
if output ==1:
st.markdown(danger_html,unsafe_allow_html=True)
else:
st.markdown(safe_html,unsafe_allow_html=True)
st.balloons()
if st.button("Model 3"):
output=predict_cancer_rf(mean_radius,mean_texture,mean_perimeter,mean_area,mean_smoothness,mean_compactness,mean_concavity,mean_concavepoints,mean_symmetry,mean_fractaldimension)
st.success('')
if output ==1:
st.markdown(danger_html,unsafe_allow_html=True)
else:
st.markdown(safe_html,unsafe_allow_html=True)
st.balloons()
if __name__=='__main__':
main()
|
const session = require('express-session');
const cookieparser = require('cookie-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const db = require('./models');
// export a function that receives the Express app we will configure for Passport
module.exports = (app) => {
// these two middlewares are required to make passport work with sessions
// sessions are optional, but an easy solution to keeping users
// logged in until they log out.
app.use(cookieparser());
app.use(session({
// this should be changed to something cryptographically secure for production
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
// automatically extends the session age on each request. useful if you want
// the user's activity to extend their session. If you want an absolute session
// expiration, set to false
rolling: true,
name: 'sid', // don't use the default session cookie name
// set your options for the session cookie
cookie: {
httpOnly: true,
// the duration in milliseconds that the cookie is valid
maxAge: 20 * 60 * 1000, // 20 minutes
// recommended you use this setting in production if you have a well-known domain you want to restrict the cookies to.
// domain: 'your.domain.com',
// recommended you use this setting in production if your site is published using HTTPS
// secure: true,
}
}));
// Only necessary when using sessions.
// This tells Passport how or what data to save about a user in the session cookie.
// It's recommended you only serialize something like a unique username or user ID.
// I prefer user ID.
passport.serializeUser((user, done) => {
done(null, user._id);
});
// Only necessary when using sessions.
// This tells Passport how to turn the user ID we serialize in the session cookie
// back into the actual User record from our Mongo database.
// Here, we simply find the user with the matching ID and return that.
// This will cause the User record to be available on each authenticated request via the req.user property.
passport.deserializeUser(function (userId, done) {
db.User.findById(userId)
.then(function (user) {
done(null, user);
})
.catch(function (err) {
done(err);
});
});
// this tells passport to use the "local" strategy, and configures the strategy
// with a function that will be called when the user tries to authenticate with
// a username and password. We simply look the user up, hash the password they
// provided with the salt from the real password, and compare the results. if
// the original and current hashes are the same, the user entered the correct password.
passport.use(new LocalStrategy((username, password, done) => {
const errorMsg = 'Invalid username or password';
db.User.findOne({ username })
.then(user => {
// if no matching user was found...
if (!user) {
return done(null, false, { message: errorMsg });
}
// call our validate method, which will call done with the user if the
// passwords match, or false if they don't
return user.validatePassword(password)
.then(isMatch => done(null, isMatch ? user : false, isMatch ? null : { message: errorMsg }));
})
.catch(done);
}));
// initialize passport. this is required, after you set up passport but BEFORE you use passport.session (if using)
app.use(passport.initialize());
// only required if using sessions. this will add middleware from passport
// that will serialize/deserialize the user from the session cookie and add
// them to req.user
app.use(passport.session());
}
|
/* testDynArray.c
* Author: Chris Kearns
* Date: 23 Aug 2016
* This file is used for testing the dynamicArray.c file.
* This test suite is by no means complete or thorough.
* More testing is needed on your own.
*/
#include <stdio.h>
#include <stdlib.h>
#include "dynArray.h"
void assertTrue(int predicate, char *message) {
printf("%s: ", message);
if (predicate)
printf("PASSED\n");
else
printf("FAILED\n");
}
/* Testing routines - comment out or add to as required. */
int main(int argc, char* argv[]){
DynArr *dyn;
dyn = newDynArr(8);
/* int i;
for (i = 0; i < 32; i++) {
addDynArr(dyn, i);
}
for (i = 0; i < 32; i++) {
printf("At dyn[%d] val %d ", i, i + 1);
assertTrue(EQ(getDynArr(dyn, i), i), "test result: ");
}
for (i = 0; i < 32; i++) {
addDynArr(dyn, i);
printf("DynArr capacity now = %d\n", capDynArr(dyn));
}
*/
printf("\n\nTesting addDynArr...\n");
addDynArr(dyn, 3);
addDynArr(dyn, 4);
addDynArr(dyn, 10);
addDynArr(dyn, 5);
addDynArr(dyn, 6);
printf("The array's content: [3,4,10,5,6]\n");
assertTrue(EQ(getDynArr(dyn, 0), 3), "Test 1st element == 3");
assertTrue(EQ(getDynArr(dyn, 1), 4), "Test 2nd element == 4");
assertTrue(EQ(getDynArr(dyn, 2), 10), "Test 3rd element == 10");
assertTrue(EQ(getDynArr(dyn, 3), 5), "Test 4th element == 5");
assertTrue(EQ(getDynArr(dyn, 4), 6), "Test 5th element == 6");
assertTrue(sizeDynArr(dyn) == 5, "Test size = 5");
printf("\n\nTesting putDynArr...\nCalling putDynArr(dyn, 2, 7)\n");
putDynArr(dyn, 2, 7);
printf("The array's content: [3,4,7,5,6]\n");
assertTrue(EQ(getDynArr(dyn, 2), 7), "Test 3rd element == 7");
assertTrue(sizeDynArr(dyn) == 5, "Test size = 5");
printf("\n\nTesting swapDynArr...\nCalling swapDynArr(dyn, 2, 4)\n");
swapDynArr(dyn, 2, 4);
printf("The array's content: [3,4,6,5,7]\n");
assertTrue(EQ(getDynArr(dyn, 2), 6), "Test 3rd element == 6");
assertTrue(EQ(getDynArr(dyn, 4), 7), "Test 5th element == 7");
printf("\n\nTesting removeAtDynArr...\nCalling removeAtDynArr(dyn, 1)\n");
removeAtDynArr(dyn, 1);
printf("The array's content: [3,6,5,7]\n");
assertTrue(EQ(getDynArr(dyn, 0), 3), "Test 1st element == 3");
assertTrue(EQ(getDynArr(dyn, 3), 7), "Test 4th element == 7");
assertTrue(sizeDynArr(dyn) == 4, "Test size = 4");
printf("\n\nTesting stack interface...\n");
printf("The stack's content: [3,6,5,7] <- top\n");
assertTrue(!isEmptyDynArr(dyn), "Testing isEmptyDynArr");
assertTrue(EQ(topDynArr(dyn), 7), "Test topDynArr == 7");
popDynArr(dyn);
printf("Poping...\nThe stack's content: [3,6,5] <- top\n");
assertTrue(EQ(topDynArr(dyn), 5), "Test topDynArr == 5");
pushDynArr(dyn, 9);
printf("Pushing 9...\nThe stack's content: [3,6,5,9] <- top\n");
assertTrue(EQ(topDynArr(dyn), 9), "Test topDynArr == 9");
printf("\n\nTesting bag interface...\n");
printf("The bag's content: [3,6,5,9]\n");
assertTrue(containsDynArr(dyn, 3), "Test containing 3");
assertTrue(containsDynArr(dyn, 6), "Test containing 6");
assertTrue(containsDynArr(dyn, 5), "Test containing 5");
assertTrue(containsDynArr(dyn, 9), "Test containing 9");
assertTrue(!containsDynArr(dyn, 7), "Test not containing 7");
removeDynArr(dyn, 3);
printf("Removing 3...\nThe stack's content: [6,5,9]\n");
assertTrue(!containsDynArr(dyn, 3), "Test not containing 3");
deleteDynArr(dyn);
return 0;
}
|
#!/bin/env python
import os
import sys
import pandas as pd
import sqlite3
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
CONN = create_connection('./db/finance.db')
BT = create_connection('./db/backtest.db')
file=open('list.txt', 'r')
ALL=file.read()
lines = ALL.split('\n')
for line in lines:
DF = pd.read_sql('select Symbol, Name from KRX where Symbol like \"' + line +'\" union select Symbol, Name from ETF_KR where Symbol like \"' + line + '\"', con = CONN)
print (DF)
# print (line)
CONN.close()
BT.close()
|
'''
setup.py - a setup script
Author: Xinyu Wang
'''
from setuptools import setup, find_packages
import os
import sys
# import BGP_Forecast_Modules
try:
setup(
name='BGP_Forecast_Modules',
version='BGP_Forecast_Modules',
author='Xinyu Wang',
author_email='xinyuwang1209@gmail.com',
description = ("BGP Forecast Project."),
url='https://github.com/xinyuwang1209/BGP_Forecast_Modules.git',
platforms = 'any',
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3'
],
keywords=['Xinyu, xinyu, pypi, package, rpki'],
packages=find_packages(include=['BGP_Forecast_Modules', 'BGP_Forecast_Modules.*']),
package_data = {
'BGP_Forecast_Modules': ['config.ini']
},
# install_requires=[
# 'ipaddress',
# 'numpy',
# 'pandas',
# 'pathos',
# 'pause',
# 'psycopg2',
# 'python-daemon',
# 'requests',
# 'sqlalchemy'
# ],
)
finally:
pass
|
import React from "react";
import "./style.css";
function Jumbotron({ children }) {
return (
<div className="jumbotron d-flex align-items-center">
<div className="container text-center">
{children}
</div>
</div>
);
}
export default Jumbotron;
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=19
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
class Opty(cirq.PointOptimizer):
def optimization_at(
self,
circuit: 'cirq.Circuit',
index: int,
op: 'cirq.Operation'
) -> Optional[cirq.PointOptimizationSummary]:
if (isinstance(op, cirq.ops.GateOperation) and isinstance(op.gate, cirq.CZPowGate)):
return cirq.PointOptimizationSummary(
clear_span=1,
clear_qubits=op.qubits,
new_operations=[
cirq.CZ(*op.qubits),
cirq.X.on_each(*op.qubits),
cirq.X.on_each(*op.qubits),
]
)
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[1])) # number=7
c.append(cirq.rx(-1.6619025137490007).on(input_qubit[2])) # number=15
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5
c.append(cirq.rx(-0.0785398163397449).on(input_qubit[2])) # number=16
c.append(cirq.H.on(input_qubit[0])) # number=12
c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=13
c.append(cirq.H.on(input_qubit[0])) # number=14
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11
c.append(cirq.Y.on(input_qubit[1])) # number=17
c.append(cirq.Y.on(input_qubit[1])) # number=18
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2940
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq_pragma758.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close()
|
import React from "react";
import Dialog from "@material-ui/core/Dialog";
import FileCopyOutlinedIcon from "@material-ui/icons/FileCopyOutlined";
import Tooltip from "@material-ui/core/Tooltip";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DoneIcon from "@material-ui/icons/Done";
import DialogTitle from "@material-ui/core/DialogTitle";
import { Button } from "@material-ui/core";
import Slide from "@material-ui/core/Slide";
import { makeStyles } from '@material-ui/core/styles'
const Transition = React.forwardRef(function Transition(props, ref) {
return <Slide direction="up" ref={ref} {...props} />;
});
const useStyles = makeStyles(theme => ({
submitBtn: {
background: '#1DBF73!important',
color: '#fff',
paddingLeft: '1rem',
paddingRight: '1rem',
display: 'inlin-flex',
alignItems: 'center',
minWidth: 130,
'& svg': {
fontSize: '19px',
marginRight: '5px'
},
'@media only screen and (max-width: 575px)': {
fontSize: '12px',
paddingLeft: '.5rem',
paddingRight: '.5rem',
minWidth: 70,
}
},
}));
export default function SnInfoModal({ open, onClose, type, title, content, showClipboardCopy = false, clipboardCopyTooltip, ...props }) {
// class SnInfoModal extends React.Component {
const classes = useStyles();
const displayContent = () => {
switch (type) {
case 'public-share':
return (
<DialogContent>
<DialogContentText id="alert-dialog-description">
Skylinks are available at the following public link :
</DialogContentText>
<DialogContentText>
<>
{content}<Tooltip title="Copy Skylink to clipboard" arrow>
<FileCopyOutlinedIcon
onClick={() => navigator.clipboard.writeText(content)}
className="cursor-pointer"
style={{ paddingLeft: 5 }}
/>
</Tooltip>
</>
</DialogContentText>
</DialogContent>
);
default:
return (
<DialogContent>
<DialogContentText id="alert-dialog-description">
{content}{showClipboardCopy && (
<Tooltip title={clipboardCopyTooltip || "Copy To Clipboard"} arrow>
<FileCopyOutlinedIcon
onClick={() => navigator.clipboard.writeText(content)}
className="cursor-pointer"
style={{ paddingLeft: 5 }}
/>
</Tooltip>)}
</DialogContentText>
</DialogContent>
);
}
}
return (
<Dialog
open={open}
onClose={onClose}
TransitionComponent={Transition}
keepMounted
maxWidth="lg"
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{title}</DialogTitle>
{displayContent()}
<DialogActions>
<Button
onClick={onClose}
autoFocus
variant="contained"
className={classes.submitBtn}
startIcon={<DoneIcon />}
>
OK
</Button>
</DialogActions>
</Dialog>
);
};
|
'use strict';
var express = require('express');
var controller = require('./user.controller');
var config = require('../../config/environment');
var auth = require('../../auth/auth.service');
var router = express.Router();
/**
* @apiDefine UserNotAuthorized
*
* @apiError User not authenticated
*
* @apiErrorExample Error-Response:
* HTTP/1.1 401 Unauthorized
* UnauthorizedError
*/
/**
* @apiDefine ApiParamsUser
*
*
* @apiParam {String} name Pseudo of the user
* @apiParam {String} email Email of the user
* @apiParam {String} role Role of the user
* @apiParam {String} hashedPassword Hashed Password
* @apiParam {String} provider Provider
* @apiParam {String} salt Password Salt
* @apiParam {String} fname First name of the user
* @apiParam {String} phone Phone number of the user
* @apiParam {Date} birthday Birthday date
* @apiParam {String} address Address - Place
* @apiParam {Number} zipcode Zip Code City
* @apiParam {String} city City Name
* @apiParam {String} country Country
* @apiParam {String} picture File id of the avatar's user
* @apiParam {Collection} facebook Facebook linked to the account
* @apiParam {Collection} twitter Twitter linked to the account
* @apiParam {Collection} google Google linked to the account
* @apiParam {Collection} github GitHub linked to the account
*/
/**
* @api {get} /api/users Get all users
* @apiVersion 0.0.0
* @apiName GetUsers
* @apiGroup Users
*
* @apiSuccess {Array} array of users
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* [
* {
* },...
* ]
*
* @apiUse UserNotAuthorized
*/
router.get('/', auth.hasRole('admin'), controller.index);
/**
* @api {delete} /api/users/:id Delete a user
* @apiName DeleteUser
* @apiGroup Users
*
* @apiParam {Number} id Id of the User you want to delete
*
* @apiSuccess {Object} Object response
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 204 No Content:
* {
* }
*
*/
router.delete('/:id', auth.hasRole('admin'), controller.destroy);
/**
* @api {get} /api/users/me Get current user connected
* @apiVersion 0.0.0
* @apiName GetCurrentUser
* @apiGroup Users
*
* @apiSuccess {User} current user
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* [
* {
* },...
* ]
*
* @apiUse UserNotAuthorized
*/
router.get('/me', auth.isAuthenticated(), controller.me);
/**
* @api {get} /api/users/roles Get roles that this user can assign
* @apiVersion 0.0.0
* @apiName GetRoles
* @apiGroup Users
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* roles: ['guest','user','admin']
* }
*
* @apiUse UserNotAuthorized
*/
router.get('/roles', auth.hasRole('admin'), controller.getRoles);
/**
* @api {put} /api/users/:id/password Change Password
* @apiName PutChangePassWord
* @apiGroup Users
*
* @apiParam {Number} id User Id you want to change password
*
* @apiSuccess {User} Modified User
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 Success-Response:
* [
* ...
* ]
*
*
*/
router.put('/:id/password', auth.isAuthenticated(), controller.changePassword);
/**
* @api {put} /api/users/prefdestination/:id Add a prefered Destination
* @apiName PutPreferedDestination
* @apiGroup Users
*
* @apiParam {Object} preferedDests List Of String of Prefered Destinations
* @apiParam {Number} id User Id you want to add a prefered destination
*
* @apiSuccess {User} code
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 Success-Response:
* [
* ...
* ]
*
*
*/
router.put('/prefdestination/:id', auth.isAuthenticated(), controller.addPreferedDestination);
/**
* @api {put} /api/users/:id Substitute a user
* @apiName SubstituteUser
* @apiGroup Users
*
* @apiUse ApiParamsUser
*
* @apiSuccess {User} Modified User
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 201 Created:
* {
* ...
* }
*
*/
router.put('/:id', auth.isAuthenticated(), controller.update);
/**
* @api {get} /api/users/:id Get By Id
* @apiVersion 0.0.0
* @apiName GetUsersById
* @apiGroup Users
*
* @apiParam {Number} id Id of the target user
*
* @apiSuccess {User} User
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "__v": 0,
* ...
* "_id": "564cf500bbb31f62475efc31"
* }
* ]
*
* @apiUse UserNotAuthorized
*/
router.get('/:id', auth.isAuthenticated(), controller.show);
/**
* @api {put} /api/users/update/automatic/visited/countries/:id Get User's visited countries
* @apiVersion 0.0.0
* @apiName GetUsersVisitedCountries
* @apiGroup Users
*
* @apiParam {Number} id Id of the target user
*
* @apiSuccess {User} User
*
*
* @apiUse UserNotAuthorized
*/
router.put('/update/automatic/visited/countries/:id', auth.isAuthenticated(), controller.putAutomaticUpdateVisetedCountries);
/**
* @api {put} /api/users/update/visited/countries/:id Get User's visited countries
* @apiVersion 0.0.0
* @apiName GetUsersVisitedCountries
* @apiGroup Users
*
* @apiParam {Number} id Id of the target user
*
* @apiSuccess {User} User
*
*
* @apiUse UserNotAuthorized
*/
router.put('/update/visited/countries/:id', auth.isAuthenticated(), controller.putUpdateVisetedCountries);
/**
* @api {get} /api/users/search/:search Search users matching search params
* @apiVersion 0.0.0
* @apiName Search users by name
* @apiGroup Users
*
* @apiParam {string} search name of the user
*
* @apiSuccess {User} User
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* status: 200,
* data:
* [
* {
* "__v": 0,
* ...
* "_id": "564cf500bbb31f62475efc31"
* }
* ]
* }
*
* @apiUse UserNotAuthorized
*/
router.get('/search/:search', auth.isAuthenticated(), controller.search);
/**
* @api {post} /api/users Insert a User
* @apiName InsertUser
* @apiGroup Users
*
* @apiUse ApiParamsUser
*
* @apiSuccess {Object} Object response
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 201 Created:
* {
* "ok":1,
* "nModified":0,
* "upserted":[
* {
* "index":0,
* "_id":"34347838758deb5"
* }
* ]
* }
*
*/
router.post('/', controller.create);
/**
* @api {put} /api/users/:id/:role Update User role
* @apiName UpdateRole
* @apiGroup Users
*
*
* @apiSuccess {Object} Object response
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 201 Created:
* {
* "ok":1
* }
*
*/
router.put('/:id/:role', auth.hasRole('admin'), controller.changeRole);
module.exports = router;
|
export { default as default } from './modules/ReactTimeAgo.js'
|
const { readFile } = require( 'fs' ).promises;
const { resolve: resolvePath } = require( 'path' );
const { ESLint } = require( 'eslint' );
const defaultConfig = require( '../index' );
describe( 'eslint-config', () => {
const fixturesPath = resolvePath( __dirname, '__fixtures__' );
it( 'fails on incorrect code', createTest( {
fixturePath: resolvePath( fixturesPath, 'invalid.js' ),
errorCount: 1
} ) );
it( 'passes on correct code', createTest( {
fixturePath: resolvePath( fixturesPath, 'valid.js' )
} ) );
// #21
it( 'allows space after async keyword in arrow functions', createTest( {
fixturePath: resolvePath( fixturesPath, 'asyncArrow.js' )
} ) );
// #23
it( 'disallows console usage', createTest( {
fixturePath: resolvePath( fixturesPath, 'console.js' ),
errorCount: 4
} ) );
// #32
it( 'disallows test environment globals in source files', createTest( {
fixturePath: resolvePath( fixturesPath, 'testGlobals.js' ),
fakePath: 'src/myTests.js',
errorCount: 5
} ) );
// #32
it( 'allows test environment globals in test files', createTest( {
fixturePath: resolvePath( fixturesPath, 'testGlobals.js' ),
fakePath: 'tests/myTests.js',
errorCount: 0
} ) );
// #37
it( 'allows async functions without await', createTest( {
fixturePath: resolvePath( fixturesPath, 'asyncNoAwait.js' ),
errorCount: 0
} ) );
// #37
it( 'allows generators without yield', createTest( {
fixturePath: resolvePath( fixturesPath, 'generatorNoYield.js' ),
errorCount: 0
} ) );
// #38
it( 'parses ES2021 code', createTest( {
fixturePath: resolvePath( fixturesPath, 'es2021.js' ),
errorCount: 0
} ) );
} );
function createTest( {
fixturePath,
config = defaultConfig,
fakePath = fixturePath,
errorCount = 0
} = {} ) {
return async () => {
const [ results ] = await lintFile( fixturePath, config, fakePath );
expect( results.errorCount ).to.equal( errorCount );
};
}
async function lintFile( path, config, fakePath = path ) {
const code = await readFile( path, 'utf8' );
const eslint = new ESLint( {
useEslintrc: false,
baseConfig: config
} );
const report = await eslint.lintText( code, {
filePath: fakePath
} );
return report;
}
|
#
# Collective Knowledge (platform - GPGPU)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (temporal data)
ck=None # Will be updated by CK (initialized CK kernel)
# Local settings
##############################################################################
# Initialize module
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':0}
##############################################################################
# Detect GPGPU
def detect(i):
"""
Input: {
(target) - if specified, use info from 'machine' module
(host_os) - host OS (detect, if omitted)
(os) or (target_os) - OS module to check (if omitted, analyze host)
(device_id) - device id if remote (such as adb)
(skip_device_init) - if 'yes', do not initialize device
(print_device_info) - if 'yes', print extra device info
(skip_info_collection) - if 'yes', do not collect info (particularly for remote)
(skip_print_os_info) - if 'yes', do not print OS info
(exchange) - if 'yes', exchange info with some repo (by default, remote-ck)
(share) - the same as 'exchange'
(exchange_repo) - which repo to record/update info (remote-ck by default)
(exchange_subrepo) - if remote, remote repo UOA
(exchange_locally) - if 'yes', exchange locally
(extra_info) - extra info about author, etc (see add from CK kernel)
(type) - cuda or opencl
(quiet) - select default dependencies
(select) - if 'yes', select specific platform and device (only when one type, i.e. opencl or cuda)
(deps) - pre-set dependencies when used inside 'program' module (to reuse already selected compilers and libs)
(compute_platform_id) - pre-select platform ID
(compute_device_id) - pre-select device ID
(sudo) - force SUDO use ...
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
features = [
{
gpgpu - GPGPU features (properties), unified
gpgpu_misc - assorted GPGPU features (properties), platform dependent
gpgpu_id - local ID {'gpgpu_platform_id', 'gpgpu_device_id'}
}
]
choices = {
(compute_platform_id)
(compute_device_id)
}
}
"""
import os
import copy
o=i.get('out','')
oo=''
if o=='con': oo=o
try:
pcur=os.getcwd()
except OSError:
os.chdir('..')
pcur=os.getcwd()
quiet=i.get('quiet','')
# Check if target
if i.get('target','')!='':
r=ck.access({'action':'init',
'module_uoa':cfg['module_deps']['machine'],
'input':i})
if r['return']>0: return r
device_cfg=i.get('device_cfg',{})
# Various params
hos=i.get('host_os','')
tos=i.get('target_os','')
if tos=='': tos=i.get('os','')
tdid=i.get('device_id','')
sic=i.get('skip_info_collection','')
sdi=i.get('skip_device_init','')
pdv=i.get('print_device_info','')
ex=i.get('exchange','')
if ex=='': ex=i.get('share','')
einf=i.get('extra_info','')
if einf=='': einf={}
# Get OS info
ii=copy.deepcopy(i)
ii['out']=oo
if i.get('skip_print_os_info','')=='yes': ii['out']=''
ii['action']='detect'
ii['module_uoa']=cfg['module_deps']['platform.cpu']
rr=ck.access(ii) # DO NOT USE rr further - will be reused as return !
if rr['return']>0: return rr
hos=rr['host_os_uid']
hosx=rr['host_os_uoa']
hosd=rr['host_os_dict']
tos=rr['os_uid']
tosx=rr['os_uoa']
tosd=rr['os_dict']
tosd.update(device_cfg.get('update_target_os_dict',{}))
tbits=tosd.get('bits','')
tdid=rr['device_id']
remote=tosd.get('remote','')
# Some params
ro=tosd.get('redirect_stdout','')
remote=tosd.get('remote','')
win=tosd.get('windows_base','')
stdirs=tosd.get('dir_sep','')
dv=''
if tdid!='': dv=' -s '+tdid
props=[]
fuid=''
fuoa=''
# Check if program to get CUDA device exists
types=['cuda','opencl']
tp=i.get('type','')
if tp=='':
if i.get('opencl','')=='yes': tp='opencl'
elif i.get('cuda','')=='yes': tp='cuda'
tpo=tp # to quit later if a specific type needs to be detected but env doesn't exist in the CK
if tp!='': types=[tp]
for tp in types:
prop={}
prop_id={}
prop_all={}
deps={}
if o=='con':
ck.out('************************************************')
ck.out('Detecting GPGPU type: '+tp)
ck.out('')
tags=cfg['tool_tags'][tp]
# Get tool env
ii={'action':'set',
'module_uoa':cfg['module_deps']['env'],
'host_os':hos,
'target_os':tos,
'device_id':tdid,
"skip_default": "yes",
'tags':tags,
'out':oo}
r=ck.access(ii)
if r['return']>0:
# Fail only if a given type (CUDA/OpenCL) is specified, otherwise continue!
if tpo=='': continue
return r
env=r['env']
deps=r['dict']['deps']
# Try to run program
rx=ck.gen_tmp_file({'prefix':'tmp-', 'suffix':'.tmp'})
if rx['return']>0: return rx
ftmp=rx['file_name']
pf=env[cfg['tool_env_key'][tp]]
if remote=='yes':
dv=''
if tdid!='': dv=' -s '+tdid
remote_init=tosd.get('remote_init','').replace('$#device#$',dv)
remote_push=tosd.get('remote_push','').replace('$#device#$',dv)
remote_shell=tosd.get('remote_shell','').replace('$#device#$',dv)
remote_dir=tosd.get('remote_dir','')
os.system(remote_init)
target_exe=os.path.basename(pf)
pff=remote_dir+'/'+target_exe
s=remote_push.replace('$#file1#$',pf).replace('$#file2#$',pff)
os.system(s)
s=remote_shell+' '+tosd.get('set_executable','')+' '+pff
os.system(s)
s=remote_shell+' '+pff
else:
s=r['bat'].rstrip('\n')+' '+hosd.get('env_separator','')+' '+pf
if tosd.get('use_bash_to_run','')!='':
s=tosd['use_bash_to_run'].replace('$#cmd#$', s)
s+=' > '+ftmp
if i.get('sudo','')=='yes':
s=hosd.get('sudo_pre','')+s
os.system(s)
er=i.get('exchange_repo','')
esr=i.get('exchange_subrepo','')
el=i.get('exchange_locally','')
if el!='yes' and er=='':
er=ck.cfg['default_exchange_repo_uoa']
esr=ck.cfg['default_exchange_subrepo_uoa']
xn=prop.get('name','')
r=ck.load_text_file({'text_file':ftmp, 'split_to_list':'yes', 'delete_after_read':'yes'})
if r['return']==0:
ll=r['lst']
for l in ll:
if l=='':
# Process if features are not empty
if len(prop_id)>0:
fuoa=''
fuid=''
# Exchanging info #################################################################
if ex=='yes':
if o=='con':
ck.out('')
ck.out('Exchanging information with '+er+' repository ...')
ii={'action':'exchange',
'module_uoa':cfg['module_deps']['platform'],
'sub_module_uoa':work['self_module_uid'],
'repo_uoa':er,
'data_name':prop.get('name',''),
'extra_info':einf,
'all':'yes',
'dict':{'features':prop, 'features_misc':prop_all}}
if esr!='': ii['remote_repo_uoa']=esr
r=ck.access(ii)
if r['return']>0: return r
fuoa=r.get('data_uoa','')
fuid=r.get('data_uid','')
prop=r['dict'].get('features',{})
prop_all=r['dict'].get('features_misc',{})
if o=='con' and r.get('found','')=='yes':
ck.out(' GPGPU CK entry already exists ('+fuid+') - loading latest meta (features) ...')
if tp=='cuda':
cc=prop_all.get('gpu compute capability','')
cc1=''
cc2=''
cc3=''
if cc=='1.0':
cc1='compute_10'
cc2='sm_10'
cc3='Tesla'
elif cc=='1.1':
cc1='compute_11'
cc2='sm_11'
cc3='Tesla'
elif cc=='1.2':
cc1='compute_12'
cc2='sm_12'
cc3='Tesla'
elif cc=='1.3':
cc1='compute_13'
cc2='sm_13'
cc3='Tesla'
elif cc=='2.0':
cc1='compute_20'
cc2='sm_20'
cc3='Fermi'
elif cc=='2.1':
cc1='compute_20'
cc2='sm_21'
cc3='Fermi'
elif cc=='3.0':
cc1='compute_30'
cc2='sm_30'
cc3='Kepler'
elif cc=='3.2':
cc1='compute_32'
cc2='sm_32'
cc3='Kepler'
elif cc=='3.5':
cc1='compute_35'
cc2='sm_35'
cc3='Kepler'
elif cc=='3.7':
cc1='compute_37'
cc2='sm_37'
cc3='Kepler'
elif cc=='5.0':
cc1='compute_50'
cc2='sm_50'
cc3='Maxwell'
elif cc=='5.2':
cc1='compute_52'
cc2='sm_52'
cc3='Maxwell'
elif cc=='5.3':
cc1='compute_53'
cc2='sm_53'
cc3='Maxwell'
elif cc=='6.0':
cc1='compute_60'
cc2='sm_60'
cc3='Pascal'
elif cc=='6.1':
cc1='compute_61'
cc2='sm_61'
cc3='Pascal'
elif cc=='6.2':
cc1='compute_62'
cc2='sm_62'
cc3='Pascal'
elif cc=='7.0':
cc1='compute_70'
cc2='sm_70'
cc3='Volta'
elif cc=='7.1':
cc1='compute_71'
cc2='sm_71'
cc3='Volta'
elif cc=='7.5':
cc1='compute_75'
cc2='sm_75'
cc3='Tesla'
elif cc=='8.0':
cc1='compute_80'
cc2='sm_80'
cc3='Ampere'
elif cc=='8.6':
cc1='compute_86'
cc2='sm_86'
cc3='Ampere'
else:
return {'return':1, 'error':'Compute capability of your CUDA device is not recognized ('+cc+') - please report at https://github.com/mlcommons/ck/issues or update module:platform.gpgpu'}
prop_all['compute_capability1']=cc1
prop_all['compute_capability2']=cc2
prop_all['compute_capability3']=cc3
prop['microarchitecture']=cc3
jj={"gpgpu":prop, "gpgpu_id":prop_id, "gpgpu_misc":prop_all}
if fuoa!='' or fuid!='':
jj['gpgpu_uoa']=fuoa
jj['gpgpu_misc_uid']=fuid
# Print without deps if needed
if o=='con':
ck.out('')
ck.out('Features (properties) in JSON:')
r=ck.dumps_json({'dict':jj})
if r['return']>0: return r
s=r['string']
ck.out('')
ck.out(s)
jj['gpgpu_deps']=deps
props.append(jj)
# Refresh
prop={}
prop_id={}
prop_all={}
# Process features
lx=[]
if l!='':
lx=l.split(':')
if len(lx)>1:
k=lx[0].strip().lower()
v=lx[1].strip()
if tp=='cuda':
if k=='gpu device id':
prop_id['gpgpu_device_id']=v
elif k=='gpu name':
prop['name']=v
prop['type']=tp
else:
prop_all[k]=v
else:
if k=='platform id':
prop_id['gpgpu_platform_id']=v
elif k=='device id':
prop_id['gpgpu_device_id']=v
elif k=='device':
prop['name']=v
prop['type']=tp
elif k=='vendor':
prop['vendor']=v
else:
prop_all[k]=v
# Check if need to select device and platform
rr={'return':0, 'features':{'gpgpu':props}}
if len(props)==0 and o=='con':
ck.out('')
ck.out('WARNING: no CK-enabled GPGPU devices found ...')
if i.get('select','')=='yes' and tp!='':
# Get Cartesian product of devies and platforms
platform_ids=[]
device_ids=[]
targets=[]
choices=[]
# Check if pre-selected
p_id=i.get('compute_platform_id','')
d_id=i.get('compute_device_id','')
for p in props:
xp_id=p.get('gpgpu_id',{}).get('gpgpu_platform_id','')
xd_id=p.get('gpgpu_id',{}).get('gpgpu_device_id','')
if xp_id!='' and xp_id not in platform_ids:
platform_ids.append(xp_id)
if xd_id!='' and xd_id not in device_ids:
device_ids.append(xd_id)
if (p_id=='' or p_id==xp_id) and (d_id=='' or d_id==xd_id):
targets.append(p)
s=p.get('gpgpu',{}).get('name','')
x=p.get('gpgpu_misc',{}).get('parallel compute units','')
if x!='':
s+=' ; '+x+' compute units '
x=p.get('gpgpu_misc',{}).get('hardware (device) version','')
if x!='':
s+=' ; '+x
choices.append(s)
# Check what to select
if len(choices)==0:
return {'return':1, 'error':'can\'t find GPGPU target with specified IDs'}
elif len(choices)==1 or quiet=='yes' or o!='con':
ch=0
else:
ck.out('')
ck.out('Multiple GPGPU targets available:')
ck.out('')
r=ck.access({'action':'select_list',
'module_uoa':cfg['module_deps']['choice'],
'choices':choices})
if r['return']>0: return r
ch=r['position']
ich=int(ch)
p_id=targets[ich].get('gpgpu_id',{}).get('gpgpu_platform_id','')
d_id=targets[ich].get('gpgpu_id',{}).get('gpgpu_device_id','')
if o=='con':
ck.out('')
ck.out('Selected GPGPU target: '+choices[ich])
rr['choices']={'compute_number':ich}
if p_id!='':
rr['choices']['compute_platform_id']=p_id
if d_id!='':
rr['choices']['compute_device_id']=d_id
os.chdir(pcur)
return rr
##############################################################################
# viewing entries as html
def show(i):
"""
Input: {
data_uoa
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
html - generated HTML
}
"""
h='<h2>GPGPUs (CUDA/OpenCL) participating in crowd-tuning</h2>\n'
h+='<i>Reuse/extend <a href="https://github.com/ctuning/ck-crowdtuning-platforms/tree/master/platform.gpgpu">CK JSON meta information</a> of these GPGPU accelerators using "ck pull repo:ck-crowdtuning-platforms" ...</i><br><br>\n'
h+='<table class="ck_table" border="0" cellpadding="6" cellspacing="0">\n'
# Check host URL prefix and default module/action
rx=ck.access({'action':'form_url_prefix',
'module_uoa':'wfe',
'host':i.get('host',''),
'port':i.get('port',''),
'template':i.get('template','')})
if rx['return']>0: return rx
url0=rx['url']
h+=' <tr style="background-color:#cfcfff;">\n'
h+=' <td><b>\n'
h+=' #\n'
h+=' </b></td>\n'
h+=' <td><b>\n'
h+=' Vendor\n'
h+=' </b></td>\n'
h+=' <td><b>\n'
h+=' Name\n'
h+=' </b></td>\n'
h+=' <td><b>\n'
h+=' Type\n'
h+=' </b></td>\n'
h+=' <td><b>\n'
h+=' <a href="'+url0+'wcid='+work['self_module_uoa']+':">CK UID</a>\n'
h+=' </b></td>\n'
h+=' </tr>\n'
ruoa=i.get('repo_uoa','')
muoa=work['self_module_uoa']
duoa=i.get('data_uoa','')
r=ck.access({'action':'search',
'module_uoa':muoa,
'data_uoa':duoa,
'repo_uoa':ruoa,
'add_info':'yes',
'add_meta':'yes'})
if r['return']>0:
return {'return':0, 'html':'Error: '+r['error']}
lst=r['lst']
num=0
for q in sorted(lst, key = lambda x: (x.get('meta',{}).get('features',{}).get('vendor','').upper(), \
x.get('meta',{}).get('features',{}).get('name','').upper())):
num+=1
duoa=q['data_uoa']
duid=q['data_uid']
meta=q['meta']
ft=meta.get('features',{})
name=ft.get('name','')
vendor=ft.get('vendor','')
tp=ft.get('type','')
h+=' <tr>\n'
h+=' <td valign="top">\n'
h+=' '+str(num)+'\n'
h+=' </td>\n'
h+=' <td valign="top">\n'
h+=' '+vendor+'\n'
h+=' </td>\n'
h+=' <td valign="top">\n'
h+=' '+name+'\n'
h+=' </td>\n'
h+=' <td valign="top">\n'
h+=' '+tp+'\n'
h+=' </td>\n'
h+=' <td valign="top">\n'
h+=' <a href="'+url0+'wcid='+work['self_module_uoa']+':'+duid+'">'+duid+'</a>\n'
h+=' </td>\n'
h+=' </tr>\n'
h+='</table><br><br>\n'
return {'return':0, 'html':h}
|
from programs.schema.attributes.abstractattribute import AbstractAttribute
from constants import CC
class RelGQAttr(AbstractAttribute):
@staticmethod
def getName():
return CC.ATTR_RELGQ
@staticmethod
def getLevels():
return {
"Householder living alone" : [0],
"Householder not living alone" : [1],
"Opposite-sex spouse" : [2],
"Opposite-sex unmarried partner" : [3],
"Same-sex spouse (Use allocation flag to determine)" : [4],
"Same-sex unmarried partner" : [5],
"Biological son or daughter" : [6],
"Adopted son or daughter" : [7],
"Stepson or stepdaughter" : [8],
"Brother or sister" : [9],
"Father or mother" : [10],
"Grandchild" : [11],
"Parent-in-law" : [12],
"Son-in-law or daughter-in-law" : [13],
"Other relative" : [14],
"Roommate or housemate" : [15],
"Foster child (If roomer/boarder and age<21)" : [16],
"Other nonrelative (also include if roomer/boarder and age>=21)" : [17],
"GQ 101 Federal detention centers" : [18],
"GQ 102 Federal prisons" : [19],
"GQ 103 State prisons" : [20],
"GQ 104 Local jails and other municipal confinements" : [21],
"GQ 105 Correctional residential facilities" : [22],
"GQ 106 Military disciplinary barracks" : [23],
"GQ 201 Group homes for juveniles" : [24],
"GQ 202 Residential treatment centers for juveniles" : [25],
"GQ 203 Correctional facilities intended for juveniles" : [26],
"GQ 301 Nursing facilities" : [27],
"GQ 401 Mental hospitals" : [28],
"GQ 402 Hospitals with patients who have no usual home elsewhere" : [29],
"GQ 403 In-patient hospice facilities" : [30],
"GQ 404 Military treatment facilities" : [31],
"GQ 405 Residential schools for people with disabilities" : [32],
"GQ 501 College/university student housing" : [33],
"GQ 601 Military quarters" : [34],
"GQ 602 Military ships" : [35],
"GQ 701 Emergency and transitional shelters" : [36],
"GQ 801 Group homes intended for adults" : [37],
"GQ 802 Residential treatment centers for adults" : [38],
"GQ 900 Maritime/merchant vessels" : [39],
"GQ 901 Workers' group living quarters and job corps centers" : [40],
"GQ 997 Other noninstitutional (GQ types 702, 704, 706, 903, 904)": [41]
}
@staticmethod
def recodegqhh():
name = CC.HHGQ_GQLEVELS
reldict = RelGQAttr.getLevels()
groupings = dict([("Household", list(range(0, 18)))])
groupings.update({k: v for k, v in reldict.items() if v[0] >= 18})
return name, groupings
# @staticmethod
# def recodeRELGQ_hhgq_gqExpanded():
# """
# Query for collapsing the relationship to householder levels to "Householder" and
# keeping all GQ levels expanded
# """
# name = "hhgq_gqExpanded"
# groups = {
# "Householder" : list(range(0,18)),
# "GQ 101 Federal detention centers" : [18],
# "GQ 102 Federal prisons" : [19],
# "GQ 103 State prisons" : [20],
# "GQ 104 Local jails and other municipal confinements" : [21],
# "GQ 105 Correctional residential facilities" : [22],
# "GQ 106 Military disciplinary barracks" : [23],
# "GQ 201 Group homes for juveniles" : [24],
# "GQ 202 Residential treatment centers for juveniles" : [25],
# "GQ 203 Correctional facilities intended for juveniles" : [26],
# "GQ 301 Nursing facilities" : [27],
# "GQ 401 Mental hospitals" : [28],
# "GQ 402 Hospitals with patients who have no usual home elsewhere" : [29],
# "GQ 403 In-patient hospice facilities" : [30],
# "GQ 404 Military treatment facilities" : [31],
# "GQ 405 Residential schools for people with disabilities" : [32],
# "GQ 501 College/university student housing" : [33],
# "GQ 601 Military quarters" : [34],
# "GQ 602 Military ships" : [35],
# "GQ 701 Emergency and transitional shelters" : [36],
# "GQ 801 Group homes intended for adults" : [37],
# "GQ 802 Residential treatment centers for adults" : [38],
# "GQ 900 Maritime/merchant vessels" : [39],
# "GQ 901 Workers' group living quarters and job corps centers" : [40],
# "GQ 997 Other noninstitutional (GQ types 702, 704, 706, 903, 904)": [41]
# }
# return name, groups
@staticmethod
def recodeRELGQ_relgq0():
"""
Query for calculating the total of the 'Householder living alone' population
"""
name = 'relgq0'
groups = {
"Householder living alone Population Total": [0]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq1():
"""
Query for calculating the total of the 'Householder not living alone' population
"""
name = 'relgq1'
groups = {
"Householder not living alone Population Total": [1]
}
return name, groups
@staticmethod
def recodeRELGQ_householders():
"""
Query for calculating the total number of householders
"""
name = 'householders'
groups = {
"Householders living alone or not alone": [0, 1]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq2():
"""
Query for calculating the total of the 'Opposite-sex spouse' population
"""
name = 'relgq2'
groups = {
"Opposite-sex spouse Population Total": [2]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq3():
"""
Query for calculating the total of the 'Opposite-sex unmarried partner' population
"""
name = 'relgq3'
groups = {
"Opposite-sex unmarried partner Population Total": [3]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq4():
"""
Query for calculating the total of the 'Same-sex spouse (Use allocation flag to determine)' population
"""
name = 'relgq4'
groups = {
"Same-sex spouse (Use allocation flag to determine) Population Total": [4]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq5():
"""
Query for calculating the total of the 'Same-sex unmarried partner' population
"""
name = 'relgq5'
groups = {
"Same-sex unmarried partner Population Total": [5]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq6():
"""
Query for calculating the total of the 'Biological son or daughter' population
"""
name = 'relgq6'
groups = {
"Biological son or daughter Population Total": [6]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq7():
"""
Query for calculating the total of the 'Adopted son or daughter' population
"""
name = 'relgq7'
groups = {
"Adopted son or daughter Population Total": [7]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq8():
"""
Query for calculating the total of the 'Stepson or stepdaughter' population
"""
name = 'relgq8'
groups = {
"Stepson or stepdaughter Population Total": [8]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq9():
"""
Query for calculating the total of the 'Brother or sister' population
"""
name = 'relgq9'
groups = {
"Brother or sister Population Total": [9]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq10():
"""
Query for calculating the total of the 'Father or mother' population
"""
name = 'relgq10'
groups = {
"Father or mother Population Total": [10]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq11():
"""
Query for calculating the total of the 'Grandchild' population
"""
name = 'relgq11'
groups = {
"Grandchild Population Total": [11]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq12():
"""
Query for calculating the total of the 'Parent-in-law' population
"""
name = 'relgq12'
groups = {
"Parent-in-law Population Total": [12]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq13():
"""
Query for calculating the total of the 'Son-in-law or daughter-in-law' population
"""
name = 'relgq13'
groups = {
"Son-in-law or daughter-in-law Population Total": [13]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq14():
"""
Query for calculating the total of the 'Other relative' population
"""
name = 'relgq14'
groups = {
"Other relative Population Total": [14]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq15():
"""
Query for calculating the total of the 'Roommate or housemate' population
"""
name = 'relgq15'
groups = {
"Roommate or housemate Population Total": [15]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq16():
"""
Query for calculating the total of the 'Foster child (If roomer/boarder and age<21)' population
"""
name = 'relgq16'
groups = {
"Foster child (If roomer/boarder and age<21) Population Total": [16]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq17():
"""
Query for calculating the total of the 'Other nonrelative (also include if roomer/boarder and age>=21)' population
"""
name = 'relgq17'
groups = {
"Other nonrelative (also include if roomer/boarder and age>=21) Population Total": [17]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq18():
"""
Query for calculating the total of the 'GQ 101 Federal detention centers' population
"""
name = 'relgq18'
groups = {
"GQ 101 Federal detention centers Population Total": [18]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq19():
"""
Query for calculating the total of the 'GQ 102 Federal prisons' population
"""
name = 'relgq19'
groups = {
"GQ 102 Federal prisons Population Total": [19]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq20():
"""
Query for calculating the total of the 'GQ 103 State prisons' population
"""
name = 'relgq20'
groups = {
"GQ 103 State prisons Population Total": [20]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq21():
"""
Query for calculating the total of the 'GQ 104 Local jails and other municipal confinements' population
"""
name = 'relgq21'
groups = {
"GQ 104 Local jails and other municipal confinements Population Total": [21]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq22():
"""
Query for calculating the total of the 'GQ 105 Correctional residential facilities' population
"""
name = 'relgq22'
groups = {
"GQ 105 Correctional residential facilities Population Total": [22]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq23():
"""
Query for calculating the total of the 'GQ 106 Military disciplinary barracks' population
"""
name = 'relgq23'
groups = {
"GQ 106 Military disciplinary barracks Population Total": [23]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq24():
"""
Query for calculating the total of the 'GQ 201 Group homes for juveniles' population
"""
name = 'relgq24'
groups = {
"GQ 201 Group homes for juveniles Population Total": [24]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq25():
"""
Query for calculating the total of the 'GQ 202 Residential treatment centers for juveniles' population
"""
name = 'relgq25'
groups = {
"GQ 202 Residential treatment centers for juveniles Population Total": [25]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq26():
"""
Query for calculating the total of the 'GQ 203 Correctional facilities intended for juveniles' population
"""
name = 'relgq26'
groups = {
"GQ 203 Correctional facilities intended for juveniles Population Total": [26]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq27():
"""
Query for calculating the total of the 'GQ 301 Nursing facilities' population
"""
name = 'relgq27'
groups = {
"GQ 301 Nursing facilities Population Total": [27]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq28():
"""
Query for calculating the total of the 'GQ 401 Mental hospitals' population
"""
name = 'relgq28'
groups = {
"GQ 401 Mental hospitals Population Total": [28]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq29():
"""
Query for calculating the total of the 'GQ 402 Hospitals with patients who have no usual home elsewhere' population
"""
name = 'relgq29'
groups = {
"GQ 402 Hospitals with patients who have no usual home elsewhere Population Total": [29]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq30():
"""
Query for calculating the total of the 'GQ 403 In-patient hospice facilities' population
"""
name = 'relgq30'
groups = {
"GQ 403 In-patient hospice facilities Population Total": [30]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq31():
"""
Query for calculating the total of the 'GQ 404 Military treatment facilities' population
"""
name = 'relgq31'
groups = {
"GQ 404 Military treatment facilities Population Total": [31]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq32():
"""
Query for calculating the total of the 'GQ 405 Residential schools for people with disabilities' population
"""
name = 'relgq32'
groups = {
"GQ 405 Residential schools for people with disabilities Population Total": [32]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq33():
"""
Query for calculating the total of the 'GQ 501 College/university student housing' population
"""
name = 'relgq33'
groups = {
"GQ 501 College/university student housing Population Total": [33]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq34():
"""
Query for calculating the total of the 'GQ 601 Military quarters' population
"""
name = 'relgq34'
groups = {
"GQ 601 Military quarters Population Total": [34]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq35():
"""
Query for calculating the total of the 'GQ 602 Military ships' population
"""
name = 'relgq35'
groups = {
"GQ 602 Military ships Population Total": [35]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq36():
"""
Query for calculating the total of the 'GQ 701 Emergency and transitional shelters' population
"""
name = 'relgq36'
groups = {
"GQ 701 Emergency and transitional shelters Population Total": [36]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq37():
"""
Query for calculating the total of the 'GQ 801 Group homes intended for adults' population
"""
name = 'relgq37'
groups = {
"GQ 801 Group homes intended for adults Population Total": [37]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq38():
"""
Query for calculating the total of the 'GQ 802 Residential treatment centers for adults' population
"""
name = 'relgq38'
groups = {
"GQ 802 Residential treatment centers for adults Population Total": [38]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq39():
"""
Query for calculating the total of the 'GQ 900 Maritime/merchant vessels' population
"""
name = 'relgq39'
groups = {
"GQ 900 Maritime/merchant vessels Population Total": [39]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq40():
"""
Query for calculating the total of the 'GQ 901 Workers' group living quarters and job corps centers' population
"""
name = 'relgq40'
groups = {
"GQ 901 Workers' group living quarters and job corps centers Population Total": [40]
}
return name, groups
@staticmethod
def recodeRELGQ_relgq41():
"""
Query for calculating the total of the 'GQ 997 Other noninstitutional (GQ types 702, 704, 706, 903, 904)' population
"""
name = 'relgq41'
groups = {
"GQ 997 Other noninstitutional (GQ types 702, 704, 706, 903, 904 Population Total)": [41]
}
return name, groups
@staticmethod
def recodeRELGQ_hhgqsimple():
name = CC.HHGQ_8LEV
groupings = {
"HOUSEHOLD": list(range(0, 18)),
"Correctional facilities for adults": list(range(18,24)),
"Juvenile facilities": list(range(24,27)),
"Nursing facilities/Skilled-nursing facilities": [27],
"Other institutional facilities": list(range(28, 33)),
"College/University student housing": [33],
"Military quarters": [34],
"Other noninstitutional facilities": list(range(35,42))
}
return name, groupings
@staticmethod
def recodeRELGQ_spousesUnmarriedPartners():
name = CC.SPOUSES_UNMARRIED_PARTNERS
groupings = {
"Spouses & Unmarried Partners": list(range(2,6)),
}
return name, groupings
# @staticmethod
# def recodeSpouseOrPartner():
# name = CC.RELGQ_SPOUSE_OR_PARTNER
# groupings = {
# "Spouse or unmarried partner": [2, 3, 4, 5]
# }
# return name, groupings
@staticmethod
def recodeRELGQ_peopleInHouseholds():
name = CC.PEOPLE_IN_HOUSEHOLDS
groupings = {
"People in Households" : list(range(0, 18)),
}
return name, groupings
|
import json
import logging
import os
import shutil
from collections import OrderedDict
from typing import List, Dict, Tuple, Iterable, Type, Union, Callable
from zipfile import ZipFile
import requests
import numpy as np
from numpy import ndarray
import transformers
import torch
from torch import nn, Tensor, device
from torch.optim import Optimizer
from torch.utils.data import DataLoader
import torch.multiprocessing as mp
from tqdm.autonotebook import tqdm, trange
import math
import queue
from . import __DOWNLOAD_SERVER__
from .evaluation import SentenceEvaluator
from .util import import_from_string, batch_to_device, http_get
from .datasets.EncodeDataset import EncodeDataset
from .models import Transformer, Pooling
from . import __version__
class SentenceTransformer(nn.Sequential):
"""
Loads or create a SentenceTransformer model, that can be used to map sentences / text to embeddings.
:param model_name_or_path: If it is a filepath on disc, it loads the model from that path. If it is not a path, it first tries to download a pre-trained SentenceTransformer model. If that fails, tries to construct a model from Huggingface models repository with that name.
:param modules: This parameter can be used to create custom SentenceTransformer models from scratch.
:param device: Device (like 'cuda' / 'cpu') that should be used for computation. If None, checks if a GPU can be used.
"""
def __init__(self, model_name_or_path: str = None, modules: Iterable[nn.Module] = None, device: str = None):
if model_name_or_path is not None and model_name_or_path != "":
logging.info("Load pretrained SentenceTransformer: {}".format(model_name_or_path))
model_path = model_name_or_path
if not os.path.isdir(model_path) and not model_path.startswith('http://') and not model_path.startswith('https://'):
logging.info("Did not find folder {}".format(model_path))
if '\\' in model_path or model_path.count('/') > 1:
raise AttributeError("Path {} not found".format(model_path))
model_path = __DOWNLOAD_SERVER__ + model_path + '.zip'
logging.info("Try to download model from server: {}".format(model_path))
if model_path.startswith('http://') or model_path.startswith('https://'):
model_url = model_path
folder_name = model_url.replace("https://", "").replace("http://", "").replace("/", "_")[:250].rstrip('.zip')
cache_folder = os.getenv('SENTENCE_TRANSFORMERS_HOME')
if cache_folder is None:
try:
from torch.hub import _get_torch_home
torch_cache_home = _get_torch_home()
except ImportError:
torch_cache_home = os.path.expanduser(os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')))
cache_folder = os.path.join(torch_cache_home, 'sentence_transformers')
model_path = os.path.join(cache_folder, folder_name)
if not os.path.exists(model_path) or not os.listdir(model_path):
if model_url[-1] == "/":
model_url = model_url[:-1]
logging.info("Downloading sentence transformer model from {} and saving it at {}".format(model_url, model_path))
model_path_tmp = model_path.rstrip("/").rstrip("\\")+"_part"
try:
zip_save_path = os.path.join(model_path_tmp, 'model.zip')
http_get(model_url, zip_save_path)
with ZipFile(zip_save_path, 'r') as zip:
zip.extractall(model_path_tmp)
os.remove(zip_save_path)
os.rename(model_path_tmp, model_path)
except requests.exceptions.HTTPError as e:
shutil.rmtree(model_path_tmp)
if e.response.status_code == 404:
logging.warning('SentenceTransformer-Model {} not found. Try to create it from scratch'.format(model_url))
logging.warning('Try to create Transformer Model {} with mean pooling'.format(model_name_or_path))
model_path = None
transformer_model = Transformer(model_name_or_path)
pooling_model = Pooling(transformer_model.get_word_embedding_dimension())
modules = [transformer_model, pooling_model]
else:
raise e
except Exception as e:
shutil.rmtree(model_path)
raise e
#### Load from disk
if model_path is not None:
logging.info("Load SentenceTransformer from folder: {}".format(model_path))
if os.path.exists(os.path.join(model_path, 'config.json')):
with open(os.path.join(model_path, 'config.json')) as fIn:
config = json.load(fIn)
if config['__version__'] > __version__:
logging.warning("You try to use a model that was created with version {}, however, your version is {}. This might cause unexpected behavior or errors. In that case, try to update to the latest version.\n\n\n".format(config['__version__'], __version__))
with open(os.path.join(model_path, 'modules.json')) as fIn:
contained_modules = json.load(fIn)
modules = OrderedDict()
for module_config in contained_modules:
module_class = import_from_string(module_config['type'])
module = module_class.load(os.path.join(model_path, module_config['path']))
modules[module_config['name']] = module
if modules is not None and not isinstance(modules, OrderedDict):
modules = OrderedDict([(str(idx), module) for idx, module in enumerate(modules)])
super().__init__(modules)
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
logging.info("Use pytorch device: {}".format(device))
self._target_device = torch.device(device)
def encode(self, sentences: Union[str, List[str], List[int]],
batch_size: int = 32,
show_progress_bar: bool = None,
output_value: str = 'sentence_embedding',
convert_to_numpy: bool = True,
convert_to_tensor: bool = False,
is_pretokenized: bool = False,
device: str = None,
num_workers: int = 0) -> Union[List[Tensor], ndarray, Tensor]:
"""
Computes sentence embeddings
:param sentences: the sentences to embed
:param batch_size: the batch size used for the computation
:param show_progress_bar: Output a progress bar when encode sentences
:param output_value: Default sentence_embedding, to get sentence embeddings. Can be set to token_embeddings to get wordpiece token embeddings.
:param convert_to_numpy: If true, the output is a list of numpy vectors. Else, it is a list of pytorch tensors.
:param convert_to_tensor: If true, you get one large tensor as return. Overwrites any setting from convert_to_numpy
:param is_pretokenized: If is_pretokenized=True, sentences must be a list of integers, containing the tokenized sentences with each token convert to the respective int.
:param device: Which torch.device to use for the computation
:param num_workers: Number of background-workers to tokenize data. Set to positive number to increase tokenization speed
:return:
By default, a list of tensors is returned. If convert_to_tensor, a stacked tensor is returned. If convert_to_numpy, a numpy matrix is returned.
"""
self.eval()
if show_progress_bar is None:
show_progress_bar = (logging.getLogger().getEffectiveLevel()==logging.INFO or logging.getLogger().getEffectiveLevel()==logging.DEBUG)
input_was_string = False
if isinstance(sentences, str): #Cast an individual sentence to a list with length 1
sentences = [sentences]
input_was_string = True
if device is None:
device = self._target_device
self.to(device)
all_embeddings = []
length_sorted_idx = np.argsort([self._text_length(sen) for sen in sentences])
sentences_sorted = [sentences[idx] for idx in length_sorted_idx]
inp_dataset = EncodeDataset(sentences_sorted, model=self, is_tokenized=is_pretokenized)
inp_dataloader = DataLoader(inp_dataset, batch_size=batch_size, collate_fn=self.smart_batching_collate_text_only, num_workers=num_workers, shuffle=False)
iterator = inp_dataloader
if show_progress_bar:
iterator = tqdm(inp_dataloader, desc="Batches")
for features in iterator:
for feature_name in features:
features[feature_name] = features[feature_name].to(device)
with torch.no_grad():
out_features = self.forward(features)
embeddings = out_features[output_value]
if output_value == 'token_embeddings':
#Set token embeddings to 0 for padding tokens
input_mask = out_features['attention_mask']
input_mask_expanded = input_mask.unsqueeze(-1).expand(embeddings.size()).float()
embeddings = embeddings * input_mask_expanded
embeddings = embeddings.detach()
# fixes for #522 and #487
# to avoid oom problems on gpu with large datasets
if convert_to_numpy:
embeddings = embeddings.cpu()
all_embeddings.extend(embeddings)
all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)]
if convert_to_tensor:
all_embeddings = torch.stack(all_embeddings)
elif convert_to_numpy:
all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])
if input_was_string:
all_embeddings = all_embeddings[0]
return all_embeddings
def start_multi_process_pool(self, target_devices: List[str] = None, encode_batch_size: int = 32):
"""
Starts multi process to process the encoding with several, independent processes.
This method is recommended if you want to encode on multiple GPUs. It is advised
to start only one process per GPU. This method works together with encode_multi_process
:param target_devices: PyTorch target devices, e.g. cuda:0, cuda:1... If None, all available CUDA devices will be used
:param encode_batch_size: Batch size for each process when calling encode
:return: Returns a dict with the target processes, an input queue and and output queue.
"""
if target_devices is None:
if torch.cuda.is_available():
target_devices = ['cuda:{}'.format(i) for i in range(torch.cuda.device_count())]
else:
logging.info("CUDA is not available. Start 4 CPU worker")
target_devices = ['cpu']*4
logging.info("Start multi-process pool on devices: {}".format(', '.join(map(str, target_devices))))
ctx = mp.get_context('spawn')
input_queue = ctx.Queue()
output_queue = ctx.Queue()
processes = []
for cuda_id in target_devices:
p = ctx.Process(target=SentenceTransformer._encode_multi_process_worker, args=(cuda_id, self, input_queue, output_queue, encode_batch_size), daemon=True)
p.start()
processes.append(p)
return {'input': input_queue, 'output': output_queue, 'processes': processes}
@staticmethod
def stop_multi_process_pool(pool):
"""
Stops all processes started with start_multi_process_pool
"""
for p in pool['processes']:
p.terminate()
for p in pool['processes']:
p.join()
p.close()
pool['input'].close()
pool['output'].close()
def encode_multi_process(self, sentences: List[str], pool: Dict[str, object], is_pretokenized: bool = False, chunk_size=None):
"""
This method allows to run encode() on multiple GPUs. The sentences are chunked into smaller packages
and sent to individual processes, which encode these on the different GPUs. This method is only suitable
for encoding large sets of sentences
:param sentences: List of sentences
:param pool: A pool of workers started with SentenceTransformer.start_multi_process_pool
:param is_pretokenized: If true, no tokenization will be applied. It is expected that the input sentences are list of ints.
:param chunk_size: Sentences are chunked and sent to the individual processes. If none, it determine a sensible size.
:return: Numpy matrix with all embeddings
"""
if chunk_size is None:
chunk_size = min(math.ceil(len(sentences) / len(pool["processes"]) / 10), 5000)
logging.info("Chunk data into packages of size {}".format(chunk_size))
input_queue = pool['input']
last_chunk_id = 0
chunk = []
for sentence in sentences:
chunk.append(sentence)
if len(chunk) >= chunk_size:
input_queue.put([last_chunk_id, is_pretokenized, chunk])
last_chunk_id += 1
chunk = []
if len(chunk) > 0:
input_queue.put([last_chunk_id, is_pretokenized, chunk])
last_chunk_id += 1
output_queue = pool['output']
results_list = sorted([output_queue.get() for _ in range(last_chunk_id)], key=lambda x: x[0])
embeddings = np.concatenate([result[1] for result in results_list])
return embeddings
@staticmethod
def _encode_multi_process_worker(target_device: str, model, input_queue, results_queue, encode_batch_size):
"""
Internal working process to encode sentences in multi-process setup
"""
while True:
try:
id, is_pretokenized, sentences = input_queue.get()
embeddings = model.encode(sentences, device=target_device, is_pretokenized=is_pretokenized, show_progress_bar=False, convert_to_numpy=True, batch_size=encode_batch_size)
results_queue.put([id, embeddings])
except queue.Empty:
break
def get_max_seq_length(self):
"""
Returns the maximal sequence length for input the model accepts. Longer inputs will be truncated
"""
if hasattr(self._first_module(), 'max_seq_length'):
return self._first_module().max_seq_length
return None
def tokenize(self, text: str):
"""
Tokenizes the text
"""
return self._first_module().tokenize(text)
def get_sentence_features(self, *features):
return self._first_module().get_sentence_features(*features)
def get_sentence_embedding_dimension(self):
for mod in reversed(self._modules.values()):
sent_embedding_dim_method = getattr(mod, "get_sentence_embedding_dimension", None)
if callable(sent_embedding_dim_method):
return sent_embedding_dim_method()
return None
def _first_module(self):
"""Returns the first module of this sequential embedder"""
return self._modules[next(iter(self._modules))]
def _last_module(self):
"""Returns the last module of this sequential embedder"""
return self._modules[next(reversed(self._modules))]
def save(self, path):
"""
Saves all elements for this seq. sentence embedder into different sub-folders
"""
if path is None:
return
os.makedirs(path, exist_ok=True)
logging.info("Save model to {}".format(path))
contained_modules = []
for idx, name in enumerate(self._modules):
module = self._modules[name]
model_path = os.path.join(path, str(idx)+"_"+type(module).__name__)
os.makedirs(model_path, exist_ok=True)
module.save(model_path)
contained_modules.append({'idx': idx, 'name': name, 'path': os.path.basename(model_path), 'type': type(module).__module__})
with open(os.path.join(path, 'modules.json'), 'w') as fOut:
json.dump(contained_modules, fOut, indent=2)
with open(os.path.join(path, 'config.json'), 'w') as fOut:
json.dump({'__version__': __version__}, fOut, indent=2)
def smart_batching_collate(self, batch):
"""
Transforms a batch from a SmartBatchingDataset to a batch of tensors for the model
Here, batch is a list of tuples: [(tokens, label), ...]
:param batch:
a batch from a SmartBatchingDataset
:return:
a batch of tensors for the model
"""
num_texts = len(batch[0][0])
labels = []
paired_texts = [[] for _ in range(num_texts)]
max_seq_len = [0] * num_texts
for tokens, label in batch:
labels.append(label)
for i in range(num_texts):
paired_texts[i].append(tokens[i])
max_seq_len[i] = max(max_seq_len[i], self._text_length(tokens[i]))
features = []
for idx in range(num_texts):
max_len = max_seq_len[idx]
feature_lists = {}
for text in paired_texts[idx]:
sentence_features = self.get_sentence_features(text, max_len)
for feature_name in sentence_features:
if feature_name not in feature_lists:
feature_lists[feature_name] = []
feature_lists[feature_name].append(sentence_features[feature_name])
for feature_name in feature_lists:
feature_lists[feature_name] = torch.cat(feature_lists[feature_name])
features.append(feature_lists)
return {'features': features, 'labels': torch.stack(labels)}
def smart_batching_collate_text_only(self, batch):
"""
Transforms a batch from a SmartBatchingDataset to a batch of tensors for the model.
Here, batch is a list of texts
:param batch:
a batch from a SmartBatchingDataset
:return:
a batch of tensors for the model
"""
max_seq_len = max([self._text_length(text) for text in batch])
feature_lists = {}
for text in batch:
sentence_features = self.get_sentence_features(text, max_seq_len)
for feature_name in sentence_features:
if feature_name not in feature_lists:
feature_lists[feature_name] = []
feature_lists[feature_name].append(sentence_features[feature_name])
for feature_name in feature_lists:
feature_lists[feature_name] = torch.cat(feature_lists[feature_name])
return feature_lists
def _text_length(self, text: Union[List[int], List[List[int]]]):
"""
Help function to get the length for the input text. Text can be either
a list of ints (which means a single text as input), or a tuple of list of ints
(representing several text inputs to the model).
"""
if len(text) == 0 or isinstance(text[0], int):
return len(text)
else:
return sum([len(t) for t in text])
def fit(self,
train_objectives: Iterable[Tuple[DataLoader, nn.Module]],
evaluator: SentenceEvaluator = None,
epochs: int = 1,
steps_per_epoch = None,
scheduler: str = 'WarmupLinear',
warmup_steps: int = 10000,
optimizer_class: Type[Optimizer] = transformers.AdamW,
optimizer_params : Dict[str, object]= {'lr': 2e-5, 'eps': 1e-6, 'correct_bias': False},
weight_decay: float = 0.01,
evaluation_steps: int = 0,
output_path: str = None,
save_best_model: bool = True,
max_grad_norm: float = 1,
use_amp: bool = False,
callback: Callable[[float, int, int], None] = None,
output_path_ignore_not_empty: bool = False
):
"""
Train the model with the given training objective
Each training objective is sampled in turn for one batch.
We sample only as many batches from each objective as there are in the smallest one
to make sure of equal training with each dataset.
:param train_objectives: Tuples of (DataLoader, LossFunction). Pass more than one for multi-task learning
:param evaluator: An evaluator (sentence_transformers.evaluation) evaluates the model performance during training on held-out dev data. It is used to determine the best model that is saved to disc.
:param epochs: Number of epochs for training
:param steps_per_epoch: Number of training steps per epoch. If set to None (default), one epoch is equal the DataLoader size from train_objectives.
:param scheduler: Learning rate scheduler. Available schedulers: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts
:param warmup_steps: Behavior depends on the scheduler. For WarmupLinear (default), the learning rate is increased from o up to the maximal learning rate. After these many training steps, the learning rate is decreased linearly back to zero.
:param optimizer_class: Optimizer
:param optimizer_params: Optimizer parameters
:param weight_decay: Weight decay for model parameters
:param evaluation_steps: If > 0, evaluate the model using evaluator after each number of training steps
:param output_path: Storage path for the model and evaluation files
:param save_best_model: If true, the best model (according to evaluator) is stored at output_path
:param max_grad_norm: Used for gradient normalization.
:param use_amp: Use Automatic Mixed Precision (AMP). Only for Pytorch >= 1.6.0
:param callback: Callback function that is invoked after each evaluation.
It must accept the following three parameters in this order:
`score`, `epoch`, `steps`
:param output_path_ignore_not_empty: deprecated, no longer used
"""
if use_amp:
from torch.cuda.amp import autocast
scaler = torch.cuda.amp.GradScaler()
self.to(self._target_device)
if output_path is not None:
os.makedirs(output_path, exist_ok=True)
dataloaders = [dataloader for dataloader, _ in train_objectives]
# Use smart batching
for dataloader in dataloaders:
dataloader.collate_fn = self.smart_batching_collate
loss_models = [loss for _, loss in train_objectives]
for loss_model in loss_models:
loss_model.to(self._target_device)
self.best_score = -9999999
if steps_per_epoch is None or steps_per_epoch == 0:
steps_per_epoch = min([len(dataloader) for dataloader in dataloaders])
num_train_steps = int(steps_per_epoch * epochs)
# Prepare optimizers
optimizers = []
schedulers = []
for loss_model in loss_models:
param_optimizer = list(loss_model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': weight_decay},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = optimizer_class(optimizer_grouped_parameters, **optimizer_params)
scheduler_obj = self._get_scheduler(optimizer, scheduler=scheduler, warmup_steps=warmup_steps, t_total=num_train_steps)
optimizers.append(optimizer)
schedulers.append(scheduler_obj)
global_step = 0
data_iterators = [iter(dataloader) for dataloader in dataloaders]
num_train_objectives = len(train_objectives)
skip_scheduler = False
for epoch in trange(epochs, desc="Epoch"):
training_steps = 0
for loss_model in loss_models:
loss_model.zero_grad()
loss_model.train()
for _ in trange(steps_per_epoch, desc="Iteration", smoothing=0.05):
for train_idx in range(num_train_objectives):
loss_model = loss_models[train_idx]
optimizer = optimizers[train_idx]
scheduler = schedulers[train_idx]
data_iterator = data_iterators[train_idx]
try:
data = next(data_iterator)
except StopIteration:
#logging.info("Restart data_iterator")
data_iterator = iter(dataloaders[train_idx])
data_iterators[train_idx] = data_iterator
data = next(data_iterator)
features, labels = batch_to_device(data, self._target_device)
if use_amp:
with autocast():
loss_value = loss_model(features, labels)
scale_before_step = scaler.get_scale()
scaler.scale(loss_value).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(loss_model.parameters(), max_grad_norm)
scaler.step(optimizer)
scaler.update()
skip_scheduler = scaler.get_scale() != scale_before_step
else:
loss_value = loss_model(features, labels)
loss_value.backward()
torch.nn.utils.clip_grad_norm_(loss_model.parameters(), max_grad_norm)
optimizer.step()
optimizer.zero_grad()
if not skip_scheduler:
scheduler.step()
training_steps += 1
global_step += 1
if evaluation_steps > 0 and training_steps % evaluation_steps == 0:
self._eval_during_training(evaluator, output_path, save_best_model, epoch,
training_steps, callback)
for loss_model in loss_models:
loss_model.zero_grad()
loss_model.train()
self._eval_during_training(evaluator, output_path, save_best_model, epoch, -1, callback)
def evaluate(self, evaluator: SentenceEvaluator, output_path: str = None):
"""
Evaluate the model
:param evaluator:
the evaluator
:param output_path:
the evaluator can write the results to this path
"""
if output_path is not None:
os.makedirs(output_path, exist_ok=True)
return evaluator(self, output_path)
def _eval_during_training(self, evaluator, output_path, save_best_model, epoch, steps, callback):
"""Runs evaluation during the training"""
if evaluator is not None:
score = evaluator(self, output_path=output_path, epoch=epoch, steps=steps)
if callback is not None:
callback(score, epoch, steps)
if score > self.best_score:
self.best_score = score
if save_best_model:
self.save(output_path)
@staticmethod
def _get_scheduler(optimizer, scheduler: str, warmup_steps: int, t_total: int):
"""
Returns the correct learning rate scheduler. Available scheduler: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts
"""
scheduler = scheduler.lower()
if scheduler == 'constantlr':
return transformers.get_constant_schedule(optimizer)
elif scheduler == 'warmupconstant':
return transformers.get_constant_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps)
elif scheduler == 'warmuplinear':
return transformers.get_linear_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total)
elif scheduler == 'warmupcosine':
return transformers.get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total)
elif scheduler == 'warmupcosinewithhardrestarts':
return transformers.get_cosine_with_hard_restarts_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total)
else:
raise ValueError("Unknown scheduler {}".format(scheduler))
@property
def device(self) -> device:
"""
Get torch.device from module, assuming that the whole module has one device.
"""
try:
return next(self.parameters()).device
except StopIteration:
# For nn.DataParallel compatibility in PyTorch 1.5
def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]:
tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
return tuples
gen = self._named_members(get_members_fn=find_tensor_attributes)
first_tuple = next(gen)
return first_tuple[1].device
@property
def tokenizer(self):
"""
Property to get the tokenizer that is used by this model
"""
return self._first_module().tokenizer
@tokenizer.setter
def tokenizer(self, value):
"""
Property to set the tokenizer that is should used by this model
"""
self._first_module().tokenizer = value
@property
def max_seq_length(self):
"""
Property to get the maximal input sequence length for the model. Longer inputs will be truncated.
"""
return self._first_module().max_seq_length
@max_seq_length.setter
def max_seq_length(self, value):
"""
Property to set the maximal input sequence length for the model. Longer inputs will be truncated.
"""
self._first_module().max_seq_length = value
|
from dispike.errors.events import InvalidEventType
import typing
from loguru import logger
import inspect
from enum import Enum
class EventTypes(str, Enum):
COMMAND = "command"
COMPONENT = "component"
MESSAGE_COMMAND = "message_command"
USER_COMMAND = "user_command"
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import ast
import os
import re
from argparse import ArgumentError, ArgumentParser, Namespace
from dataclasses import _MISSING_TYPE, MISSING
from enum import Enum
import inspect
from typing import Any, Dict, List, Tuple, Type
from fairseq.dataclass import FairseqDataclass
from fairseq.dataclass.configs import FairseqConfig
from hydra.experimental import compose, initialize
from omegaconf import DictConfig, OmegaConf, open_dict
def eval_str_list(x, x_type=float):
if x is None:
return None
if isinstance(x, str):
if len(x) == 0:
return []
x = ast.literal_eval(x)
try:
return list(map(x_type, x))
except TypeError:
return [x_type(x)]
def interpret_dc_type(field_type):
if isinstance(field_type, str):
raise RuntimeError("field should be a type")
if field_type == Any:
return str
typestring = str(field_type)
if re.match(r"(typing.|^)Union\[(.*), NoneType\]$", typestring):
return field_type.__args__[0]
return field_type
def gen_parser_from_dataclass(
parser: ArgumentParser,
dataclass_instance: FairseqDataclass,
delete_default: bool = False,
) -> None:
"""convert a dataclass instance to tailing parser arguments"""
def argparse_name(name: str):
if name == "data":
# normally data is positional args
return name
if name == "_name":
# private member, skip
return None
return "--" + name.replace("_", "-")
def get_kwargs_from_dc(
dataclass_instance: FairseqDataclass, k: str
) -> Dict[str, Any]:
"""k: dataclass attributes"""
kwargs = {}
field_type = dataclass_instance._get_type(k)
inter_type = interpret_dc_type(field_type)
field_default = dataclass_instance._get_default(k)
if isinstance(inter_type, type) and issubclass(inter_type, Enum):
field_choices = [t.value for t in list(inter_type)]
else:
field_choices = None
field_help = dataclass_instance._get_help(k)
field_const = dataclass_instance._get_argparse_const(k)
if isinstance(field_default, str) and field_default.startswith("${"):
kwargs["default"] = field_default
else:
if field_default is MISSING:
kwargs["required"] = True
if field_choices is not None:
kwargs["choices"] = field_choices
if (
isinstance(inter_type, type)
and (issubclass(inter_type, List) or issubclass(inter_type, Tuple))
) or ("List" in str(inter_type) or "Tuple" in str(inter_type)):
if "int" in str(inter_type):
kwargs["type"] = lambda x: eval_str_list(x, int)
elif "float" in str(inter_type):
kwargs["type"] = lambda x: eval_str_list(x, float)
elif "str" in str(inter_type):
kwargs["type"] = lambda x: eval_str_list(x, str)
else:
raise NotImplementedError(
"parsing of type " + str(inter_type) + " is not implemented"
)
if field_default is not MISSING:
kwargs["default"] = (
",".join(map(str, field_default))
if field_default is not None
else None
)
elif (
isinstance(inter_type, type) and issubclass(inter_type, Enum)
) or "Enum" in str(inter_type):
kwargs["type"] = str
if field_default is not MISSING:
if isinstance(field_default, Enum):
kwargs["default"] = field_default.value
else:
kwargs["default"] = field_default
elif inter_type is bool:
kwargs["action"] = (
"store_false" if field_default is True else "store_true"
)
kwargs["default"] = field_default
else:
kwargs["type"] = inter_type
if field_default is not MISSING:
kwargs["default"] = field_default
kwargs["help"] = field_help
if field_const is not None:
kwargs["const"] = field_const
kwargs["nargs"] = "?"
return kwargs
for k in dataclass_instance._get_all_attributes():
field_name = argparse_name(dataclass_instance._get_name(k))
field_type = dataclass_instance._get_type(k)
if field_name is None:
continue
elif inspect.isclass(field_type) and issubclass(field_type, FairseqDataclass):
gen_parser_from_dataclass(parser, field_type(), delete_default)
continue
kwargs = get_kwargs_from_dc(dataclass_instance, k)
field_args = [field_name]
alias = dataclass_instance._get_argparse_alias(k)
if alias is not None:
field_args.append(alias)
if "default" in kwargs:
if isinstance(kwargs["default"], str) and kwargs["default"].startswith(
"${"
):
continue
if delete_default:
del kwargs["default"]
try:
parser.add_argument(*field_args, **kwargs)
except ArgumentError:
pass
def _set_legacy_defaults(args, cls):
"""Helper to set default arguments based on *add_args*."""
if not hasattr(cls, "add_args"):
return
import argparse
parser = argparse.ArgumentParser(
argument_default=argparse.SUPPRESS, allow_abbrev=False
)
cls.add_args(parser)
# copied from argparse.py:
defaults = argparse.Namespace()
for action in parser._actions:
if action.dest is not argparse.SUPPRESS:
if not hasattr(defaults, action.dest):
if action.default is not argparse.SUPPRESS:
setattr(defaults, action.dest, action.default)
for key, default_value in vars(defaults).items():
if not hasattr(args, key):
setattr(args, key, default_value)
def _override_attr(
sub_node: str, data_class: Type[FairseqDataclass], args: Namespace
) -> List[str]:
overrides = []
if not inspect.isclass(data_class) or not issubclass(data_class, FairseqDataclass):
return overrides
def get_default(f):
if not isinstance(f.default_factory, _MISSING_TYPE):
return f.default_factory()
return f.default
for k, v in data_class.__dataclass_fields__.items():
if k.startswith("_"):
# private member, skip
continue
val = get_default(v) if not hasattr(args, k) else getattr(args, k)
field_type = interpret_dc_type(v.type)
if (
isinstance(val, str)
and not val.startswith("${") # not interpolation
and field_type != str
and inspect.isclass(field_type) and not issubclass(field_type, Enum) # not choices enum
):
# upgrade old models that stored complex parameters as string
val = ast.literal_eval(val)
if isinstance(val, tuple):
val = list(val)
if getattr(v.type, "__origin__", None) is List:
# if type is int but val is float, then we will crash later - try to convert here
t_args = v.type.__args__
if len(t_args) == 1:
val = list(map(t_args[0], val))
if val is None:
overrides.append("{}.{}=null".format(sub_node, k))
elif val == "":
overrides.append("{}.{}=''".format(sub_node, k))
elif isinstance(val, str):
val = val.replace("'", r"\'")
overrides.append("{}.{}='{}'".format(sub_node, k, val))
elif isinstance(val, FairseqDataclass):
overrides += _override_attr(f"{sub_node}.{k}", type(val), args)
else:
overrides.append("{}.{}={}".format(sub_node, k, val))
return overrides
def migrate_registry(
name, value, registry, args, overrides, deletes, use_name_as_val=False
):
if value in registry:
overrides.append("{}={}".format(name, value))
overrides.append("{}._name={}".format(name, value))
overrides.extend(_override_attr(name, registry[value], args))
elif use_name_as_val and value is not None:
overrides.append("{}={}".format(name, value))
else:
deletes.append(name)
def override_module_args(args: Namespace) -> Tuple[List[str], List[str]]:
"""use the field in args to overrides those in cfg"""
overrides = []
deletes = []
for k in FairseqConfig.__dataclass_fields__.keys():
overrides.extend(
_override_attr(k, FairseqConfig.__dataclass_fields__[k].type, args)
)
if args is not None:
if hasattr(args, "task"):
from fairseq.tasks import TASK_DATACLASS_REGISTRY
migrate_registry(
"task", args.task, TASK_DATACLASS_REGISTRY, args, overrides, deletes
)
else:
deletes.append("task")
# these options will be set to "None" if they have not yet been migrated
# so we can populate them with the entire flat args
CORE_REGISTRIES = {"criterion", "optimizer", "lr_scheduler"}
from fairseq.registry import REGISTRIES
for k, v in REGISTRIES.items():
if hasattr(args, k):
migrate_registry(
k,
getattr(args, k),
v["dataclass_registry"],
args,
overrides,
deletes,
use_name_as_val=k not in CORE_REGISTRIES,
)
else:
deletes.append(k)
no_dc = True
if hasattr(args, "arch"):
from fairseq.models import ARCH_MODEL_REGISTRY, ARCH_MODEL_NAME_REGISTRY
if args.arch in ARCH_MODEL_REGISTRY:
m_cls = ARCH_MODEL_REGISTRY[args.arch]
dc = getattr(m_cls, "__dataclass", None)
if dc is not None:
m_name = ARCH_MODEL_NAME_REGISTRY[args.arch]
overrides.append("model={}".format(m_name))
overrides.append("model._name={}".format(args.arch))
# override model params with those exist in args
overrides.extend(_override_attr("model", dc, args))
no_dc = False
if no_dc:
deletes.append("model")
return overrides, deletes
def convert_namespace_to_omegaconf(args: Namespace) -> DictConfig:
"""Convert a flat argparse.Namespace to a structured DictConfig."""
# Here we are using field values provided in args to override counterparts inside config object
overrides, deletes = override_module_args(args)
# configs will be in fairseq/config after installation
config_path = os.path.join("..", "config")
with initialize(config_path=config_path):
composed_cfg = compose("config", overrides=overrides, strict=False)
for k in deletes:
composed_cfg[k] = None
cfg = OmegaConf.create(
OmegaConf.to_container(composed_cfg, resolve=True, enum_to_str=True)
)
# hack to be able to set Namespace in dict config. this should be removed when we update to newer
# omegaconf version that supports object flags, or when we migrate all existing models
from omegaconf import _utils
old_primitive = _utils.is_primitive_type
_utils.is_primitive_type = lambda _: True
if cfg.task is None and getattr(args, "task", None):
cfg.task = Namespace(**vars(args))
from fairseq.tasks import TASK_REGISTRY
_set_legacy_defaults(cfg.task, TASK_REGISTRY[args.task])
cfg.task._name = args.task
if cfg.model is None and getattr(args, "arch", None):
cfg.model = Namespace(**vars(args))
from fairseq.models import ARCH_MODEL_REGISTRY
_set_legacy_defaults(cfg.model, ARCH_MODEL_REGISTRY[args.arch])
cfg.model._name = args.arch
if cfg.optimizer is None and getattr(args, "optimizer", None):
cfg.optimizer = Namespace(**vars(args))
from fairseq.optim import OPTIMIZER_REGISTRY
_set_legacy_defaults(cfg.optimizer, OPTIMIZER_REGISTRY[args.optimizer])
cfg.optimizer._name = args.optimizer
if cfg.lr_scheduler is None and getattr(args, "lr_scheduler", None):
cfg.lr_scheduler = Namespace(**vars(args))
from fairseq.optim.lr_scheduler import LR_SCHEDULER_REGISTRY
_set_legacy_defaults(cfg.lr_scheduler, LR_SCHEDULER_REGISTRY[args.lr_scheduler])
cfg.lr_scheduler._name = args.lr_scheduler
if cfg.criterion is None and getattr(args, "criterion", None):
cfg.criterion = Namespace(**vars(args))
from fairseq.criterions import CRITERION_REGISTRY
_set_legacy_defaults(cfg.criterion, CRITERION_REGISTRY[args.criterion])
cfg.criterion._name = args.criterion
_utils.is_primitive_type = old_primitive
OmegaConf.set_struct(cfg, True)
return cfg
def populate_dataclass(
dataclass: FairseqDataclass, args: Namespace,
) -> FairseqDataclass:
for k in dataclass.__dataclass_fields__.keys():
if k.startswith("_"):
# private member, skip
continue
if hasattr(args, k):
setattr(dataclass, k, getattr(args, k))
return dataclass
def overwrite_args_by_name(cfg: DictConfig, overrides: Dict[str, any]):
# this will be deprecated when we get rid of argparse and model_overrides logic
from fairseq.registry import REGISTRIES
with open_dict(cfg):
for k in cfg.keys():
# "k in cfg" will return false if its a "mandatory value (e.g. ???)"
if k in cfg and isinstance(cfg[k], DictConfig):
overwrite_args_by_name(cfg[k], overrides)
elif k in cfg and isinstance(cfg[k], Namespace):
for override_key, val in overrides.items():
setattr(cfg[k], override_key, val)
elif k in overrides:
if (
k in REGISTRIES
and overrides[k] in REGISTRIES[k]["dataclass_registry"]
):
cfg[k] = DictConfig(
REGISTRIES[k]["dataclass_registry"][overrides[k]]
)
overwrite_args_by_name(cfg[k], overrides)
cfg[k]._name = overrides[k]
else:
cfg[k] = overrides[k]
def merge_with_parent(dc: FairseqDataclass, cfg: FairseqDataclass):
dc_instance = DictConfig(dc)
dc_instance.__dict__["_parent"] = cfg.__dict__["_parent"]
cfg = OmegaConf.merge(dc_instance, cfg)
OmegaConf.set_struct(cfg, True)
return cfg
|
# Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
store, seen = [], set()
curr = head
while curr:
store.append(curr)
curr = curr.next
if len(store) == 1:
return store[0]
curr = store[0]
first, last = 1, -1
trigger = False
while True:
if not trigger:
if store[last] in seen:
break
seen.add(store[last])
curr.next = store[last]
last -= 1
trigger = True
else:
if store[first] in seen:
break
seen.add(store[first])
curr.next = store[first]
first += 1
trigger = False
curr = curr.next
curr.next = None
return store[0]
|
'use strict'
var npm = require('../../lib/npm.js')
var log = require('npmlog')
var test = require('tap').test
var mockLog = {
finish: function () {},
silly: function () {}
}
var actions
test('setup', function (t) {
npm.load(function () {
log.disableProgress()
actions = require('../../lib/install/actions.js').actions
t.end()
})
})
test('->optdep:a->dep:b', function (t) {
var moduleA = {
name: 'a',
path: '/a',
package: {
scripts: {
postinstall: 'false'
},
dependencies: {
b: '*'
}
},
isTop: true
}
var moduleB = {
name: 'b',
path: '/b',
package: {},
requires: [],
requiredBy: [moduleA]
}
moduleA.requires = [moduleB]
var tree = {
path: '/',
package: {
optionalDependencies: {
a: '*'
}
},
children: [moduleA, moduleB],
requires: [moduleA],
isTop: true
}
moduleA.requiredBy = [tree]
moduleA.parent = tree
moduleB.parent = tree
t.plan(3)
return actions.postinstall('/', moduleA, mockLog).then(() => {
throw new Error('was not supposed to succeed')
}, (err) => {
t.is(err && err.code, 'ELIFECYCLE', 'Lifecycle failed')
t.ok(moduleA.failed, 'moduleA (optional dep) is marked failed')
t.ok(moduleB.failed, 'moduleB (direct dep of moduleA) is marked as failed')
t.end()
})
})
test('->dep:b,->optdep:a->dep:b', function (t) {
var moduleA = {
name: 'a',
path: '/',
package: {
scripts: {
postinstall: 'false'
},
dependencies: {
b: '*'
}
},
isTop: false
}
var moduleB = {
name: 'b',
path: '/',
package: {},
requires: [],
requiredBy: [moduleA],
isTop: false
}
moduleA.requires = [moduleB]
var tree = {
path: '/',
package: {
dependencies: {
b: '*'
},
optionalDependencies: {
a: '*'
}
},
children: [moduleA, moduleB],
requires: [moduleA, moduleB],
isTop: true
}
moduleA.requiredBy = [tree]
moduleB.requiredBy.push(tree)
moduleA.parent = tree
moduleB.parent = tree
t.plan(3)
return actions.postinstall('/', moduleA, mockLog).then(() => {
throw new Error('was not supposed to succeed')
}, (err) => {
t.ok(err && err.code === 'ELIFECYCLE', 'Lifecycle failed')
t.ok(moduleA.failed, 'moduleA (optional dep) is marked failed')
t.ok(!moduleB.failed, 'moduleB (direct dep of moduleA) is marked as failed')
t.end()
})
})
|
/* eslint-disable import/prefer-default-export */
import {
FETCH_CONTENT_START,
FETCH_CONTENT_SUCCESS,
FETCH_CONTENT_ERROR,
} from '../constants';
import { selectContent } from '../reducers/content';
const query = `
query($path:String!,$locale:String!) {
content(path:$path,locale:$locale) {
title,content,
}
}
`;
export function getContent({ path, locale, force }) {
return async (dispatch, getState, { graphqlRequest }) => {
const state = getState();
// eslint-disable-next-line no-param-reassign
locale = locale || state.intl.locale;
const payload = {
path,
locale,
};
if (!force) {
const cachedContent = selectContent(state, payload);
if (cachedContent) {
return true;
}
}
dispatch({
type: FETCH_CONTENT_START,
payload,
});
try {
const { data } = await graphqlRequest(query, { path, locale });
dispatch({
type: FETCH_CONTENT_SUCCESS,
payload: {
...data.content,
path,
locale,
},
});
} catch (err) {
dispatch({
type: FETCH_CONTENT_ERROR,
payload: {
err,
path,
locale,
},
});
return false;
}
return true;
};
}
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var randu = require( '@stdlib/random/base/randu' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var EPS = require( '@stdlib/constants/float64/eps' );
var stdev = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof stdev, 'function', 'main export is a function' );
t.end();
});
tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
var v = stdev( NaN, 0.5 );
t.equal( isnan( v ), true, 'returns NaN' );
v = stdev( 10.0, NaN );
t.equal( isnan( v ), true, 'returns NaN' );
t.end();
});
tape( 'if provided a nonpositive `a`, the function returns `NaN`', function test( t ) {
var y;
y = stdev( 0.0, 2.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( -1.0, 2.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( -1.0, 2.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( NINF, 1.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( NINF, PINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( NINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( NINF, NaN );
t.equal( isnan( y ), true, 'returns NaN' );
t.end();
});
tape( 'if provided a nonpositive `b`, the function returns `NaN`', function test( t ) {
var y;
y = stdev( 2.0, 0.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( 2.0, -1.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( 2.0, -1/0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( 1.0, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( PINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( NINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = stdev( NaN, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
t.end();
});
tape( 'the function returns the standard deviation of a Kumaraswamy\'s double bounded distribution', function test( t ) {
var a;
var b;
var i;
var y;
// TODO: Add fixtures
for ( i = 0; i < 100; i++ ) {
a = ( randu()*5.0 ) + EPS;
b = ( randu()*5.0 ) + EPS;
y = stdev( a, b );
t.equal( isNumber( y ), true, 'returns a number' );
}
t.end();
});
|
/**
* jQuery-csv (jQuery Plugin)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Acknowledgements:
* The original design and influence to implement this library as a jquery
* plugin is influenced by jquery-json (http://code.google.com/p/jquery-json/).
* If you're looking to use native JSON.Stringify but want additional backwards
* compatibility for browsers that don't support it, I highly recommend you
* check it out.
*
* A special thanks goes out to rwk@acm.org for providing a lot of valuable
* feedback to the project including the core for the new FSM
* (Finite State Machine) parsers. If you're looking for a stable TSV parser
* be sure to take a look at jquery-tsv (http://code.google.com/p/jquery-tsv/).
* For legal purposes I'll include the "NO WARRANTY EXPRESSED OR IMPLIED.
* USE AT YOUR OWN RISK.". Which, in 'layman's terms' means, by using this
* library you are accepting responsibility if it breaks your code.
*
* Legal jargon aside, I will do my best to provide a useful and stable core
* that can effectively be built on.
*
* Copyrighted 2012 by Evan Plaice.
*/
RegExp.escape = function (s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
(function () {
'use strict';
var $;
// to keep backwards compatibility
if (typeof jQuery !== 'undefined' && jQuery) {
$ = jQuery;
} else {
$ = {};
}
/**
* jQuery.csv.defaults
* Encapsulates the method paramater defaults for the CSV plugin module.
*/
$.csv = {
defaults: {
separator: ',',
delimiter: '"',
headers: true
},
hooks: {
castToScalar: function (value, state) {
var hasDot = /\./;
if (isNaN(value)) {
return value;
} else {
if (hasDot.test(value)) {
return parseFloat(value);
} else {
var integer = parseInt(value);
if (isNaN(integer)) {
return null;
} else {
return integer;
}
}
}
}
},
parsers: {
parse: function (csv, options) {
// cache settings
var separator = options.separator;
var delimiter = options.delimiter;
// set initial state if it's missing
if (!options.state.rowNum) {
options.state.rowNum = 1;
}
if (!options.state.colNum) {
options.state.colNum = 1;
}
// clear initial state
var data = [];
var entry = [];
var state = 0;
var value = '';
var exit = false;
function endOfEntry () {
// reset the state
state = 0;
value = '';
// if 'start' hasn't been met, don't output
if (options.start && options.state.rowNum < options.start) {
// update global state
entry = [];
options.state.rowNum++;
options.state.colNum = 1;
return;
}
if (options.onParseEntry === undefined) {
// onParseEntry hook not set
data.push(entry);
} else {
var hookVal = options.onParseEntry(entry, options.state); // onParseEntry Hook
// false skips the row, configurable through a hook
if (hookVal !== false) {
data.push(hookVal);
}
}
// console.log('entry:' + entry);
// cleanup
entry = [];
// if 'end' is met, stop parsing
if (options.end && options.state.rowNum >= options.end) {
exit = true;
}
// update global state
options.state.rowNum++;
options.state.colNum = 1;
}
function endOfValue () {
if (options.onParseValue === undefined) {
// onParseValue hook not set
entry.push(value);
} else {
var hook = options.onParseValue(value, options.state); // onParseValue Hook
// false skips the row, configurable through a hook
if (hook !== false) {
entry.push(hook);
}
}
// console.log('value:' + value);
// reset the state
value = '';
state = 0;
// update global state
options.state.colNum++;
}
// escape regex-specific control chars
var escSeparator = RegExp.escape(separator);
var escDelimiter = RegExp.escape(delimiter);
// compile the regEx str using the custom delimiter/separator
var match = /(D|S|\r\n|\n|\r|[^DS\r\n]+)/;
var matchSrc = match.source;
matchSrc = matchSrc.replace(/S/g, escSeparator);
matchSrc = matchSrc.replace(/D/g, escDelimiter);
match = new RegExp(matchSrc, 'gm');
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(match, function (m0) {
if (exit) {
return;
}
switch (state) {
// the start of a value
case 0:
// null last value
if (m0 === separator) {
value += '';
endOfValue();
break;
}
// opening delimiter
if (m0 === delimiter) {
state = 1;
break;
}
// null last value
if (/^(\r\n|\n|\r)$/.test(m0)) {
endOfValue();
endOfEntry();
break;
}
// un-delimited value
value += m0;
state = 3;
break;
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
state = 2;
break;
}
// delimited data
value += m0;
state = 1;
break;
// delimiter found in delimited input
case 2:
// escaped delimiter?
if (m0 === delimiter) {
value += m0;
state = 1;
break;
}
// null value
if (m0 === separator) {
endOfValue();
break;
}
// end of entry
if (/^(\r\n|\n|\r)$/.test(m0)) {
endOfValue();
endOfEntry();
break;
}
// broken paser?
throw new Error('CSVDataError: Illegal State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
// un-delimited input
case 3:
// null last value
if (m0 === separator) {
endOfValue();
break;
}
// end of entry
if (/^(\r\n|\n|\r)$/.test(m0)) {
endOfValue();
endOfEntry();
break;
}
if (m0 === delimiter) {
// non-compliant data
throw new Error('CSVDataError: Illegal Quote [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
// broken parser?
throw new Error('CSVDataError: Illegal Data [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
default:
// shenanigans
throw new Error('CSVDataError: Unknown State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
// console.log('val:' + m0 + ' state:' + state);
});
// submit the last entry
// ignore null last line
if (entry.length !== 0) {
endOfValue();
endOfEntry();
}
return data;
},
// a csv-specific line splitter
splitLines: function (csv, options) {
if (!csv) {
return undefined;
}
options = options || {};
// cache settings
var separator = options.separator || $.csv.defaults.separator;
var delimiter = options.delimiter || $.csv.defaults.delimiter;
// set initial state if it's missing
options.state = options.state || {};
if (!options.state.rowNum) {
options.state.rowNum = 1;
}
// clear initial state
var entries = [];
var state = 0;
var entry = '';
var exit = false;
function endOfLine () {
// reset the state
state = 0;
// if 'start' hasn't been met, don't output
if (options.start && options.state.rowNum < options.start) {
// update global state
entry = '';
options.state.rowNum++;
return;
}
if (options.onParseEntry === undefined) {
// onParseEntry hook not set
entries.push(entry);
} else {
var hookVal = options.onParseEntry(entry, options.state); // onParseEntry Hook
// false skips the row, configurable through a hook
if (hookVal !== false) {
entries.push(hookVal);
}
}
// cleanup
entry = '';
// if 'end' is met, stop parsing
if (options.end && options.state.rowNum >= options.end) {
exit = true;
}
// update global state
options.state.rowNum++;
}
// escape regex-specific control chars
var escSeparator = RegExp.escape(separator);
var escDelimiter = RegExp.escape(delimiter);
// compile the regEx str using the custom delimiter/separator
var match = /(D|S|\n|\r|[^DS\r\n]+)/;
var matchSrc = match.source;
matchSrc = matchSrc.replace(/S/g, escSeparator);
matchSrc = matchSrc.replace(/D/g, escDelimiter);
match = new RegExp(matchSrc, 'gm');
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(match, function (m0) {
if (exit) {
return;
}
switch (state) {
// the start of a value/entry
case 0:
// null value
if (m0 === separator) {
entry += m0;
state = 0;
break;
}
// opening delimiter
if (m0 === delimiter) {
entry += m0;
state = 1;
break;
}
// end of line
if (m0 === '\n') {
endOfLine();
break;
}
// phantom carriage return
if (/^\r$/.test(m0)) {
break;
}
// un-delimit value
entry += m0;
state = 3;
break;
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
entry += m0;
state = 2;
break;
}
// delimited data
entry += m0;
state = 1;
break;
// delimiter found in delimited input
case 2:
// escaped delimiter?
var prevChar = entry.substr(entry.length - 1);
if (m0 === delimiter && prevChar === delimiter) {
entry += m0;
state = 1;
break;
}
// end of value
if (m0 === separator) {
entry += m0;
state = 0;
break;
}
// end of line
if (m0 === '\n') {
endOfLine();
break;
}
// phantom carriage return
if (m0 === '\r') {
break;
}
// broken paser?
throw new Error('CSVDataError: Illegal state [Row:' + options.state.rowNum + ']');
// un-delimited input
case 3:
// null value
if (m0 === separator) {
entry += m0;
state = 0;
break;
}
// end of line
if (m0 === '\n') {
endOfLine();
break;
}
// phantom carriage return
if (m0 === '\r') {
break;
}
// non-compliant data
if (m0 === delimiter) {
throw new Error('CSVDataError: Illegal quote [Row:' + options.state.rowNum + ']');
}
// broken parser?
throw new Error('CSVDataError: Illegal state [Row:' + options.state.rowNum + ']');
default:
// shenanigans
throw new Error('CSVDataError: Unknown state [Row:' + options.state.rowNum + ']');
}
// console.log('val:' + m0 + ' state:' + state);
});
// submit the last entry
// ignore null last line
if (entry !== '') {
endOfLine();
}
return entries;
},
// a csv entry parser
parseEntry: function (csv, options) {
// cache settings
var separator = options.separator;
var delimiter = options.delimiter;
// set initial state if it's missing
if (!options.state.rowNum) {
options.state.rowNum = 1;
}
if (!options.state.colNum) {
options.state.colNum = 1;
}
// clear initial state
var entry = [];
var state = 0;
var value = '';
function endOfValue () {
if (options.onParseValue === undefined) {
// onParseValue hook not set
entry.push(value);
} else {
var hook = options.onParseValue(value, options.state); // onParseValue Hook
// false skips the value, configurable through a hook
if (hook !== false) {
entry.push(hook);
}
}
// reset the state
value = '';
state = 0;
// update global state
options.state.colNum++;
}
// checked for a cached regEx first
if (!options.match) {
// escape regex-specific control chars
var escSeparator = RegExp.escape(separator);
var escDelimiter = RegExp.escape(delimiter);
// compile the regEx str using the custom delimiter/separator
var match = /(D|S|\n|\r|[^DS\r\n]+)/;
var matchSrc = match.source;
matchSrc = matchSrc.replace(/S/g, escSeparator);
matchSrc = matchSrc.replace(/D/g, escDelimiter);
options.match = new RegExp(matchSrc, 'gm');
}
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(options.match, function (m0) {
switch (state) {
// the start of a value
case 0:
// null last value
if (m0 === separator) {
value += '';
endOfValue();
break;
}
// opening delimiter
if (m0 === delimiter) {
state = 1;
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// un-delimited value
value += m0;
state = 3;
break;
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
state = 2;
break;
}
// delimited data
value += m0;
state = 1;
break;
// delimiter found in delimited input
case 2:
// escaped delimiter?
if (m0 === delimiter) {
value += m0;
state = 1;
break;
}
// null value
if (m0 === separator) {
endOfValue();
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// broken paser?
throw new Error('CSVDataError: Illegal State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
// un-delimited input
case 3:
// null last value
if (m0 === separator) {
endOfValue();
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// non-compliant data
if (m0 === delimiter) {
throw new Error('CSVDataError: Illegal Quote [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
// broken parser?
throw new Error('CSVDataError: Illegal Data [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
default:
// shenanigans
throw new Error('CSVDataError: Unknown State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
// console.log('val:' + m0 + ' state:' + state);
});
// submit the last value
endOfValue();
return entry;
}
},
helpers: {
/**
* $.csv.helpers.collectPropertyNames(objectsArray)
* Collects all unique property names from all passed objects.
*
* @param {Array} objects Objects to collect properties from.
*
* Returns an array of property names (array will be empty,
* if objects have no own properties).
*/
collectPropertyNames: function (objects) {
var o = [];
var propName = [];
var props = [];
for (o in objects) {
for (propName in objects[o]) {
if ((objects[o].hasOwnProperty(propName)) &&
(props.indexOf(propName) < 0) &&
(typeof objects[o][propName] !== 'function')) {
props.push(propName);
}
}
}
return props;
}
},
/**
* $.csv.toArray(csv)
* Converts a CSV entry string to a javascript array.
*
* @param {Array} csv The string containing the CSV data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
*
* This method deals with simple CSV strings only. It's useful if you only
* need to parse a single entry. If you need to parse more than one line,
* use $.csv2Array instead.
*/
toArray: function (csv, options, callback) {
options = (options !== undefined ? options : {});
var config = {};
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false);
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator;
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter;
var state = (options.state !== undefined ? options.state : {});
// setup
options = {
delimiter: config.delimiter,
separator: config.separator,
onParseEntry: options.onParseEntry,
onParseValue: options.onParseValue,
state: state
};
var entry = $.csv.parsers.parseEntry(csv, options);
// push the value to a callback if one is defined
if (!config.callback) {
return entry;
} else {
config.callback('', entry);
}
},
/**
* $.csv.toArrays(csv)
* Converts a CSV string to a javascript array.
*
* @param {String} csv The string containing the raw CSV data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
*
* This method deals with multi-line CSV. The breakdown is simple. The first
* dimension of the array represents the line (or entry/row) while the second
* dimension contains the values (or values/columns).
*/
toArrays: function (csv, options, callback) {
options = (options !== undefined ? options : {});
var config = {};
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false);
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator;
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter;
// setup
var data = [];
options = {
delimiter: config.delimiter,
separator: config.separator,
onPreParse: options.onPreParse,
onParseEntry: options.onParseEntry,
onParseValue: options.onParseValue,
onPostParse: options.onPostParse,
start: options.start,
end: options.end,
state: {
rowNum: 1,
colNum: 1
}
};
// onPreParse hook
if (options.onPreParse !== undefined) {
options.onPreParse(csv, options.state);
}
// parse the data
data = $.csv.parsers.parse(csv, options);
// onPostParse hook
if (options.onPostParse !== undefined) {
options.onPostParse(data, options.state);
}
// push the value to a callback if one is defined
if (!config.callback) {
return data;
} else {
config.callback('', data);
}
},
/**
* $.csv.toObjects(csv)
* Converts a CSV string to a javascript object.
* @param {String} csv The string containing the raw CSV data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
* @param {Boolean} [headers] Indicates whether the data contains a header line. Defaults to true.
*
* This method deals with multi-line CSV strings. Where the headers line is
* used as the key for each value per entry.
*/
toObjects: function (csv, options, callback) {
options = (options !== undefined ? options : {});
var config = {};
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false);
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator;
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter;
config.headers = 'headers' in options ? options.headers : $.csv.defaults.headers;
options.start = 'start' in options ? options.start : 1;
// account for headers
if (config.headers) {
options.start++;
}
if (options.end && config.headers) {
options.end++;
}
// setup
var lines = [];
var data = [];
options = {
delimiter: config.delimiter,
separator: config.separator,
onPreParse: options.onPreParse,
onParseEntry: options.onParseEntry,
onParseValue: options.onParseValue,
onPostParse: options.onPostParse,
start: options.start,
end: options.end,
state: {
rowNum: 1,
colNum: 1
},
match: false,
transform: options.transform
};
// fetch the headers
var headerOptions = {
delimiter: config.delimiter,
separator: config.separator,
start: 1,
end: 1,
state: {
rowNum: 1,
colNum: 1
}
};
// onPreParse hook
if (options.onPreParse !== undefined) {
options.onPreParse(csv, options.state);
}
// parse the csv
var headerLine = $.csv.parsers.splitLines(csv, headerOptions);
var headers = $.csv.toArray(headerLine[0], options);
// fetch the data
lines = $.csv.parsers.splitLines(csv, options);
// reset the state for re-use
options.state.colNum = 1;
if (headers) {
options.state.rowNum = 2;
} else {
options.state.rowNum = 1;
}
// convert data to objects
for (var i = 0, len = lines.length; i < len; i++) {
var entry = $.csv.toArray(lines[i], options);
var object = {};
for (var j = 0; j < headers.length; j++) {
object[headers[j]] = entry[j];
}
if (options.transform !== undefined) {
data.push(options.transform.call(undefined, object));
} else {
data.push(object);
}
// update row state
options.state.rowNum++;
}
// onPostParse hook
if (options.onPostParse !== undefined) {
options.onPostParse(data, options.state);
}
// push the value to a callback if one is defined
if (!config.callback) {
return data;
} else {
config.callback('', data);
}
},
/**
* $.csv.fromArrays(arrays)
* Converts a javascript array to a CSV String.
*
* @param {Array} arrays An array containing an array of CSV entries.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
*
* This method generates a CSV file from an array of arrays (representing entries).
*/
fromArrays: function (arrays, options, callback) {
options = (options !== undefined ? options : {});
var config = {};
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false);
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator;
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter;
var output = '';
var line;
var lineValues;
var i;
var j;
for (i = 0; i < arrays.length; i++) {
line = arrays[i];
lineValues = [];
for (j = 0; j < line.length; j++) {
var strValue = (line[j] === undefined || line[j] === null) ? '' : line[j].toString();
if (strValue.indexOf(config.delimiter) > -1) {
strValue = strValue.replace(new RegExp(config.delimiter, 'g'), config.delimiter + config.delimiter);
}
var escMatcher = '\n|\r|S|D';
escMatcher = escMatcher.replace('S', config.separator);
escMatcher = escMatcher.replace('D', config.delimiter);
if (strValue.search(escMatcher) > -1) {
strValue = config.delimiter + strValue + config.delimiter;
}
lineValues.push(strValue);
}
output += lineValues.join(config.separator) + '\n';
}
// push the value to a callback if one is defined
if (!config.callback) {
return output;
} else {
config.callback('', output);
}
},
/**
* $.csv.fromObjects(objects)
* Converts a javascript dictionary to a CSV string.
*
* @param {Object} objects An array of objects containing the data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
* @param {Character} [sortOrder] Sort order of columns (named after
* object properties). Use 'alpha' for alphabetic. Default is 'declare',
* which means, that properties will _probably_ appear in order they were
* declared for the object. But without any guarantee.
* @param {Character or Array} [manualOrder] Manually order columns. May be
* a strin in a same csv format as an output or an array of header names
* (array items won't be parsed). All the properties, not present in
* `manualOrder` will be appended to the end in accordance with `sortOrder`
* option. So the `manualOrder` always takes preference, if present.
*
* This method generates a CSV file from an array of objects (name:value pairs).
* It starts by detecting the headers and adding them as the first line of
* the CSV file, followed by a structured dump of the data.
*/
fromObjects: function (objects, options, callback) {
options = (options !== undefined ? options : {});
var config = {};
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false);
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator;
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter;
config.headers = 'headers' in options ? options.headers : $.csv.defaults.headers;
config.sortOrder = 'sortOrder' in options ? options.sortOrder : 'declare';
config.manualOrder = 'manualOrder' in options ? options.manualOrder : [];
config.transform = options.transform;
if (typeof config.manualOrder === 'string') {
config.manualOrder = $.csv.toArray(config.manualOrder, config);
}
if (config.transform !== undefined) {
var origObjects = objects;
objects = [];
var i;
for (i = 0; i < origObjects.length; i++) {
objects.push(config.transform.call(undefined, origObjects[i]));
}
}
var props = $.csv.helpers.collectPropertyNames(objects);
if (config.sortOrder === 'alpha') {
props.sort();
} // else {} - nothing to do for 'declare' order
if (config.manualOrder.length > 0) {
var propsManual = [].concat(config.manualOrder);
let p;
for (p = 0; p < props.length; p++) {
if (propsManual.indexOf(props[p]) < 0) {
propsManual.push(props[p]);
}
}
props = propsManual;
}
var o, p, line, output, propName;
if (config.headers) {
output.push(props);
}
for (o = 0; o < objects.length; o++) {
line = [];
for (p = 0; p < props.length; p++) {
propName = props[p];
if (propName in objects[o] && typeof objects[o][propName] !== 'function') {
line.push(objects[o][propName]);
} else {
line.push('');
}
}
output.push(line);
}
// push the value to a callback if one is defined
return $.csv.fromArrays(output, options, config.callback);
}
};
// Maintenance code to maintain backward-compatibility
// Will be removed in release 1.0
$.csvEntry2Array = $.csv.toArray;
$.csv2Array = $.csv.toArrays;
$.csv2Dictionary = $.csv.toObjects;
// CommonJS module is defined
if (typeof module !== 'undefined' && module.exports) {
module.exports = $.csv;
}
}).call(this);
|